From 3eb9039c5392abaabd96d08c0006ea4066346a60 Mon Sep 17 00:00:00 2001 From: Dinh Nguyen Date: Tue, 17 Aug 2010 16:46:40 -0500 Subject: ENGR00126692-3: Upgrade kernel to 2.6.35 This patch contains changes to /drivers files Contains all checkpatch and copyright fixes. Acked-by: Rob Herring Signed-off-by: Dinh Nguyen --- Documentation/imx_nfc.txt | 369 + drivers/Kconfig | 2 + drivers/Makefile | 3 + drivers/ata/Kconfig | 8 + drivers/ata/Makefile | 1 + drivers/ata/pata_fsl.c | 1041 +++ drivers/char/Kconfig | 23 + drivers/char/Makefile | 5 + drivers/char/hw_random/Kconfig | 24 + drivers/char/hw_random/Makefile | 2 + drivers/char/hw_random/fsl-rnga.c | 238 + drivers/char/hw_random/fsl-rngc.c | 372 + drivers/char/imx_sim.c | 1498 ++++ drivers/char/mxc_iim.c | 161 + drivers/char/mxc_si4702.c | 1223 +++ drivers/char/mxs_viim.c | 175 + drivers/crypto/Kconfig | 12 + drivers/crypto/Makefile | 1 + drivers/crypto/dcp.c | 1697 ++++ drivers/crypto/dcp.h | 717 ++ drivers/crypto/dcp_bootstream_ioctl.h | 32 + drivers/dma/Kconfig | 9 + drivers/dma/Makefile | 1 + drivers/dma/pxp/Makefile | 2 + drivers/dma/pxp/pxp_device.c | 512 ++ drivers/dma/pxp/pxp_dma.c | 1383 ++++ drivers/dma/pxp/regs-pxp.h | 949 +++ drivers/hwmon/Kconfig | 10 + drivers/hwmon/Makefile | 2 + drivers/hwmon/isl29003.c | 439 ++ drivers/hwmon/mxc_mma7450.c | 788 ++ drivers/i2c-slave/Kconfig | 39 + drivers/i2c-slave/Makefile | 8 + drivers/i2c-slave/i2c_slave_client.c | 81 + drivers/i2c-slave/i2c_slave_core.c | 359 + drivers/i2c-slave/i2c_slave_device.c | 271 + drivers/i2c-slave/i2c_slave_device.h | 79 + drivers/i2c-slave/i2c_slave_ring_buffer.c | 185 + drivers/i2c-slave/i2c_slave_ring_buffer.h | 39 + drivers/i2c-slave/mxc_i2c_slave.c | 335 + drivers/i2c-slave/mxc_i2c_slave.h | 44 + drivers/i2c-slave/mxc_i2c_slave_reg.h | 41 + drivers/i2c/busses/Kconfig | 58 + drivers/i2c/busses/Makefile | 4 + drivers/i2c/busses/i2c-mxs.c | 598 ++ drivers/i2c/busses/i2c-mxs.h | 41 + drivers/i2c/busses/mxc_i2c.c | 808 ++ drivers/i2c/busses/mxc_i2c_hs.c | 553 ++ drivers/i2c/busses/mxc_i2c_hs_reg.h | 97 + drivers/i2c/busses/mxc_i2c_reg.h | 40 + drivers/input/keyboard/Kconfig | 27 + drivers/input/keyboard/Makefile | 4 + drivers/input/keyboard/mc9s08dz60_keyb.c | 248 + drivers/input/keyboard/mpr084.c | 500 ++ drivers/input/keyboard/mxc_keyb.c | 1203 +++ drivers/input/keyboard/mxs-kbd.c | 365 + drivers/input/touchscreen/Kconfig | 40 + drivers/input/touchscreen/Makefile | 4 + drivers/input/touchscreen/imx_adc_ts.c | 114 + drivers/input/touchscreen/mxc_ts.c | 189 + drivers/input/touchscreen/mxs-ts.c | 463 ++ drivers/leds/Kconfig | 11 + drivers/leds/Makefile | 2 + drivers/leds/leds-mc13892.c | 153 + drivers/leds/leds-mxs-pwm.c | 192 + drivers/media/video/Kconfig | 30 + drivers/media/video/Makefile | 5 + drivers/media/video/mxc/capture/Kconfig | 123 + drivers/media/video/mxc/capture/Makefile | 39 + drivers/media/video/mxc/capture/adv7180.c | 1001 +++ drivers/media/video/mxc/capture/csi_v4l2_capture.c | 1466 ++++ drivers/media/video/mxc/capture/fsl_csi.c | 288 + drivers/media/video/mxc/capture/fsl_csi.h | 198 + drivers/media/video/mxc/capture/ipu_csi_enc.c | 332 + drivers/media/video/mxc/capture/ipu_prp_enc.c | 489 ++ drivers/media/video/mxc/capture/ipu_prp_sw.h | 38 + drivers/media/video/mxc/capture/ipu_prp_vf_adc.c | 601 ++ drivers/media/video/mxc/capture/ipu_prp_vf_sdc.c | 467 ++ .../media/video/mxc/capture/ipu_prp_vf_sdc_bg.c | 443 ++ drivers/media/video/mxc/capture/ipu_still.c | 268 + drivers/media/video/mxc/capture/mt9v111.c | 1076 +++ drivers/media/video/mxc/capture/mt9v111.h | 431 + drivers/media/video/mxc/capture/mxc_v4l2_capture.c | 2728 +++++++ drivers/media/video/mxc/capture/mxc_v4l2_capture.h | 206 + drivers/media/video/mxc/capture/ov2640.c | 1080 +++ drivers/media/video/mxc/capture/ov3640.c | 1429 ++++ drivers/media/video/mxc/capture/sensor_clock.c | 97 + drivers/media/video/mxc/output/Kconfig | 28 + drivers/media/video/mxc/output/Makefile | 11 + .../media/video/mxc/output/mx31_v4l2_wvga_output.c | 1928 +++++ drivers/media/video/mxc/output/mxc_v4l2_output.c | 2616 ++++++ drivers/media/video/mxc/output/mxc_v4l2_output.h | 154 + drivers/media/video/mxs_pxp.c | 1414 ++++ drivers/media/video/mxs_pxp.h | 158 + drivers/media/video/pxp.c | 1409 ++++ drivers/media/video/pxp.h | 130 + drivers/misc/Kconfig | 5 + drivers/misc/Makefile | 1 + drivers/misc/mxs-persistent.c | 271 + drivers/mmc/card/Kconfig | 12 + drivers/mmc/card/Makefile | 1 + drivers/mmc/card/unifi_fs/Makefile | 2 + drivers/mmc/card/unifi_fs/fs_lx.c | 683 ++ drivers/mmc/card/unifi_fs/fs_sdio_api.h | 68 + drivers/mmc/host/Kconfig | 54 + drivers/mmc/host/Makefile | 4 +- drivers/mmc/host/mx_sdhci.c | 2296 ++++++ drivers/mmc/host/mx_sdhci.h | 295 + drivers/mmc/host/mxc_mmc.c | 1534 ++++ drivers/mmc/host/mxc_mmc.h | 124 + drivers/mmc/host/mxs-mmc.c | 1318 ++++ drivers/mtd/devices/Kconfig | 8 + drivers/mtd/devices/Makefile | 1 + drivers/mtd/devices/mxc_dataflash.c | 1037 +++ drivers/mtd/maps/Kconfig | 10 + drivers/mtd/maps/Makefile | 1 + drivers/mtd/maps/mxc_nor.c | 181 + drivers/mtd/nand/Kconfig | 62 + drivers/mtd/nand/Makefile | 4 + drivers/mtd/nand/gpmi-nfc/Makefile | 10 + drivers/mtd/nand/gpmi-nfc/gpmi-nfc-bch-regs-v0.h | 550 ++ drivers/mtd/nand/gpmi-nfc/gpmi-nfc-bch-regs-v1.h | 557 ++ .../mtd/nand/gpmi-nfc/gpmi-nfc-event-reporting.c | 307 + drivers/mtd/nand/gpmi-nfc/gpmi-nfc-gpmi-regs-v0.h | 416 + drivers/mtd/nand/gpmi-nfc/gpmi-nfc-gpmi-regs-v1.h | 421 + drivers/mtd/nand/gpmi-nfc/gpmi-nfc-hal-common.c | 1037 +++ drivers/mtd/nand/gpmi-nfc/gpmi-nfc-hal-v0.c | 924 +++ drivers/mtd/nand/gpmi-nfc/gpmi-nfc-hal-v1.c | 866 ++ drivers/mtd/nand/gpmi-nfc/gpmi-nfc-main.c | 1880 +++++ drivers/mtd/nand/gpmi-nfc/gpmi-nfc-mil.c | 2600 ++++++ drivers/mtd/nand/gpmi-nfc/gpmi-nfc-rom-common.c | 59 + drivers/mtd/nand/gpmi-nfc/gpmi-nfc-rom-v0.c | 297 + drivers/mtd/nand/gpmi-nfc/gpmi-nfc-rom-v1.c | 82 + drivers/mtd/nand/gpmi-nfc/gpmi-nfc.h | 643 ++ drivers/mtd/nand/imx_nfc.c | 8286 ++++++++++++++++++++ drivers/mtd/nand/mxc_nand.c | 3 +- drivers/mtd/nand/mxc_nd.c | 1413 ++++ drivers/mtd/nand/mxc_nd.h | 112 + drivers/mtd/nand/mxc_nd2.c | 1628 ++++ drivers/mtd/nand/mxc_nd2.h | 712 ++ drivers/mtd/nand/nand_device_info.c | 2286 ++++++ drivers/mtd/nand/nand_device_info.h | 140 + drivers/mxc/Kconfig | 39 + drivers/mxc/Makefile | 17 + drivers/mxc/adc/Kconfig | 14 + drivers/mxc/adc/Makefile | 4 + drivers/mxc/adc/imx_adc.c | 1134 +++ drivers/mxc/adc/imx_adc_reg.h | 242 + drivers/mxc/asrc/Kconfig | 13 + drivers/mxc/asrc/Makefile | 7 + drivers/mxc/asrc/mxc_asrc.c | 1692 ++++ drivers/mxc/bt/Kconfig | 13 + drivers/mxc/bt/Makefile | 4 + drivers/mxc/bt/mxc_bt.c | 128 + drivers/mxc/dam/Kconfig | 13 + drivers/mxc/dam/Makefile | 9 + drivers/mxc/dam/dam.c | 427 + drivers/mxc/dam/dam.h | 258 + drivers/mxc/dam/dam_v1.c | 617 ++ drivers/mxc/gps_ioctrl/Kconfig | 13 + drivers/mxc/gps_ioctrl/Makefile | 5 + drivers/mxc/gps_ioctrl/agpsgpiodev.c | 332 + drivers/mxc/gps_ioctrl/agpsgpiodev.h | 46 + drivers/mxc/hmp4e/Kconfig | 24 + drivers/mxc/hmp4e/Makefile | 8 + drivers/mxc/hmp4e/mxc_hmp4e.c | 812 ++ drivers/mxc/hmp4e/mxc_hmp4e.h | 70 + drivers/mxc/hw_event/Kconfig | 11 + drivers/mxc/hw_event/Makefile | 1 + drivers/mxc/hw_event/mxc_hw_event.c | 266 + drivers/mxc/ipu/Kconfig | 4 + drivers/mxc/ipu/Makefile | 5 + drivers/mxc/ipu/ipu_adc.c | 689 ++ drivers/mxc/ipu/ipu_calc_stripes_sizes.c | 374 + drivers/mxc/ipu/ipu_common.c | 1970 +++++ drivers/mxc/ipu/ipu_csi.c | 225 + drivers/mxc/ipu/ipu_device.c | 696 ++ drivers/mxc/ipu/ipu_ic.c | 590 ++ drivers/mxc/ipu/ipu_param_mem.h | 176 + drivers/mxc/ipu/ipu_prv.h | 59 + drivers/mxc/ipu/ipu_regs.h | 396 + drivers/mxc/ipu/ipu_sdc.c | 357 + drivers/mxc/ipu/pf/Kconfig | 7 + drivers/mxc/ipu/pf/Makefile | 1 + drivers/mxc/ipu/pf/mxc_pf.c | 991 +++ drivers/mxc/ipu3/Kconfig | 5 + drivers/mxc/ipu3/Makefile | 4 + drivers/mxc/ipu3/ipu_calc_stripes_sizes.c | 373 + drivers/mxc/ipu3/ipu_capture.c | 719 ++ drivers/mxc/ipu3/ipu_common.c | 2589 ++++++ drivers/mxc/ipu3/ipu_device.c | 510 ++ drivers/mxc/ipu3/ipu_disp.c | 1805 +++++ drivers/mxc/ipu3/ipu_ic.c | 826 ++ drivers/mxc/ipu3/ipu_param_mem.h | 562 ++ drivers/mxc/ipu3/ipu_prv.h | 102 + drivers/mxc/ipu3/ipu_regs.h | 666 ++ drivers/mxc/mcu_pmic/Kconfig | 17 + drivers/mxc/mcu_pmic/Makefile | 6 + drivers/mxc/mcu_pmic/max8660.c | 154 + drivers/mxc/mcu_pmic/max8660.h | 49 + drivers/mxc/mcu_pmic/mc9s08dz60.c | 197 + drivers/mxc/mcu_pmic/mc9s08dz60.h | 73 + drivers/mxc/mcu_pmic/mcu_pmic_core.c | 226 + drivers/mxc/mcu_pmic/mcu_pmic_core.h | 43 + drivers/mxc/mcu_pmic/mcu_pmic_gpio.c | 131 + drivers/mxc/mlb/Kconfig | 13 + drivers/mxc/mlb/Makefile | 5 + drivers/mxc/mlb/mxc_mlb.c | 1056 +++ drivers/mxc/pmic/Kconfig | 64 + drivers/mxc/pmic/Makefile | 7 + drivers/mxc/pmic/core/Makefile | 21 + drivers/mxc/pmic/core/mc13783.c | 380 + drivers/mxc/pmic/core/mc13892.c | 335 + drivers/mxc/pmic/core/mc34704.c | 329 + drivers/mxc/pmic/core/pmic-dev.c | 317 + drivers/mxc/pmic/core/pmic.h | 138 + drivers/mxc/pmic/core/pmic_common.c | 127 + drivers/mxc/pmic/core/pmic_core_i2c.c | 348 + drivers/mxc/pmic/core/pmic_core_spi.c | 303 + drivers/mxc/pmic/core/pmic_event.c | 236 + drivers/mxc/pmic/core/pmic_external.c | 100 + drivers/mxc/pmic/mc13783/Kconfig | 55 + drivers/mxc/pmic/mc13783/Makefile | 18 + drivers/mxc/pmic/mc13783/pmic_adc.c | 1541 ++++ drivers/mxc/pmic/mc13783/pmic_adc_defs.h | 321 + drivers/mxc/pmic/mc13783/pmic_audio.c | 5873 ++++++++++++++ drivers/mxc/pmic/mc13783/pmic_battery.c | 1220 +++ drivers/mxc/pmic/mc13783/pmic_battery_defs.h | 81 + drivers/mxc/pmic/mc13783/pmic_convity.c | 2468 ++++++ drivers/mxc/pmic/mc13783/pmic_light.c | 2764 +++++++ drivers/mxc/pmic/mc13783/pmic_light_defs.h | 144 + drivers/mxc/pmic/mc13783/pmic_power.c | 3146 ++++++++ drivers/mxc/pmic/mc13783/pmic_power_defs.h | 509 ++ drivers/mxc/pmic/mc13783/pmic_rtc.c | 544 ++ drivers/mxc/pmic/mc13783/pmic_rtc_defs.h | 47 + drivers/mxc/pmic/mc13892/Kconfig | 48 + drivers/mxc/pmic/mc13892/Makefile | 10 + drivers/mxc/pmic/mc13892/pmic_adc.c | 984 +++ drivers/mxc/pmic/mc13892/pmic_battery.c | 634 ++ drivers/mxc/pmic/mc13892/pmic_light.c | 685 ++ drivers/mxc/security/Kconfig | 11 + drivers/mxc/security/Makefile | 1 + drivers/mxc/security/dryice-regs.h | 207 + drivers/mxc/security/dryice.c | 1123 +++ drivers/mxc/security/dryice.h | 287 + drivers/mxc/ssi/Kconfig | 12 + drivers/mxc/ssi/Makefile | 7 + drivers/mxc/ssi/registers.h | 208 + drivers/mxc/ssi/ssi.c | 1221 +++ drivers/mxc/ssi/ssi.h | 574 ++ drivers/mxc/ssi/ssi_types.h | 367 + drivers/mxc/vpu/Kconfig | 30 + drivers/mxc/vpu/Makefile | 10 + drivers/mxc/vpu/mxc_vl2cc.c | 124 + drivers/mxc/vpu/mxc_vpu.c | 862 ++ drivers/net/Kconfig | 2 +- drivers/net/can/Kconfig | 9 + drivers/net/can/Makefile | 1 + drivers/net/can/flexcan/Makefile | 3 + drivers/net/can/flexcan/dev.c | 732 ++ drivers/net/can/flexcan/drv.c | 628 ++ drivers/net/can/flexcan/flexcan.h | 222 + drivers/net/can/flexcan/mbm.c | 361 + drivers/net/enc28j60.c | 18 +- drivers/net/fec.c | 205 +- drivers/net/fec.h | 5 +- drivers/net/irda/Kconfig | 4 + drivers/net/irda/Makefile | 1 + drivers/net/irda/mxc_ir.c | 1781 +++++ drivers/net/irda/mxc_ir.h | 131 + drivers/pcmcia/Kconfig | 8 + drivers/pcmcia/Makefile | 1 + drivers/pcmcia/mx31ads-pcmcia.c | 1293 +++ drivers/pcmcia/mx31ads-pcmcia.h | 155 + drivers/power/Kconfig | 21 + drivers/power/Makefile | 1 + drivers/power/mxs/Makefile | 9 + drivers/power/mxs/ddi_bc_api.c | 559 ++ drivers/power/mxs/ddi_bc_hw.c | 397 + drivers/power/mxs/ddi_bc_hw.h | 77 + drivers/power/mxs/ddi_bc_init.c | 188 + drivers/power/mxs/ddi_bc_internal.h | 53 + drivers/power/mxs/ddi_bc_ramp.c | 724 ++ drivers/power/mxs/ddi_bc_ramp.h | 50 + drivers/power/mxs/ddi_bc_sm.c | 918 +++ drivers/power/mxs/ddi_bc_sm.h | 46 + drivers/power/mxs/ddi_power_battery.c | 1908 +++++ drivers/power/mxs/ddi_power_battery.h | 95 + drivers/power/mxs/fiq.S | 125 + drivers/power/mxs/linux.c | 1182 +++ drivers/regulator/Kconfig | 25 + drivers/regulator/Makefile | 10 +- drivers/regulator/core.c | 5 + drivers/regulator/max17135-regulator.c | 736 ++ drivers/regulator/mxs-regulator.c | 302 + drivers/regulator/reg-mc13783.c | 2662 +++++++ drivers/regulator/reg-mc13892.c | 1850 +++++ drivers/regulator/reg-mc34704.c | 289 + drivers/regulator/reg-mc9s08dz60.c | 236 + drivers/rtc/Kconfig | 46 + drivers/rtc/Makefile | 5 + drivers/rtc/rtc-imxdi.c | 581 ++ drivers/rtc/rtc-mc13892.c | 257 + drivers/rtc/rtc-mxc.c | 4 +- drivers/rtc/rtc-mxc_v2.c | 766 ++ drivers/rtc/rtc-mxs.c | 320 + drivers/serial/Kconfig | 104 + drivers/serial/Makefile | 4 + drivers/serial/mxc_uart.c | 1954 +++++ drivers/serial/mxc_uart_early.c | 184 + drivers/serial/mxc_uart_reg.h | 128 + drivers/serial/mxs-auart.c | 1108 +++ drivers/serial/mxs-duart.c | 803 ++ drivers/serial/regs-duart.h | 301 + drivers/serial/regs-uartapp.h | 307 + drivers/spi/Kconfig | 12 + drivers/spi/Makefile | 2 + drivers/spi/mxc_spi.c | 1313 ++++ drivers/spi/spi_mxs.c | 711 ++ drivers/spi/spi_mxs.h | 52 + drivers/usb/gadget/Kconfig | 57 +- drivers/usb/gadget/Makefile | 1 + drivers/usb/gadget/arcotg_udc.c | 3105 ++++++++ drivers/usb/gadget/arcotg_udc.h | 703 ++ drivers/usb/gadget/fsl_udc_core.c | 9 +- drivers/usb/gadget/fsl_updater.c | 79 +- drivers/usb/gadget/fsl_updater.h | 1 + drivers/usb/gadget/stmp_updater.c | 504 ++ drivers/usb/gadget/stmp_updater.h | 140 + drivers/usb/host/Kconfig | 92 + drivers/usb/host/ehci-arc.c | 709 ++ drivers/usb/host/ehci-fsl.h | 7 + drivers/usb/otg/Kconfig | 7 + drivers/usb/otg/Makefile | 2 + drivers/usb/otg/fsl_otg.c | 1300 +++ drivers/usb/otg/fsl_otg.h | 412 + drivers/usb/otg/otg_fsm.c | 371 + drivers/usb/otg/otg_fsm.h | 151 + drivers/video/Kconfig | 8 + drivers/video/Makefile | 2 + drivers/video/backlight/Kconfig | 33 + drivers/video/backlight/Makefile | 6 + drivers/video/backlight/mxc_ipu_bl.c | 158 + drivers/video/backlight/mxc_lcdc_bl.c | 161 + drivers/video/backlight/mxc_mc13892_bl.c | 180 + drivers/video/backlight/mxc_pmic_bl.c | 200 + drivers/video/backlight/mxs_bl.c | 385 + drivers/video/backlight/wm8350_bl.c | 299 + drivers/video/mxc/Kconfig | 103 + drivers/video/mxc/Makefile | 24 + drivers/video/mxc/ch7024.c | 866 ++ drivers/video/mxc/elcdif_regs.h | 678 ++ drivers/video/mxc/epdc_regs.h | 301 + drivers/video/mxc/ldb.c | 1449 ++++ drivers/video/mxc/mxc_edid.c | 88 + drivers/video/mxc/mxc_elcdif_fb.c | 1436 ++++ drivers/video/mxc/mxc_epdc_fb.c | 3058 ++++++++ drivers/video/mxc/mxc_ipuv3_fb.c | 1867 +++++ drivers/video/mxc/mxcfb.c | 1372 ++++ drivers/video/mxc/mxcfb_ch7026.c | 370 + drivers/video/mxc/mxcfb_claa_wvga.c | 239 + drivers/video/mxc/mxcfb_epson.c | 1153 +++ drivers/video/mxc/mxcfb_epson_vga.c | 362 + drivers/video/mxc/mxcfb_modedb.c | 69 + drivers/video/mxc/tve.c | 922 +++ drivers/video/mxs/Kconfig | 28 + drivers/video/mxs/Makefile | 6 + drivers/video/mxs/lcd_43wvf1g.c | 289 + drivers/video/mxs/lcd_lms430.c | 300 + drivers/video/mxs/lcdif.c | 136 + drivers/video/mxs/mxsfb.c | 950 +++ drivers/video/mxs/regs-tvenc.h | 583 ++ drivers/video/mxs/tvenc.c | 279 + drivers/w1/masters/mxc_w1.c | 4 +- drivers/w1/slaves/Kconfig | 22 + drivers/w1/slaves/Makefile | 2 + drivers/w1/slaves/w1_ds2438.c | 585 ++ drivers/w1/slaves/w1_ds2438.h | 119 + drivers/w1/slaves/w1_ds2751.c | 320 + drivers/w1/w1_family.h | 2 + drivers/watchdog/Kconfig | 21 + drivers/watchdog/Makefile | 2 + drivers/watchdog/mxc_wdt.c | 376 + drivers/watchdog/mxc_wdt.h | 37 + drivers/watchdog/mxs-wdt.c | 303 + net/core/dev.c | 6 + sound/arm/Kconfig | 49 + sound/arm/Makefile | 11 + sound/arm/mxc-alsa-common.h | 68 + sound/arm/mxc-alsa-mixer.c | 411 + sound/arm/mxc-alsa-pmic.c | 3793 +++++++++ sound/arm/mxc-alsa-pmic.h | 110 + sound/arm/mxc-alsa-spdif.c | 2263 ++++++ sound/soc/Kconfig | 1 + sound/soc/Makefile | 1 + sound/soc/codecs/Kconfig | 23 + sound/soc/codecs/Makefile | 14 + sound/soc/codecs/ak4647.c | 800 ++ sound/soc/codecs/ak4647.h | 92 + sound/soc/codecs/ak5702.c | 608 ++ sound/soc/codecs/ak5702.h | 130 + sound/soc/codecs/bluetooth.c | 162 + sound/soc/codecs/cs42888.c | 1196 +++ sound/soc/codecs/cs42888.h | 31 + sound/soc/codecs/mxs-adc-codec.c | 1221 +++ sound/soc/codecs/mxs-adc-codec.h | 87 + sound/soc/codecs/mxs_spdif.c | 455 ++ sound/soc/codecs/mxs_spdif.h | 172 + sound/soc/codecs/sgtl5000.c | 1294 +++ sound/soc/codecs/sgtl5000.h | 406 + sound/soc/imx/Kconfig | 72 + sound/soc/imx/Makefile | 25 +- sound/soc/imx/imx-3stack-ak4647.c | 445 ++ sound/soc/imx/imx-3stack-ak5702.c | 226 + sound/soc/imx/imx-3stack-bt.c | 256 + sound/soc/imx/imx-3stack-bt.h | 21 + sound/soc/imx/imx-3stack-cs42888.c | 410 + sound/soc/imx/imx-3stack-sgtl5000.c | 689 ++ sound/soc/imx/imx-3stack-wm8350.c | 696 ++ sound/soc/imx/imx-3stack-wm8580.c | 434 + sound/soc/imx/imx-ac97.c | 564 ++ sound/soc/imx/imx-esai.c | 709 ++ sound/soc/imx/imx-esai.h | 314 + sound/soc/imx/imx-pcm.c | 688 ++ sound/soc/imx/imx-pcm.h | 83 + sound/soc/imx/imx-ssi.c | 27 +- sound/soc/mxs/Kconfig | 51 + sound/soc/mxs/Makefile | 16 + sound/soc/mxs/mxs-adc.c | 453 ++ sound/soc/mxs/mxs-adc.h | 21 + sound/soc/mxs/mxs-dai.c | 657 ++ sound/soc/mxs/mxs-dai.h | 42 + sound/soc/mxs/mxs-devb-spdif.c | 90 + sound/soc/mxs/mxs-devb.c | 296 + sound/soc/mxs/mxs-evk-adc.c | 198 + sound/soc/mxs/mxs-pcm.c | 505 ++ sound/soc/mxs/mxs-pcm.h | 31 + sound/soc/mxs/mxs-spdif-dai.c | 203 + sound/soc/mxs/mxs-spdif-dai.h | 21 + 439 files changed, 200840 insertions(+), 109 deletions(-) create mode 100644 Documentation/imx_nfc.txt create mode 100644 drivers/ata/pata_fsl.c create mode 100644 drivers/char/hw_random/fsl-rnga.c create mode 100644 drivers/char/hw_random/fsl-rngc.c create mode 100644 drivers/char/imx_sim.c create mode 100644 drivers/char/mxc_iim.c create mode 100644 drivers/char/mxc_si4702.c create mode 100644 drivers/char/mxs_viim.c create mode 100644 drivers/crypto/dcp.c create mode 100644 drivers/crypto/dcp.h create mode 100644 drivers/crypto/dcp_bootstream_ioctl.h create mode 100644 drivers/dma/pxp/Makefile create mode 100644 drivers/dma/pxp/pxp_device.c create mode 100644 drivers/dma/pxp/pxp_dma.c create mode 100644 drivers/dma/pxp/regs-pxp.h create mode 100644 drivers/hwmon/isl29003.c create mode 100644 drivers/hwmon/mxc_mma7450.c create mode 100644 drivers/i2c-slave/Kconfig create mode 100644 drivers/i2c-slave/Makefile create mode 100644 drivers/i2c-slave/i2c_slave_client.c create mode 100644 drivers/i2c-slave/i2c_slave_core.c create mode 100644 drivers/i2c-slave/i2c_slave_device.c create mode 100644 drivers/i2c-slave/i2c_slave_device.h create mode 100644 drivers/i2c-slave/i2c_slave_ring_buffer.c create mode 100644 drivers/i2c-slave/i2c_slave_ring_buffer.h create mode 100644 drivers/i2c-slave/mxc_i2c_slave.c create mode 100644 drivers/i2c-slave/mxc_i2c_slave.h create mode 100644 drivers/i2c-slave/mxc_i2c_slave_reg.h create mode 100644 drivers/i2c/busses/i2c-mxs.c create mode 100644 drivers/i2c/busses/i2c-mxs.h create mode 100644 drivers/i2c/busses/mxc_i2c.c create mode 100644 drivers/i2c/busses/mxc_i2c_hs.c create mode 100644 drivers/i2c/busses/mxc_i2c_hs_reg.h create mode 100644 drivers/i2c/busses/mxc_i2c_reg.h create mode 100644 drivers/input/keyboard/mc9s08dz60_keyb.c create mode 100644 drivers/input/keyboard/mpr084.c create mode 100644 drivers/input/keyboard/mxc_keyb.c create mode 100644 drivers/input/keyboard/mxs-kbd.c create mode 100644 drivers/input/touchscreen/imx_adc_ts.c create mode 100644 drivers/input/touchscreen/mxc_ts.c create mode 100644 drivers/input/touchscreen/mxs-ts.c create mode 100644 drivers/leds/leds-mc13892.c create mode 100644 drivers/leds/leds-mxs-pwm.c create mode 100644 drivers/media/video/mxc/capture/Kconfig create mode 100644 drivers/media/video/mxc/capture/Makefile create mode 100644 drivers/media/video/mxc/capture/adv7180.c create mode 100644 drivers/media/video/mxc/capture/csi_v4l2_capture.c create mode 100644 drivers/media/video/mxc/capture/fsl_csi.c create mode 100644 drivers/media/video/mxc/capture/fsl_csi.h create mode 100644 drivers/media/video/mxc/capture/ipu_csi_enc.c create mode 100644 drivers/media/video/mxc/capture/ipu_prp_enc.c create mode 100644 drivers/media/video/mxc/capture/ipu_prp_sw.h create mode 100644 drivers/media/video/mxc/capture/ipu_prp_vf_adc.c create mode 100644 drivers/media/video/mxc/capture/ipu_prp_vf_sdc.c create mode 100644 drivers/media/video/mxc/capture/ipu_prp_vf_sdc_bg.c create mode 100644 drivers/media/video/mxc/capture/ipu_still.c create mode 100644 drivers/media/video/mxc/capture/mt9v111.c create mode 100644 drivers/media/video/mxc/capture/mt9v111.h create mode 100644 drivers/media/video/mxc/capture/mxc_v4l2_capture.c create mode 100644 drivers/media/video/mxc/capture/mxc_v4l2_capture.h create mode 100644 drivers/media/video/mxc/capture/ov2640.c create mode 100644 drivers/media/video/mxc/capture/ov3640.c create mode 100644 drivers/media/video/mxc/capture/sensor_clock.c create mode 100644 drivers/media/video/mxc/output/Kconfig create mode 100644 drivers/media/video/mxc/output/Makefile create mode 100644 drivers/media/video/mxc/output/mx31_v4l2_wvga_output.c create mode 100644 drivers/media/video/mxc/output/mxc_v4l2_output.c create mode 100644 drivers/media/video/mxc/output/mxc_v4l2_output.h create mode 100644 drivers/media/video/mxs_pxp.c create mode 100644 drivers/media/video/mxs_pxp.h create mode 100644 drivers/media/video/pxp.c create mode 100644 drivers/media/video/pxp.h create mode 100644 drivers/misc/mxs-persistent.c create mode 100644 drivers/mmc/card/unifi_fs/Makefile create mode 100644 drivers/mmc/card/unifi_fs/fs_lx.c create mode 100644 drivers/mmc/card/unifi_fs/fs_sdio_api.h create mode 100644 drivers/mmc/host/mx_sdhci.c create mode 100644 drivers/mmc/host/mx_sdhci.h create mode 100644 drivers/mmc/host/mxc_mmc.c create mode 100644 drivers/mmc/host/mxc_mmc.h create mode 100644 drivers/mmc/host/mxs-mmc.c create mode 100644 drivers/mtd/devices/mxc_dataflash.c create mode 100644 drivers/mtd/maps/mxc_nor.c create mode 100644 drivers/mtd/nand/gpmi-nfc/Makefile create mode 100644 drivers/mtd/nand/gpmi-nfc/gpmi-nfc-bch-regs-v0.h create mode 100644 drivers/mtd/nand/gpmi-nfc/gpmi-nfc-bch-regs-v1.h create mode 100644 drivers/mtd/nand/gpmi-nfc/gpmi-nfc-event-reporting.c create mode 100644 drivers/mtd/nand/gpmi-nfc/gpmi-nfc-gpmi-regs-v0.h create mode 100644 drivers/mtd/nand/gpmi-nfc/gpmi-nfc-gpmi-regs-v1.h create mode 100644 drivers/mtd/nand/gpmi-nfc/gpmi-nfc-hal-common.c create mode 100644 drivers/mtd/nand/gpmi-nfc/gpmi-nfc-hal-v0.c create mode 100644 drivers/mtd/nand/gpmi-nfc/gpmi-nfc-hal-v1.c create mode 100644 drivers/mtd/nand/gpmi-nfc/gpmi-nfc-main.c create mode 100644 drivers/mtd/nand/gpmi-nfc/gpmi-nfc-mil.c create mode 100644 drivers/mtd/nand/gpmi-nfc/gpmi-nfc-rom-common.c create mode 100644 drivers/mtd/nand/gpmi-nfc/gpmi-nfc-rom-v0.c create mode 100644 drivers/mtd/nand/gpmi-nfc/gpmi-nfc-rom-v1.c create mode 100644 drivers/mtd/nand/gpmi-nfc/gpmi-nfc.h create mode 100644 drivers/mtd/nand/imx_nfc.c create mode 100644 drivers/mtd/nand/mxc_nd.c create mode 100644 drivers/mtd/nand/mxc_nd.h create mode 100644 drivers/mtd/nand/mxc_nd2.c create mode 100644 drivers/mtd/nand/mxc_nd2.h create mode 100644 drivers/mtd/nand/nand_device_info.c create mode 100644 drivers/mtd/nand/nand_device_info.h create mode 100644 drivers/mxc/Kconfig create mode 100644 drivers/mxc/Makefile create mode 100644 drivers/mxc/adc/Kconfig create mode 100644 drivers/mxc/adc/Makefile create mode 100644 drivers/mxc/adc/imx_adc.c create mode 100644 drivers/mxc/adc/imx_adc_reg.h create mode 100644 drivers/mxc/asrc/Kconfig create mode 100644 drivers/mxc/asrc/Makefile create mode 100644 drivers/mxc/asrc/mxc_asrc.c create mode 100644 drivers/mxc/bt/Kconfig create mode 100644 drivers/mxc/bt/Makefile create mode 100644 drivers/mxc/bt/mxc_bt.c create mode 100644 drivers/mxc/dam/Kconfig create mode 100644 drivers/mxc/dam/Makefile create mode 100644 drivers/mxc/dam/dam.c create mode 100644 drivers/mxc/dam/dam.h create mode 100644 drivers/mxc/dam/dam_v1.c create mode 100644 drivers/mxc/gps_ioctrl/Kconfig create mode 100644 drivers/mxc/gps_ioctrl/Makefile create mode 100644 drivers/mxc/gps_ioctrl/agpsgpiodev.c create mode 100644 drivers/mxc/gps_ioctrl/agpsgpiodev.h create mode 100644 drivers/mxc/hmp4e/Kconfig create mode 100644 drivers/mxc/hmp4e/Makefile create mode 100644 drivers/mxc/hmp4e/mxc_hmp4e.c create mode 100644 drivers/mxc/hmp4e/mxc_hmp4e.h create mode 100644 drivers/mxc/hw_event/Kconfig create mode 100644 drivers/mxc/hw_event/Makefile create mode 100644 drivers/mxc/hw_event/mxc_hw_event.c create mode 100644 drivers/mxc/ipu/Kconfig create mode 100644 drivers/mxc/ipu/Makefile create mode 100644 drivers/mxc/ipu/ipu_adc.c create mode 100644 drivers/mxc/ipu/ipu_calc_stripes_sizes.c create mode 100644 drivers/mxc/ipu/ipu_common.c create mode 100644 drivers/mxc/ipu/ipu_csi.c create mode 100644 drivers/mxc/ipu/ipu_device.c create mode 100644 drivers/mxc/ipu/ipu_ic.c create mode 100644 drivers/mxc/ipu/ipu_param_mem.h create mode 100644 drivers/mxc/ipu/ipu_prv.h create mode 100644 drivers/mxc/ipu/ipu_regs.h create mode 100644 drivers/mxc/ipu/ipu_sdc.c create mode 100644 drivers/mxc/ipu/pf/Kconfig create mode 100644 drivers/mxc/ipu/pf/Makefile create mode 100644 drivers/mxc/ipu/pf/mxc_pf.c create mode 100644 drivers/mxc/ipu3/Kconfig create mode 100644 drivers/mxc/ipu3/Makefile create mode 100644 drivers/mxc/ipu3/ipu_calc_stripes_sizes.c create mode 100644 drivers/mxc/ipu3/ipu_capture.c create mode 100644 drivers/mxc/ipu3/ipu_common.c create mode 100644 drivers/mxc/ipu3/ipu_device.c create mode 100644 drivers/mxc/ipu3/ipu_disp.c create mode 100644 drivers/mxc/ipu3/ipu_ic.c create mode 100644 drivers/mxc/ipu3/ipu_param_mem.h create mode 100644 drivers/mxc/ipu3/ipu_prv.h create mode 100644 drivers/mxc/ipu3/ipu_regs.h create mode 100644 drivers/mxc/mcu_pmic/Kconfig create mode 100644 drivers/mxc/mcu_pmic/Makefile create mode 100644 drivers/mxc/mcu_pmic/max8660.c create mode 100644 drivers/mxc/mcu_pmic/max8660.h create mode 100644 drivers/mxc/mcu_pmic/mc9s08dz60.c create mode 100644 drivers/mxc/mcu_pmic/mc9s08dz60.h create mode 100644 drivers/mxc/mcu_pmic/mcu_pmic_core.c create mode 100644 drivers/mxc/mcu_pmic/mcu_pmic_core.h create mode 100644 drivers/mxc/mcu_pmic/mcu_pmic_gpio.c create mode 100644 drivers/mxc/mlb/Kconfig create mode 100644 drivers/mxc/mlb/Makefile create mode 100644 drivers/mxc/mlb/mxc_mlb.c create mode 100644 drivers/mxc/pmic/Kconfig create mode 100644 drivers/mxc/pmic/Makefile create mode 100644 drivers/mxc/pmic/core/Makefile create mode 100644 drivers/mxc/pmic/core/mc13783.c create mode 100644 drivers/mxc/pmic/core/mc13892.c create mode 100644 drivers/mxc/pmic/core/mc34704.c create mode 100644 drivers/mxc/pmic/core/pmic-dev.c create mode 100644 drivers/mxc/pmic/core/pmic.h create mode 100644 drivers/mxc/pmic/core/pmic_common.c create mode 100644 drivers/mxc/pmic/core/pmic_core_i2c.c create mode 100644 drivers/mxc/pmic/core/pmic_core_spi.c create mode 100644 drivers/mxc/pmic/core/pmic_event.c create mode 100644 drivers/mxc/pmic/core/pmic_external.c create mode 100644 drivers/mxc/pmic/mc13783/Kconfig create mode 100644 drivers/mxc/pmic/mc13783/Makefile create mode 100644 drivers/mxc/pmic/mc13783/pmic_adc.c create mode 100644 drivers/mxc/pmic/mc13783/pmic_adc_defs.h create mode 100644 drivers/mxc/pmic/mc13783/pmic_audio.c create mode 100644 drivers/mxc/pmic/mc13783/pmic_battery.c create mode 100644 drivers/mxc/pmic/mc13783/pmic_battery_defs.h create mode 100644 drivers/mxc/pmic/mc13783/pmic_convity.c create mode 100644 drivers/mxc/pmic/mc13783/pmic_light.c create mode 100644 drivers/mxc/pmic/mc13783/pmic_light_defs.h create mode 100644 drivers/mxc/pmic/mc13783/pmic_power.c create mode 100644 drivers/mxc/pmic/mc13783/pmic_power_defs.h create mode 100644 drivers/mxc/pmic/mc13783/pmic_rtc.c create mode 100644 drivers/mxc/pmic/mc13783/pmic_rtc_defs.h create mode 100644 drivers/mxc/pmic/mc13892/Kconfig create mode 100644 drivers/mxc/pmic/mc13892/Makefile create mode 100644 drivers/mxc/pmic/mc13892/pmic_adc.c create mode 100644 drivers/mxc/pmic/mc13892/pmic_battery.c create mode 100644 drivers/mxc/pmic/mc13892/pmic_light.c create mode 100644 drivers/mxc/security/Kconfig create mode 100644 drivers/mxc/security/Makefile create mode 100644 drivers/mxc/security/dryice-regs.h create mode 100644 drivers/mxc/security/dryice.c create mode 100644 drivers/mxc/security/dryice.h create mode 100644 drivers/mxc/ssi/Kconfig create mode 100644 drivers/mxc/ssi/Makefile create mode 100644 drivers/mxc/ssi/registers.h create mode 100644 drivers/mxc/ssi/ssi.c create mode 100644 drivers/mxc/ssi/ssi.h create mode 100644 drivers/mxc/ssi/ssi_types.h create mode 100644 drivers/mxc/vpu/Kconfig create mode 100644 drivers/mxc/vpu/Makefile create mode 100644 drivers/mxc/vpu/mxc_vl2cc.c create mode 100644 drivers/mxc/vpu/mxc_vpu.c create mode 100644 drivers/net/can/flexcan/Makefile create mode 100644 drivers/net/can/flexcan/dev.c create mode 100644 drivers/net/can/flexcan/drv.c create mode 100644 drivers/net/can/flexcan/flexcan.h create mode 100644 drivers/net/can/flexcan/mbm.c create mode 100644 drivers/net/irda/mxc_ir.c create mode 100644 drivers/net/irda/mxc_ir.h create mode 100644 drivers/pcmcia/mx31ads-pcmcia.c create mode 100644 drivers/pcmcia/mx31ads-pcmcia.h create mode 100644 drivers/power/mxs/Makefile create mode 100644 drivers/power/mxs/ddi_bc_api.c create mode 100644 drivers/power/mxs/ddi_bc_hw.c create mode 100644 drivers/power/mxs/ddi_bc_hw.h create mode 100644 drivers/power/mxs/ddi_bc_init.c create mode 100644 drivers/power/mxs/ddi_bc_internal.h create mode 100644 drivers/power/mxs/ddi_bc_ramp.c create mode 100644 drivers/power/mxs/ddi_bc_ramp.h create mode 100644 drivers/power/mxs/ddi_bc_sm.c create mode 100644 drivers/power/mxs/ddi_bc_sm.h create mode 100644 drivers/power/mxs/ddi_power_battery.c create mode 100644 drivers/power/mxs/ddi_power_battery.h create mode 100644 drivers/power/mxs/fiq.S create mode 100644 drivers/power/mxs/linux.c create mode 100644 drivers/regulator/max17135-regulator.c create mode 100644 drivers/regulator/mxs-regulator.c create mode 100644 drivers/regulator/reg-mc13783.c create mode 100644 drivers/regulator/reg-mc13892.c create mode 100644 drivers/regulator/reg-mc34704.c create mode 100644 drivers/regulator/reg-mc9s08dz60.c create mode 100644 drivers/rtc/rtc-imxdi.c create mode 100644 drivers/rtc/rtc-mc13892.c create mode 100644 drivers/rtc/rtc-mxc_v2.c create mode 100644 drivers/rtc/rtc-mxs.c create mode 100644 drivers/serial/mxc_uart.c create mode 100644 drivers/serial/mxc_uart_early.c create mode 100644 drivers/serial/mxc_uart_reg.h create mode 100644 drivers/serial/mxs-auart.c create mode 100644 drivers/serial/mxs-duart.c create mode 100644 drivers/serial/regs-duart.h create mode 100644 drivers/serial/regs-uartapp.h create mode 100644 drivers/spi/mxc_spi.c create mode 100644 drivers/spi/spi_mxs.c create mode 100644 drivers/spi/spi_mxs.h create mode 100644 drivers/usb/gadget/arcotg_udc.c create mode 100644 drivers/usb/gadget/arcotg_udc.h create mode 100644 drivers/usb/gadget/stmp_updater.c create mode 100644 drivers/usb/gadget/stmp_updater.h create mode 100644 drivers/usb/host/ehci-arc.c create mode 100644 drivers/usb/otg/fsl_otg.c create mode 100644 drivers/usb/otg/fsl_otg.h create mode 100644 drivers/usb/otg/otg_fsm.c create mode 100644 drivers/usb/otg/otg_fsm.h create mode 100644 drivers/video/backlight/mxc_ipu_bl.c create mode 100644 drivers/video/backlight/mxc_lcdc_bl.c create mode 100644 drivers/video/backlight/mxc_mc13892_bl.c create mode 100644 drivers/video/backlight/mxc_pmic_bl.c create mode 100644 drivers/video/backlight/mxs_bl.c create mode 100644 drivers/video/backlight/wm8350_bl.c create mode 100644 drivers/video/mxc/Kconfig create mode 100644 drivers/video/mxc/Makefile create mode 100644 drivers/video/mxc/ch7024.c create mode 100644 drivers/video/mxc/elcdif_regs.h create mode 100644 drivers/video/mxc/epdc_regs.h create mode 100644 drivers/video/mxc/ldb.c create mode 100644 drivers/video/mxc/mxc_edid.c create mode 100644 drivers/video/mxc/mxc_elcdif_fb.c create mode 100644 drivers/video/mxc/mxc_epdc_fb.c create mode 100644 drivers/video/mxc/mxc_ipuv3_fb.c create mode 100644 drivers/video/mxc/mxcfb.c create mode 100644 drivers/video/mxc/mxcfb_ch7026.c create mode 100644 drivers/video/mxc/mxcfb_claa_wvga.c create mode 100644 drivers/video/mxc/mxcfb_epson.c create mode 100644 drivers/video/mxc/mxcfb_epson_vga.c create mode 100644 drivers/video/mxc/mxcfb_modedb.c create mode 100644 drivers/video/mxc/tve.c create mode 100644 drivers/video/mxs/Kconfig create mode 100644 drivers/video/mxs/Makefile create mode 100644 drivers/video/mxs/lcd_43wvf1g.c create mode 100644 drivers/video/mxs/lcd_lms430.c create mode 100644 drivers/video/mxs/lcdif.c create mode 100644 drivers/video/mxs/mxsfb.c create mode 100644 drivers/video/mxs/regs-tvenc.h create mode 100644 drivers/video/mxs/tvenc.c create mode 100644 drivers/w1/slaves/w1_ds2438.c create mode 100644 drivers/w1/slaves/w1_ds2438.h create mode 100644 drivers/w1/slaves/w1_ds2751.c create mode 100644 drivers/watchdog/mxc_wdt.c create mode 100644 drivers/watchdog/mxc_wdt.h create mode 100644 drivers/watchdog/mxs-wdt.c create mode 100644 sound/arm/mxc-alsa-common.h create mode 100644 sound/arm/mxc-alsa-mixer.c create mode 100644 sound/arm/mxc-alsa-pmic.c create mode 100644 sound/arm/mxc-alsa-pmic.h create mode 100644 sound/arm/mxc-alsa-spdif.c create mode 100644 sound/soc/codecs/ak4647.c create mode 100644 sound/soc/codecs/ak4647.h create mode 100644 sound/soc/codecs/ak5702.c create mode 100644 sound/soc/codecs/ak5702.h create mode 100644 sound/soc/codecs/bluetooth.c create mode 100644 sound/soc/codecs/cs42888.c create mode 100644 sound/soc/codecs/cs42888.h create mode 100644 sound/soc/codecs/mxs-adc-codec.c create mode 100644 sound/soc/codecs/mxs-adc-codec.h create mode 100644 sound/soc/codecs/mxs_spdif.c create mode 100644 sound/soc/codecs/mxs_spdif.h create mode 100644 sound/soc/codecs/sgtl5000.c create mode 100644 sound/soc/codecs/sgtl5000.h create mode 100644 sound/soc/imx/imx-3stack-ak4647.c create mode 100644 sound/soc/imx/imx-3stack-ak5702.c create mode 100644 sound/soc/imx/imx-3stack-bt.c create mode 100644 sound/soc/imx/imx-3stack-bt.h create mode 100644 sound/soc/imx/imx-3stack-cs42888.c create mode 100644 sound/soc/imx/imx-3stack-sgtl5000.c create mode 100644 sound/soc/imx/imx-3stack-wm8350.c create mode 100644 sound/soc/imx/imx-3stack-wm8580.c create mode 100644 sound/soc/imx/imx-ac97.c create mode 100644 sound/soc/imx/imx-esai.c create mode 100644 sound/soc/imx/imx-esai.h create mode 100644 sound/soc/imx/imx-pcm.c create mode 100644 sound/soc/imx/imx-pcm.h create mode 100644 sound/soc/mxs/Kconfig create mode 100644 sound/soc/mxs/Makefile create mode 100644 sound/soc/mxs/mxs-adc.c create mode 100644 sound/soc/mxs/mxs-adc.h create mode 100644 sound/soc/mxs/mxs-dai.c create mode 100644 sound/soc/mxs/mxs-dai.h create mode 100644 sound/soc/mxs/mxs-devb-spdif.c create mode 100644 sound/soc/mxs/mxs-devb.c create mode 100644 sound/soc/mxs/mxs-evk-adc.c create mode 100644 sound/soc/mxs/mxs-pcm.c create mode 100644 sound/soc/mxs/mxs-pcm.h create mode 100644 sound/soc/mxs/mxs-spdif-dai.c create mode 100644 sound/soc/mxs/mxs-spdif-dai.h diff --git a/Documentation/imx_nfc.txt b/Documentation/imx_nfc.txt new file mode 100644 index 000000000000..7fec999c2884 --- /dev/null +++ b/Documentation/imx_nfc.txt @@ -0,0 +1,369 @@ +i.MX NAND Flash Controller Driver Documentation +=============================================== + + +Definitions of Terms +==================== + +To avoid confusion, let's carefully define some of the terms we'll be using: + + "NAND Flash Chip" or "Chip" + A NAND Flash storage array and controller (including a chip select + signal, ready/busy signal, data register, etc.). + + "NAND Flash Package" or "Package" + A hardware package containing one or more NAND Flash chips that share + data lines and most control signals, but with separate chip select + and ready/busy signals. Package "boundaries" are unimportant to MTD. + + "NAND Flash Medium" or "Medium" + A collection of one or more NAND Flash chips that the system views as + logically contiguous. + + "Memory Technology Device" or "MTD" + An abstraction of underlying memory hardware, represented by a single + struct mtd_info. + + "NAND Flash MTD" + An abstraction of a NAND Flash medium that is represented by a single + struct nand_chip (the name of this structure is misleading because it + has evolved to represent an entire medium, not just a single chip). + All the physical chips in a NAND Flash MTD medium have answered the + "Read ID" command with the same manufacturer code and device code and + are presumed to have identical characteristics. + + "NAND Flash MTD Hardware-independent Layer" or "HIL" + The code that implements an MTD interface and drives all NAND Flash + MTDs. + + "NAND Flash MTD Hardware Abstraction Layer" or "HAL" + Code that implements the internal NAND Flash hardware model and + matches it to specific hardware. + + "NAND Flash MTD Reference Implementation" + A reference implementation of a HAL "stack." + + "Out-of-Band" or "OOB" + An adjective describing information that is not part of the "data" in + a NAND Flash page. NAND Flash pages are generally described in terms + of the amount of data they can hold (e.g., "2K pages" or "4K pages"). + The physical page size is actually larger than this and the + additional bytes are called "out-of-band." + + + +The Structure of the MTD NAND Flash System +========================================== + +The following figure illustrates how control flows down from the system's +MTD interface into the NAND Flash MTD system and down to the hardware- +specific implementation (this driver): + + + + / +---------------------------------------+ + | | MTD | + | +---------------------------------------+ + MTD | | + | | +----------+ + | | | | + | v v | + \ ======================================== | + - struct mtd_info | + / ======================================== | + | | | + | v | + | +---------------------------------------+ | + | | NAND Flash MTD | | + NAND Flash | | Interface Functions | | + Hardware- | +---------------------------------------+ | + Independent | | | | + Layer | | v | + (HIL) | +-------------+ | +-------------+ +-------------+ + | | Init | | | Support | | Reference | + | | Functions | | | Functions | |BBT Functions| + | +-------------+ | +-------------+ +-------------+ + | | | | ^ + | v v v | + \ ======================================== | + - struct nand_chip | + / ======================================== | + | | ^ | ^ | | + NAND Flash | | | | | | | + Hardware | v | v | | | + Abstraction | +--------------+ +---------------+ | | + Layer | | Hardware- | | Reference | +-----------+ + (HAL) | | Specific | | | + | |Implementation| |Implementations| + \ +--------------+ +---------------+ + + + +The function pointers and attributes in struct mtd_info embody an abstract +model of memory technology devices. + +The struct nand_chip is an aggregation of two categories of function pointers +and attributes: + + - Function pointers and attributes used by the HIL. These members embody + an abstract model of NAND Flash media, or a hardware abstraction + layer (HAL). + + - Function pointers and attributes used by the reference implementations. + +The single most confusing thing about the MTD NAND Flash system is that +struct nand_chip contains all the main HAL members mixed up with all the +members used only by the reference implementation, without any clear +distinction. Recognizing the distinction is critical for understanding the +relationship between the HIL and HAL, and can greatly simplify driver +implementation. + +The fundamental operations represented by the function pointers in +struct nand_chip fall into the following categories (from conceptually +"low-level" to "high-level"): + + - Signal Control + - Chip Control + - Low-level I/O + - ECC Control + - ECC-aware I/O + - Error Recovery + - High-level I/O + - Bad Block Management + +The HIL uses only the following "Replaceable" function pointers in +struct nand_chip: + + - Signal Control + - None + - Chip Control + - dev_ready + - select_chip + - cmdfunc + - waitfunc + - Low-level I/O + - read_byte + - ECC Control + - None + - ECC-aware I/O + - ecc.read_page + - ecc.read_page_raw + - Error Recovery + - None + - High-level I/O + - write_page + - ecc.read_oob + - ecc.write_oob + - Bad Block Management + - block_bad + - block_markbad + - scan_bbt + +Note that the HIL calls erase_cmd, but this member is marked "Internal." + +The HIL uses only the following commands with cmdfunc: + + * NAND_CMD_STATUS + - nand_check_wp() - Checks if the current chip is + write-protected. + * NAND_CMD_READID + - nand_get_flash_type() - Gets information about the first chip. + - nand_scan_ident() - Scans for additional chips. + * NAND_CMD_RESET + - nand_do_write_oob() - Clears a bug observed on the + Toshiba TC5832DC and DiskOnChip 2000. + * NAND_CMD_READ0 + - nand_do_read_ops() - Used to begin a full page read (both with + and without ECC). + * NAND_CMD_ERASE1 + - single_erase_cmd() - Starts a block erase operation. + - multi_erase_cmd() - Starts a block erase operation. + * NAND_CMD_ERASE2 + - single_erase_cmd() - Finishes a block erase operation. + - multi_erase_cmd() - Finishes a block erase operation. + + +Since this is all the HIL uses, this is all a driver needs to implement. + + + +The Structure of the imx_nfc Driver +=================================== + +This driver supports many different versions of underlying controller, and +also supports higher-level abstractions like interleaving. To facilitate this +versatility, the code is layered as shown in the following diagram: + + + +--------------------------------------+ + | MTD | + +--------------------------------------+ + | NAND Flash MTD | + ======================================== <-- struct nand_chip + / | MTD Interface Layer (mil_*) | + | | +----------------------------------+ + | | | Medium Abstraction Layer (mal_*) | + imx_nfc | | | | + driver | | | +------------------------+ + | | | | NFC Utils (nfc_util_*) | + | ======================================== <-- struct nfc_hal + \ | NFC HAL (nfc_x_y_*) | + ======================================== <-- Hardware Interface + | NFC Hardware | + +--------------------------------------+ + + +MTD Interface Layer +------------------- +This layer includes functions that the NAND Flash MTD system calls directly. +In a manner of speaking, this layer "parses" the function calls made by MTD +and translates them into fundamental operations understood by the Medium +Abstraction Layer. Some simple operations don't need any abstraction, so code +in this layer can sometimes use the NFC HAL directly. + + +Medium Abstraction Layer +------------------------ +This layer implements the abstract model of the NAND Flash medium and hides +details that shouldn't concern higher layers (e.g., interleaving). + + +NFC Utilities +------------- +These functions make it easier to use the NFC HAL. Even though this layer +is shown above the NFC HAL in the diagram, it's actually possible for the +NFC HAL to call some of these functions. + + +NFC HAL +------- +This layer implements the abstract model of an i.MX NAND Flash controller. + + +Other Collections of Functions +------------------------------ + +- System Interface + - imx_nfc_* + +- sysfs Interface + - get_module_* + - set_module_* + - show_device_* + - store_device_* + + + + +i.MX NAND Flash Controller Versions +=================================== + +The i.MX NAND Flash controller (NFC) has evolved over time. Both its memory +layout and behaviors have changed. In this driver, we use major and minor +version numbers to label these stages in the NFC's evolution. These version +numbers are very useful, but they are entirely a figment of this driver's +imagination -- you will never find them in Freescale hardware reference +manuals. + +When the platform code instantiates an i.MX NFC device, it provides a struct +imx_nfc_platform_data that contains platform-specific information. This +includes the major and minor version numbers for the NFC. This driver uses +the version numbers to select an appopriate NFC HAL structure. + + + +i.MX NFC Memory Map +=================== + +While many things have changed during the evolution of the NFC, much has +remained the same. All i.MX NFCs have two or three essential memory-mapped +regions: a set of buffers, and one or two sets of registers (one on the AXI +bus and perhaps a second on the IP bus). + +The buffer area contains the captive memory to which the NFC writes data +received from the NAND Flash medium. This area is subdivided into several +contiguous "main" buffers that hold 512-byte chunks of data, and several +"spare" buffers that hold varying-size chunks of out-of-band bytes. The +number of main buffers is always the same as the number of spare buffers, but +the exact count and the size of the spare buffers varies across NFC versions. + +The register areas contain the NFC's control interface. Some versions have +only one set of registers, and some have two. + +The platform-specific resources passed to this driver include the starting +and ending physical addresses of the buffer and register areas. This driver +maps those physical addresses to virtual addresses, and then uses version- +specific offsets and bit masks to operate the NFC. + + + +Matching the NAND Flash MTD Page Model with the i.MX NFC +======================================================== + +The NAND Flash MTD HAL model views a page as containing two essentially +independent groups of bytes: "data" bytes and "out-of-band" bytes. If the +underlying physical format has data and out-of-band bytes distributed across +the page, they must be reassembled before being delivered to the caller +(e.g., see the function nand_read_page_syndrome(), which is part of the +reference implementation). + +The i.MX NFC hardware imposes both a physical page layout and a layout in its +memory buffer that differ from the HAL model. The following figure shows how +all these layouts relate to each other: + + + i.MX NFC i.MX NFC + Physical Memory NAND Flash + Page Buffers MTD Model + + +--------+ +--------+ +--------+ + |OOB[N-1]| |OOB[N-1]| |OOB[N-1]| + +--------+ +--------+ +--------+ + | | |OOB[ 1 ]| + | Data | +--------+ +--------+ + | [N-1] | |OOB[ 1 ]| |OOB[ 0 ]| + | | +--------+ +--------+ + +--------+ + ... +--------+ +--------+ + +--------+ |OOB[ 0 ]| | | + |OOB[ 1 ]| +--------+ | Data | + +--------+ | | | [N-1] | + | | | Data | | | + | Data | | [N-1] | +--------+ + | [ 1 ] | | | | | + | | +--------+ | Data | + +--------+ ... | [ 1 ] | + |OOB[ 0 ]| +--------+ | | + +--------+ | | +--------+ + | | | Data | | | + | Data | | [ 1 ] | | Data | + | [ 0 ] | | | | [ 0 ] | + | | +--------+ | | + +--------+ | | +--------+ + | Data | + | [ 0 ] | + | | + +--------+ + + +The NFC memory is *almost* what we want, but not quite. The problems are: + + 1) There are gaps between the out-of-band fragments. + + 2) The NFC memory responds only to 16-byte or 32-byte reads and writes. + +To resolve these problems, we've encapsulated the NFC memory behind these +functions: + + nfc_util_copy_from_the_nfc() - Copies data to main memory from the the NFC. + nfc_util_copy_to_the_nfc() - Copies data from main memory to the NFC. + +These functions don't take pointers to locations within the NFC memory - they +take a "column address." These functions know how to skip over the gaps and +handle the NFC memory such that it looks like all the data and out-of-band +bytes are completely contiguous. They also handle copying arbitrary bytes +from/to a memory that only responds to 16- or 32-byte reads/writes. If you're +accessing the NFC memory without these functions, you're *probably* doing +something wrong. + + diff --git a/drivers/Kconfig b/drivers/Kconfig index a2b902f4d437..21e6f277c8dc 100644 --- a/drivers/Kconfig +++ b/drivers/Kconfig @@ -111,4 +111,6 @@ source "drivers/xen/Kconfig" source "drivers/staging/Kconfig" source "drivers/platform/Kconfig" + +source "drivers/mxc/Kconfig" endmenu diff --git a/drivers/Makefile b/drivers/Makefile index 91874e048552..fd1cbd50acaf 100644 --- a/drivers/Makefile +++ b/drivers/Makefile @@ -75,6 +75,7 @@ obj-$(CONFIG_INPUT) += input/ obj-$(CONFIG_I2O) += message/ obj-$(CONFIG_RTC_LIB) += rtc/ obj-y += i2c/ media/ +obj-$(CONFIG_I2C_SLAVE) += i2c-slave/ obj-$(CONFIG_PPS) += pps/ obj-$(CONFIG_W1) += w1/ obj-$(CONFIG_POWER_SUPPLY) += power/ @@ -92,6 +93,8 @@ obj-$(CONFIG_EISA) += eisa/ obj-y += lguest/ obj-$(CONFIG_CPU_FREQ) += cpufreq/ obj-$(CONFIG_CPU_IDLE) += cpuidle/ +obj-y += idle/ +obj-$(CONFIG_ARCH_MXC) += mxc/ obj-$(CONFIG_MMC) += mmc/ obj-$(CONFIG_MEMSTICK) += memstick/ obj-$(CONFIG_NEW_LEDS) += leds/ diff --git a/drivers/ata/Kconfig b/drivers/ata/Kconfig index aa85a98d3a4f..c3205953863e 100644 --- a/drivers/ata/Kconfig +++ b/drivers/ata/Kconfig @@ -382,6 +382,14 @@ config PATA_EFAR If unsure, say N. +config PATA_FSL + tristate "Freescale on-chip PATA support" + depends on (ARCH_MX5 || ARCH_MX37 || ARCH_MX35 || ARCH_MX3 || ARCH_MX27) + help + On Freescale processors, say Y here if you wish to use the on-chip + ATA interface. + If you are unsure, say N to this. + config PATA_HPT366 tristate "HPT 366/368 PATA support" depends on PCI diff --git a/drivers/ata/Makefile b/drivers/ata/Makefile index 7ef89d73df63..04e27237b993 100644 --- a/drivers/ata/Makefile +++ b/drivers/ata/Makefile @@ -41,6 +41,7 @@ obj-$(CONFIG_PATA_CS5535) += pata_cs5535.o obj-$(CONFIG_PATA_CS5536) += pata_cs5536.o obj-$(CONFIG_PATA_CYPRESS) += pata_cypress.o obj-$(CONFIG_PATA_EFAR) += pata_efar.o +obj-$(CONFIG_PATA_FSL) += pata_fsl.o obj-$(CONFIG_PATA_HPT366) += pata_hpt366.o obj-$(CONFIG_PATA_HPT37X) += pata_hpt37x.o obj-$(CONFIG_PATA_HPT3X2N) += pata_hpt3x2n.o diff --git a/drivers/ata/pata_fsl.c b/drivers/ata/pata_fsl.c new file mode 100644 index 000000000000..42976f2193aa --- /dev/null +++ b/drivers/ata/pata_fsl.c @@ -0,0 +1,1041 @@ +/* + * Freescale integrated PATA driver + */ + +/* + * Copyright 2007-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define DRV_NAME "pata_fsl" + +struct pata_fsl_priv { + int ultra; + u8 *fsl_ata_regs; + struct clk *clk; + int dma_rchan; + int dma_wchan; + int dma_done; + int dma_dir; + unsigned int adma_des_paddr; + unsigned int *adma_des_tp; +}; + +struct adma_bd { + unsigned char *sg_buf; + unsigned char *work_buf; + unsigned int dma_address; + int length; +}; + +struct adma_bulk { + struct adma_bd adma_bd_table[64]; + struct ata_queued_cmd *qc; + int sg_ents; + int reserved[2]; +}; + +enum { + /* various constants */ + FSL_ATA_MAX_SG_LEN = ATA_DMA_BOUNDARY << 1, + + /* offsets to registers */ + FSL_ATA_TIMING_REGS = 0x00, + FSL_ATA_FIFO_FILL = 0x20, + FSL_ATA_CONTROL = 0x24, + FSL_ATA_INT_PEND = 0x28, + FSL_ATA_INT_EN = 0x2C, + FSL_ATA_INT_CLEAR = 0x30, + FSL_ATA_FIFO_ALARM = 0x34, + FSL_ATA_ADMA_ERROR_STATUS = 0x38, + FSL_ATA_SYS_DMA_BADDR = 0x3C, + FSL_ATA_ADMA_SYS_ADDR = 0x40, + FSL_ATA_BLOCK_COUNT = 0x48, + FSL_ATA_BURST_LENGTH = 0x4C, + FSL_ATA_SECTOR_SIZE = 0x50, + FSL_ATA_DRIVE_DATA = 0xA0, + FSL_ATA_DRIVE_CONTROL = 0xD8, + + /* bits within FSL_ATA_CONTROL */ + FSL_ATA_CTRL_DMA_SRST = 0x1000, + FSL_ATA_CTRL_DMA_64ADMA = 0x800, + FSL_ATA_CTRL_DMA_32ADMA = 0x400, + FSL_ATA_CTRL_DMA_STAT_STOP = 0x200, + FSL_ATA_CTRL_DMA_ENABLE = 0x100, + FSL_ATA_CTRL_FIFO_RST_B = 0x80, + FSL_ATA_CTRL_ATA_RST_B = 0x40, + FSL_ATA_CTRL_FIFO_TX_EN = 0x20, + FSL_ATA_CTRL_FIFO_RCV_EN = 0x10, + FSL_ATA_CTRL_DMA_PENDING = 0x08, + FSL_ATA_CTRL_DMA_ULTRA = 0x04, + FSL_ATA_CTRL_DMA_WRITE = 0x02, + FSL_ATA_CTRL_IORDY_EN = 0x01, + + /* bits within the interrupt control registers */ + FSL_ATA_INTR_ATA_INTRQ1 = 0x80, + FSL_ATA_INTR_FIFO_UNDERFLOW = 0x40, + FSL_ATA_INTR_FIFO_OVERFLOW = 0x20, + FSL_ATA_INTR_CTRL_IDLE = 0x10, + FSL_ATA_INTR_ATA_INTRQ2 = 0x08, + FSL_ATA_INTR_DMA_ERR = 0x04, + FSL_ATA_INTR_DMA_TRANS_OVER = 0x02, + + /* ADMA Addr Descriptor Attribute Filed */ + FSL_ADMA_DES_ATTR_VALID = 0x01, + FSL_ADMA_DES_ATTR_END = 0x02, + FSL_ADMA_DES_ATTR_INT = 0x04, + FSL_ADMA_DES_ATTR_SET = 0x10, + FSL_ADMA_DES_ATTR_TRAN = 0x20, + FSL_ADMA_DES_ATTR_LINK = 0x30, +}; + +/* + * This structure contains the timing parameters for + * ATA bus timing in the 5 PIO modes. The timings + * are in nanoseconds, and are converted to clock + * cycles before being stored in the ATA controller + * timing registers. + */ +static struct { + short t0, t1, t2_8, t2_16, t2i, t4, t9, tA; +} pio_specs[] = { + [0] = { + .t0 = 600, .t1 = 70, .t2_8 = 290, .t2_16 = 165, .t2i = 0, .t4 = + 30, .t9 = 20, .tA = 50,}, + [1] = { + .t0 = 383, .t1 = 50, .t2_8 = 290, .t2_16 = 125, .t2i = 0, .t4 = + 20, .t9 = 15, .tA = 50,}, + [2] = { + .t0 = 240, .t1 = 30, .t2_8 = 290, .t2_16 = 100, .t2i = 0, .t4 = + 15, .t9 = 10, .tA = 50,}, + [3] = { + .t0 = 180, .t1 = 30, .t2_8 = 80, .t2_16 = 80, .t2i = 0, .t4 = + 10, .t9 = 10, .tA = 50,}, + [4] = { + .t0 = 120, .t1 = 25, .t2_8 = 70, .t2_16 = 70, .t2i = 0, .t4 = + 10, .t9 = 10, .tA = 50,}, + }; + +#define NR_PIO_SPECS (sizeof pio_specs / sizeof pio_specs[0]) + +/* + * This structure contains the timing parameters for + * ATA bus timing in the 3 MDMA modes. The timings + * are in nanoseconds, and are converted to clock + * cycles before being stored in the ATA controller + * timing registers. + */ +static struct { + short t0M, tD, tH, tJ, tKW, tM, tN, tJNH; +} mdma_specs[] = { + [0] = { + .t0M = 480, .tD = 215, .tH = 20, .tJ = 20, .tKW = 215, .tM = 50, .tN = + 15, .tJNH = 20,}, + [1] = { + .t0M = 150, .tD = 80, .tH = 15, .tJ = 5, .tKW = 50, .tM = 30, .tN = + 10, .tJNH = 15,}, + [2] = { + .t0M = 120, .tD = 70, .tH = 10, .tJ = 5, .tKW = 25, .tM = 25, .tN = + 10, .tJNH = 10,}, + }; + +#define NR_MDMA_SPECS (sizeof mdma_specs / sizeof mdma_specs[0]) + +/* + * This structure contains the timing parameters for + * ATA bus timing in the 6 UDMA modes. The timings + * are in nanoseconds, and are converted to clock + * cycles before being stored in the ATA controller + * timing registers. + */ +static struct { + short t2CYC, tCYC, tDS, tDH, tDVS, tDVH, tCVS, tCVH, tFS_min, tLI_max, + tMLI, tAZ, tZAH, tENV_min, tSR, tRFS, tRP, tACK, tSS, tDZFS; +} udma_specs[] = { + [0] = { + .t2CYC = 235, .tCYC = 114, .tDS = 15, .tDH = 5, .tDVS = 70, .tDVH = + 6, .tCVS = 70, .tCVH = 6, .tFS_min = 0, .tLI_max = + 100, .tMLI = 20, .tAZ = 10, .tZAH = 20, .tENV_min = + 20, .tSR = 50, .tRFS = 75, .tRP = 160, .tACK = 20, .tSS = + 50, .tDZFS = 80,}, + [1] = { + .t2CYC = 156, .tCYC = 75, .tDS = 10, .tDH = 5, .tDVS = 48, .tDVH = + 6, .tCVS = 48, .tCVH = 6, .tFS_min = 0, .tLI_max = + 100, .tMLI = 20, .tAZ = 10, .tZAH = 20, .tENV_min = + 20, .tSR = 30, .tRFS = 70, .tRP = 125, .tACK = 20, .tSS = + 50, .tDZFS = 63,}, + [2] = { + .t2CYC = 117, .tCYC = 55, .tDS = 7, .tDH = 5, .tDVS = 34, .tDVH = + 6, .tCVS = 34, .tCVH = 6, .tFS_min = 0, .tLI_max = + 100, .tMLI = 20, .tAZ = 10, .tZAH = 20, .tENV_min = + 20, .tSR = 20, .tRFS = 60, .tRP = 100, .tACK = 20, .tSS = + 50, .tDZFS = 47,}, + [3] = { + .t2CYC = 86, .tCYC = 39, .tDS = 7, .tDH = 5, .tDVS = 20, .tDVH = + 6, .tCVS = 20, .tCVH = 6, .tFS_min = 0, .tLI_max = + 100, .tMLI = 20, .tAZ = 10, .tZAH = 20, .tENV_min = + 20, .tSR = 20, .tRFS = 60, .tRP = 100, .tACK = 20, .tSS = + 50, .tDZFS = 35,}, + [4] = { + .t2CYC = 57, .tCYC = 25, .tDS = 5, .tDH = 5, .tDVS = 7, .tDVH = + 6, .tCVS = 7, .tCVH = 6, .tFS_min = 0, .tLI_max = + 100, .tMLI = 20, .tAZ = 10, .tZAH = 20, .tENV_min = + 20, .tSR = 50, .tRFS = 60, .tRP = 100, .tACK = 20, .tSS = + 50, .tDZFS = 25,}, + [5] = { + .t2CYC = 38, .tCYC = 17, .tDS = 4, .tDH = 5, .tDVS = 5, .tDVH = + 6, .tCVS = 10, .tCVH = 10, .tFS_min = + 0, .tLI_max = 75, .tMLI = 20, .tAZ = 10, .tZAH = + 20, .tENV_min = 20, .tSR = 20, .tRFS = + 50, .tRP = 85, .tACK = 20, .tSS = 50, .tDZFS = 40,}, +}; + +#define NR_UDMA_SPECS (sizeof udma_specs / sizeof udma_specs[0]) + +struct fsl_ata_time_regs { + u8 time_off, time_on, time_1, time_2w; + u8 time_2r, time_ax, time_pio_rdx, time_4; + u8 time_9, time_m, time_jn, time_d; + u8 time_k, time_ack, time_env, time_rpx; + u8 time_zah, time_mlix, time_dvh, time_dzfs; + u8 time_dvs, time_cvh, time_ss, time_cyc; +}; + +static struct regulator *io_reg; +static struct regulator *core_reg; +static struct adma_bulk adma_info; + +static void +update_timing_config(struct fsl_ata_time_regs *tp, struct ata_host *host) +{ + u32 *lp = (u32 *) tp; + struct pata_fsl_priv *priv = host->private_data; + u32 *ctlp = (u32 *) priv->fsl_ata_regs; + int i; + + for (i = 0; i < 5; i++) { + __raw_writel(*lp, ctlp); + lp++; + ctlp++; + } +} + +/*! + * Calculate values for the ATA bus timing registers and store + * them into the hardware. + * + * @param xfer_mode specifies XFER xfer_mode + * @param pdev specifies platform_device + * + * @return EINVAL speed out of range, or illegal mode + */ +static int set_ata_bus_timing(u8 xfer_mode, struct platform_device *pdev) +{ + struct ata_host *host = dev_get_drvdata(&pdev->dev); + struct pata_fsl_priv *priv = host->private_data; + + /* get the bus clock cycle time, in ns */ + int T = 1 * 1000 * 1000 * 1000 / clk_get_rate(priv->clk); + struct fsl_ata_time_regs tr = { 0 }; + + /* + * every mode gets the same t_off and t_on + */ + tr.time_off = 3; + tr.time_on = 3; + + if (xfer_mode >= XFER_UDMA_0) { + int speed = xfer_mode - XFER_UDMA_0; + if (speed >= NR_UDMA_SPECS) + return -EINVAL; + + tr.time_ack = (udma_specs[speed].tACK + T) / T; + tr.time_env = (udma_specs[speed].tENV_min + T) / T; + tr.time_rpx = (udma_specs[speed].tRP + T) / T + 2; + tr.time_zah = (udma_specs[speed].tZAH + T) / T; + tr.time_mlix = (udma_specs[speed].tMLI + T) / T; + tr.time_dvh = (udma_specs[speed].tDVH + T) / T + 1; + tr.time_dzfs = (udma_specs[speed].tDZFS + T) / T; + + tr.time_dvs = (udma_specs[speed].tDVS + T) / T; + tr.time_cvh = (udma_specs[speed].tCVH + T) / T; + tr.time_ss = (udma_specs[speed].tSS + T) / T; + tr.time_cyc = (udma_specs[speed].tCYC + T) / T; + } else if (xfer_mode >= XFER_MW_DMA_0) { + int speed = xfer_mode - XFER_MW_DMA_0; + if (speed >= NR_MDMA_SPECS) + return -EINVAL; + + tr.time_m = (mdma_specs[speed].tM + T) / T; + tr.time_jn = (mdma_specs[speed].tJNH + T) / T; + tr.time_d = (mdma_specs[speed].tD + T) / T; + + tr.time_k = (mdma_specs[speed].tKW + T) / T; + } else { + int speed = xfer_mode - XFER_PIO_0; + if (speed >= NR_PIO_SPECS) + return -EINVAL; + + tr.time_1 = (pio_specs[speed].t1 + T) / T; + tr.time_2w = (pio_specs[speed].t2_8 + T) / T; + + tr.time_2r = (pio_specs[speed].t2_8 + T) / T; + tr.time_ax = (pio_specs[speed].tA + T) / T + 2; + tr.time_pio_rdx = 1; + tr.time_4 = (pio_specs[speed].t4 + T) / T; + + tr.time_9 = (pio_specs[speed].t9 + T) / T; + } + + update_timing_config(&tr, host); + + return 0; +} + +static void pata_fsl_set_piomode(struct ata_port *ap, struct ata_device *adev) +{ + set_ata_bus_timing(adev->pio_mode, to_platform_device(ap->dev)); +} + +static void pata_fsl_set_dmamode(struct ata_port *ap, struct ata_device *adev) +{ + struct pata_fsl_priv *priv = ap->host->private_data; + + priv->ultra = adev->dma_mode >= XFER_UDMA_0; + + set_ata_bus_timing(adev->dma_mode, to_platform_device(ap->dev)); +} + +static int pata_fsl_port_start(struct ata_port *ap) +{ + return 0; +} + +static void pata_adma_bulk_unmap(struct ata_queued_cmd *qc) +{ + int i; + struct adma_bd *bdp = adma_info.adma_bd_table; + if (adma_info.qc == NULL) + return; + BUG_ON(adma_info.qc != qc); + + adma_info.qc = NULL; + + for (i = 0; i < adma_info.sg_ents; i++) { + if (bdp->work_buf != bdp->sg_buf) { + if (qc->dma_dir == DMA_FROM_DEVICE) { + dma_unmap_single(qc->ap->dev, bdp->dma_address, + bdp->dma_address, DMA_FROM_DEVICE); + memcpy(bdp->sg_buf, bdp->work_buf, bdp->length); + } + dma_free_coherent(qc->ap->dev, bdp->length, + bdp->work_buf, bdp->dma_address); + } + bdp->work_buf = bdp->sg_buf = NULL; + bdp++; + } +} + +static int pata_adma_bulk_map(struct ata_queued_cmd *qc) +{ + unsigned int si; + struct scatterlist *sg; + struct adma_bd *bdp = adma_info.adma_bd_table; + + BUG_ON(adma_info.qc); + + adma_info.qc = qc; + adma_info.sg_ents = 0; + + for_each_sg(qc->sg, sg, qc->n_elem, si) { + /* + * The ADMA mode is used setup the ADMA descriptor table + */ + bdp->sg_buf = sg_virt(sg); + bdp->length = sg->length; + if (sg->dma_address & 0xFFF) { + bdp->work_buf = + dma_alloc_coherent(qc->ap->dev, bdp->length, + &bdp->dma_address, GFP_KERNEL); + if (!bdp->work_buf) { + printk(KERN_WARNING + "can not allocate aligned buffer\n"); + goto fail; + } + if (qc->dma_dir == DMA_TO_DEVICE) + memcpy(bdp->work_buf, bdp->sg_buf, bdp->length); + } else { + bdp->work_buf = bdp->sg_buf; + bdp->dma_address = sg->dma_address; + } + + adma_info.sg_ents++; + bdp++; + } + return 0; + fail: + pata_adma_bulk_unmap(qc); + return -1; +} + +static void dma_callback(void *arg, int error_status, unsigned int count) +{ + struct ata_port *ap = arg; + struct pata_fsl_priv *priv = ap->host->private_data; + u8 *ata_regs = priv->fsl_ata_regs; + + priv->dma_done = 1; + /* + * DMA is finished, so unmask INTRQ from the drive to allow the + * normal ISR to fire. + */ + __raw_writel(FSL_ATA_INTR_ATA_INTRQ2, ata_regs + FSL_ATA_INT_EN); +} + +static irqreturn_t pata_fsl_adma_intr(int irq, void *dev_instance) +{ + struct ata_host *host = dev_instance; + struct pata_fsl_priv *priv = host->private_data; + u8 *ata_regs = priv->fsl_ata_regs; + unsigned int handled = 0; + unsigned int i; + unsigned long flags; + unsigned int pending = __raw_readl(ata_regs + FSL_ATA_INT_PEND); + + if (FSL_ATA_INTR_DMA_TRANS_OVER & pending) { + priv->dma_done = 1; + __raw_writel(pending, ata_regs + FSL_ATA_INT_CLEAR); + handled = 1; + } else if (FSL_ATA_INTR_DMA_ERR & pending) { + printk(KERN_ERR "dma err status 0x%x ...\n", + __raw_readl(ata_regs + FSL_ATA_ADMA_ERROR_STATUS)); + __raw_writel(pending, ata_regs + FSL_ATA_INT_CLEAR); + handled = 1; + i = __raw_readl(ata_regs + FSL_ATA_CONTROL) && 0xFF; + i |= FSL_ATA_CTRL_DMA_SRST | FSL_ATA_CTRL_DMA_32ADMA | + FSL_ATA_CTRL_DMA_ENABLE; + __raw_writel(i, ata_regs + FSL_ATA_CONTROL); + } + + spin_lock_irqsave(&host->lock, flags); + + for (i = 0; i < host->n_ports; i++) { + struct ata_port *ap; + struct ata_queued_cmd *qc; + + ap = host->ports[i]; + + qc = ata_qc_from_tag(ap, ap->link.active_tag); + raw_local_irq_restore(flags); + pata_adma_bulk_unmap(qc); + raw_local_irq_save(flags); + if (qc && !(qc->tf.flags & ATA_TFLAG_POLLING)) + handled |= ata_bmdma_port_intr(ap, qc); + } + + spin_unlock_irqrestore(&host->lock, flags); + + return IRQ_RETVAL(handled); +} + +static int pata_fsl_check_atapi_dma(struct ata_queued_cmd *qc) +{ + return 1; /* ATAPI DMA not yet supported */ +} + +unsigned long pata_fsl_bmdma_mode_filter(struct ata_device *adev, + unsigned long xfer_mask) +{ + /* Capability of the controller has been specified in the + * platform data. Do not filter any modes, just return + * the xfer_mask */ + return xfer_mask; +} + +static void pata_fsl_bmdma_setup(struct ata_queued_cmd *qc) +{ + int chan, i; + int dma_mode = 0, dma_ultra; + u32 ata_control; + struct ata_port *ap = qc->ap; + struct pata_fsl_priv *priv = ap->host->private_data; + u8 *ata_regs = priv->fsl_ata_regs; + struct fsl_ata_platform_data *plat = ap->dev->platform_data; + int err; + unsigned int si; + + priv->dma_dir = qc->dma_dir; + + /* + * Configure the on-chip ATA interface hardware. + */ + dma_ultra = priv->ultra ? FSL_ATA_CTRL_DMA_ULTRA : 0; + + ata_control = FSL_ATA_CTRL_FIFO_RST_B | + FSL_ATA_CTRL_ATA_RST_B | FSL_ATA_CTRL_DMA_PENDING | dma_ultra; + if (plat->adma_flag) + ata_control |= FSL_ATA_CTRL_DMA_32ADMA | + FSL_ATA_CTRL_DMA_ENABLE; + + if (qc->dma_dir == DMA_TO_DEVICE) { + chan = priv->dma_wchan; + ata_control |= FSL_ATA_CTRL_FIFO_TX_EN | FSL_ATA_CTRL_DMA_WRITE; + dma_mode = MXC_DMA_MODE_WRITE; + } else { + chan = priv->dma_rchan; + ata_control |= FSL_ATA_CTRL_FIFO_RCV_EN; + dma_mode = MXC_DMA_MODE_READ; + } + + __raw_writel(ata_control, ata_regs + FSL_ATA_CONTROL); + __raw_writel(plat->fifo_alarm, ata_regs + FSL_ATA_FIFO_ALARM); + + if (plat->adma_flag) { + i = FSL_ATA_INTR_DMA_TRANS_OVER | FSL_ATA_INTR_DMA_ERR; + __raw_writel(FSL_ATA_INTR_ATA_INTRQ2 | i, + ata_regs + FSL_ATA_INT_EN); + } else { + __raw_writel(FSL_ATA_INTR_ATA_INTRQ1, + ata_regs + FSL_ATA_INT_EN); + /* + * Set up the DMA completion callback. + */ + mxc_dma_callback_set(chan, dma_callback, (void *)ap); + } + + /* + * Copy the sg list to an array. + */ + if (plat->adma_flag) { + struct adma_bd *bdp = adma_info.adma_bd_table; + pata_adma_bulk_map(qc); + for (i = 0; i < adma_info.sg_ents; i++) { + priv->adma_des_tp[i << 1] = bdp->length << 12; + priv->adma_des_tp[i << 1] |= FSL_ADMA_DES_ATTR_SET; + priv->adma_des_tp[i << 1] |= FSL_ADMA_DES_ATTR_VALID; + priv->adma_des_tp[(i << 1) + 1] = bdp->dma_address; + priv->adma_des_tp[(i << 1) + 1] |= + FSL_ADMA_DES_ATTR_TRAN; + priv->adma_des_tp[(i << 1) + 1] |= + FSL_ADMA_DES_ATTR_VALID; + if (adma_info.sg_ents == (i + 1)) + priv->adma_des_tp[(i << 1) + 1] |= + FSL_ADMA_DES_ATTR_END; + bdp++; + } + __raw_writel((qc->nbytes / qc->sect_size), ata_regs + + FSL_ATA_BLOCK_COUNT); + __raw_writel(plat->fifo_alarm, ata_regs + FSL_ATA_BURST_LENGTH); + __raw_writel(priv->adma_des_paddr, + ata_regs + FSL_ATA_ADMA_SYS_ADDR); + } else { + int nr_sg = 0; + struct scatterlist tmp[64], *tsg, *sg; + tsg = tmp; + for_each_sg(qc->sg, sg, qc->n_elem, si) { + memcpy(tsg, sg, sizeof(*sg)); + tsg++; + nr_sg++; + } + err = mxc_dma_sg_config(chan, tmp, nr_sg, 0, dma_mode); + if (err) + printk(KERN_ERR "pata_fsl_bmdma_setup: error %d\n", + err); + } +} + +static void pata_fsl_bmdma_start(struct ata_queued_cmd *qc) +{ + struct ata_port *ap = qc->ap; + struct pata_fsl_priv *priv = ap->host->private_data; + u8 *ata_regs = priv->fsl_ata_regs; + struct fsl_ata_platform_data *plat = ap->dev->platform_data; + int chan; + int err; + unsigned i; + + if (1 == plat->adma_flag) { + i = FSL_ATA_CTRL_DMA_32ADMA | FSL_ATA_CTRL_DMA_ENABLE; + /* The adma mode is used, set dma_start_stop to 1 */ + __raw_writel(i | __raw_readl(ata_regs + FSL_ATA_CONTROL) | + FSL_ATA_CTRL_DMA_STAT_STOP, + ata_regs + FSL_ATA_CONTROL); + } else { + /* + * Start the channel. + */ + chan = qc->dma_dir == DMA_TO_DEVICE ? priv->dma_wchan : + priv->dma_rchan; + + err = mxc_dma_enable(chan); + if (err) + printk(KERN_ERR "%s: : error %d\n", __func__, err); + } + + priv->dma_done = 0; + + ata_sff_exec_command(ap, &qc->tf); +} + +static void pata_fsl_bmdma_stop(struct ata_queued_cmd *qc) +{ + struct ata_port *ap = qc->ap; + struct pata_fsl_priv *priv = ap->host->private_data; + u8 *ata_regs = priv->fsl_ata_regs; + struct fsl_ata_platform_data *plat = ap->dev->platform_data; + unsigned i; + + if (plat->adma_flag) { + /* The adma mode is used, set dma_start_stop to 0 */ + i = FSL_ATA_CTRL_DMA_32ADMA | FSL_ATA_CTRL_DMA_ENABLE; + __raw_writel((i | __raw_readl(ata_regs + FSL_ATA_CONTROL)) & + (~FSL_ATA_CTRL_DMA_STAT_STOP), + ata_regs + FSL_ATA_CONTROL); + } + + /* do a dummy read as in ata_bmdma_stop */ +#if 0 + ata_sff_dma_pause(ap); +#endif +} + +static u8 pata_fsl_bmdma_status(struct ata_port *ap) +{ + struct pata_fsl_priv *priv = ap->host->private_data; + + return priv->dma_done ? ATA_DMA_INTR : 0; +} + +static void pata_fsl_dma_init(struct ata_port *ap) +{ + struct pata_fsl_priv *priv = ap->host->private_data; + + priv->dma_rchan = -1; + priv->dma_wchan = -1; + + priv->dma_rchan = mxc_dma_request(MXC_DMA_ATA_RX, "MXC ATA RX"); + if (priv->dma_rchan < 0) { + dev_printk(KERN_ERR, ap->dev, "couldn't get RX DMA channel\n"); + goto err_out; + } + + priv->dma_wchan = mxc_dma_request(MXC_DMA_ATA_TX, "MXC ATA TX"); + if (priv->dma_wchan < 0) { + dev_printk(KERN_ERR, ap->dev, "couldn't get TX DMA channel\n"); + goto err_out; + } + + dev_printk(KERN_ERR, ap->dev, "rchan=%d wchan=%d\n", priv->dma_rchan, + priv->dma_wchan); + return; + + err_out: + ap->mwdma_mask = 0; + ap->udma_mask = 0; + mxc_dma_free(priv->dma_rchan); + mxc_dma_free(priv->dma_wchan); + kfree(priv); +} + +#if 0 +static u8 pata_fsl_irq_ack(struct ata_port *ap, unsigned int chk_drq) +{ + unsigned int bits = chk_drq ? ATA_BUSY | ATA_DRQ : ATA_BUSY; + u8 status; + + status = ata_sff_busy_wait(ap, bits, 1000); + if (status & bits) + if (ata_msg_err(ap)) + printk(KERN_ERR "abnormal status 0x%X\n", status); + + return status; +} +#endif + +static void ata_dummy_noret(struct ata_port *ap) +{ + return; +} + +static struct scsi_host_template pata_fsl_sht = { + .module = THIS_MODULE, + .name = DRV_NAME, + .ioctl = ata_scsi_ioctl, + .queuecommand = ata_scsi_queuecmd, + .can_queue = ATA_DEF_QUEUE, + .this_id = ATA_SHT_THIS_ID, + .sg_tablesize = LIBATA_MAX_PRD, + .cmd_per_lun = ATA_SHT_CMD_PER_LUN, + .emulated = ATA_SHT_EMULATED, + .use_clustering = ATA_SHT_USE_CLUSTERING, + .proc_name = DRV_NAME, + .dma_boundary = FSL_ATA_MAX_SG_LEN, + .slave_configure = ata_scsi_slave_config, + .slave_destroy = ata_scsi_slave_destroy, + .bios_param = ata_std_bios_param, +}; + +static struct ata_port_operations pata_fsl_port_ops = { + .inherits = &ata_bmdma_port_ops, + .set_piomode = pata_fsl_set_piomode, + .set_dmamode = pata_fsl_set_dmamode, + + .check_atapi_dma = pata_fsl_check_atapi_dma, + .cable_detect = ata_cable_unknown, + .mode_filter = pata_fsl_bmdma_mode_filter, + + .bmdma_setup = pata_fsl_bmdma_setup, + .bmdma_start = pata_fsl_bmdma_start, + .bmdma_stop = pata_fsl_bmdma_stop, + .bmdma_status = pata_fsl_bmdma_status, + + .qc_prep = ata_noop_qc_prep, + + .sff_data_xfer = ata_sff_data_xfer_noirq, + .sff_irq_clear = ata_dummy_noret, + .sff_irq_on = ata_sff_irq_on, + + .port_start = pata_fsl_port_start, +}; + +static void fsl_setup_port(struct ata_ioports *ioaddr) +{ + unsigned int shift = 2; + + ioaddr->data_addr = ioaddr->cmd_addr + (ATA_REG_DATA << shift); + ioaddr->error_addr = ioaddr->cmd_addr + (ATA_REG_ERR << shift); + ioaddr->feature_addr = ioaddr->cmd_addr + (ATA_REG_FEATURE << shift); + ioaddr->nsect_addr = ioaddr->cmd_addr + (ATA_REG_NSECT << shift); + ioaddr->lbal_addr = ioaddr->cmd_addr + (ATA_REG_LBAL << shift); + ioaddr->lbam_addr = ioaddr->cmd_addr + (ATA_REG_LBAM << shift); + ioaddr->lbah_addr = ioaddr->cmd_addr + (ATA_REG_LBAH << shift); + ioaddr->device_addr = ioaddr->cmd_addr + (ATA_REG_DEVICE << shift); + ioaddr->status_addr = ioaddr->cmd_addr + (ATA_REG_STATUS << shift); + ioaddr->command_addr = ioaddr->cmd_addr + (ATA_REG_CMD << shift); +} + +/** + * pata_fsl_probe - attach a platform interface + * @pdev: platform device + * + * Register a platform bus integrated ATA host controller + * + * The 3 platform device resources are used as follows: + * + * - I/O Base (IORESOURCE_MEM) virt. addr. of ATA controller regs + * - CTL Base (IORESOURCE_MEM) unused + * - IRQ (IORESOURCE_IRQ) platform IRQ assigned to ATA + * + */ +static int __devinit pata_fsl_probe(struct platform_device *pdev) +{ + int ret = 0; + struct resource *io_res; + struct ata_host *host; + struct ata_port *ap; + struct fsl_ata_platform_data *plat = (struct fsl_ata_platform_data *) + pdev->dev.platform_data; + struct pata_fsl_priv *priv; + u8 *ata_regs; + unsigned int int_enable; + + /* + * Set up resources + */ + if (unlikely(pdev->num_resources != 2)) { + dev_err(&pdev->dev, "invalid number of resources\n"); + return -EINVAL; + } + + /* + * Get an ata_host structure for this device + */ + host = ata_host_alloc(&pdev->dev, 1); + if (!host) + return -ENOMEM; + ap = host->ports[0]; + + /* + * Allocate private data + */ + priv = kzalloc(sizeof(struct pata_fsl_priv), GFP_KERNEL); + if (priv == NULL) { + ret = -ENOMEM; + goto err0; + } + host->private_data = priv; + + /* + * Set up resources + */ + io_res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + ata_regs = + (u8 *) ioremap(io_res->start, io_res->end - io_res->start + 1); + priv->fsl_ata_regs = ata_regs; + ap->ioaddr.cmd_addr = (void *)(ata_regs + FSL_ATA_DRIVE_DATA); + ap->ioaddr.ctl_addr = (void *)(ata_regs + FSL_ATA_DRIVE_CONTROL); + ap->ioaddr.altstatus_addr = ap->ioaddr.ctl_addr; + ap->ops = &pata_fsl_port_ops; + ap->pio_mask = plat->pio_mask; /* support pio 0~4 */ + ap->mwdma_mask = plat->mwdma_mask; /* support mdma 0~2 */ + ap->udma_mask = plat->udma_mask; + pata_fsl_sht.sg_tablesize = plat->max_sg; + fsl_setup_port(&ap->ioaddr); + + if (plat->adma_flag) { + priv->adma_des_tp = + dma_alloc_coherent(&(pdev->dev), + (2 * plat->max_sg) * + sizeof(unsigned int), + &(priv->adma_des_paddr), GFP_DMA); + if (priv->adma_des_tp == NULL) { + ret = -ENOMEM; + goto err1; + } + } + /* + * Do platform-specific initialization (e.g. allocate pins, + * turn on clock). After this call it is assumed that + * plat->get_clk_rate() can be called to calculate + * timing. + */ + if (plat->init && plat->init(pdev)) { + ret = -ENODEV; + goto err2; + } + + priv->clk = clk_get(&pdev->dev, "ata_clk"); + clk_enable(priv->clk); + + /* Deassert the reset bit to enable the interface */ + __raw_writel(FSL_ATA_CTRL_ATA_RST_B, ata_regs + FSL_ATA_CONTROL); + + /* Enable Core regulator & IO Regulator */ + if (plat->core_reg != NULL) { + core_reg = regulator_get(&pdev->dev, plat->core_reg); + if (regulator_enable(core_reg)) + printk(KERN_INFO "enable core regulator error.\n"); + msleep(100); + + } else + core_reg = NULL; + + if (plat->io_reg != NULL) { + io_reg = regulator_get(&pdev->dev, plat->io_reg); + if (regulator_enable(io_reg)) + printk(KERN_INFO "enable io regulator error.\n"); + msleep(100); + + } else + io_reg = NULL; + + /* Set initial timing and mode */ + set_ata_bus_timing(XFER_PIO_4, pdev); + + /* get DMA ready */ + if (plat->adma_flag == 0) + pata_fsl_dma_init(ap); + + /* + * Enable the ATA INTRQ interrupt from the bus, but + * only allow the CPU to see it (INTRQ2) at this point. + * INTRQ1, which goes to the DMA, will be enabled later. + */ + int_enable = FSL_ATA_INTR_DMA_TRANS_OVER | FSL_ATA_INTR_DMA_ERR | + FSL_ATA_INTR_ATA_INTRQ2; + if (plat->adma_flag) + __raw_writel(int_enable, ata_regs + FSL_ATA_INT_EN); + else + __raw_writel(FSL_ATA_INTR_ATA_INTRQ2, + ata_regs + FSL_ATA_INT_EN); + + /* activate */ + if (plat->adma_flag) + ret = ata_host_activate(host, platform_get_irq(pdev, 0), + pata_fsl_adma_intr, 0, &pata_fsl_sht); + else + ret = ata_host_activate(host, platform_get_irq(pdev, 0), + ata_sff_interrupt, 0, &pata_fsl_sht); + + if (!ret) + return ret; + + clk_disable(priv->clk); + regulator_disable(core_reg); + regulator_disable(io_reg); + err2: + if (plat->adma_flag && priv->adma_des_tp) + dma_free_coherent(&(pdev->dev), + (2 * plat->max_sg + + 1) * sizeof(unsigned int), priv->adma_des_tp, + priv->adma_des_paddr); + err1: + iounmap(ata_regs); + kfree(priv); + err0: + ata_host_detach(host); + return ret; + +} + +/** + * pata_fsl_remove - unplug a platform interface + * @pdev: platform device + * + * A platform bus ATA device has been unplugged. Perform the needed + * cleanup. Also called on module unload for any active devices. + */ +static int __devexit pata_fsl_remove(struct platform_device *pdev) +{ + struct device *dev = &pdev->dev; + struct ata_host *host = dev_get_drvdata(dev); + struct pata_fsl_priv *priv = host->private_data; + struct fsl_ata_platform_data *plat = (struct fsl_ata_platform_data *) + pdev->dev.platform_data; + u8 *ata_regs = priv->fsl_ata_regs; + + __raw_writel(0, ata_regs + FSL_ATA_INT_EN); /* Disable interrupts */ + + ata_host_detach(host); + + clk_disable(priv->clk); + clk_put(priv->clk); + priv->clk = NULL; + + /* Disable Core regulator & IO Regulator */ + if (plat->core_reg != NULL) { + regulator_disable(core_reg); + regulator_put(core_reg); + } + if (plat->io_reg != NULL) { + regulator_disable(io_reg); + regulator_put(io_reg); + } + + if (plat->exit) + plat->exit(); + + if (plat->adma_flag && priv->adma_des_tp) + dma_free_coherent(&(pdev->dev), + (2 * plat->max_sg) * + sizeof(unsigned int), priv->adma_des_tp, + priv->adma_des_paddr); + iounmap(ata_regs); + + kfree(priv); + + return 0; +} + +#ifdef CONFIG_PM +static int pata_fsl_suspend(struct platform_device *pdev, pm_message_t state) +{ + struct ata_host *host = dev_get_drvdata(&pdev->dev); + struct pata_fsl_priv *priv = host->private_data; + struct fsl_ata_platform_data *plat = (struct fsl_ata_platform_data *) + pdev->dev.platform_data; + u8 *ata_regs = priv->fsl_ata_regs; + + ata_host_suspend(host, state); + + /* Disable interrupts. */ + __raw_writel(0, ata_regs + FSL_ATA_INT_EN); + + clk_disable(priv->clk); + + if (plat->exit) + plat->exit(); + + return 0; +} + +static int pata_fsl_resume(struct platform_device *pdev) +{ + struct ata_host *host = dev_get_drvdata(&pdev->dev); + struct pata_fsl_priv *priv = host->private_data; + struct fsl_ata_platform_data *plat = (struct fsl_ata_platform_data *) + pdev->dev.platform_data; + u8 *ata_regs = priv->fsl_ata_regs; + unsigned char int_enable; + + if (plat->init && plat->init(pdev)) + return -ENODEV; + + clk_enable(priv->clk); + + /* Deassert the reset bit to enable the interface */ + __raw_writel(FSL_ATA_CTRL_ATA_RST_B, ata_regs + FSL_ATA_CONTROL); + + /* Set initial timing and mode */ + set_ata_bus_timing(XFER_PIO_4, pdev); + + /* + * Enable hardware interrupts. + */ + int_enable = FSL_ATA_INTR_DMA_TRANS_OVER | FSL_ATA_INTR_DMA_ERR | + FSL_ATA_INTR_ATA_INTRQ2; + if (1 == plat->adma_flag) + __raw_writel(int_enable, ata_regs + FSL_ATA_INT_EN); + else + __raw_writel(FSL_ATA_INTR_ATA_INTRQ2, + ata_regs + FSL_ATA_INT_EN); + + ata_host_resume(host); + + return 0; +} +#endif + +static struct platform_driver pata_fsl_driver = { + .probe = pata_fsl_probe, + .remove = __devexit_p(pata_fsl_remove), +#ifdef CONFIG_PM + .suspend = pata_fsl_suspend, + .resume = pata_fsl_resume, +#endif + .driver = { + .name = DRV_NAME, + .owner = THIS_MODULE, + }, +}; + +static int __init pata_fsl_init(void) +{ + return platform_driver_register(&pata_fsl_driver); + + return 0; +} + +static void __exit pata_fsl_exit(void) +{ + platform_driver_unregister(&pata_fsl_driver); +} + +module_init(pata_fsl_init); +module_exit(pata_fsl_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("low-level driver for Freescale ATA"); +MODULE_LICENSE("GPL"); diff --git a/drivers/char/Kconfig b/drivers/char/Kconfig index 7cfcc629a7fd..552f45c6a7b5 100644 --- a/drivers/char/Kconfig +++ b/drivers/char/Kconfig @@ -426,6 +426,29 @@ config SGI_MBCS If you have an SGI Altix with an attached SABrick say Y or M here, otherwise say N. +config FM_SI4702 + tristate "SI4702 FM device driver" + depends on (MACH_MX31_3DS || MACH_MX35_3DS || MACH_MX37_3DS || MACH_MX51_3DS) + default n + +config MXC_IIM + tristate "MXC IIM device driver" + depends on ARCH_MXC + help + Support for access to MXC IIM device, most people should say N here. + +config MXS_VIIM + tristate "MXS Virtual IIM device driver" + depends on (ARCH_STMP3XXX || ARCH_MXS || ARCH_MX5) + help + Support for access to MXS Virtual IIM device, most people should say N here. + +config IMX_SIM + tristate "IMX SIM support" + depends on (ARCH_MX5 || ARCH_MX25) + ---help--- + Say Y to enable the SIM driver support. + source "drivers/serial/Kconfig" config UNIX98_PTYS diff --git a/drivers/char/Makefile b/drivers/char/Makefile index 88d6eac69754..4d2551bf742c 100644 --- a/drivers/char/Makefile +++ b/drivers/char/Makefile @@ -9,6 +9,11 @@ FONTMAPFILE = cp437.uni obj-y += mem.o random.o tty_io.o n_tty.o tty_ioctl.o tty_ldisc.o tty_buffer.o tty_port.o +obj-$(CONFIG_FM_SI4702) += mxc_si4702.o +obj-$(CONFIG_MXC_IIM) += mxc_iim.o +obj-$(CONFIG_MXS_VIIM) += mxs_viim.o +obj-$(CONFIG_IMX_SIM) += imx_sim.o + obj-$(CONFIG_LEGACY_PTYS) += pty.o obj-$(CONFIG_UNIX98_PTYS) += pty.o obj-y += misc.o diff --git a/drivers/char/hw_random/Kconfig b/drivers/char/hw_random/Kconfig index d31483c54883..92bc50685360 100644 --- a/drivers/char/hw_random/Kconfig +++ b/drivers/char/hw_random/Kconfig @@ -60,6 +60,30 @@ config HW_RANDOM_AMD If unsure, say Y. +config HW_RANDOM_FSL_RNGA + tristate "Freescale RNGA Random Number Generator" + depends on HW_RANDOM && ARCH_HAS_RNGA && !MXC_SECURITY_RNG + ---help--- + This driver provides kernel-side support for the Random Number + Generator hardware found on Freescale i.MX processors. + + To compile this driver as a module, choose M here: the + module will be called fsl-rnga. + + If unsure, say Y. + +config HW_RANDOM_FSL_RNGC + tristate "Freescale RNGC Random Number Generator" + depends on HW_RANDOM && ARCH_HAS_RNGC && !MXC_SECURITY_RNG + ---help--- + This driver provides kernel-side support for the Random Number + Generator hardware found on Freescale i.MX processors. + + To compile this driver as a module, choose M here: the + module will be called fsl-rngc. + + If unsure, say Y. + config HW_RANDOM_GEODE tristate "AMD Geode HW Random Number Generator support" depends on HW_RANDOM && X86_32 && PCI diff --git a/drivers/char/hw_random/Makefile b/drivers/char/hw_random/Makefile index 4273308aa1e3..d0bf5cca29c7 100644 --- a/drivers/char/hw_random/Makefile +++ b/drivers/char/hw_random/Makefile @@ -7,6 +7,8 @@ rng-core-y := core.o obj-$(CONFIG_HW_RANDOM_TIMERIOMEM) += timeriomem-rng.o obj-$(CONFIG_HW_RANDOM_INTEL) += intel-rng.o obj-$(CONFIG_HW_RANDOM_AMD) += amd-rng.o +obj-$(CONFIG_HW_RANDOM_FSL_RNGA) += fsl-rnga.o +obj-$(CONFIG_HW_RANDOM_FSL_RNGC) += fsl-rngc.o obj-$(CONFIG_HW_RANDOM_GEODE) += geode-rng.o obj-$(CONFIG_HW_RANDOM_N2RNG) += n2-rng.o n2-rng-y := n2-drv.o n2-asm.o diff --git a/drivers/char/hw_random/fsl-rnga.c b/drivers/char/hw_random/fsl-rnga.c new file mode 100644 index 000000000000..20b22bc65d53 --- /dev/null +++ b/drivers/char/hw_random/fsl-rnga.c @@ -0,0 +1,238 @@ +/* + * RNG driver for Freescale RNGA + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/* + * Hardware driver for the Intel/AMD/VIA Random Number Generators (RNG) + * (c) Copyright 2003 Red Hat Inc + * + * derived from + * + * Hardware driver for the AMD 768 Random Number Generator (RNG) + * (c) Copyright 2001 Red Hat Inc + * + * derived from + * + * Hardware driver for Intel i810 Random Number Generator (RNG) + * Copyright 2000,2001 Jeff Garzik + * Copyright 2000,2001 Philipp Rumpf + * + * This file is licensed under the terms of the GNU General Public + * License version 2. This program is licensed "as is" without any + * warranty of any kind, whether express or implied. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +/* RNGA Registers */ +#define RNGA_CONTROL 0x00 +#define RNGA_STATUS 0x04 +#define RNGA_ENTROPY 0x08 +#define RNGA_OUTPUT_FIFO 0x0c +#define RNGA_MODE 0x10 +#define RNGA_VERIFICATION_CONTROL 0x14 +#define RNGA_OSC_CONTROL_COUNTER 0x18 +#define RNGA_OSC1_COUNTER 0x1c +#define RNGA_OSC2_COUNTER 0x20 +#define RNGA_OSC_COUNTER_STATUS 0x24 + +/* RNGA Registers Range */ +#define RNG_ADDR_RANGE 0x28 + +/* RNGA Control Register */ +#define RNGA_CONTROL_SLEEP 0x00000010 +#define RNGA_CONTROL_CLEAR_INT 0x00000008 +#define RNGA_CONTROL_MASK_INTS 0x00000004 +#define RNGA_CONTROL_HIGH_ASSURANCE 0x00000002 +#define RNGA_CONTROL_GO 0x00000001 + +#define RNGA_STATUS_LEVEL_MASK 0x0000ff00 + +/* RNGA Status Register */ +#define RNGA_STATUS_OSC_DEAD 0x80000000 +#define RNGA_STATUS_SLEEP 0x00000010 +#define RNGA_STATUS_ERROR_INT 0x00000008 +#define RNGA_STATUS_FIFO_UNDERFLOW 0x00000004 +#define RNGA_STATUS_LAST_READ_STATUS 0x00000002 +#define RNGA_STATUS_SECURITY_VIOLATION 0x00000001 + +static struct platform_device *rng_dev; + +static int fsl_rnga_data_present(struct hwrng *rng) +{ + int level; + u32 rng_base = (u32) rng->priv; + + /* how many random numbers is in FIFO? [0-16] */ + level = ((__raw_readl(rng_base + RNGA_STATUS) & + RNGA_STATUS_LEVEL_MASK) >> 8); + + return level > 0 ? 1 : 0; +} + +static int fsl_rnga_data_read(struct hwrng *rng, u32 * data) +{ + int err; + u32 ctrl, rng_base = (u32) rng->priv; + + /* retrieve a random number from FIFO */ + *data = __raw_readl(rng_base + RNGA_OUTPUT_FIFO); + + /* some error while reading this random number? */ + err = __raw_readl(rng_base + RNGA_STATUS) & RNGA_STATUS_ERROR_INT; + + /* if error: clear error interrupt, but doesn't return random number */ + if (err) { + dev_dbg(&rng_dev->dev, "Error while reading random number!\n"); + ctrl = __raw_readl(rng_base + RNGA_CONTROL); + __raw_writel(ctrl | RNGA_CONTROL_CLEAR_INT, + rng_base + RNGA_CONTROL); + return 0; + } else + return 4; +} + +static int fsl_rnga_init(struct hwrng *rng) +{ + u32 ctrl, osc, rng_base = (u32) rng->priv; + + /* wake up */ + ctrl = __raw_readl(rng_base + RNGA_CONTROL); + __raw_writel(ctrl & ~RNGA_CONTROL_SLEEP, rng_base + RNGA_CONTROL); + + /* verify if oscillator is working */ + osc = __raw_readl(rng_base + RNGA_STATUS); + if (osc & RNGA_STATUS_OSC_DEAD) { + dev_err(&rng_dev->dev, "RNGA Oscillator is dead!\n"); + return -ENODEV; + } + + /* go running */ + ctrl = __raw_readl(rng_base + RNGA_CONTROL); + __raw_writel(ctrl | RNGA_CONTROL_GO, rng_base + RNGA_CONTROL); + + return 0; +} + +static void fsl_rnga_cleanup(struct hwrng *rng) +{ + u32 ctrl, rng_base = (u32) rng->priv; + + ctrl = __raw_readl(rng_base + RNGA_CONTROL); + + /* stop rnga */ + __raw_writel(ctrl & ~RNGA_CONTROL_GO, rng_base + RNGA_CONTROL); +} + +static struct hwrng fsl_rnga = { + .name = "fsl-rnga", + .init = fsl_rnga_init, + .cleanup = fsl_rnga_cleanup, + .data_present = fsl_rnga_data_present, + .data_read = fsl_rnga_data_read +}; + +static int __init fsl_rnga_probe(struct platform_device *pdev) +{ + int err = -ENODEV; + struct clk *clk; + struct resource *res, *mem; + void __iomem *rng_base = NULL; + + if (rng_dev) + return -EBUSY; + + clk = clk_get(NULL, "rng_clk"); + + if (IS_ERR(clk)) { + dev_err(&pdev->dev, "Could not get rng_clk!\n"); + err = PTR_ERR(clk); + return err; + } + + clk_enable(clk); + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + + if (!res) + return -ENOENT; + + mem = request_mem_region(res->start, res->end - res->start, pdev->name); + + if (mem == NULL) + return -EBUSY; + + dev_set_drvdata(&pdev->dev, mem); + rng_base = ioremap(res->start, res->end - res->start); + + fsl_rnga.priv = (unsigned long)rng_base; + + err = hwrng_register(&fsl_rnga); + if (err) { + dev_err(&pdev->dev, "FSL RNGA registering failed (%d)\n", err); + return err; + } + + rng_dev = pdev; + + dev_info(&pdev->dev, "FSL RNGA Registered.\n"); + + return 0; +} + +static int __exit fsl_rnga_remove(struct platform_device *pdev) +{ + struct resource *mem = dev_get_drvdata(&pdev->dev); + void __iomem *rng_base = (void __iomem *)fsl_rnga.priv; + + hwrng_unregister(&fsl_rnga); + + release_resource(mem); + + iounmap(rng_base); + + return 0; +} + +static struct platform_driver fsl_rnga_driver = { + .driver = { + .name = "fsl_rnga", + .owner = THIS_MODULE, + }, + .remove = __exit_p(fsl_rnga_remove), +}; + +static int __init mod_init(void) +{ + return platform_driver_probe(&fsl_rnga_driver, fsl_rnga_probe); +} + +static void __exit mod_exit(void) +{ + platform_driver_unregister(&fsl_rnga_driver); +} + +module_init(mod_init); +module_exit(mod_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("H/W RNGA driver for i.MX"); +MODULE_LICENSE("GPL"); diff --git a/drivers/char/hw_random/fsl-rngc.c b/drivers/char/hw_random/fsl-rngc.c new file mode 100644 index 000000000000..678c5bd3e9a9 --- /dev/null +++ b/drivers/char/hw_random/fsl-rngc.c @@ -0,0 +1,372 @@ +/* + * RNG driver for Freescale RNGC + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/* + * Hardware driver for the Intel/AMD/VIA Random Number Generators (RNG) + * (c) Copyright 2003 Red Hat Inc + * + * derived from + * + * Hardware driver for the AMD 768 Random Number Generator (RNG) + * (c) Copyright 2001 Red Hat Inc + * + * derived from + * + * Hardware driver for Intel i810 Random Number Generator (RNG) + * Copyright 2000,2001 Jeff Garzik + * Copyright 2000,2001 Philipp Rumpf + * + * This file is licensed under the terms of the GNU General Public + * License version 2. This program is licensed "as is" without any + * warranty of any kind, whether express or implied. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define RNGC_VERSION_MAJOR3 3 + +#define RNGC_VERSION_ID 0x0000 +#define RNGC_COMMAND 0x0004 +#define RNGC_CONTROL 0x0008 +#define RNGC_STATUS 0x000C +#define RNGC_ERROR 0x0010 +#define RNGC_FIFO 0x0014 +#define RNGC_VERIF_CTRL 0x0020 +#define RNGC_OSC_CTRL_COUNT 0x0028 +#define RNGC_OSC_COUNT 0x002C +#define RNGC_OSC_COUNT_STATUS 0x0030 + +#define RNGC_VERID_ZEROS_MASK 0x0f000000 +#define RNGC_VERID_RNG_TYPE_MASK 0xf0000000 +#define RNGC_VERID_RNG_TYPE_SHIFT 28 +#define RNGC_VERID_CHIP_VERSION_MASK 0x00ff0000 +#define RNGC_VERID_CHIP_VERSION_SHIFT 16 +#define RNGC_VERID_VERSION_MAJOR_MASK 0x0000ff00 +#define RNGC_VERID_VERSION_MAJOR_SHIFT 8 +#define RNGC_VERID_VERSION_MINOR_MASK 0x000000ff +#define RNGC_VERID_VERSION_MINOR_SHIFT 0 + +#define RNGC_CMD_ZEROS_MASK 0xffffff8c +#define RNGC_CMD_SW_RST 0x00000040 +#define RNGC_CMD_CLR_ERR 0x00000020 +#define RNGC_CMD_CLR_INT 0x00000010 +#define RNGC_CMD_SEED 0x00000002 +#define RNGC_CMD_SELF_TEST 0x00000001 + +#define RNGC_CTRL_ZEROS_MASK 0xfffffc8c +#define RNGC_CTRL_CTL_ACC 0x00000200 +#define RNGC_CTRL_VERIF_MODE 0x00000100 +#define RNGC_CTRL_MASK_ERROR 0x00000040 + +#define RNGC_CTRL_MASK_DONE 0x00000020 +#define RNGC_CTRL_AUTO_SEED 0x00000010 +#define RNGC_CTRL_FIFO_UFLOW_MASK 0x00000003 +#define RNGC_CTRL_FIFO_UFLOW_SHIFT 0 + +#define RNGC_CTRL_FIFO_UFLOW_ZEROS_ERROR 0 +#define RNGC_CTRL_FIFO_UFLOW_ZEROS_ERROR2 1 +#define RNGC_CTRL_FIFO_UFLOW_BUS_XFR 2 +#define RNGC_CTRL_FIFO_UFLOW_ZEROS_INTR 3 + +#define RNGC_STATUS_ST_PF_MASK 0x00c00000 +#define RNGC_STATUS_ST_PF_SHIFT 22 +#define RNGC_STATUS_ST_PF_TRNG 0x00800000 +#define RNGC_STATUS_ST_PF_PRNG 0x00400000 +#define RNGC_STATUS_ERROR 0x00010000 +#define RNGC_STATUS_FIFO_SIZE_MASK 0x0000f000 +#define RNGC_STATUS_FIFO_SIZE_SHIFT 12 +#define RNGC_STATUS_FIFO_LEVEL_MASK 0x00000f00 +#define RNGC_STATUS_FIFO_LEVEL_SHIFT 8 +#define RNGC_STATUS_NEXT_SEED_DONE 0x00000040 +#define RNGC_STATUS_SEED_DONE 0x00000020 +#define RNGC_STATUS_ST_DONE 0x00000010 +#define RNGC_STATUS_RESEED 0x00000008 +#define RNGC_STATUS_SLEEP 0x00000004 +#define RNGC_STATUS_BUSY 0x00000002 +#define RNGC_STATUS_SEC_STATE 0x00000001 + +#define RNGC_ERROR_STATUS_ZEROS_MASK 0xffffffc0 +#define RNGC_ERROR_STATUS_BAD_KEY 0x00000040 +#define RNGC_ERROR_STATUS_RAND_ERR 0x00000020 +#define RNGC_ERROR_STATUS_FIFO_ERR 0x00000010 +#define RNGC_ERROR_STATUS_STAT_ERR 0x00000008 +#define RNGC_ERROR_STATUS_ST_ERR 0x00000004 +#define RNGC_ERROR_STATUS_OSC_ERR 0x00000002 +#define RNGC_ERROR_STATUS_LFSR_ERR 0x00000001 + +#define RNG_ADDR_RANGE 0x34 + +static DECLARE_COMPLETION(rng_self_testing); +static DECLARE_COMPLETION(rng_seed_done); + +static struct platform_device *rng_dev; + +int irq_rng; + +static int fsl_rngc_data_present(struct hwrng *rng) +{ + int level; + u32 rngc_base = (u32) rng->priv; + + /* how many random numbers are in FIFO? [0-16] */ + level = (__raw_readl(rngc_base + RNGC_STATUS) & + RNGC_STATUS_FIFO_LEVEL_MASK) >> RNGC_STATUS_FIFO_LEVEL_SHIFT; + + return level > 0 ? 1 : 0; +} + +static int fsl_rngc_data_read(struct hwrng *rng, u32 * data) +{ + int err; + u32 rngc_base = (u32) rng->priv; + + /* retrieve a random number from FIFO */ + *data = __raw_readl(rngc_base + RNGC_FIFO); + + /* is there some error while reading this random number? */ + err = __raw_readl(rngc_base + RNGC_STATUS) & RNGC_STATUS_ERROR; + + /* if error happened doesn't return random number */ + return err ? 0 : 4; +} + +static irqreturn_t rngc_irq(int irq, void *dev) +{ + int handled = 0; + u32 rngc_base = (u32) dev; + + /* is the seed creation done? */ + if (__raw_readl(rngc_base + RNGC_STATUS) & RNGC_STATUS_SEED_DONE) { + complete(&rng_seed_done); + __raw_writel(RNGC_CMD_CLR_INT | RNGC_CMD_CLR_ERR, + rngc_base + RNGC_COMMAND); + handled = 1; + } + + /* is the self test done? */ + if (__raw_readl(rngc_base + RNGC_STATUS) & RNGC_STATUS_ST_DONE) { + complete(&rng_self_testing); + __raw_writel(RNGC_CMD_CLR_INT | RNGC_CMD_CLR_ERR, + rngc_base + RNGC_COMMAND); + handled = 1; + } + + /* is there any error? */ + if (__raw_readl(rngc_base + RNGC_STATUS) & RNGC_STATUS_ERROR) { + /* clear interrupt */ + __raw_writel(RNGC_CMD_CLR_INT | RNGC_CMD_CLR_ERR, + rngc_base + RNGC_COMMAND); + handled = 1; + } + + return handled; +} + +static int fsl_rngc_init(struct hwrng *rng) +{ + int err; + u32 cmd, ctrl, osc, rngc_base = (u32) rng->priv; + + INIT_COMPLETION(rng_self_testing); + INIT_COMPLETION(rng_seed_done); + + err = __raw_readl(rngc_base + RNGC_STATUS) & RNGC_STATUS_ERROR; + if (err) { + /* is this a bad keys error ? */ + if (__raw_readl(rngc_base + RNGC_ERROR) & + RNGC_ERROR_STATUS_BAD_KEY) { + dev_err(&rng_dev->dev, "Can't start, Bad Keys.\n"); + return -EIO; + } + } + + /* mask all interrupts, will be unmasked soon */ + ctrl = __raw_readl(rngc_base + RNGC_CONTROL); + __raw_writel(ctrl | RNGC_CTRL_MASK_DONE | RNGC_CTRL_MASK_ERROR, + rngc_base + RNGC_CONTROL); + + /* verify if oscillator is working */ + osc = __raw_readl(rngc_base + RNGC_ERROR); + if (osc & RNGC_ERROR_STATUS_OSC_ERR) { + dev_err(&rng_dev->dev, "RNGC Oscillator is dead!\n"); + return -EIO; + } + + err = request_irq(irq_rng, rngc_irq, 0, "fsl_rngc", (void *)rng->priv); + if (err) { + dev_err(&rng_dev->dev, "Can't get interrupt working.\n"); + return -EIO; + } + + /* do self test, repeat until get success */ + do { + /* clear error */ + cmd = __raw_readl(rngc_base + RNGC_COMMAND); + __raw_writel(cmd | RNGC_CMD_CLR_ERR, rngc_base + RNGC_COMMAND); + + /* unmask all interrupt */ + ctrl = __raw_readl(rngc_base + RNGC_CONTROL); + __raw_writel(ctrl & ~(RNGC_CTRL_MASK_DONE | + RNGC_CTRL_MASK_ERROR), rngc_base + RNGC_CONTROL); + + /* run self test */ + cmd = __raw_readl(rngc_base + RNGC_COMMAND); + __raw_writel(cmd | RNGC_CMD_SELF_TEST, + rngc_base + RNGC_COMMAND); + + wait_for_completion(&rng_self_testing); + + } while (__raw_readl(rngc_base + RNGC_ERROR) & + RNGC_ERROR_STATUS_ST_ERR); + + /* clear interrupt. Is it really necessary here? */ + __raw_writel(RNGC_CMD_CLR_INT | RNGC_CMD_CLR_ERR, + rngc_base + RNGC_COMMAND); + + /* create seed, repeat while there is some statistical error */ + do { + /* clear error */ + cmd = __raw_readl(rngc_base + RNGC_COMMAND); + __raw_writel(cmd | RNGC_CMD_CLR_ERR, rngc_base + RNGC_COMMAND); + + /* seed creation */ + cmd = __raw_readl(rngc_base + RNGC_COMMAND); + __raw_writel(cmd | RNGC_CMD_SEED, rngc_base + RNGC_COMMAND); + + wait_for_completion(&rng_seed_done); + + } while (__raw_readl(rngc_base + RNGC_ERROR) & + RNGC_ERROR_STATUS_STAT_ERR); + + err = __raw_readl(rngc_base + RNGC_ERROR) & + (RNGC_ERROR_STATUS_STAT_ERR | + RNGC_ERROR_STATUS_RAND_ERR | + RNGC_ERROR_STATUS_FIFO_ERR | + RNGC_ERROR_STATUS_ST_ERR | + RNGC_ERROR_STATUS_OSC_ERR | + RNGC_ERROR_STATUS_LFSR_ERR); + + if (err) { + dev_err(&rng_dev->dev, "FSL RNGC appears inoperable.\n"); + return -EIO; + } + + return 0; +} + +static struct hwrng fsl_rngc = { + .name = "fsl-rngc", + .init = fsl_rngc_init, + .data_present = fsl_rngc_data_present, + .data_read = fsl_rngc_data_read +}; + +static int __init fsl_rngc_probe(struct platform_device *pdev) +{ + int err = -ENODEV; + struct clk *clk; + struct resource *res, *mem; + void __iomem *rngc_base = NULL; + + if (rng_dev) + return -EBUSY; + + clk = clk_get(NULL, "rng_clk"); + + if (IS_ERR(clk)) { + dev_err(&pdev->dev, "Can not get rng_clk\n"); + err = PTR_ERR(clk); + return err; + } + + clk_enable(clk); + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + + if (!res) + return -ENOENT; + + mem = request_mem_region(res->start, res->end - res->start, pdev->name); + + if (mem == NULL) + return -EBUSY; + + dev_set_drvdata(&pdev->dev, mem); + rngc_base = ioremap(res->start, res->end - res->start); + + fsl_rngc.priv = (unsigned long)rngc_base; + + irq_rng = platform_get_irq(pdev, 0); + + err = hwrng_register(&fsl_rngc); + if (err) { + dev_err(&pdev->dev, "FSL RNGC registering failed (%d)\n", err); + return err; + } + + rng_dev = pdev; + + dev_info(&pdev->dev, "FSL RNGC Registered.\n"); + + return 0; +} + +static int __exit fsl_rngc_remove(struct platform_device *pdev) +{ + struct resource *mem = dev_get_drvdata(&pdev->dev); + void __iomem *rngc_base = (void __iomem *)fsl_rngc.priv; + + hwrng_unregister(&fsl_rngc); + + release_resource(mem); + + iounmap(rngc_base); + + return 0; +} + +static struct platform_driver fsl_rngc_driver = { + .driver = { + .name = "fsl_rngc", + .owner = THIS_MODULE, + }, + .remove = __exit_p(fsl_rngc_remove), +}; + +static int __init mod_init(void) +{ + return platform_driver_probe(&fsl_rngc_driver, fsl_rngc_probe); +} + +static void __exit mod_exit(void) +{ + platform_driver_unregister(&fsl_rngc_driver); +} + +module_init(mod_init); +module_exit(mod_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("H/W RNGC driver for i.MX"); +MODULE_LICENSE("GPL"); diff --git a/drivers/char/imx_sim.c b/drivers/char/imx_sim.c new file mode 100644 index 000000000000..eba202df4551 --- /dev/null +++ b/drivers/char/imx_sim.c @@ -0,0 +1,1498 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mxc_sim.c + * + * @brief Driver for Freescale IMX SIM interface + * + */ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#define SIM_INTERNAL_CLK 0 +#define SIM_RFU -1 + +/* Default communication parameters: FI=372, DI=1, PI1=5V, II=50mA, WWT=10 */ +#define SIM_PARAM_DEFAULT { 0, 1, 1, 5, 1, 0, 0, 0, 10 } + +/* Transmit and receive buffer sizes */ +#define SIM_XMT_BUFFER_SIZE 256 +#define SIM_RCV_BUFFER_SIZE 256 + +/* Interface character references */ +#define SIM_IFC_TXI(letter, number) (letter + number * 4) +#define SIM_IFC_TA1 SIM_IFC_TXI(0, 0) +#define SIM_IFC_TB1 SIM_IFC_TXI(0, 1) +#define SIM_IFC_TC1 SIM_IFC_TXI(0, 2) +#define SIM_IFC_TD1 SIM_IFC_TXI(0, 3) +#define SIM_IFC_TA2 SIM_IFC_TXI(1, 0) +#define SIM_IFC_TB2 SIM_IFC_TXI(1, 1) +#define SIM_IFC_TC2 SIM_IFC_TXI(1, 2) +#define SIM_IFC_TD2 SIM_IFC_TXI(1, 3) +#define SIM_IFC_TA3 SIM_IFC_TXI(2, 0) +#define SIM_IFC_TB3 SIM_IFC_TXI(2, 1) +#define SIM_IFC_TC3 SIM_IFC_TXI(2, 2) +#define SIM_IFC_TD3 SIM_IFC_TXI(2, 3) +#define SIM_IFC_TA4 SIM_IFC_TXI(3, 0) +#define SIM_IFC_TB4 SIM_IFC_TXI(3, 1) +#define SIM_IFC_TC4 SIM_IFC_TXI(3, 2) +#define SIM_IFC_TD4 SIM_IFC_TXI(3, 3) + +/* ATR and OPS states */ +#define SIM_STATE_REMOVED 0 +#define SIM_STATE_OPERATIONAL_IDLE 1 +#define SIM_STATE_OPERATIONAL_COMMAND 2 +#define SIM_STATE_OPERATIONAL_RESPONSE 3 +#define SIM_STATE_OPERATIONAL_STATUS1 4 +#define SIM_STATE_OPERATIONAL_STATUS2 5 +#define SIM_STATE_OPERATIONAL_PTS 6 +#define SIM_STATE_DETECTED_ATR_T0 7 +#define SIM_STATE_DETECTED_ATR_TS 8 +#define SIM_STATE_DETECTED_ATR_TXI 9 +#define SIM_STATE_DETECTED_ATR_THB 10 +#define SIM_STATE_DETECTED_ATR_TCK 11 + +/* Definitions of the offset of the SIM hardware registers */ +#define PORT1_CNTL 0x00 /* 00 */ +#define SETUP 0x04 /* 04 */ +#define PORT1_DETECT 0x08 /* 08 */ +#define PORT1_XMT_BUF 0x0C /* 0c */ +#define PORT1_RCV_BUF 0x10 /* 10 */ +#define PORT0_CNTL 0x14 /* 14 */ +#define CNTL 0x18 /* 18 */ +#define CLK_PRESCALER 0x1C /* 1c */ +#define RCV_THRESHOLD 0x20 /* 20 */ +#define ENABLE 0x24 /* 24 */ +#define XMT_STATUS 0x28 /* 28 */ +#define RCV_STATUS 0x2C /* 2c */ +#define INT_MASK 0x30 /* 30 */ +#define PORTO_XMT_BUF 0x34 /* 34 */ +#define PORT0_RCV_BUF 0x38 /* 38 */ +#define PORT0_DETECT 0x3C /* 3c */ +#define DATA_FORMAT 0x40 /* 40 */ +#define XMT_THRESHOLD 0x44 /* 44 */ +#define GUARD_CNTL 0x48 /* 48 */ +#define OD_CONFIG 0x4C /* 4c */ +#define RESET_CNTL 0x50 /* 50 */ +#define CHAR_WAIT 0x54 /* 54 */ +#define GPCNT 0x58 /* 58 */ +#define DIVISOR 0x5C /* 5c */ +#define BWT 0x60 /* 60 */ +#define BGT 0x64 /* 64 */ +#define BWT_H 0x68 /* 68 */ +#define XMT_FIFO_STAT 0x6C /* 6c */ +#define RCV_FIFO_CNT 0x70 /* 70 */ +#define RCV_FIFO_WPTR 0x74 /* 74 */ +#define RCV_FIFO_RPTR 0x78 /* 78 */ + +/* SIM port[0|1]_cntl register bits */ +#define SIM_PORT_CNTL_SFPD (1<<7) +#define SIM_PORT_CNTL_3VOLT (1<<6) +#define SIM_PORT_CNTL_SCSP (1<<5) +#define SIM_PORT_CNTL_SCEN (1<<4) +#define SIM_PORT_CNTL_SRST (1<<3) +#define SIM_PORT_CNTL_STEN (1<<2) +#define SIM_PORT_CNTL_SVEN (1<<1) +#define SIM_PORT_CNTL_SAPD (1<<0) + +/* SIM od_config register bits */ +#define SIM_OD_CONFIG_OD_P1 (1<<1) +#define SIM_OD_CONFIG_OD_P0 (1<<0) + +/* SIM enable register bits */ +#define SIM_ENABLE_XMTEN (1<<1) +#define SIM_ENABLE_RCVEN (1<<0) + +/* SIM int_mask register bits */ +#define SIM_INT_MASK_RFEM (1<<13) +#define SIM_INT_MASK_BGTM (1<<12) +#define SIM_INT_MASK_BWTM (1<<11) +#define SIM_INT_MASK_RTM (1<<10) +#define SIM_INT_MASK_CWTM (1<<9) +#define SIM_INT_MASK_GPCM (1<<8) +#define SIM_INT_MASK_TDTFM (1<<7) +#define SIM_INT_MASK_TFOM (1<<6) +#define SIM_INT_MASK_XTM (1<<5) +#define SIM_INT_MASK_TFEIM (1<<4) +#define SIM_INT_MASK_ETCIM (1<<3) +#define SIM_INT_MASK_OIM (1<<2) +#define SIM_INT_MASK_TCIM (1<<1) +#define SIM_INT_MASK_RIM (1<<0) + +/* SIM xmt_status register bits */ +#define SIM_XMT_STATUS_GPCNT (1<<8) +#define SIM_XMT_STATUS_TDTF (1<<7) +#define SIM_XMT_STATUS_TFO (1<<6) +#define SIM_XMT_STATUS_TC (1<<5) +#define SIM_XMT_STATUS_ETC (1<<4) +#define SIM_XMT_STATUS_TFE (1<<3) +#define SIM_XMT_STATUS_XTE (1<<0) + +/* SIM rcv_status register bits */ +#define SIM_RCV_STATUS_BGT (1<<11) +#define SIM_RCV_STATUS_BWT (1<<10) +#define SIM_RCV_STATUS_RTE (1<<9) +#define SIM_RCV_STATUS_CWT (1<<8) +#define SIM_RCV_STATUS_CRCOK (1<<7) +#define SIM_RCV_STATUS_LRCOK (1<<6) +#define SIM_RCV_STATUS_RDRF (1<<5) +#define SIM_RCV_STATUS_RFD (1<<4) +#define SIM_RCV_STATUS_RFE (1<<1) +#define SIM_RCV_STATUS_OEF (1<<0) + +/* SIM cntl register bits */ +#define SIM_CNTL_BWTEN (1<<15) +#define SIM_CNTL_XMT_CRC_LRC (1<<14) +#define SIM_CNTL_CRCEN (1<<13) +#define SIM_CNTL_LRCEN (1<<12) +#define SIM_CNTL_CWTEN (1<<11) +#define SIM_CNTL_SAMPLE12 (1<<4) +#define SIM_CNTL_ONACK (1<<3) +#define SIM_CNTL_ANACK (1<<2) +#define SIM_CNTL_ICM (1<<1) +#define SIM_CNTL_GPCNT_CLK_SEL(x) ((x&0x03)<<9) +#define SIM_CNTL_GPCNT_CLK_SEL_MASK (0x03<<9) +#define SIM_CNTL_BAUD_SEL(x) ((x&0x07)<<6) +#define SIM_CNTL_BAUD_SEL_MASK (0x07<<6) + +/* SIM rcv_threshold register bits */ +#define SIM_RCV_THRESHOLD_RTH(x) ((x&0x0f)<<9) +#define SIM_RCV_THRESHOLD_RTH_MASK (0x0f<<9) +#define SIM_RCV_THRESHOLD_RDT(x) ((x&0x1ff)<<0) +#define SIM_RCV_THRESHOLD_RDT_MASK (0x1ff<<0) + +/* SIM xmt_threshold register bits */ +#define SIM_XMT_THRESHOLD_XTH(x) ((x&0x0f)<<4) +#define SIM_XMT_THRESHOLD_XTH_MASK (0x0f<<4) +#define SIM_XMT_THRESHOLD_TDT(x) ((x&0x0f)<<0) +#define SIM_XMT_THRESHOLD_TDT_MASK (0x0f<<0) + +/* SIM guard_cntl register bits */ +#define SIM_GUARD_CNTL_RCVR11 (1<<8) +#define SIM_GIARD_CNTL_GETU(x) (x&0xff) +#define SIM_GIARD_CNTL_GETU_MASK (0xff) + +/* SIM port[0|]_detect register bits */ +#define SIM_PORT_DETECT_SPDS (1<<3) +#define SIM_PORT_DETECT_SPDP (1<<2) +#define SIM_PORT_DETECT_SDI (1<<1) +#define SIM_PORT_DETECT_SDIM (1<<0) + +/* END of REGS definitions */ + +/* ATR parser data (the parser state is stored in the main device structure) */ +typedef struct { + uint8_t T0; /* ATR T0 */ + uint8_t TS; /* ATR TS */ + /* ATR TA1, TB1, TC1, TD1, TB1, ... , TD4 */ + uint8_t TXI[16]; + uint8_t THB[15]; /* ATR historical bytes */ + uint8_t TCK; /* ATR checksum */ + uint16_t ifc_valid; /* valid interface characters */ + uint8_t ifc_current_valid; /* calid ifcs in the current batch */ + uint8_t cnt; /* number of current batch */ + uint8_t num_hb; /* number of historical bytes */ +} sim_atrparser_t; + +/* Main SIM driver structure */ +typedef struct { + /* card inserted = 1, ATR received = 2, card removed = 0 */ + int present; + /* current ATR or OPS state */ + int state; + /* current power state */ + int power; + /* error code occured during transfer */ + int errval; + struct clk *clk; /* Clock id */ + uint8_t clk_flag; + struct resource *res; /* IO map memory */ + void __iomem *ioaddr; /* Mapped address */ + int ipb_irq; /* sim ipb IRQ num */ + int dat_irq; /* sim dat IRQ num */ + /* parser for incoming ATR stream */ + sim_atrparser_t atrparser; + /* raw ATR stream received */ + sim_atr_t atr; + /* communication parameters according to ATR */ + sim_param_t param_atr; + /* current communication parameters */ + sim_param_t param; + /* current TPDU or PTS transfer */ + sim_xfer_t xfer; + /* transfer is on the way = 1, idle = 2 */ + int xfer_ongoing; + /* remaining bytes to transmit for the current transfer */ + int xmt_remaining; + /* transmit position */ + int xmt_pos; + /* receive position / number of bytes received */ + int rcv_count; + uint8_t rcv_buffer[SIM_RCV_BUFFER_SIZE]; + uint8_t xmt_buffer[SIM_XMT_BUFFER_SIZE]; + /* transfer completion notifier */ + struct completion xfer_done; + /* async notifier for card and ATR detection */ + struct fasync_struct *fasync; + /* Platform specific data */ + struct mxc_sim_platform_data *plat_data; +} sim_t; + +static int sim_param_F[] = { + SIM_INTERNAL_CLK, 372, 558, 744, 1116, 1488, 1860, SIM_RFU, + SIM_RFU, 512, 768, 1024, 1536, 2048, SIM_RFU, SIM_RFU +}; + +static int sim_param_D[] = { + SIM_RFU, 64 * 1, 64 * 2, 64 * 4, 64 * 8, 64 * 16, SIM_RFU, SIM_RFU, + SIM_RFU, SIM_RFU, 64 * 1 / 2, 64 * 1 / 4, 64 * 1 / 8, 64 * 1 / 16, + 64 * 1 / 32, 64 * 1 / 64 +}; + +static struct miscdevice sim_dev; + +/* Function: sim_calc_param + * + * Description: determine register values depending on communication parameters + * + * Parameters: + * uint32_t fi ATR frequency multiplier index + * uint32_t di ATR frequency divider index + * uint32_t* ptr_divisor location to store divisor result + * uint32_t* ptr_sample12 location to store sample12 result + * + * Return Values: + * SIM_OK calculation finished without errors + * -SIM_E_PARAM_DIVISOR_RANGE calculated divisor > 255 + * -SIM_E_PARAM_FBYD_NOTDIVBY8OR12 F/D not divisable by 12 (as required) + * -SIM_E_PARAM_FBYD_WITHFRACTION F/D has a remainder + * -SIM_E_PARAM_DI_INVALID frequency multiplyer index not supported + * -SIM_E_PARAM_FI_INVALID frequency divider index not supported + */ + +static int sim_calc_param(uint32_t fi, uint32_t di, uint32_t *ptr_divisor, + uint32_t *ptr_sample12) +{ + int32_t errval = SIM_OK; + int32_t f = sim_param_F[fi]; + int32_t d = sim_param_D[di]; + int32_t stage2_fra = (64 * f) % d; + int32_t stage2_div = (64 * f) / d; + uint32_t sample12 = 1; + uint32_t divisor = 31; + + pr_debug("%s entering.\n", __func__); + if ((f > 0) || (d > 0)) { + if (stage2_fra == 0) { + if ((stage2_div % 12) == 0) { + sample12 = 1; + divisor = stage2_div / 12; + } else if ((stage2_div % 8) == 0) { + sample12 = 0; + divisor = stage2_div / 8; + } else + sample12 = -1; + if (sample12 >= 0) { + if (divisor < 256) { + pr_debug("fi=%i", fi); + pr_debug("di=%i", di); + pr_debug("f=%i", f); + pr_debug("d=%i/64", d); + pr_debug("div=%i", stage2_div); + pr_debug("divisor=%i", divisor); + pr_debug("sample12=%i\n", sample12); + + *ptr_divisor = divisor; + *ptr_sample12 = sample12; + errval = SIM_OK; + } else + errval = -SIM_E_PARAM_DIVISOR_RANGE; + } else + errval = -SIM_E_PARAM_FBYD_NOTDIVBY8OR12; + } else + errval = -SIM_E_PARAM_FBYD_WITHFRACTION; + } else + errval = -SIM_E_PARAM_FI_INVALID; + + return errval; +}; + +/* Function: sim_set_param + * + * Description: apply communication parameters (setup devisor and sample12) + * + * Parameters: + * sim_t* sim pointer to SIM device handler + * sim_param_t* param pointer to communication parameters + * + * Return Values: + * see function sim_calc_param + */ + +static int sim_set_param(sim_t *sim, sim_param_t *param) +{ + uint32_t divisor, sample12, reg_data; + int errval; + + pr_debug("%s entering.\n", __func__); + errval = sim_calc_param(param->FI, param->DI, &divisor, &sample12); + if (errval == SIM_OK) { + __raw_writel(divisor, sim->ioaddr + DIVISOR); + if (sample12) { + reg_data = __raw_readl(sim->ioaddr + CNTL); + reg_data |= SIM_CNTL_SAMPLE12; + __raw_writel(reg_data, sim->ioaddr + CNTL); + } else { + reg_data = __raw_readl(sim->ioaddr + CNTL); + reg_data &= ~SIM_CNTL_SAMPLE12; + __raw_writel(reg_data, sim->ioaddr + CNTL); + } + } + + return errval; +}; + +/* Function: sim_atr_received + * + * Description: this function is called whenever a valid ATR has been received. + * It determines the communication parameters from the ATR received and notifies + * the user space application with SIGIO. + * + * Parameters: + * sim_t* sim pointer to SIM device handler + */ + +static void sim_atr_received(sim_t *sim) +{ + sim_param_t param_default = SIM_PARAM_DEFAULT; + sim->param_atr = param_default; + + pr_debug("%s entering.\n", __func__); + if (sim->atrparser.ifc_valid & (1 << (SIM_IFC_TA1))) { + sim->param_atr.FI = sim->atrparser.TXI[SIM_IFC_TA1] >> 4; + sim->param_atr.DI = sim->atrparser.TXI[SIM_IFC_TA1] & 0x0f; + } + if (sim->atrparser.ifc_valid & (1 << (SIM_IFC_TB1))) { + sim->param_atr.PI1 = (sim->atrparser.TXI[SIM_IFC_TB1] >> 4) + & 0x07; + sim->param_atr.II = sim->atrparser.TXI[SIM_IFC_TB1] & 0x07f; + } + if (sim->atrparser.ifc_valid & (1 << (SIM_IFC_TC1))) + sim->param_atr.N = sim->atrparser.TXI[SIM_IFC_TC1]; + + if (sim->atrparser.ifc_valid & (1 << (SIM_IFC_TD1))) + sim->param_atr.T = sim->atrparser.TXI[SIM_IFC_TD1] & 0x0f; + + if (sim->atrparser.ifc_valid & (1 << (SIM_IFC_TB2))) + sim->param_atr.PI2 = sim->atrparser.TXI[SIM_IFC_TB2]; + + if (sim->atrparser.ifc_valid & (1 << (SIM_IFC_TC2))) + sim->param_atr.WWT = sim->atrparser.TXI[SIM_IFC_TC2]; + + if (sim->fasync) + kill_fasync(&sim->fasync, SIGIO, POLL_IN); + +}; + +/* Function: sim_xmt_fill + * + * Description: fill the transmit FIFO until the FIFO is full or + * the end of the transmission has been reached. + * + * Parameters: + * sim_t* sim pointer to SIM device handler + */ + +static void sim_xmt_fill(sim_t *sim) +{ + uint32_t reg_data; + int bytesleft; + + reg_data = __raw_readl(sim->ioaddr + XMT_FIFO_STAT); + bytesleft = 16 - ((reg_data >> 8) & 0x0f); + + pr_debug("txfill: remaining=%i bytesleft=%i\n", + sim->xmt_remaining, bytesleft); + if (bytesleft > sim->xmt_remaining) + bytesleft = sim->xmt_remaining; + + sim->xmt_remaining -= bytesleft; + for (; bytesleft > 0; bytesleft--) { + __raw_writel(sim->xmt_buffer[sim->xmt_pos], + sim->ioaddr + PORT1_XMT_BUF); + sim->xmt_pos++; + }; +/* FIXME: optimization - keep filling until fifo full */ +}; + +/* Function: sim_xmt_start + * + * Description: initiate a transfer + * + * Parameters: + * sim_t* sim pointer to SIM device handler + * int pos position in the xfer transmit buffer + * int count number of bytes to be transmitted + */ + +static void sim_xmt_start(sim_t *sim, int pos, int count) +{ + uint32_t reg_data; + + pr_debug("tx\n"); + sim->xmt_remaining = count; + sim->xmt_pos = pos; + sim_xmt_fill(sim); + + if (sim->xmt_remaining) { + reg_data = __raw_readl(sim->ioaddr + INT_MASK); + reg_data &= ~SIM_INT_MASK_TDTFM; + __raw_writel(reg_data, sim->ioaddr + INT_MASK); + } else { + reg_data = __raw_readl(sim->ioaddr + INT_MASK); + reg_data &= ~SIM_INT_MASK_TCIM; + __raw_writel(reg_data, sim->ioaddr + INT_MASK); + __raw_writel(SIM_XMT_STATUS_TC | SIM_XMT_STATUS_TDTF, + sim->ioaddr + XMT_STATUS); + reg_data = __raw_readl(sim->ioaddr + ENABLE); + reg_data |= SIM_ENABLE_XMTEN; + __raw_writel(reg_data, sim->ioaddr + ENABLE); + } +}; + +/* Function: sim_atr_add + * + * Description: add a byte to the raw ATR string + * + * Parameters: + * sim_t* sim pointer to SIM device handler + * uint8_t data byte to be added + */ + +static void sim_atr_add(sim_t *sim, uint8_t data) +{ + pr_debug("%s entering.\n", __func__); + if (sim->atr.size < SIM_ATR_LENGTH_MAX) + sim->atr.t[sim->atr.size++] = data; + else + printk(KERN_ERR "sim.c: ATR received is too big!\n"); +}; + +/* Function: sim_fsm + * + * Description: main finite state machine running in ISR context. + * + * Parameters: + * sim_t* sim pointer to SIM device handler + * uint8_t data byte received + */ + +static void sim_fsm(sim_t *sim, uint16_t data) +{ + uint32_t temp, i = 0; + switch (sim->state) { + + pr_debug("%s stat is %d \n", __func__, sim->state); + /* OPS FSM */ + + case SIM_STATE_OPERATIONAL_IDLE: + printk(KERN_INFO "data received unexpectidly (%04x)\n", data); + break; + + case SIM_STATE_OPERATIONAL_COMMAND: + if (data == sim->xmt_buffer[1]) { + if (sim->xfer.rcv_length) { + sim->state = SIM_STATE_OPERATIONAL_RESPONSE; + } else { + sim->state = SIM_STATE_OPERATIONAL_STATUS1; + if (sim->xfer.xmt_length > 5) + sim_xmt_start(sim, 5, + sim->xfer.xmt_length - 5); + }; + } else if (((data & 0xf0) == 0x60) | ((data & 0xf0) == 0x90)) { + sim->xfer.sw1 = data; + sim->state = SIM_STATE_OPERATIONAL_STATUS2; + } else { + sim->errval = -SIM_E_NACK; + complete(&sim->xfer_done); + }; + break; + + case SIM_STATE_OPERATIONAL_RESPONSE: + sim->rcv_buffer[sim->rcv_count] = data; + sim->rcv_count++; + if (sim->rcv_count == sim->xfer.rcv_length) + sim->state = SIM_STATE_OPERATIONAL_STATUS1; + break; + + case SIM_STATE_OPERATIONAL_STATUS1: + sim->xfer.sw1 = data; + sim->state = SIM_STATE_OPERATIONAL_STATUS2; + break; + + case SIM_STATE_OPERATIONAL_STATUS2: + sim->xfer.sw2 = data; + sim->state = SIM_STATE_OPERATIONAL_IDLE; + complete(&sim->xfer_done); + break; + + case SIM_STATE_OPERATIONAL_PTS: + sim->rcv_buffer[sim->rcv_count] = data; + sim->rcv_count++; + if (sim->rcv_count == sim->xfer.rcv_length) + sim->state = SIM_STATE_OPERATIONAL_IDLE; + break; + + /* ATR FSM */ + + case SIM_STATE_DETECTED_ATR_T0: + sim_atr_add(sim, data); + pr_debug("T0 %02x\n", data); + sim->atrparser.T0 = data; + sim->state = SIM_STATE_DETECTED_ATR_TS; + break; + + case SIM_STATE_DETECTED_ATR_TS: + sim_atr_add(sim, data); + pr_debug("TS %02x\n", data); + sim->atrparser.TS = data; + if (data & 0xf0) { + sim->atrparser.ifc_current_valid = (data >> 4) & 0x0f; + sim->atrparser.num_hb = data & 0x0f; + sim->atrparser.ifc_valid = 0; + sim->state = SIM_STATE_DETECTED_ATR_TXI; + sim->atrparser.cnt = 0; + } else { + goto sim_fsm_atr_thb; + }; + break; + + case SIM_STATE_DETECTED_ATR_TXI: + sim_atr_add(sim, data); + i = ffs(sim->atrparser.ifc_current_valid) - 1; + pr_debug("T%c%i %02x\n", 'A' + i, sim->atrparser.cnt + 1, data); + sim->atrparser.TXI[SIM_IFC_TXI(i, sim->atrparser.cnt)] = data; + sim->atrparser.ifc_valid |= 1 << SIM_IFC_TXI(i, + sim->atrparser. + cnt); + sim->atrparser.ifc_current_valid &= ~(1 << i); + + if (sim->atrparser.ifc_current_valid == 0) { + if (i == 3) { + sim->atrparser.ifc_current_valid = (data >> 4) + & 0x0f; + sim->atrparser.cnt++; + + if (sim->atrparser.cnt >= 4) { + /* error */ + printk(KERN_ERR "ERROR !\n"); + break; + }; + + if (sim->atrparser.ifc_current_valid == 0) + goto sim_fsm_atr_thb; + } else { +sim_fsm_atr_thb: + if (sim->atrparser.num_hb) { + sim->state = SIM_STATE_DETECTED_ATR_THB; + sim->atrparser.cnt = 0; + } else { + goto sim_fsm_atr_tck; + }; + }; + }; + break; + + case SIM_STATE_DETECTED_ATR_THB: + sim_atr_add(sim, data); + pr_debug("THB%i %02x\n", i, data); + sim->atrparser.THB[sim->atrparser.cnt] = data; + sim->atrparser.cnt++; + + if (sim->atrparser.cnt == sim->atrparser.num_hb) { +sim_fsm_atr_tck: + i = sim->atrparser.ifc_valid & (1 << (SIM_IFC_TD1)); + temp = sim->atrparser.TXI[SIM_IFC_TD1] & 0x0f; + if ((i && temp) == SIM_PROTOCOL_T1) + sim->state = SIM_STATE_DETECTED_ATR_TCK; + else + goto sim_fsm_atr_received; + }; + break; + + case SIM_STATE_DETECTED_ATR_TCK: + sim_atr_add(sim, data); + /* checksum not required for T=0 */ + sim->atrparser.TCK = data; +sim_fsm_atr_received: + sim->state = SIM_STATE_OPERATIONAL_IDLE; + sim->present = SIM_PRESENT_OPERATIONAL; + sim_atr_received(sim); + break; + }; +}; + +/* Function: sim_irq_handler + * + * Description: interrupt service routine. + * + * Parameters: + * int irq interrupt number + * void *dev_id pointer to SIM device handler + * + * Return values: + * IRQ_HANDLED OS specific + */ + +static irqreturn_t sim_irq_handler(int irq, void *dev_id) +{ + uint32_t reg_data, reg_data0, reg_data1; + + sim_t *sim = (sim_t *) dev_id; + + pr_debug("%s entering\n", __func__); + + reg_data0 = __raw_readl(sim->ioaddr + XMT_STATUS); + reg_data1 = __raw_readl(sim->ioaddr + INT_MASK); + if ((reg_data0 & SIM_XMT_STATUS_TC) + && (!(reg_data1 & SIM_INT_MASK_TCIM))) { + pr_debug("TC_IRQ\n"); + __raw_writel(SIM_XMT_STATUS_TC, sim->ioaddr + XMT_STATUS); + reg_data = __raw_readl(sim->ioaddr + INT_MASK); + reg_data |= SIM_INT_MASK_TCIM; + __raw_writel(reg_data, sim->ioaddr + INT_MASK); + reg_data = __raw_readl(sim->ioaddr + ENABLE); + reg_data &= ~SIM_ENABLE_XMTEN; + __raw_writel(reg_data, sim->ioaddr + ENABLE); + }; + + reg_data0 = __raw_readl(sim->ioaddr + XMT_STATUS); + reg_data1 = __raw_readl(sim->ioaddr + INT_MASK); + if ((reg_data0 & SIM_XMT_STATUS_TDTF) + && (!(reg_data1 & SIM_INT_MASK_TDTFM))) { + pr_debug("TDTF_IRQ\n"); + __raw_writel(SIM_XMT_STATUS_TDTF, sim->ioaddr + XMT_STATUS); + sim_xmt_fill(sim); + + if (sim->xmt_remaining == 0) { + __raw_writel(SIM_XMT_STATUS_TC, + sim->ioaddr + XMT_STATUS); + reg_data = __raw_readl(sim->ioaddr + INT_MASK); + reg_data &= ~SIM_INT_MASK_TCIM; + reg_data |= SIM_INT_MASK_TDTFM; + __raw_writel(reg_data, sim->ioaddr + INT_MASK); + }; + }; + + reg_data0 = __raw_readl(sim->ioaddr + RCV_STATUS); + reg_data1 = __raw_readl(sim->ioaddr + INT_MASK); + if ((reg_data0 & SIM_RCV_STATUS_RDRF) + && (!(reg_data1 & SIM_INT_MASK_RIM))) { + pr_debug("%s RDRF_IRQ\n", __func__); + __raw_writel(SIM_RCV_STATUS_RDRF, sim->ioaddr + RCV_STATUS); + + while (__raw_readl(sim->ioaddr + RCV_FIFO_CNT)) { + uint32_t data; + data = __raw_readl(sim->ioaddr + PORT1_RCV_BUF); + pr_debug("RX = %02x state = %i\n", data, sim->state); + if (data & 0x700) { + if (sim->xfer_ongoing) { + /* error */ + printk(KERN_ERR "ERROR !\n"); + return IRQ_HANDLED; + }; + } else + sim_fsm(sim, data); + }; + }; + + reg_data0 = __raw_readl(sim->ioaddr + PORT0_DETECT); + if (reg_data0 & SIM_PORT_DETECT_SDI) { + pr_debug("%s PD_IRQ\n", __func__); + reg_data = __raw_readl(sim->ioaddr + PORT0_DETECT); + reg_data |= SIM_PORT_DETECT_SDI; + __raw_writel(reg_data, sim->ioaddr + PORT0_DETECT); + + reg_data0 = __raw_readl(sim->ioaddr + PORT0_DETECT); + if (reg_data0 & SIM_PORT_DETECT_SPDP) { + reg_data = __raw_readl(sim->ioaddr + PORT0_DETECT); + reg_data &= ~SIM_PORT_DETECT_SPDS; + __raw_writel(reg_data, sim->ioaddr + PORT0_DETECT); + + if (sim->present != SIM_PRESENT_REMOVED) { + pr_debug("Removed sim card\n"); + sim->present = SIM_PRESENT_REMOVED; + sim->state = SIM_STATE_REMOVED; + + if (sim->fasync) + kill_fasync(&sim->fasync, + SIGIO, POLL_IN); + }; + } else { + reg_data = __raw_readl(sim->ioaddr + PORT0_DETECT); + reg_data |= SIM_PORT_DETECT_SPDS; + __raw_writel(reg_data, sim->ioaddr + PORT0_DETECT); + + if (sim->present == SIM_PRESENT_REMOVED) { + pr_debug("Inserted sim card\n"); + sim->state = SIM_STATE_DETECTED_ATR_T0; + sim->present = SIM_PRESENT_DETECTED; + + if (sim->fasync) + kill_fasync(&sim->fasync, + SIGIO, POLL_IN); + }; + }; + }; + + return IRQ_HANDLED; +}; + +/* Function: sim_power_on + * + * Description: run the power on sequence + * + * Parameters: + * sim_t* sim pointer to SIM device handler + */ + +static void sim_power_on(sim_t *sim) +{ + uint32_t reg_data; + + /* power on sequence */ + pr_debug("%s Powering on the sim port.\n", __func__); + reg_data = __raw_readl(sim->ioaddr + PORT0_CNTL); + reg_data |= SIM_PORT_CNTL_SVEN; + __raw_writel(reg_data, sim->ioaddr + PORT0_CNTL); + msleep(10); + reg_data = __raw_readl(sim->ioaddr + PORT0_CNTL); + reg_data |= SIM_PORT_CNTL_SCEN; + __raw_writel(reg_data, sim->ioaddr + PORT0_CNTL); + msleep(10); + reg_data = SIM_RCV_THRESHOLD_RTH(0) | SIM_RCV_THRESHOLD_RDT(1); + __raw_writel(reg_data, sim->ioaddr + RCV_THRESHOLD); + __raw_writel(SIM_RCV_STATUS_RDRF, sim->ioaddr + RCV_STATUS); + reg_data = __raw_readl(sim->ioaddr + INT_MASK); + reg_data &= ~SIM_INT_MASK_RIM; + __raw_writel(reg_data, sim->ioaddr + INT_MASK); + __raw_writel(31, sim->ioaddr + DIVISOR); + reg_data = __raw_readl(sim->ioaddr + CNTL); + reg_data |= SIM_CNTL_SAMPLE12; + __raw_writel(reg_data, sim->ioaddr + CNTL); + reg_data = __raw_readl(sim->ioaddr + ENABLE); + reg_data |= SIM_ENABLE_RCVEN; + __raw_writel(reg_data, sim->ioaddr + ENABLE); + reg_data = __raw_readl(sim->ioaddr + PORT0_CNTL); + reg_data |= SIM_PORT_CNTL_SRST; + __raw_writel(reg_data, sim->ioaddr + PORT0_CNTL); + pr_debug("%s port0_ctl is 0x%x.\n", __func__, + __raw_readl(sim->ioaddr + PORT0_CNTL)); + sim->power = SIM_POWER_ON; +}; + +/* Function: sim_power_off + * + * Description: run the power off sequence + * + * Parameters: + * sim_t* sim pointer to SIM device handler + */ + +static void sim_power_off(sim_t *sim) +{ + uint32_t reg_data; + + pr_debug("%s entering.\n", __func__); + /* sim_power_off sequence */ + reg_data = __raw_readl(sim->ioaddr + PORT0_CNTL); + reg_data &= ~SIM_PORT_CNTL_SCEN; + __raw_writel(reg_data, sim->ioaddr + PORT0_CNTL); + reg_data = __raw_readl(sim->ioaddr + ENABLE); + reg_data &= ~SIM_ENABLE_RCVEN; + __raw_writel(reg_data, sim->ioaddr + ENABLE); + reg_data = __raw_readl(sim->ioaddr + INT_MASK); + reg_data |= SIM_INT_MASK_RIM; + __raw_writel(reg_data, sim->ioaddr + INT_MASK); + __raw_writel(0, sim->ioaddr + RCV_THRESHOLD); + reg_data = __raw_readl(sim->ioaddr + PORT0_CNTL); + reg_data &= ~SIM_PORT_CNTL_SRST; + __raw_writel(reg_data, sim->ioaddr + PORT0_CNTL); + reg_data = __raw_readl(sim->ioaddr + PORT0_CNTL); + reg_data &= ~SIM_PORT_CNTL_SVEN; + __raw_writel(reg_data, sim->ioaddr + PORT0_CNTL); + sim->power = SIM_POWER_OFF; +}; + +/* Function: sim_start + * + * Description: ramp up the SIM interface + * + * Parameters: + * sim_t* sim pointer to SIM device handler + */ + +static void sim_start(sim_t *sim) +{ + uint32_t reg_data, clk_rate, clk_div = 0; + + pr_debug("%s entering.\n", __func__); + /* Configuring SIM for Operation */ + reg_data = SIM_XMT_THRESHOLD_XTH(0) | SIM_XMT_THRESHOLD_TDT(4); + __raw_writel(reg_data, sim->ioaddr + XMT_THRESHOLD); + __raw_writel(0, sim->ioaddr + SETUP); + /* ~ 4 MHz */ + clk_rate = clk_get_rate(sim->clk); + clk_div = clk_rate / sim->plat_data->clk_rate; + if (clk_rate % sim->plat_data->clk_rate) + clk_div++; + pr_debug("%s prescaler is 0x%x.\n", __func__, clk_div); + __raw_writel(clk_div, sim->ioaddr + CLK_PRESCALER); + + reg_data = SIM_CNTL_GPCNT_CLK_SEL(0) | SIM_CNTL_BAUD_SEL(7) + | SIM_CNTL_SAMPLE12 | SIM_CNTL_ANACK | SIM_CNTL_ICM; + __raw_writel(reg_data, sim->ioaddr + CNTL); + __raw_writel(31, sim->ioaddr + DIVISOR); + reg_data = __raw_readl(sim->ioaddr + OD_CONFIG); + reg_data |= SIM_OD_CONFIG_OD_P0; + __raw_writel(reg_data, sim->ioaddr + OD_CONFIG); + reg_data = __raw_readl(sim->ioaddr + PORT0_CNTL); + reg_data |= SIM_PORT_CNTL_3VOLT | SIM_PORT_CNTL_STEN; + __raw_writel(reg_data, sim->ioaddr + PORT0_CNTL); + + /* presense detect */ + pr_debug("%s p0_det is 0x%x \n", __func__, + __raw_readl(sim->ioaddr + PORT0_DETECT)); + if (__raw_readl(sim->ioaddr + PORT0_DETECT) & SIM_PORT_DETECT_SPDP) { + pr_debug("%s card removed \n", __func__); + reg_data = __raw_readl(sim->ioaddr + PORT0_DETECT); + reg_data &= ~SIM_PORT_DETECT_SPDS; + __raw_writel(reg_data, sim->ioaddr + PORT0_DETECT); + sim->present = SIM_PRESENT_REMOVED; + sim->state = SIM_STATE_REMOVED; + } else { + pr_debug("%s card inserted \n", __func__); + reg_data = __raw_readl(sim->ioaddr + PORT0_DETECT); + reg_data |= SIM_PORT_DETECT_SPDS; + __raw_writel(reg_data, sim->ioaddr + PORT0_DETECT); + sim->present = SIM_PRESENT_DETECTED; + sim->state = SIM_STATE_DETECTED_ATR_T0; + }; + reg_data = __raw_readl(sim->ioaddr + PORT0_DETECT); + reg_data |= SIM_PORT_DETECT_SDI; + reg_data &= ~SIM_PORT_DETECT_SDIM; + __raw_writel(reg_data, sim->ioaddr + PORT0_DETECT); + + /* + * Since there is no PD0 layout on MX51, assume + * that there is a SIM card in slot defaulty. + * */ + if (0 == (sim->plat_data->detect)) { + reg_data = __raw_readl(sim->ioaddr + PORT0_DETECT); + reg_data |= SIM_PORT_DETECT_SPDS; + __raw_writel(reg_data, sim->ioaddr + PORT0_DETECT); + sim->present = SIM_PRESENT_DETECTED; + sim->state = SIM_STATE_DETECTED_ATR_T0; + } + + if (sim->present == SIM_PRESENT_DETECTED) + sim_power_on(sim); + +}; + +/* Function: sim_stop + * + * Description: shut down the SIM interface + * + * Parameters: + * sim_t* sim pointer to SIM device handler + */ + +static void sim_stop(sim_t *sim) +{ + pr_debug("%s entering.\n", __func__); + __raw_writel(0, sim->ioaddr + SETUP); + __raw_writel(0, sim->ioaddr + ENABLE); + __raw_writel(0, sim->ioaddr + PORT0_CNTL); + __raw_writel(0x06, sim->ioaddr + CNTL); + __raw_writel(0, sim->ioaddr + CLK_PRESCALER); + __raw_writel(0, sim->ioaddr + SETUP); + __raw_writel(0, sim->ioaddr + OD_CONFIG); + __raw_writel(0, sim->ioaddr + XMT_THRESHOLD); + __raw_writel(0xb8, sim->ioaddr + XMT_STATUS); + __raw_writel(4, sim->ioaddr + RESET_CNTL); + mdelay(1); +}; + +/* Function: sim_data_reset + * + * Description: reset a SIM structure to default values + * + * Parameters: + * sim_t* sim pointer to SIM device handler + */ + +static void sim_data_reset(sim_t *sim) +{ + sim_param_t param_default = SIM_PARAM_DEFAULT; + sim->present = SIM_PRESENT_REMOVED; + sim->state = SIM_STATE_REMOVED; + sim->power = SIM_POWER_OFF; + sim->errval = SIM_OK; + memset(&sim->atrparser, 0, sizeof(sim->atrparser)); + memset(&sim->atr, 0, sizeof(sim->atr)); + sim->param_atr = param_default; + memset(&sim->param, 0, sizeof(sim->param)); + memset(&sim->xfer, 0, sizeof(sim->xfer)); + sim->xfer_ongoing = 0; + sim->xmt_remaining = 0; + sim->xmt_pos = 0; + sim->rcv_count = 0; + memset(sim->rcv_buffer, 0, SIM_RCV_BUFFER_SIZE); + memset(sim->xmt_buffer, 0, SIM_XMT_BUFFER_SIZE); +}; + +/* Function: sim_cold_reset + * + * Description: cold reset the SIM interface, including card + * power down and interface hardware reset. + * + * Parameters: + * sim_t* sim pointer to SIM device handler + */ + +static void sim_cold_reset(sim_t *sim) +{ + pr_debug("%s entering.\n", __func__); + if (sim->present != SIM_PRESENT_REMOVED) { + sim_power_off(sim); + sim_stop(sim); + sim_data_reset(sim); + sim->state = SIM_STATE_DETECTED_ATR_T0; + sim->present = SIM_PRESENT_DETECTED; + msleep(50); + sim_start(sim); + sim_power_on(sim); + }; +}; + +/* Function: sim_warm_reset + * + * Description: warm reset the SIM interface: just invoke the + * reset signal and reset the SIM structure for the interface. + * + * Parameters: + * sim_t* sim pointer to SIM device handler + */ + +static void sim_warm_reset(sim_t *sim) +{ + uint32_t reg_data; + + pr_debug("%s entering.\n", __func__); + if (sim->present != SIM_PRESENT_REMOVED) { + reg_data = __raw_readl(sim->ioaddr + PORT0_CNTL); + reg_data |= SIM_PORT_CNTL_SRST; + __raw_writel(reg_data, sim->ioaddr + PORT0_CNTL); + sim_data_reset(sim); + msleep(50); + reg_data = __raw_readl(sim->ioaddr + PORT0_CNTL); + reg_data &= ~SIM_PORT_CNTL_SRST; + __raw_writel(reg_data, sim->ioaddr + PORT0_CNTL); + }; +}; + +/* Function: sim_card_lock + * + * Description: physically lock the SIM card. + * + * Parameters: + * sim_t* sim pointer to SIM device handler + */ + +static int sim_card_lock(sim_t *sim) +{ + int errval; + + pr_debug("%s entering.\n", __func__); + /* place holder for true physcial locking */ + if (sim->present != SIM_PRESENT_REMOVED) + errval = SIM_OK; + else + errval = -SIM_E_NOCARD; + return errval; +}; + +/* Function: sim_card_eject + * + * Description: physically unlock and eject the SIM card. + * + * Parameters: + * sim_t* sim pointer to SIM device handler + */ + +static int sim_card_eject(sim_t *sim) +{ + int errval; + + pr_debug("%s entering.\n", __func__); + /* place holder for true physcial locking */ + if (sim->present != SIM_PRESENT_REMOVED) + errval = SIM_OK; + else + errval = -SIM_E_NOCARD; + return errval; +}; + +/* Function: sim_ioctl + * + * Description: handle ioctl calls + * + * Parameters: OS specific + */ + +static int sim_ioctl(struct inode *inode, struct file *file, + unsigned int cmd, unsigned long arg) +{ + int ret, errval = SIM_OK; + unsigned long timeout; + + sim_t *sim = (sim_t *) file->private_data; + + pr_debug("%s entering.\n", __func__); + switch (cmd) { + pr_debug("ioctl cmd %d is issued...\n", cmd); + + case SIM_IOCTL_GET_ATR: + if (sim->present != SIM_PRESENT_OPERATIONAL) { + errval = -SIM_E_NOCARD; + break; + }; + ret = copy_to_user((sim_atr_t *) arg, &sim->atr, + sizeof(sim_atr_t)); + if (ret) + errval = -SIM_E_ACCESS; + break; + + case SIM_IOCTL_GET_PARAM_ATR: + if (sim->present != SIM_PRESENT_OPERATIONAL) { + errval = -SIM_E_NOCARD; + break; + }; + ret = copy_to_user((sim_param_t *) arg, &sim->param_atr, + sizeof(sim_param_t)); + if (ret) + errval = -SIM_E_ACCESS; + break; + + case SIM_IOCTL_GET_PARAM: + ret = copy_to_user((sim_param_t *) arg, &sim->param, + sizeof(sim_param_t)); + if (ret) + errval = -SIM_E_ACCESS; + break; + + case SIM_IOCTL_SET_PARAM: + ret = copy_from_user(&sim->param, (sim_param_t *) arg, + sizeof(sim_param_t)); + if (ret) + errval = -SIM_E_ACCESS; + else + errval = sim_set_param(sim, &sim->param); + break; + + case SIM_IOCTL_POWER_ON: + if (sim->power == SIM_POWER_ON) { + errval = -SIM_E_POWERED_ON; + break; + }; + sim_power_on(sim); + break; + + case SIM_IOCTL_POWER_OFF: + if (sim->power == SIM_POWER_OFF) { + errval = -SIM_E_POWERED_OFF; + break; + }; + sim_power_off(sim); + break; + + case SIM_IOCTL_COLD_RESET: + if (sim->power == SIM_POWER_OFF) { + errval = -SIM_E_POWERED_OFF; + break; + }; + sim_cold_reset(sim); + break; + + case SIM_IOCTL_WARM_RESET: + sim_warm_reset(sim); + if (sim->power == SIM_POWER_OFF) { + errval = -SIM_E_POWERED_OFF; + break; + }; + break; + + case SIM_IOCTL_XFER: + if (sim->present != SIM_PRESENT_OPERATIONAL) { + errval = -SIM_E_NOCARD; + break; + }; + + ret = copy_from_user(&sim->xfer, (sim_xfer_t *) arg, + sizeof(sim_xfer_t)); + if (ret) { + errval = -SIM_E_ACCESS; + break; + }; + + ret = copy_from_user(sim->xmt_buffer, sim->xfer.xmt_buffer, + sim->xfer.xmt_length); + if (ret) { + errval = -SIM_E_ACCESS; + break; + }; + + sim->rcv_count = 0; + sim->xfer.sw1 = 0; + sim->xfer.sw2 = 0; + + if (sim->xfer.type == SIM_XFER_TYPE_TPDU) { + if (sim->xfer.xmt_length < 5) { + errval = -SIM_E_TPDUSHORT; + break; + } + sim->state = SIM_STATE_OPERATIONAL_COMMAND; + } else if (sim->xfer.type == SIM_XFER_TYPE_PTS) { + if (sim->xfer.xmt_length == 0) { + errval = -SIM_E_PTSEMPTY; + break; + } + sim->state = SIM_STATE_OPERATIONAL_PTS; + } else { + errval = -SIM_E_INVALIDXFERTYPE; + break; + }; + + if (sim->xfer.xmt_length > SIM_XMT_BUFFER_SIZE) { + errval = -SIM_E_INVALIDXMTLENGTH; + break; + }; + + if (sim->xfer.rcv_length > SIM_XMT_BUFFER_SIZE) { + errval = -SIM_E_INVALIDRCVLENGTH; + break; + }; + + sim->errval = 0; + sim->xfer_ongoing = 1; + init_completion(&sim->xfer_done); + sim_xmt_start(sim, 0, 5); + timeout = + wait_for_completion_interruptible_timeout(&sim->xfer_done, + sim->xfer. + timeout); + sim->xfer_ongoing = 0; + + if (sim->errval) { + errval = sim->errval; + break; + }; + + if (timeout == 0) { + errval = -SIM_E_TIMEOUT; + break; + } + + ret = copy_to_user(sim->xfer.rcv_buffer, sim->rcv_buffer, + sim->xfer.rcv_length); + if (ret) { + errval = -SIM_E_ACCESS; + break; + }; + + ret = copy_to_user((sim_xfer_t *) arg, &sim->xfer, + sizeof(sim_xfer_t)); + if (ret) + errval = -SIM_E_ACCESS; + break; + + case SIM_IOCTL_GET_PRESENSE: + if (put_user(sim->present, (int *)arg)) + errval = -SIM_E_ACCESS; + break; + + case SIM_IOCTL_CARD_LOCK: + errval = sim_card_lock(sim); + break; + + case SIM_IOCTL_CARD_EJECT: + errval = sim_card_eject(sim); + break; + + }; + + return errval; +}; + +/* Function: sim_fasync + * + * Description: async handler + * + * Parameters: OS specific + */ + +static int sim_fasync(int fd, struct file *file, int mode) +{ + sim_t *sim = (sim_t *) file->private_data; + pr_debug("%s entering.\n", __func__); + return fasync_helper(fd, file, mode, &sim->fasync); +} + +/* Function: sim_open + * + * Description: ramp up interface when being opened + * + * Parameters: OS specific + */ + +static int sim_open(struct inode *inode, struct file *file) +{ + int errval = SIM_OK; + + sim_t *sim = dev_get_drvdata(sim_dev.parent); + file->private_data = sim; + + pr_debug("%s entering.\n", __func__); + if (!sim->ioaddr) { + errval = -ENOMEM; + return errval; + } + + if (!(sim->clk_flag)) { + pr_debug("\n%s enable the clock\n", __func__); + clk_enable(sim->clk); + sim->clk_flag = 1; + } + + sim_start(sim); + + return errval; +}; + +/* Function: sim_release + * + * Description: shut down interface when being closed + * + * Parameters: OS specific + */ + +static int sim_release(struct inode *inode, struct file *file) +{ + uint32_t reg_data; + + sim_t *sim = (sim_t *) file->private_data; + + pr_debug("%s entering.\n", __func__); + if (sim->clk_flag) { + pr_debug("\n%s disable the clock\n", __func__); + clk_disable(sim->clk); + sim->clk_flag = 0; + } + + /* disable presense detection */ + reg_data = __raw_readl(sim->ioaddr + PORT0_DETECT); + __raw_writel(reg_data | SIM_PORT_DETECT_SDIM, + sim->ioaddr + PORT0_DETECT); + + if (sim->present != SIM_PRESENT_REMOVED) { + sim_power_off(sim); + if (sim->fasync) + kill_fasync(&sim->fasync, SIGIO, POLL_IN); + }; + + sim_stop(sim); + + sim_fasync(-1, file, 0); + + pr_debug("exit\n"); + return 0; +}; + +static const struct file_operations sim_fops = { + .open = sim_open, + .ioctl = sim_ioctl, + .fasync = sim_fasync, + .release = sim_release +}; + +static struct miscdevice sim_dev = { + MISC_DYNAMIC_MINOR, + "mxc_sim", + &sim_fops +}; + +/*****************************************************************************\ + * * + * Driver init/exit * + * * +\*****************************************************************************/ + +static int sim_probe(struct platform_device *pdev) +{ + int ret = 0; + struct mxc_sim_platform_data *sim_plat = pdev->dev.platform_data; + + sim_t *sim = kzalloc(sizeof(sim_t), GFP_KERNEL); + + if (sim == 0) { + ret = -ENOMEM; + printk(KERN_ERR "Can't get the MEMORY\n"); + return ret; + }; + + BUG_ON(pdev == NULL); + + sim->plat_data = sim_plat; + sim->clk_flag = 0; + + sim->res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!sim->res) { + ret = -ENOMEM; + printk(KERN_ERR "Can't get the MEMORY\n"); + goto out; + } + + /* request the sim clk and sim_serial_clk */ + sim->clk = clk_get(NULL, sim->plat_data->clock_sim); + if (IS_ERR(sim->clk)) { + ret = PTR_ERR(sim->clk); + printk(KERN_ERR "Get CLK ERROR !\n"); + goto out; + } + pr_debug("sim clock:%lu\n", clk_get_rate(sim->clk)); + + sim->ipb_irq = platform_get_irq(pdev, 0); + sim->dat_irq = platform_get_irq(pdev, 1); + if (!(sim->ipb_irq | sim->dat_irq)) { + ret = -ENOMEM; + goto out1; + } + + if (!request_mem_region(sim->res->start, + sim->res->end - + sim->res->start + 1, pdev->name)) { + printk(KERN_ERR "request_mem_region failed\n"); + ret = -ENOMEM; + goto out1; + } + + sim->ioaddr = (void *)ioremap(sim->res->start, sim->res->end - + sim->res->start + 1); + if (sim->ipb_irq) + ret = request_irq(sim->ipb_irq, sim_irq_handler, + 0, "mxc_sim_ipb", sim); + if (sim->dat_irq) + ret |= request_irq(sim->dat_irq, sim_irq_handler, + 0, "mxc_sim_dat", sim); + + if (ret) { + printk(KERN_ERR "Can't get the irq\n"); + goto out2; + }; + + platform_set_drvdata(pdev, sim); + sim_dev.parent = &(pdev->dev); + + misc_register(&sim_dev); + + return ret; +out2: + if (sim->ipb_irq) + free_irq(sim->ipb_irq, sim); + if (sim->dat_irq) + free_irq(sim->dat_irq, sim); + release_mem_region(sim->res->start, + sim->res->end - sim->res->start + 1); +out1: + clk_put(sim->clk); +out: + kfree(sim); + return ret; +} + +static int sim_remove(struct platform_device *pdev) +{ + sim_t *sim = platform_get_drvdata(pdev); + + clk_put(sim->clk); + + if (sim->ipb_irq) + free_irq(sim->ipb_irq, sim); + if (sim->dat_irq) + free_irq(sim->dat_irq, sim); + + iounmap(sim->ioaddr); + + kfree(sim); + release_mem_region(sim->res->start, + sim->res->end - sim->res->start + 1); + + misc_deregister(&sim_dev); + return 0; +} + +static struct platform_driver sim_driver = { + .driver = { + .name = "mxc_sim", + }, + .probe = sim_probe, + .remove = sim_remove, + .suspend = NULL, + .resume = NULL, +}; + +static int __init sim_drv_init(void) +{ + return platform_driver_register(&sim_driver); +} + +static void __exit sim_drv_exit(void) +{ + platform_driver_unregister(&sim_driver); +} + +module_init(sim_drv_init); +module_exit(sim_drv_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MXC SIM Driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/char/mxc_iim.c b/drivers/char/mxc_iim.c new file mode 100644 index 000000000000..ee78349dc81e --- /dev/null +++ b/drivers/char/mxc_iim.c @@ -0,0 +1,161 @@ +/* + * Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include +#include + +static unsigned long iim_reg_base, iim_reg_end, iim_reg_size; +static struct clk *iim_clk; +static struct device *iim_dev; + +/*! + * MXC IIM interface - memory map function + * This function maps 4KB IIM registers from IIM base address. + * + * @param file struct file * + * @param vma structure vm_area_struct * + * + * @return Return 0 on success or negative error code on error + */ +static int mxc_iim_mmap(struct file *file, struct vm_area_struct *vma) +{ + vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); + + /* Remap-pfn-range will mark the range VM_IO and VM_RESERVED */ + if (remap_pfn_range(vma, + vma->vm_start, + iim_reg_base >> PAGE_SHIFT, + iim_reg_size, + vma->vm_page_prot)) + return -EAGAIN; + + return 0; +} + +/*! + * MXC IIM interface - open function + * + * @param inode struct inode * + * @param filp struct file * + * + * @return Return 0 on success or negative error code on error + */ +static int mxc_iim_open(struct inode *inode, struct file *filp) +{ + iim_clk = clk_get(NULL, "iim_clk"); + if (IS_ERR(iim_clk)) { + dev_err(iim_dev, "No IIM clock defined\n"); + return -ENODEV; + } + clk_enable(iim_clk); + + return 0; +} + +/*! + * MXC IIM interface - release function + * + * @param inode struct inode * + * @param filp struct file * + * + * @return Return 0 on success or negative error code on error + */ +static int mxc_iim_release(struct inode *inode, struct file *filp) +{ + clk_disable(iim_clk); + clk_put(iim_clk); + return 0; +} + +static const struct file_operations mxc_iim_fops = { + .mmap = mxc_iim_mmap, + .open = mxc_iim_open, + .release = mxc_iim_release, +}; + +static struct miscdevice mxc_iim_miscdev = { + .minor = MISC_DYNAMIC_MINOR, + .name = "mxc_iim", + .fops = &mxc_iim_fops, +}; + +/*! + * This function is called by the driver framework to get iim base/end address + * and register iim misc device. + * + * @param dev The device structure for IIM passed in by the driver + * framework. + * + * @return Returns 0 on success or negative error code on error + */ +static int mxc_iim_probe(struct platform_device *pdev) +{ + struct resource *res; + int ret; + + iim_dev = &pdev->dev; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (IS_ERR(res)) { + dev_err(iim_dev, "Unable to get IIM resource\n"); + return -ENODEV; + } + + iim_reg_base = res->start; + iim_reg_end = res->end; + iim_reg_size = iim_reg_end - iim_reg_base + 1; + + ret = misc_register(&mxc_iim_miscdev); + if (ret) + return ret; + + return 0; +} + +static int mxc_iim_remove(struct platform_device *pdev) +{ + misc_deregister(&mxc_iim_miscdev); + return 0; +} + +static struct platform_driver mxc_iim_driver = { + .driver = { + .owner = THIS_MODULE, + .name = "mxc_iim", + }, + .probe = mxc_iim_probe, + .remove = mxc_iim_remove, +}; + +static int __init mxc_iim_dev_init(void) +{ + return platform_driver_register(&mxc_iim_driver); +} + +static void __exit mxc_iim_dev_cleanup(void) +{ + platform_driver_unregister(&mxc_iim_driver); +} + +module_init(mxc_iim_dev_init); +module_exit(mxc_iim_dev_cleanup); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MXC IIM driver"); +MODULE_LICENSE("GPL"); +MODULE_ALIAS_MISCDEV(MISC_DYNAMIC_MINOR); diff --git a/drivers/char/mxc_si4702.c b/drivers/char/mxc_si4702.c new file mode 100644 index 000000000000..7d36f2902bb4 --- /dev/null +++ b/drivers/char/mxc_si4702.c @@ -0,0 +1,1223 @@ +/* + * linux/drivers/char/mxc_si4702.c + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SI4702_DEV_NAME "si4702" +#define DEV_MAJOR 0 /* this could be module param */ +#define DEV_MINOR 0 +#define DEV_BASE_MINOR 0 +#define DEV_MINOR_COUNT 256 +#define SI4702_I2C_ADDR 0x10 /* 7bits I2C address */ +#define DELAY_WAIT 0xffff /* loop_counter max value */ +/* register define */ +#define SI4702_DEVICEID 0x00 +#define SI4702_CHIPID 0x01 +#define SI4702_POWERCFG 0x02 +#define SI4702_CHANNEL 0x03 +#define SI4702_SYSCONFIG1 0x04 +#define SI4702_SYSCONFIG2 0x05 +#define SI4702_SYSCONFIG3 0x06 +#define SI4702_TEST1 0x07 +#define SI4702_TEST2 0x08 +#define SI4702_B00TCONFIG 0x09 +#define SI4702_STATUSRSSI 0x0A +#define SI4702_READCHAN 0x0B +#define SI4702_REG_NUM 0x10 +#define SI4702_REG_BYTE (SI4702_REG_NUM * 2) +#define SI4702_DEVICE_ID 0x1242 +#define SI4702_RW_REG_NUM (SI4702_STATUSRSSI - SI4702_POWERCFG) +#define SI4702_RW_OFFSET \ + (SI4702_REG_NUM - SI4702_STATUSRSSI + SI4702_POWERCFG) + +#define SI4702_SPACE_MASK 0x0030 +#define SI4702_SPACE_200K 0x0 +#define SI4702_SPACE_100K 0x10 +#define SI4702_SPACE_50K 0x20 + +#define SI4702_BAND_MASK 0x00c0 +#define SI4702_BAND_LSB 6 + +#define SI4702_SEEKTH_MASK 0xff00 +#define SI4702_SEEKTH_LSB 8 + +#define SI4702_SNR_MASK 0x00f0 +#define SI4702_SNR_LSB 4 + +#define SI4702_CNT_MASK 0x000f +#define SI4702_CNT_LSB 0 + +#define SI4702_VOL_MASK 0x000f +#define SI4702_VOL_LSB 0 + +#define SI4702_CHAN_MASK 0x03ff +#define SI4702_TUNE_BIT 0x8000 +#define SI4702_STC_BIT 0x4000 +#define SI4702_DMUTE_BIT 0x4000 +#define SI4702_SEEKUP_BIT 0x0200 +#define SI4702_SEEK_BIT 0x0100 +#define SI4702_SF_BIT 0x2000 +#define SI4702_ENABLE_BIT 0x0001 +#define SI4702_DISABLE_BIT 0x0040 + +enum { + BAND_USA = 0, + BAND_JAP_W, + BAND_JAP +}; + +struct si4702_info { + int min_band; + int max_band; + int space; + int volume; + int channel; + int mute; +}; + +struct si4702_drvdata { + struct regulator *vio; + struct regulator *vdd; + struct class *radio_class; + struct si4702_info info; + /*by default, dev major is zero, and it's alloc dynamicaly. */ + int major; + int minor; + struct cdev *cdev; + int count; /* open count */ + struct i2c_client *client; + unsigned char reg_rw_buf[SI4702_REG_BYTE]; + struct mxc_fm_platform_data *plat_data; +}; + +static struct si4702_drvdata *si4702_drvdata; + +DEFINE_SPINLOCK(count_lock); + +#ifdef DEBUG +static void si4702_dump_reg(void) +{ + int i, j; + unsigned char *reg_rw_buf; + + if (NULL == si4702_drvdata) + return; + + reg_rw_buf = si4702_drvdata->reg_rw_buf; + + for (i = 0; i < 10; i++) { + j = i * 2 + 12; + pr_debug("reg[%02d] = %04x\n", i, + ((reg_rw_buf[j] << 8) & 0xFF00) + + (reg_rw_buf[j + 1] & 0x00FF)); + } + for (; i < 16; i++) { + j = (i - 10) * 2; + pr_debug("reg[%02d] = %04x\n", i, + ((reg_rw_buf[j] << 8) & 0xFF00) + + (reg_rw_buf[j + 1] & 0x00FF)); + } +} +#else +static void si4702_dump_reg(void) +{ +} +#endif /* DEBUG */ + +/* + *check the si4702 spec for the read/write concequence. + * + *0 2 A F0 A F + *------------------------------- + * buf:0 2 A F + */ +#define REG_to_BUF(reg) (((reg >= 0) && (reg < SI4702_STATUSRSSI)) ? \ + (reg - SI4702_STATUSRSSI + SI4702_REG_NUM) : \ + ((reg >= SI4702_STATUSRSSI) && (reg < SI4702_REG_NUM)) ? \ + (reg - SI4702_STATUSRSSI) : -1) + +static int si4702_read_reg(const int reg, u16 *value) +{ + int ret, index; + unsigned char *reg_rw_buf; + + if (NULL == si4702_drvdata) + return -1; + + reg_rw_buf = si4702_drvdata->reg_rw_buf; + + index = REG_to_BUF(reg); + + if (-1 == index) + return -1; + + ret = + i2c_master_recv(si4702_drvdata->client, reg_rw_buf, + SI4702_REG_BYTE); + + *value = (reg_rw_buf[index * 2] << 8) & 0xFF00; + *value |= reg_rw_buf[index * 2 + 1] & 0x00FF; + + return ret < 0 ? ret : 0; +} + +static int si4702_write_reg(const int reg, const u16 value) +{ + int index, ret; + unsigned char *reg_rw_buf; + + if (NULL == si4702_drvdata) + return -1; + + reg_rw_buf = si4702_drvdata->reg_rw_buf; + + index = REG_to_BUF(reg); + + if (-1 == index) + return -1; + + reg_rw_buf[index * 2] = (value & 0xFF00) >> 8; + reg_rw_buf[index * 2 + 1] = value & 0x00FF; + + ret = i2c_master_send(si4702_drvdata->client, + ®_rw_buf[SI4702_RW_OFFSET * 2], + (SI4702_STATUSRSSI - SI4702_POWERCFG) * 2); + return ret < 0 ? ret : 0; +} + +static void si4702_gpio_get(void) +{ + if (NULL == si4702_drvdata) + return; + + si4702_drvdata->plat_data->gpio_get(); +} + +static void si4702_gpio_put(void) +{ + if (NULL == si4702_drvdata) + return; + + si4702_drvdata->plat_data->gpio_put(); +} + +static void si4702_reset(void) +{ + if (NULL == si4702_drvdata) + return; + + si4702_drvdata->plat_data->reset(); +} + +static void si4702_clock_en(int flag) +{ + if (NULL == si4702_drvdata) + return; + + si4702_drvdata->plat_data->clock_ctl(flag); +} + +static int si4702_id_detect(struct i2c_client *client) +{ + int ret, index; + unsigned int ID = 0; + unsigned char reg_rw_buf[SI4702_REG_BYTE]; + + si4702_gpio_get(); + si4702_reset(); + si4702_clock_en(1); + + ret = i2c_master_recv(client, (char *)reg_rw_buf, SI4702_REG_BYTE); + + si4702_gpio_put(); + + if (ret < 0) + return ret; + + index = REG_to_BUF(SI4702_DEVICEID); + if (index < 0) + return index; + + ID = (reg_rw_buf[index * 2] << 8) & 0xFF00; + ID |= reg_rw_buf[index * 2 + 1] & 0x00FF; + + return ID; +} + +/* valid args 50/100/200 */ +static int si4702_set_space(int space) +{ + u16 reg; + int ret; + struct si4702_info *info; + + if (NULL == si4702_drvdata) + return -1; + + ret = si4702_read_reg(SI4702_SYSCONFIG2, ®); + if (ret == -1) + return ret; + + reg &= ~SI4702_SPACE_MASK; + switch (space) { + case 50: + reg |= SI4702_SPACE_50K; + break; + case 100: + reg |= SI4702_SPACE_100K; + break; + case 200: + ret |= SI4702_SPACE_200K; + break; + default: + return -1; + } + + ret = si4702_write_reg(SI4702_SYSCONFIG2, reg); + if (ret == -1) + return ret; + + info = &si4702_drvdata->info; + info->space = space; + return 0; +} + +static int si4702_set_band_range(int band) +{ + u16 reg; + int ret, band_min, band_max; + struct si4702_info *info; + + if (NULL == si4702_drvdata) + return -1; + + switch (band) { + case BAND_USA: + band_min = 87500; + band_max = 108000; + break; + case BAND_JAP_W: + band_min = 76000; + band_max = 108000; + break; + case BAND_JAP: + band_min = 76000; + band_max = 90000; + break; + default: + return -1; + } + + ret = si4702_read_reg(SI4702_SYSCONFIG2, ®); + if (ret == -1) + return ret; + + reg = (reg & ~SI4702_BAND_MASK) + | ((band << SI4702_BAND_LSB) & SI4702_BAND_MASK); + ret = si4702_write_reg(SI4702_SYSCONFIG2, reg); + if (ret == -1) + return ret; + + info = &si4702_drvdata->info; + info->min_band = band_min; + info->max_band = band_max; + return 0; +} + +static int si4702_set_seekth(u8 seekth) +{ + u16 reg; + int ret; + + if (NULL == si4702_drvdata) + return -1; + + ret = si4702_read_reg(SI4702_SYSCONFIG2, ®); + if (ret == -1) + return ret; + + reg = + (reg & ~SI4702_SEEKTH_MASK) | ((seekth << SI4702_SEEKTH_LSB) & + SI4702_SEEKTH_MASK); + ret = si4702_write_reg(SI4702_SYSCONFIG2, reg); + if (ret == -1) + return ret; + + return 0; +} + +static int si4702_set_sksnr(u8 sksnr) +{ + u16 reg; + int ret; + + if (NULL == si4702_drvdata) + return -1; + + ret = si4702_read_reg(SI4702_SYSCONFIG3, ®); + if (ret == -1) + return ret; + + reg = + (reg & ~SI4702_SNR_MASK) | ((sksnr << SI4702_SNR_LSB) & + SI4702_SNR_MASK); + ret = si4702_write_reg(SI4702_SYSCONFIG3, reg); + if (ret == -1) + return ret; + + return 0; +} + +static int si4702_set_skcnt(u8 skcnt) +{ + u16 reg; + int ret; + + if (NULL == si4702_drvdata) + return -1; + + ret = si4702_read_reg(SI4702_SYSCONFIG3, ®); + if (ret == -1) + return ret; + + reg = (reg & ~SI4702_CNT_MASK) | (skcnt & SI4702_CNT_MASK); + ret = si4702_write_reg(SI4702_SYSCONFIG3, reg); + if (ret == -1) + return ret; + + return 0; +} + +static int si4702_set_vol(int vol) +{ + u16 reg; + int ret; + struct si4702_info *info; + + if (NULL == si4702_drvdata) + return -1; + + ret = si4702_read_reg(SI4702_SYSCONFIG2, ®); + if (ret == -1) + return ret; + + reg = (reg & ~SI4702_VOL_MASK) | (vol & SI4702_VOL_MASK); + ret = si4702_write_reg(SI4702_SYSCONFIG2, reg); + if (ret == -1) + return ret; + + info = &si4702_drvdata->info; + info->volume = vol; + + return 0; +} + +static u8 si4702_channel_select(u32 freq) +{ + u16 loop_counter = 0; + s16 channel; + u16 si4702_reg_data; + u8 error_ind = 0; + struct i2c_client *client; + struct si4702_info *info; + + if (NULL == si4702_drvdata) + return -1; + + info = &si4702_drvdata->info; + client = si4702_drvdata->client; + + dev_info(&client->dev, "Input frequnce is %d\n", freq); + if (freq < 76000 || freq > 108000) { + dev_err(&client->dev, "Input frequnce is invalid\n"); + return -1; + } + /* convert freq to channel */ + channel = (freq - info->min_band) / info->space; + + si4702_reg_data = SI4702_TUNE_BIT | (channel & SI4702_CHAN_MASK); + /* set channel */ + error_ind = si4702_write_reg(SI4702_CHANNEL, si4702_reg_data); + if (error_ind) { + dev_err(&client->dev, "Failed to set channel\n"); + return -1; + } + dev_info(&client->dev, "Set channel to %d\n", channel); + + /* wait for STC == 1 */ + do { + error_ind = + si4702_read_reg(SI4702_STATUSRSSI, &si4702_reg_data); + + if (error_ind) { + dev_err(&client->dev, "Failed to read setted STC\n"); + return -1; + } + if ((si4702_reg_data & SI4702_STC_BIT) != 0) + break; + } while (++loop_counter < DELAY_WAIT); + + /* check loop_counter */ + if (loop_counter >= DELAY_WAIT) { + dev_err(&client->dev, "Can't wait for STC bit set"); + return -1; + } + dev_info(&client->dev, "loop counter %d\n", loop_counter); + + loop_counter = 0; + /* clear tune bit */ + error_ind = si4702_write_reg(SI4702_CHANNEL, 0); + + if (error_ind) { + dev_err(&client->dev, "Failed to set stop tune\n"); + return -1; + } + + /* wait for STC == 0 */ + do { + error_ind = + si4702_read_reg(SI4702_STATUSRSSI, &si4702_reg_data); + + if (error_ind) { + dev_err(&client->dev, "Failed to set read STC\n"); + return -1; + } + if ((si4702_reg_data & SI4702_STC_BIT) == 0) + break; + } while (++loop_counter < DELAY_WAIT); + + /* check loop_counter */ + if (loop_counter >= DELAY_WAIT) { + dev_err(&client->dev, "Can't wait for STC bit clean"); + return -1; + } + dev_info(&client->dev, "loop counter %d\n", loop_counter); + + /* read RSSI */ + error_ind = si4702_read_reg(SI4702_READCHAN, &si4702_reg_data); + + if (error_ind) { + dev_err(&client->dev, "Failed to read RSSI\n"); + return -1; + } + + channel = si4702_reg_data & SI4702_CHAN_MASK; + dev_info(&client->dev, "seek finish: channel(%d)\n", channel); + + return 0; +} + +static s32 si4702_channel_seek(s16 dir) +{ + u16 loop_counter = 0; + u16 si4702_reg_data, reg_power_cfg; + u8 error_ind = 0; + u32 channel, freq; + struct i2c_client *client; + struct si4702_info *info; + + if (NULL == si4702_drvdata) + return -1; + + info = &si4702_drvdata->info; + client = si4702_drvdata->client; + + error_ind = si4702_read_reg(SI4702_POWERCFG, ®_power_cfg); + + if (info->mute) { + /* check disable mute */ + reg_power_cfg &= ~SI4702_DMUTE_BIT; + } else { + reg_power_cfg |= SI4702_DMUTE_BIT; + } + + if (dir) { + reg_power_cfg |= SI4702_SEEKUP_BIT; + } else { + reg_power_cfg &= ~SI4702_SEEKUP_BIT; + } + /* start seek */ + reg_power_cfg |= SI4702_SEEK_BIT; + error_ind = si4702_write_reg(SI4702_POWERCFG, reg_power_cfg); + + if (error_ind) { + dev_err(&client->dev, "Failed to set seek start bit\n"); + return -1; + } + + /* wait STC == 1 */ + do { + error_ind = + si4702_read_reg(SI4702_STATUSRSSI, &si4702_reg_data); + if (error_ind) { + dev_err(&client->dev, "Failed to read STC bit\n"); + return -1; + } + + if ((si4702_reg_data & SI4702_STC_BIT) != 0) + break; + } while (++loop_counter < DELAY_WAIT); + + /* clear seek bit */ + reg_power_cfg &= ~SI4702_SEEK_BIT; + error_ind = si4702_write_reg(SI4702_POWERCFG, reg_power_cfg); + if (error_ind) { + dev_err(&client->dev, "Failed to stop seek\n"); + return -1; + } + + if (loop_counter >= DELAY_WAIT) { + dev_err(&client->dev, "Can't wait for STC bit set\n"); + return -1; + } + + /* check whether SF==1 (seek failed bit) */ + if ((si4702_reg_data & SI4702_SF_BIT) != 0) { + dev_err(&client->dev, "Failed to seek any channel\n"); + return -1; + } + + loop_counter = 0; + /* wait STC == 0 */ + do { + error_ind = + si4702_read_reg(SI4702_STATUSRSSI, &si4702_reg_data); + + if (error_ind) { + dev_err(&client->dev, + "Failed to wait STC bit to clear\n"); + return -1; + } + if ((si4702_reg_data & SI4702_STC_BIT) == 0) + break; + } while (++loop_counter < DELAY_WAIT); + + /* check loop_counter */ + if (loop_counter >= DELAY_WAIT) { + dev_err(&client->dev, "Can't wait for STC bit clean"); + return -1; + } + + error_ind = si4702_read_reg(SI4702_READCHAN, &si4702_reg_data); + + if (error_ind) { + dev_err(&client->dev, "I2C simulate failed\n"); + return -1; + } + + channel = si4702_reg_data & SI4702_CHAN_MASK; + freq = channel * info->space + info->min_band; + dev_err(&client->dev, + "seek finish: channel(%d), freq(%dKHz)\n", channel, freq); + + return 0; +} + +static int si4702_startup(void) +{ + u16 magic = 0, id; + struct i2c_client *client; + struct mxc_fm_platform_data *data; + + if (NULL == si4702_drvdata) + return -1; + + if (si4702_drvdata->vio) + regulator_enable(si4702_drvdata->vio); + if (si4702_drvdata->vdd) + regulator_enable(si4702_drvdata->vdd); + data = si4702_drvdata->plat_data; + client = si4702_drvdata->client; + + /* read prior to write, otherwise write op will fail */ + si4702_read_reg(SI4702_DEVICEID, &id); + dev_err(&client->dev, "si4702: DEVICEID: 0x%x\n", id); + + si4702_clock_en(1); + msleep(100); + + /* disable mute, stereo, seek down, powerup */ + si4702_write_reg(SI4702_POWERCFG, SI4702_DMUTE_BIT | SI4702_ENABLE_BIT); + msleep(500); + si4702_read_reg(SI4702_TEST1, &magic); + if (magic != 0x3C04) + dev_err(&client->dev, "magic number 0x%x.\n", magic); + /* close tune, set channel to 0 */ + si4702_write_reg(SI4702_CHANNEL, 0); + /* disable interrupt, disable GPIO */ + si4702_write_reg(SI4702_SYSCONFIG1, 0); + /* set volume to middle level */ + si4702_set_vol(0xf); + + si4702_set_space(data->space); + si4702_set_band_range(data->band); + si4702_set_seekth(data->seekth); + si4702_set_skcnt(data->skcnt); + si4702_set_sksnr(data->sksnr); + + return 0; +} + +static void si4702_shutdown(void) +{ + if (NULL == si4702_drvdata) + return; + + si4702_write_reg(SI4702_POWERCFG, SI4702_DMUTE_BIT | + SI4702_ENABLE_BIT | SI4702_DISABLE_BIT); + msleep(100); + si4702_clock_en(0); + + if (si4702_drvdata->vdd) + regulator_disable(si4702_drvdata->vdd); + if (si4702_drvdata->vio) + regulator_disable(si4702_drvdata->vio); +} + +enum { + FM_STARTUP = 0, + FM_SHUTDOWN, + FM_RESET, + FM_VOLUP, + FM_VOLDOWN, + FM_SEEK_UP, + FM_SEEK_DOWN, + FM_MUTEON, + FM_MUTEDIS, + FM_SEL, + FM_SEEKTH, + FM_DL, + FM_CTL_MAX +}; + +static const char *const fm_control[FM_CTL_MAX] = { + [FM_STARTUP] = "start", + [FM_SHUTDOWN] = "halt", + [FM_RESET] = "reset", + [FM_VOLUP] = "volup", + [FM_VOLDOWN] = "voldown", + [FM_SEEK_UP] = "seeku", + [FM_SEEK_DOWN] = "seekd", + [FM_MUTEON] = "mute", + [FM_MUTEDIS] = "muted", + [FM_SEL] = "select", + [FM_SEEKTH] = "seekth", + [FM_DL] = "delay" +}; + +static int cmd(unsigned int index, int arg) +{ + struct i2c_client *client; + struct mxc_fm_platform_data *plat_data; + + if (NULL == si4702_drvdata) + return -1; + + client = si4702_drvdata->client; + plat_data = si4702_drvdata->plat_data; + + switch (index) { + case FM_SHUTDOWN: + dev_err(&client->dev, "FM_SHUTDOWN\n"); + si4702_shutdown(); + break; + case FM_STARTUP: + dev_err(&client->dev, "FM_STARTUP\n"); + si4702_reset(); + si4702_startup(); + break; + case FM_RESET: + dev_err(&client->dev, "FM_RESET\n"); + si4702_reset(); + break; + case FM_SEEK_DOWN: + dev_err(&client->dev, "SEEK DOWN\n"); + si4702_channel_seek(0); + break; + case FM_SEEK_UP: + dev_err(&client->dev, "SEEK UP\n"); + si4702_channel_seek(1); + break; + case FM_SEL: + dev_err(&client->dev, "select %d\n", arg * 100); + si4702_channel_select(arg * 100); + break; + case FM_SEEKTH: + dev_err(&client->dev, "seekth = %d\n", arg); + si4702_set_seekth(arg); + break; + case FM_DL: + dev_err(&client->dev, "delay = %d\n", arg); + break; + default: + dev_err(&client->dev, "error command\n"); + break; + } + return 0; +} + +static ssize_t si4702_show(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct si4702_drvdata *drv_data = dev_get_drvdata(dev); + u16 device_id; + + dev_err(&(drv_data->client->dev), "si4702 show\n"); + si4702_read_reg(SI4702_DEVICEID, &device_id); + pr_info("device id %x\n", device_id); + si4702_dump_reg(); + return 0; +} + +static ssize_t si4702_store(struct device *dev, + struct device_attribute *attr, const char *buf, + size_t count) +{ + int state = 0; + const char *const *s; + char *p = NULL; + int error; + int len, arg = 0; + struct si4702_drvdata *drv_data = dev_get_drvdata(dev); + struct i2c_client *client = drv_data->client; + + dev_err(&client->dev, "si4702 store %d\n", count); + + p = memchr(buf, ' ', count); + if (p) { + len = p - buf; + *p = '\0'; + } else + len = count; + + len -= 1; + dev_err(&client->dev, "cmd %s\n", buf); + + for (s = &fm_control[state]; state < FM_CTL_MAX; s++, state++) { + if (*s && !strncmp(buf, *s, len)) { + break; + } + } + if (state < FM_CTL_MAX && *s) { + if (p) + arg = simple_strtoul(p + 1, NULL, 0); + dev_err(&client->dev, "arg = %d\n", arg); + error = cmd(state, arg); + } else { + dev_err(&client->dev, "error cmd\n"); + error = -EINVAL; + } + + return error ? error : count; +} + +static int ioctl_si4702(struct inode *inode, struct file *file, + unsigned int cmd, unsigned long arg) +{ + void __user *argp = (void __user *)arg; + int mute = 0; + u16 data; + int error; + u8 volume; + unsigned int freq; + int dir; + struct i2c_client *client; + struct si4702_info *info; + + if (NULL == si4702_drvdata) + return -1; + + info = &si4702_drvdata->info; + client = si4702_drvdata->client; + + dev_err(&client->dev, "ioctl, cmd: 0x%x, arg: 0x%lx\n", cmd, arg); + + switch (cmd) { + case SI4702_SETVOLUME: + /* get volume from user */ + if (copy_from_user(&volume, argp, sizeof(u8))) { + + dev_err(&client->dev, + "ioctl, copy volume value from user failed\n"); + return -EFAULT; + } + dev_err(&client->dev, "volume %d\n", volume); + /* refill the register value */ + volume &= 0x0f; + if (info->mute) + error = si4702_write_reg(SI4702_POWERCFG, 0x0001); + else + error = si4702_write_reg(SI4702_POWERCFG, 0x4001); + + error = si4702_write_reg(SI4702_CHANNEL, 0); + error = si4702_write_reg(SI4702_SYSCONFIG1, 0); + error = si4702_write_reg(SI4702_SYSCONFIG2, 0x0f10 | volume); + if (error) { + dev_err(&client->dev, "ioctl, set volume failed\n"); + return -EFAULT; + } + /* renew the device info */ + info->volume = volume; + + break; + case SI4702_GETVOLUME: + /* just copy volume value to user */ + if (copy_to_user(argp, &(info->volume), sizeof(unsigned int))) { + dev_err(&client->dev, "ioctl, copy to user failed\n"); + return -EFAULT; + } + break; + case SI4702_MUTEON: + mute = 1; + case SI4702_MUTEOFF: + if (mute) { + /* enable mute */ + si4702_read_reg(SI4702_POWERCFG, &data); + data &= 0x00FF; + error = si4702_write_reg(SI4702_POWERCFG, data); + } else { + si4702_read_reg(SI4702_POWERCFG, &data); + data &= 0x00FF; + data |= 0x4000; + error = si4702_write_reg(SI4702_POWERCFG, data); + } + if (error) { + dev_err(&client->dev, "ioctl, set mute failed\n"); + return -EFAULT; + } + break; + case SI4702_SELECT: + if (copy_from_user(&freq, argp, sizeof(unsigned int))) { + + dev_err(&client->dev, + "ioctl, copy frequence from user failed\n"); + return -EFAULT; + } + /* check frequence */ + if (freq > info->max_band || freq < info->min_band) { + dev_err(&client->dev, + "the frequence select is out of band\n"); + return -EINVAL; + } + if (si4702_channel_select(freq)) { + dev_err(&client->dev, + "ioctl, failed to select channel\n"); + return -EFAULT; + } + break; + case SI4702_SEEK: + if (copy_from_user(&dir, argp, sizeof(int))) { + + dev_err(&client->dev, "ioctl, copy from user failed\n"); + return -EFAULT; + } + /* get seeked channel */ + dir = si4702_channel_seek(dir); + if (dir == -1) { + return -EAGAIN; + } else if (dir == -2) { + return -EFAULT; + } + if (copy_to_user(argp, &dir, sizeof(int))) { + + dev_err(&client->dev, + "ioctl, copy seek frequnce to user failed\n"); + return -EFAULT; + } + break; + default: + dev_err(&client->dev, "SI4702: Invalid ioctl command\n"); + return -EINVAL; + + } + return 0; +} + +static int open_si4702(struct inode *inode, struct file *file) +{ + struct i2c_client *client; + + if (NULL == si4702_drvdata) + return -1; + + client = si4702_drvdata->client; + + spin_lock(&count_lock); + if (si4702_drvdata->count != 0) { + dev_err(&client->dev, "device has been open already\n"); + spin_unlock(&count_lock); + return -EBUSY; + } + si4702_drvdata->count++; + spin_unlock(&count_lock); + + /* request and active GPIO */ + si4702_gpio_get(); + /* reset the si4702 from it's reset pin */ + si4702_reset(); + + /* startup si4702 */ + if (si4702_startup()) { + spin_lock(&count_lock); + si4702_drvdata->count--; + spin_unlock(&count_lock); + return -ENODEV; + } + + return 0; +} + +static int release_si4702(struct inode *inode, struct file *file) +{ + struct i2c_client *client; + + if (NULL == si4702_drvdata) + return -1; + + client = si4702_drvdata->client; + + dev_err(&client->dev, "release\n"); + /* software shutdown */ + si4702_shutdown(); + /* inactive, free GPIO, cut power */ + si4702_gpio_put(); + + spin_lock(&count_lock); + si4702_drvdata->count--; + spin_unlock(&count_lock); + + return 0; +} + +static int si4702_suspend(struct i2c_client *client, pm_message_t state) +{ + return 0; +} + +static int si4702_resume(struct i2c_client *client) +{ + return 0; +} + +static struct device_attribute si4702_dev_attr = { + .attr = { + .name = "si4702_ctl", + .mode = S_IRUSR | S_IWUSR, + }, + .show = si4702_show, + .store = si4702_store, +}; + +static struct file_operations si4702_fops = { + .owner = THIS_MODULE, + .open = open_si4702, + .release = release_si4702, + .ioctl = ioctl_si4702, +}; + +static int __devinit si4702_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + int ret = 0; + struct mxc_fm_platform_data *plat_data; + struct si4702_drvdata *drv_data; + struct device *dev; + + dev_info(&client->dev, "si4702 device probe process start.\n"); + + plat_data = (struct mxc_fm_platform_data *)client->dev.platform_data; + if (plat_data == NULL) { + dev_err(&client->dev, "lack of platform data!\n"); + return -ENODEV; + } + + drv_data = kmalloc(sizeof(struct si4702_drvdata), GFP_KERNEL); + if (drv_data == NULL) { + dev_err(&client->dev, "lack of kernel memory!\n"); + return -ENOMEM; + } + memset(drv_data, 0, sizeof(struct si4702_drvdata)); + drv_data->plat_data = plat_data; + drv_data->major = DEV_MAJOR; + drv_data->minor = DEV_MINOR; + drv_data->count = 0; + + /*enable power supply */ + if (plat_data->reg_vio != NULL) { + drv_data->vio = regulator_get(&client->dev, plat_data->reg_vio); + if (drv_data->vio == ERR_PTR(-ENOENT)) + goto free_drv_data; + regulator_enable(drv_data->vio); + } + + /* here, we assume that vio and vdd are not the same */ + if (plat_data->reg_vdd != NULL) { + drv_data->vdd = regulator_get(&client->dev, plat_data->reg_vdd); + if (drv_data->vdd == ERR_PTR(-ENOENT)) + goto disable_vio; + regulator_enable(drv_data->vdd); + } + + /*attach client and check device id */ + if (SI4702_DEVICE_ID != si4702_id_detect(client)) { + dev_err(&client->dev, "id wrong.\n"); + goto disable_vdd; + } + dev_info(&client->dev, "chip id %x detect.\n", SI4702_DEVICE_ID); + drv_data->client = client; + + /*user interface begain */ + /*create device file in sysfs as a user interface, + * also for debug support */ + ret = device_create_file(&client->dev, &si4702_dev_attr); + if (ret) { + dev_err(&client->dev, "create device file failed!\n"); + goto gpio_put; /* shall i use some meanful error code? */ + } + + /*create a char dev for application code access */ + if (drv_data->major) { + ret = register_chrdev(drv_data->major, "si4702", &si4702_fops);; + } else { + ret = register_chrdev(0, "si4702", &si4702_fops); + } + + if (drv_data->major == 0) + drv_data->major = ret; + + /* create class and device for udev information */ + drv_data->radio_class = class_create(THIS_MODULE, "radio"); + if (IS_ERR(drv_data->radio_class)) { + dev_err(&client->dev, "SI4702: failed to create radio class\n"); + goto char_dev_remove; + } + + dev = device_create(drv_data->radio_class, NULL, + MKDEV(drv_data->major, drv_data->minor), NULL, + "si4702"); + if (IS_ERR(dev)) { + dev_err(&client->dev, + "SI4702: failed to create radio class device\n"); + goto class_remove; + } + /*User interface end */ + dev_set_drvdata(&client->dev, drv_data); + si4702_drvdata = drv_data; + + si4702_gpio_get(); + dev_info(&client->dev, "si4702 device probe successfully.\n"); + si4702_shutdown(); + + return 0; + +class_remove: + class_destroy(drv_data->radio_class); +char_dev_remove: + unregister_chrdev(drv_data->major, "si4702"); + device_remove_file(&client->dev, &si4702_dev_attr); +gpio_put: + si4702_gpio_put(); +disable_vdd: + if (plat_data->reg_vdd) { + regulator_disable(drv_data->vdd); + regulator_put(drv_data->vdd); + } +disable_vio: + if (plat_data->reg_vio) { + regulator_disable(drv_data->vio); + regulator_put(drv_data->vio); + } + +free_drv_data: + kfree(drv_data); + + return -ENODEV; +} + +static int __devexit si4702_remove(struct i2c_client *client) +{ + struct mxc_fm_platform_data *plat_data; + struct si4702_drvdata *drv_data = dev_get_drvdata(&client->dev); + + plat_data = (struct mxc_fm_platform_data *)client->dev.platform_data; + + device_destroy(drv_data->radio_class, + MKDEV(drv_data->major, drv_data->minor)); + class_destroy(drv_data->radio_class); + + unregister_chrdev(drv_data->major, "si4702"); + device_remove_file(&client->dev, &si4702_dev_attr); + si4702_gpio_put(); + + if (plat_data->reg_vdd) + regulator_put(drv_data->vdd); + + if (plat_data->reg_vio) + regulator_put(drv_data->vio); + + kfree(si4702_drvdata); + si4702_drvdata = NULL; + + return 0; +} + +static const struct i2c_device_id si4702_id[] = { + {"si4702", 0}, + {}, +}; + +MODULE_DEVICE_TABLE(i2c, si4702_id); + +static struct i2c_driver i2c_si4702_driver = { + .driver = { + .name = "si4702", + }, + .probe = si4702_probe, + .remove = si4702_remove, + .suspend = si4702_suspend, + .resume = si4702_resume, + .id_table = si4702_id, +}; + +static int __init init_si4702(void) +{ + /*add to i2c driver */ + pr_info("add si4702 i2c driver\n"); + return i2c_add_driver(&i2c_si4702_driver); +} + +static void __exit exit_si4702(void) +{ + i2c_del_driver(&i2c_si4702_driver); +} + +module_init(init_si4702); +module_exit(exit_si4702); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("SI4702 FM driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/char/mxs_viim.c b/drivers/char/mxs_viim.c new file mode 100644 index 000000000000..302d967d12e2 --- /dev/null +++ b/drivers/char/mxs_viim.c @@ -0,0 +1,175 @@ +/* + * Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include + +static unsigned long iim_reg_base0, iim_reg_end0, iim_reg_size0; +static unsigned long iim_reg_base1, iim_reg_end1, iim_reg_size1; +static struct device *iim_dev; + +/*! + * MXS Virtual IIM interface - memory map function + * This function maps one page size VIIM registers from VIIM base address0 + * if the size of the required virtual memory space is less than or equal to + * one page size, otherwise this function will also map one page size VIIM + * registers from VIIM base address1. + * + * @param file struct file * + * @param vma structure vm_area_struct * + * + * @return Return 0 on success or negative error code on error + */ +static int mxs_viim_mmap(struct file *file, struct vm_area_struct *vma) +{ + size_t size = vma->vm_end - vma->vm_start; + + vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); + + /* Remap-pfn-range will mark the range VM_IO and VM_RESERVED */ + if (remap_pfn_range(vma, + vma->vm_start, + iim_reg_base0 >> PAGE_SHIFT, + iim_reg_size0, + vma->vm_page_prot)) + return -EAGAIN; + + if (size > iim_reg_size0) { + if (remap_pfn_range(vma, + vma->vm_start + iim_reg_size0, + iim_reg_base1 >> PAGE_SHIFT, + iim_reg_size1, + vma->vm_page_prot)) + return -EAGAIN; + } + + return 0; +} + +/*! + * MXS Virtual IIM interface - open function + * + * @param inode struct inode * + * @param filp struct file * + * + * @return Return 0 on success or negative error code on error + */ +static int mxs_viim_open(struct inode *inode, struct file *filp) +{ + return 0; +} + +/*! + * MXS Virtual IIM interface - release function + * + * @param inode struct inode * + * @param filp struct file * + * + * @return Return 0 on success or negative error code on error + */ +static int mxs_viim_release(struct inode *inode, struct file *filp) +{ + return 0; +} + +static const struct file_operations mxs_viim_fops = { + .mmap = mxs_viim_mmap, + .open = mxs_viim_open, + .release = mxs_viim_release, +}; + +static struct miscdevice mxs_viim_miscdev = { + .minor = MISC_DYNAMIC_MINOR, + .name = "mxs_viim", + .fops = &mxs_viim_fops, +}; + +/*! + * This function is called by the driver framework to get virtual iim base/end + * address and register iim misc device. + * + * @param dev The device structure for Virtual IIM passed in by the + * driver framework. + * + * @return Returns 0 on success or negative error code on error + */ +static int mxs_viim_probe(struct platform_device *pdev) +{ + struct resource *res; + int ret; + + iim_dev = &pdev->dev; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (IS_ERR(res)) { + dev_err(iim_dev, "Unable to get Virtual IIM resource 0\n"); + return -ENODEV; + } + + iim_reg_base0 = res->start; + iim_reg_end0 = res->end; + iim_reg_size0 = iim_reg_end0 - iim_reg_base0 + 1; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 1); + if (IS_ERR(res)) { + dev_err(iim_dev, "Unable to get Virtual IIM resource 1\n"); + return -ENODEV; + } + + iim_reg_base1 = res->start; + iim_reg_end1 = res->end; + iim_reg_size1 = iim_reg_end1 - iim_reg_base1 + 1; + + ret = misc_register(&mxs_viim_miscdev); + if (ret) + return ret; + + return 0; +} + +static int mxs_viim_remove(struct platform_device *pdev) +{ + misc_deregister(&mxs_viim_miscdev); + return 0; +} + +static struct platform_driver mxs_viim_driver = { + .driver = { + .owner = THIS_MODULE, + .name = "mxs_viim", + }, + .probe = mxs_viim_probe, + .remove = mxs_viim_remove, +}; + +static int __init mxs_viim_dev_init(void) +{ + return platform_driver_register(&mxs_viim_driver); +} + +static void __exit mxs_viim_dev_cleanup(void) +{ + platform_driver_unregister(&mxs_viim_driver); +} + +module_init(mxs_viim_dev_init); +module_exit(mxs_viim_dev_cleanup); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MXS Virtual IIM driver"); +MODULE_LICENSE("GPL"); +MODULE_ALIAS_MISCDEV(MISC_DYNAMIC_MINOR); diff --git a/drivers/crypto/Kconfig b/drivers/crypto/Kconfig index fbf94cf496f0..739c53da924f 100644 --- a/drivers/crypto/Kconfig +++ b/drivers/crypto/Kconfig @@ -243,4 +243,16 @@ config CRYPTO_DEV_OMAP_SHAM OMAP processors have SHA1/MD5 hw accelerator. Select this if you want to use the OMAP module for SHA1/MD5 algorithms. +config CRYPTO_DEV_DCP + tristate "Support for the DCP engine" + depends on ARCH_MX28 || ARCH_MX23 + select CRYPTO_ALGAPI + select CRYPTO_BLKCIPHER + help + Say 'Y' here to use the DCP AES and SHA + engine for the CryptoAPI algorithms. + + To compile this driver as a module, choose M here: the module + will be called geode-aes. + endif # CRYPTO_HW diff --git a/drivers/crypto/Makefile b/drivers/crypto/Makefile index 6dbbe00c4524..c375d1903e9e 100644 --- a/drivers/crypto/Makefile +++ b/drivers/crypto/Makefile @@ -9,4 +9,5 @@ obj-$(CONFIG_CRYPTO_DEV_TALITOS) += talitos.o obj-$(CONFIG_CRYPTO_DEV_IXP4XX) += ixp4xx_crypto.o obj-$(CONFIG_CRYPTO_DEV_PPC4XX) += amcc/ obj-$(CONFIG_CRYPTO_DEV_OMAP_SHAM) += omap-sham.o +obj-$(CONFIG_CRYPTO_DEV_DCP) += dcp.o diff --git a/drivers/crypto/dcp.c b/drivers/crypto/dcp.c new file mode 100644 index 000000000000..9589a19c1872 --- /dev/null +++ b/drivers/crypto/dcp.c @@ -0,0 +1,1697 @@ +/* + * Copyright (C) 2008-2010 Freescale Semiconductor, Inc. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +/* + * Based on geode-aes.c + * Copyright (C) 2004-2006, Advanced Micro Devices, Inc. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include "dcp.h" +#include "dcp_bootstream_ioctl.h" + +/* Following data only used by DCP bootstream interface */ +struct dcpboot_dma_area { + struct dcp_hw_packet hw_packet; + uint16_t block[16]; +}; + +struct dcp { + struct device *dev; + spinlock_t lock; + struct mutex op_mutex[DCP_NUM_CHANNELS]; + struct completion op_wait[DCP_NUM_CHANNELS]; + int wait[DCP_NUM_CHANNELS]; + int dcp_vmi_irq; + int dcp_irq; + u32 dcp_regs_base; + + /* Following buffers used in hashing to meet 64-byte len alignment */ + char *buf1; + char *buf2; + dma_addr_t buf1_phys; + dma_addr_t buf2_phys; + struct dcp_hash_coherent_block *buf1_desc; + struct dcp_hash_coherent_block *buf2_desc; + struct dcp_hash_coherent_block *user_buf_desc; + + /* Following data only used by DCP bootstream interface */ + struct dcpboot_dma_area *dcpboot_dma_area; + dma_addr_t dcpboot_dma_area_phys; +}; + +/* cipher flags */ +#define DCP_ENC 0x0001 +#define DCP_DEC 0x0002 +#define DCP_ECB 0x0004 +#define DCP_CBC 0x0008 +#define DCP_CBC_INIT 0x0010 +#define DCP_OTPKEY 0x0020 + +/* hash flags */ +#define DCP_INIT 0x0001 +#define DCP_UPDATE 0x0002 +#define DCP_FINAL 0x0004 + +#define DCP_AES 0x1000 +#define DCP_SHA1 0x2000 +#define DCP_CRC32 0x3000 +#define DCP_COPY 0x4000 +#define DCP_FILL 0x5000 +#define DCP_MODE_MASK 0xf000 + +struct dcp_op { + + unsigned int flags; + + void *src; + dma_addr_t src_phys; + + void *dst; + dma_addr_t dst_phys; + + int len; + + /* the key contains the IV for block modes */ + union { + struct { + u8 key[2 * AES_KEYSIZE_128] + __attribute__ ((__aligned__(32))); + dma_addr_t key_phys; + int keylen; + } cipher; + struct { + u8 digest[SHA256_DIGEST_SIZE] + __attribute__ ((__aligned__(32))); + dma_addr_t digest_phys; + int digestlen; + int init; + } hash; + }; + + union { + struct crypto_blkcipher *blk; + struct crypto_cipher *cip; + struct crypto_hash *hash; + } fallback; + + struct dcp_hw_packet pkt + __attribute__ ((__aligned__(32))); +}; + +struct dcp_hash_coherent_block { + struct dcp_hw_packet pkt[1] + __attribute__ ((__aligned__(32))); + u8 digest[SHA256_DIGEST_SIZE] + __attribute__ ((__aligned__(32))); + unsigned int len; + dma_addr_t src_phys; + void *src; + void *dst; + dma_addr_t my_phys; + u32 hash_sel; + struct dcp_hash_coherent_block *next; +}; + +struct dcp_hash_op { + + unsigned int flags; + + /* the key contains the IV for block modes */ + union { + struct { + u8 key[2 * AES_KEYSIZE_128] + __attribute__ ((__aligned__(32))); + dma_addr_t key_phys; + int keylen; + } cipher; + struct { + u8 digest[SHA256_DIGEST_SIZE] + __attribute__ ((__aligned__(32))); + dma_addr_t digest_phys; + int digestlen; + int init; + } hash; + }; + + u32 length; + struct dcp_hash_coherent_block *head_desc; + struct dcp_hash_coherent_block *tail_desc; +}; + +/* only one */ +static struct dcp *global_sdcp; + +static void dcp_perform_op(struct dcp_op *op) +{ + struct dcp *sdcp = global_sdcp; + struct mutex *mutex; + struct dcp_hw_packet *pkt; + int chan; + u32 pkt1, pkt2; + unsigned long timeout; + dma_addr_t pkt_phys; + u32 stat; + + pkt1 = BM_DCP_PACKET1_DECR_SEMAPHORE | BM_DCP_PACKET1_INTERRUPT; + + switch (op->flags & DCP_MODE_MASK) { + + case DCP_AES: + + chan = CIPHER_CHAN; + + /* key is at the payload */ + pkt1 |= BM_DCP_PACKET1_ENABLE_CIPHER; + if ((op->flags & DCP_OTPKEY) == 0) + pkt1 |= BM_DCP_PACKET1_PAYLOAD_KEY; + if (op->flags & DCP_ENC) + pkt1 |= BM_DCP_PACKET1_CIPHER_ENCRYPT; + if (op->flags & DCP_CBC_INIT) + pkt1 |= BM_DCP_PACKET1_CIPHER_INIT; + + pkt2 = BF(0, DCP_PACKET2_CIPHER_CFG) | + BF(0, DCP_PACKET2_KEY_SELECT) | + BF(BV_DCP_PACKET2_CIPHER_SELECT__AES128, + DCP_PACKET2_CIPHER_SELECT); + + if (op->flags & DCP_ECB) + pkt2 |= BF(BV_DCP_PACKET2_CIPHER_MODE__ECB, + DCP_PACKET2_CIPHER_MODE); + else if (op->flags & DCP_CBC) + pkt2 |= BF(BV_DCP_PACKET2_CIPHER_MODE__CBC, + DCP_PACKET2_CIPHER_MODE); + + break; + + case DCP_SHA1: + + chan = HASH_CHAN; + + pkt1 |= BM_DCP_PACKET1_ENABLE_HASH; + if (op->flags & DCP_INIT) + pkt1 |= BM_DCP_PACKET1_HASH_INIT; + if (op->flags & DCP_FINAL) { + pkt1 |= BM_DCP_PACKET1_HASH_TERM; + BUG_ON(op->hash.digest == NULL); + } + + pkt2 = BF(BV_DCP_PACKET2_HASH_SELECT__SHA1, + DCP_PACKET2_HASH_SELECT); + break; + + default: + dev_err(sdcp->dev, "Unsupported mode\n"); + return; + } + + mutex = &sdcp->op_mutex[chan]; + pkt = &op->pkt; + + pkt->pNext = 0; + pkt->pkt1 = pkt1; + pkt->pkt2 = pkt2; + pkt->pSrc = (u32)op->src_phys; + pkt->pDst = (u32)op->dst_phys; + pkt->size = op->len; + pkt->pPayload = chan == CIPHER_CHAN ? + (u32)op->cipher.key_phys : (u32)op->hash.digest_phys; + pkt->stat = 0; + + pkt_phys = dma_map_single(sdcp->dev, pkt, sizeof(*pkt), + DMA_BIDIRECTIONAL); + if (dma_mapping_error(sdcp->dev, pkt_phys)) { + dev_err(sdcp->dev, "Unable to map packet descriptor\n"); + return; + } + + /* submit the work */ + mutex_lock(mutex); + + __raw_writel(-1, sdcp->dcp_regs_base + HW_DCP_CHnSTAT_CLR(chan)); + + /* Load the work packet pointer and bump the channel semaphore */ + __raw_writel((u32)pkt_phys, sdcp->dcp_regs_base + + HW_DCP_CHnCMDPTR(chan)); + + /* XXX wake from interrupt instead of looping */ + timeout = jiffies + msecs_to_jiffies(1000); + + sdcp->wait[chan] = 0; + __raw_writel(BF(1, DCP_CHnSEMA_INCREMENT), sdcp->dcp_regs_base + + HW_DCP_CHnSEMA(chan)); + while (time_before(jiffies, timeout) && sdcp->wait[chan] == 0) + cpu_relax(); + + if (!time_before(jiffies, timeout)) { + dev_err(sdcp->dev, "Timeout while waiting STAT 0x%08x\n", + __raw_readl(sdcp->dcp_regs_base + HW_DCP_STAT)); + goto out; + } + + stat = __raw_readl(sdcp->dcp_regs_base + HW_DCP_CHnSTAT(chan)); + if ((stat & 0xff) != 0) + dev_err(sdcp->dev, "Channel stat error 0x%02x\n", + __raw_readl(sdcp->dcp_regs_base + + HW_DCP_CHnSTAT(chan)) & 0xff); +out: + mutex_unlock(mutex); + + dma_unmap_single(sdcp->dev, pkt_phys, sizeof(*pkt), DMA_TO_DEVICE); +} + +static int dcp_aes_setkey_cip(struct crypto_tfm *tfm, const u8 *key, + unsigned int len) +{ + struct dcp_op *op = crypto_tfm_ctx(tfm); + unsigned int ret; + + op->cipher.keylen = len; + + if (len == AES_KEYSIZE_128) { + memcpy(op->cipher.key, key, len); + return 0; + } + + if (len != AES_KEYSIZE_192 && len != AES_KEYSIZE_256) { + /* not supported at all */ + tfm->crt_flags |= CRYPTO_TFM_RES_BAD_KEY_LEN; + return -EINVAL; + } + + /* + * The requested key size is not supported by HW, do a fallback + */ + op->fallback.blk->base.crt_flags &= ~CRYPTO_TFM_REQ_MASK; + op->fallback.blk->base.crt_flags |= (tfm->crt_flags & + CRYPTO_TFM_REQ_MASK); + + ret = crypto_cipher_setkey(op->fallback.cip, key, len); + if (ret) { + tfm->crt_flags &= ~CRYPTO_TFM_RES_MASK; + tfm->crt_flags |= (op->fallback.blk->base.crt_flags & + CRYPTO_TFM_RES_MASK); + } + return ret; +} + +static void dcp_aes_encrypt(struct crypto_tfm *tfm, u8 *out, const u8 *in) +{ + struct dcp *sdcp = global_sdcp; + struct dcp_op *op = crypto_tfm_ctx(tfm); + + if (unlikely(op->cipher.keylen != AES_KEYSIZE_128)) { + crypto_cipher_encrypt_one(op->fallback.cip, out, in); + return; + } + + op->src = (void *) in; + op->dst = (void *) out; + op->flags = DCP_AES | DCP_ENC | DCP_ECB; + op->len = AES_KEYSIZE_128; + + /* map the data */ + op->src_phys = dma_map_single(sdcp->dev, (void *)in, AES_KEYSIZE_128, + DMA_TO_DEVICE); + if (dma_mapping_error(sdcp->dev, op->src_phys)) { + dev_err(sdcp->dev, "Unable to map source\n"); + return; + } + + op->dst_phys = dma_map_single(sdcp->dev, out, AES_KEYSIZE_128, + DMA_FROM_DEVICE); + if (dma_mapping_error(sdcp->dev, op->dst_phys)) { + dev_err(sdcp->dev, "Unable to map dest\n"); + goto err_unmap_src; + } + + op->cipher.key_phys = dma_map_single(sdcp->dev, op->cipher.key, + AES_KEYSIZE_128, DMA_TO_DEVICE); + if (dma_mapping_error(sdcp->dev, op->cipher.key_phys)) { + dev_err(sdcp->dev, "Unable to map key\n"); + goto err_unmap_dst; + } + + /* perform the operation */ + dcp_perform_op(op); + + dma_unmap_single(sdcp->dev, op->cipher.key_phys, AES_KEYSIZE_128, + DMA_TO_DEVICE); +err_unmap_dst: + dma_unmap_single(sdcp->dev, op->dst_phys, op->len, DMA_FROM_DEVICE); +err_unmap_src: + dma_unmap_single(sdcp->dev, op->src_phys, op->len, DMA_TO_DEVICE); +} + +static void dcp_aes_decrypt(struct crypto_tfm *tfm, u8 *out, const u8 *in) +{ + struct dcp *sdcp = global_sdcp; + struct dcp_op *op = crypto_tfm_ctx(tfm); + + if (unlikely(op->cipher.keylen != AES_KEYSIZE_128)) { + crypto_cipher_decrypt_one(op->fallback.cip, out, in); + return; + } + + op->src = (void *) in; + op->dst = (void *) out; + op->flags = DCP_AES | DCP_DEC | DCP_ECB; + op->len = AES_KEYSIZE_128; + + /* map the data */ + op->src_phys = dma_map_single(sdcp->dev, (void *)in, AES_KEYSIZE_128, + DMA_TO_DEVICE); + if (dma_mapping_error(sdcp->dev, op->src_phys)) { + dev_err(sdcp->dev, "Unable to map source\n"); + return; + } + + op->dst_phys = dma_map_single(sdcp->dev, out, AES_KEYSIZE_128, + DMA_FROM_DEVICE); + if (dma_mapping_error(sdcp->dev, op->dst_phys)) { + dev_err(sdcp->dev, "Unable to map dest\n"); + goto err_unmap_src; + } + + op->cipher.key_phys = dma_map_single(sdcp->dev, op->cipher.key, + AES_KEYSIZE_128, DMA_TO_DEVICE); + if (dma_mapping_error(sdcp->dev, op->cipher.key_phys)) { + dev_err(sdcp->dev, "Unable to map key\n"); + goto err_unmap_dst; + } + + /* perform the operation */ + dcp_perform_op(op); + + dma_unmap_single(sdcp->dev, op->cipher.key_phys, AES_KEYSIZE_128, + DMA_TO_DEVICE); +err_unmap_dst: + dma_unmap_single(sdcp->dev, op->dst_phys, op->len, DMA_FROM_DEVICE); +err_unmap_src: + dma_unmap_single(sdcp->dev, op->src_phys, op->len, DMA_TO_DEVICE); +} + +static int fallback_init_cip(struct crypto_tfm *tfm) +{ + const char *name = tfm->__crt_alg->cra_name; + struct dcp_op *op = crypto_tfm_ctx(tfm); + + op->fallback.cip = crypto_alloc_cipher(name, 0, + CRYPTO_ALG_ASYNC | CRYPTO_ALG_NEED_FALLBACK); + + if (IS_ERR(op->fallback.cip)) { + printk(KERN_ERR "Error allocating fallback algo %s\n", name); + return PTR_ERR(op->fallback.cip); + } + + return 0; +} + +static void fallback_exit_cip(struct crypto_tfm *tfm) +{ + struct dcp_op *op = crypto_tfm_ctx(tfm); + + crypto_free_cipher(op->fallback.cip); + op->fallback.cip = NULL; +} + +static struct crypto_alg dcp_aes_alg = { + .cra_name = "aes", + .cra_driver_name = "dcp-aes", + .cra_priority = 300, + .cra_alignmask = 15, + .cra_flags = CRYPTO_ALG_TYPE_CIPHER | + CRYPTO_ALG_NEED_FALLBACK, + .cra_init = fallback_init_cip, + .cra_exit = fallback_exit_cip, + .cra_blocksize = AES_KEYSIZE_128, + .cra_ctxsize = sizeof(struct dcp_op), + .cra_module = THIS_MODULE, + .cra_list = LIST_HEAD_INIT(dcp_aes_alg.cra_list), + .cra_u = { + .cipher = { + .cia_min_keysize = AES_MIN_KEY_SIZE, + .cia_max_keysize = AES_MAX_KEY_SIZE, + .cia_setkey = dcp_aes_setkey_cip, + .cia_encrypt = dcp_aes_encrypt, + .cia_decrypt = dcp_aes_decrypt + } + } +}; + +static int dcp_aes_setkey_blk(struct crypto_tfm *tfm, const u8 *key, + unsigned int len) +{ + struct dcp_op *op = crypto_tfm_ctx(tfm); + unsigned int ret; + + op->cipher.keylen = len; + + if (len == AES_KEYSIZE_128) { + memcpy(op->cipher.key, key, len); + return 0; + } + + if (len != AES_KEYSIZE_192 && len != AES_KEYSIZE_256) { + /* not supported at all */ + tfm->crt_flags |= CRYPTO_TFM_RES_BAD_KEY_LEN; + return -EINVAL; + } + + /* + * The requested key size is not supported by HW, do a fallback + */ + op->fallback.blk->base.crt_flags &= ~CRYPTO_TFM_REQ_MASK; + op->fallback.blk->base.crt_flags |= (tfm->crt_flags & + CRYPTO_TFM_REQ_MASK); + + ret = crypto_blkcipher_setkey(op->fallback.blk, key, len); + if (ret) { + tfm->crt_flags &= ~CRYPTO_TFM_RES_MASK; + tfm->crt_flags |= (op->fallback.blk->base.crt_flags & + CRYPTO_TFM_RES_MASK); + } + return ret; +} + +static int fallback_blk_dec(struct blkcipher_desc *desc, + struct scatterlist *dst, struct scatterlist *src, + unsigned int nbytes) +{ + unsigned int ret; + struct crypto_blkcipher *tfm; + struct dcp_op *op = crypto_blkcipher_ctx(desc->tfm); + + tfm = desc->tfm; + desc->tfm = op->fallback.blk; + + ret = crypto_blkcipher_decrypt_iv(desc, dst, src, nbytes); + + desc->tfm = tfm; + return ret; +} + +static int fallback_blk_enc(struct blkcipher_desc *desc, + struct scatterlist *dst, struct scatterlist *src, + unsigned int nbytes) +{ + unsigned int ret; + struct crypto_blkcipher *tfm; + struct dcp_op *op = crypto_blkcipher_ctx(desc->tfm); + + tfm = desc->tfm; + desc->tfm = op->fallback.blk; + + ret = crypto_blkcipher_encrypt_iv(desc, dst, src, nbytes); + + desc->tfm = tfm; + return ret; +} + +static int fallback_init_blk(struct crypto_tfm *tfm) +{ + const char *name = tfm->__crt_alg->cra_name; + struct dcp_op *op = crypto_tfm_ctx(tfm); + + op->fallback.blk = crypto_alloc_blkcipher(name, 0, + CRYPTO_ALG_ASYNC | CRYPTO_ALG_NEED_FALLBACK); + + if (IS_ERR(op->fallback.blk)) { + printk(KERN_ERR "Error allocating fallback algo %s\n", name); + return PTR_ERR(op->fallback.blk); + } + + return 0; +} + +static void fallback_exit_blk(struct crypto_tfm *tfm) +{ + struct dcp_op *op = crypto_tfm_ctx(tfm); + + crypto_free_blkcipher(op->fallback.blk); + op->fallback.blk = NULL; +} + +static int +dcp_aes_ecb_decrypt(struct blkcipher_desc *desc, + struct scatterlist *dst, struct scatterlist *src, + unsigned int nbytes) +{ + struct dcp *sdcp = global_sdcp; + struct dcp_op *op = crypto_blkcipher_ctx(desc->tfm); + struct blkcipher_walk walk; + int err; + + if (unlikely(op->cipher.keylen != AES_KEYSIZE_128)) + return fallback_blk_dec(desc, dst, src, nbytes); + + blkcipher_walk_init(&walk, dst, src, nbytes); + + /* key needs to be mapped only once */ + op->cipher.key_phys = dma_map_single(sdcp->dev, op->cipher.key, + AES_KEYSIZE_128, DMA_TO_DEVICE); + if (dma_mapping_error(sdcp->dev, op->cipher.key_phys)) { + dev_err(sdcp->dev, "Unable to map key\n"); + return -ENOMEM; + } + + err = blkcipher_walk_virt(desc, &walk); + while (err == 0 && (nbytes = walk.nbytes) > 0) { + op->src = walk.src.virt.addr, + op->dst = walk.dst.virt.addr; + op->flags = DCP_AES | DCP_DEC | + DCP_ECB; + op->len = nbytes - (nbytes % AES_KEYSIZE_128); + + /* map the data */ + op->src_phys = dma_map_single(sdcp->dev, op->src, op->len, + DMA_TO_DEVICE); + if (dma_mapping_error(sdcp->dev, op->src_phys)) { + dev_err(sdcp->dev, "Unable to map source\n"); + err = -ENOMEM; + break; + } + + op->dst_phys = dma_map_single(sdcp->dev, op->dst, op->len, + DMA_FROM_DEVICE); + if (dma_mapping_error(sdcp->dev, op->dst_phys)) { + dma_unmap_single(sdcp->dev, op->src_phys, op->len, + DMA_TO_DEVICE); + dev_err(sdcp->dev, "Unable to map dest\n"); + err = -ENOMEM; + break; + } + + /* perform! */ + dcp_perform_op(op); + + dma_unmap_single(sdcp->dev, op->dst_phys, op->len, + DMA_FROM_DEVICE); + dma_unmap_single(sdcp->dev, op->src_phys, op->len, + DMA_TO_DEVICE); + + nbytes -= op->len; + err = blkcipher_walk_done(desc, &walk, nbytes); + } + + dma_unmap_single(sdcp->dev, op->cipher.key_phys, AES_KEYSIZE_128, + DMA_TO_DEVICE); + + return err; +} + +static int +dcp_aes_ecb_encrypt(struct blkcipher_desc *desc, + struct scatterlist *dst, struct scatterlist *src, + unsigned int nbytes) +{ + struct dcp *sdcp = global_sdcp; + struct dcp_op *op = crypto_blkcipher_ctx(desc->tfm); + struct blkcipher_walk walk; + int err, ret; + + if (unlikely(op->cipher.keylen != AES_KEYSIZE_128)) + return fallback_blk_enc(desc, dst, src, nbytes); + + blkcipher_walk_init(&walk, dst, src, nbytes); + + /* key needs to be mapped only once */ + op->cipher.key_phys = dma_map_single(sdcp->dev, op->cipher.key, + AES_KEYSIZE_128, DMA_TO_DEVICE); + if (dma_mapping_error(sdcp->dev, op->cipher.key_phys)) { + dev_err(sdcp->dev, "Unable to map key\n"); + return -ENOMEM; + } + + err = blkcipher_walk_virt(desc, &walk); + + err = 0; + while (err == 0 && (nbytes = walk.nbytes) > 0) { + op->src = walk.src.virt.addr, + op->dst = walk.dst.virt.addr; + op->flags = DCP_AES | DCP_ENC | + DCP_ECB; + op->len = nbytes - (nbytes % AES_KEYSIZE_128); + + /* map the data */ + op->src_phys = dma_map_single(sdcp->dev, op->src, op->len, + DMA_TO_DEVICE); + if (dma_mapping_error(sdcp->dev, op->src_phys)) { + dev_err(sdcp->dev, "Unable to map source\n"); + err = -ENOMEM; + break; + } + + op->dst_phys = dma_map_single(sdcp->dev, op->dst, op->len, + DMA_FROM_DEVICE); + if (dma_mapping_error(sdcp->dev, op->dst_phys)) { + dma_unmap_single(sdcp->dev, op->src_phys, op->len, + DMA_TO_DEVICE); + dev_err(sdcp->dev, "Unable to map dest\n"); + err = -ENOMEM; + break; + } + + /* perform! */ + dcp_perform_op(op); + + dma_unmap_single(sdcp->dev, op->dst_phys, op->len, + DMA_FROM_DEVICE); + dma_unmap_single(sdcp->dev, op->src_phys, op->len, + DMA_TO_DEVICE); + + nbytes -= op->len; + ret = blkcipher_walk_done(desc, &walk, nbytes); + } + + dma_unmap_single(sdcp->dev, op->cipher.key_phys, AES_KEYSIZE_128, + DMA_TO_DEVICE); + + return err; +} + + +static struct crypto_alg dcp_aes_ecb_alg = { + .cra_name = "ecb(aes)", + .cra_driver_name = "dcp-ecb-aes", + .cra_priority = 400, + .cra_alignmask = 15, + .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER | + CRYPTO_ALG_NEED_FALLBACK, + .cra_init = fallback_init_blk, + .cra_exit = fallback_exit_blk, + .cra_blocksize = AES_KEYSIZE_128, + .cra_ctxsize = sizeof(struct dcp_op), + .cra_type = &crypto_blkcipher_type, + .cra_module = THIS_MODULE, + .cra_list = LIST_HEAD_INIT(dcp_aes_ecb_alg.cra_list), + .cra_u = { + .blkcipher = { + .min_keysize = AES_MIN_KEY_SIZE, + .max_keysize = AES_MAX_KEY_SIZE, + .setkey = dcp_aes_setkey_blk, + .encrypt = dcp_aes_ecb_encrypt, + .decrypt = dcp_aes_ecb_decrypt + } + } +}; + +static int +dcp_aes_cbc_decrypt(struct blkcipher_desc *desc, + struct scatterlist *dst, struct scatterlist *src, + unsigned int nbytes) +{ + struct dcp *sdcp = global_sdcp; + struct dcp_op *op = crypto_blkcipher_ctx(desc->tfm); + struct blkcipher_walk walk; + int err, blockno; + + if (unlikely(op->cipher.keylen != AES_KEYSIZE_128)) + return fallback_blk_dec(desc, dst, src, nbytes); + + blkcipher_walk_init(&walk, dst, src, nbytes); + + blockno = 0; + err = blkcipher_walk_virt(desc, &walk); + while (err == 0 && (nbytes = walk.nbytes) > 0) { + op->src = walk.src.virt.addr, + op->dst = walk.dst.virt.addr; + op->flags = DCP_AES | DCP_DEC | + DCP_CBC; + if (blockno == 0) { + op->flags |= DCP_CBC_INIT; + memcpy(op->cipher.key + AES_KEYSIZE_128, walk.iv, + AES_KEYSIZE_128); + } + op->len = nbytes - (nbytes % AES_KEYSIZE_128); + + /* key (+iv) needs to be mapped only once */ + op->cipher.key_phys = dma_map_single(sdcp->dev, op->cipher.key, + AES_KEYSIZE_128 * 2, DMA_BIDIRECTIONAL); + if (dma_mapping_error(sdcp->dev, op->cipher.key_phys)) { + dev_err(sdcp->dev, "Unable to map key\n"); + err = -ENOMEM; + break; + } + + /* map the data */ + op->src_phys = dma_map_single(sdcp->dev, op->src, op->len, + DMA_TO_DEVICE); + if (dma_mapping_error(sdcp->dev, op->src_phys)) { + dma_unmap_single(sdcp->dev, op->cipher.key_phys, + AES_KEYSIZE_128 * 2, DMA_BIDIRECTIONAL); + dev_err(sdcp->dev, "Unable to map source\n"); + err = -ENOMEM; + break; + } + + op->dst_phys = dma_map_single(sdcp->dev, op->dst, op->len, + DMA_FROM_DEVICE); + if (dma_mapping_error(sdcp->dev, op->dst_phys)) { + dma_unmap_single(sdcp->dev, op->cipher.key_phys, + AES_KEYSIZE_128 * 2, DMA_BIDIRECTIONAL); + dma_unmap_single(sdcp->dev, op->src_phys, op->len, + DMA_TO_DEVICE); + dev_err(sdcp->dev, "Unable to map dest\n"); + err = -ENOMEM; + break; + } + + /* perform! */ + dcp_perform_op(op); + + dma_unmap_single(sdcp->dev, op->cipher.key_phys, + AES_KEYSIZE_128 * 2, DMA_BIDIRECTIONAL); + dma_unmap_single(sdcp->dev, op->dst_phys, op->len, + DMA_FROM_DEVICE); + dma_unmap_single(sdcp->dev, op->src_phys, op->len, + DMA_TO_DEVICE); + + nbytes -= op->len; + err = blkcipher_walk_done(desc, &walk, nbytes); + + blockno++; + } + + return err; +} + +static int +dcp_aes_cbc_encrypt(struct blkcipher_desc *desc, + struct scatterlist *dst, struct scatterlist *src, + unsigned int nbytes) +{ + struct dcp *sdcp = global_sdcp; + struct dcp_op *op = crypto_blkcipher_ctx(desc->tfm); + struct blkcipher_walk walk; + int err, ret, blockno; + + if (unlikely(op->cipher.keylen != AES_KEYSIZE_128)) + return fallback_blk_enc(desc, dst, src, nbytes); + + blkcipher_walk_init(&walk, dst, src, nbytes); + + blockno = 0; + + err = blkcipher_walk_virt(desc, &walk); + while (err == 0 && (nbytes = walk.nbytes) > 0) { + op->src = walk.src.virt.addr, + op->dst = walk.dst.virt.addr; + op->flags = DCP_AES | DCP_ENC | + DCP_CBC; + if (blockno == 0) { + op->flags |= DCP_CBC_INIT; + memcpy(op->cipher.key + AES_KEYSIZE_128, walk.iv, + AES_KEYSIZE_128); + } + op->len = nbytes - (nbytes % AES_KEYSIZE_128); + + /* key needs to be mapped only once */ + op->cipher.key_phys = dma_map_single(sdcp->dev, op->cipher.key, + AES_KEYSIZE_128 * 2, DMA_BIDIRECTIONAL); + if (dma_mapping_error(sdcp->dev, op->cipher.key_phys)) { + dev_err(sdcp->dev, "Unable to map key\n"); + return -ENOMEM; + } + + /* map the data */ + op->src_phys = dma_map_single(sdcp->dev, op->src, op->len, + DMA_TO_DEVICE); + if (dma_mapping_error(sdcp->dev, op->src_phys)) { + dma_unmap_single(sdcp->dev, op->cipher.key_phys, + AES_KEYSIZE_128 * 2, DMA_BIDIRECTIONAL); + dev_err(sdcp->dev, "Unable to map source\n"); + err = -ENOMEM; + break; + } + + op->dst_phys = dma_map_single(sdcp->dev, op->dst, op->len, + DMA_FROM_DEVICE); + if (dma_mapping_error(sdcp->dev, op->dst_phys)) { + dma_unmap_single(sdcp->dev, op->cipher.key_phys, + AES_KEYSIZE_128 * 2, DMA_BIDIRECTIONAL); + dma_unmap_single(sdcp->dev, op->src_phys, op->len, + DMA_TO_DEVICE); + dev_err(sdcp->dev, "Unable to map dest\n"); + err = -ENOMEM; + break; + } + + /* perform! */ + dcp_perform_op(op); + + dma_unmap_single(sdcp->dev, op->cipher.key_phys, + AES_KEYSIZE_128 * 2, DMA_BIDIRECTIONAL); + dma_unmap_single(sdcp->dev, op->dst_phys, op->len, + DMA_FROM_DEVICE); + dma_unmap_single(sdcp->dev, op->src_phys, op->len, + DMA_TO_DEVICE); + + nbytes -= op->len; + ret = blkcipher_walk_done(desc, &walk, nbytes); + + blockno++; + } + + return err; +} + +static struct crypto_alg dcp_aes_cbc_alg = { + .cra_name = "cbc(aes)", + .cra_driver_name = "dcp-cbc-aes", + .cra_priority = 400, + .cra_alignmask = 15, + .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER | + CRYPTO_ALG_NEED_FALLBACK, + .cra_init = fallback_init_blk, + .cra_exit = fallback_exit_blk, + .cra_blocksize = AES_KEYSIZE_128, + .cra_ctxsize = sizeof(struct dcp_op), + .cra_type = &crypto_blkcipher_type, + .cra_module = THIS_MODULE, + .cra_list = LIST_HEAD_INIT(dcp_aes_cbc_alg.cra_list), + .cra_u = { + .blkcipher = { + .min_keysize = AES_MIN_KEY_SIZE, + .max_keysize = AES_MAX_KEY_SIZE, + .setkey = dcp_aes_setkey_blk, + .encrypt = dcp_aes_cbc_encrypt, + .decrypt = dcp_aes_cbc_decrypt, + .ivsize = AES_KEYSIZE_128, + } + } +}; + +static int dcp_perform_hash_op( + struct dcp_hash_coherent_block *input, + u32 num_desc, bool init, bool terminate) +{ + struct dcp *sdcp = global_sdcp; + int chan; + struct dcp_hw_packet *pkt; + struct dcp_hash_coherent_block *hw; + unsigned long timeout; + u32 stat; + int descno, mapped; + + chan = HASH_CHAN; + + hw = input; + pkt = hw->pkt; + + for (descno = 0; descno < num_desc; descno++) { + + if (descno != 0) { + + /* set next ptr and CHAIN bit in last packet */ + pkt->pNext = hw->next->my_phys + offsetof( + struct dcp_hash_coherent_block, + pkt[0]); + pkt->pkt1 |= BM_DCP_PACKET1_CHAIN; + + /* iterate to next descriptor */ + hw = hw->next; + pkt = hw->pkt; + } + + pkt->pkt1 = BM_DCP_PACKET1_DECR_SEMAPHORE | + BM_DCP_PACKET1_ENABLE_HASH; + + if (init && descno == 0) + pkt->pkt1 |= BM_DCP_PACKET1_HASH_INIT; + + pkt->pkt2 = BF(hw->hash_sel, + DCP_PACKET2_HASH_SELECT); + + /* no need to flush buf1 or buf2, which are uncached */ + if (hw->src != sdcp->buf1 && hw->src != sdcp->buf2) { + + /* we have to flush the cache for the buffer */ + hw->src_phys = dma_map_single(sdcp->dev, + hw->src, hw->len, DMA_TO_DEVICE); + + if (dma_mapping_error(sdcp->dev, hw->src_phys)) { + dev_err(sdcp->dev, "Unable to map source\n"); + + /* unmap any previous mapped buffers */ + for (mapped = 0, hw = input; mapped < descno; + mapped++) { + + if (mapped != 0) + hw = hw->next; + if (hw->src != sdcp->buf1 && + hw->src != sdcp->buf2) + dma_unmap_single(sdcp->dev, + hw->src_phys, hw->len, + DMA_TO_DEVICE); + } + + return -EFAULT; + } + } + + pkt->pSrc = (u32)hw->src_phys; + pkt->pDst = 0; + pkt->size = hw->len; + pkt->pPayload = 0; + pkt->stat = 0; + + /* set HASH_TERM bit on last buf if terminate was set */ + if (terminate && (descno == (num_desc - 1))) { + pkt->pkt1 |= BM_DCP_PACKET1_HASH_TERM; + + memset(input->digest, 0, sizeof(input->digest)); + + /* set payload ptr to the 1st buffer's digest */ + pkt->pPayload = (u32)input->my_phys + + offsetof( + struct dcp_hash_coherent_block, + digest); + } + } + + /* submit the work */ + + __raw_writel(-1, sdcp->dcp_regs_base + HW_DCP_CHnSTAT_CLR(chan)); + + mb(); + /* Load the 1st descriptor's physical address */ + __raw_writel((u32)input->my_phys + + offsetof(struct dcp_hash_coherent_block, + pkt[0]), sdcp->dcp_regs_base + HW_DCP_CHnCMDPTR(chan)); + + /* XXX wake from interrupt instead of looping */ + timeout = jiffies + msecs_to_jiffies(1000); + + /* write num_desc into sema register */ + __raw_writel(BF(num_desc, DCP_CHnSEMA_INCREMENT), + sdcp->dcp_regs_base + HW_DCP_CHnSEMA(chan)); + + while (time_before(jiffies, timeout) && + ((__raw_readl(sdcp->dcp_regs_base + + HW_DCP_CHnSEMA(chan)) >> 16) & 0xff) != 0) { + + cpu_relax(); + } + + if (!time_before(jiffies, timeout)) { + dev_err(sdcp->dev, + "Timeout while waiting STAT 0x%08x\n", + __raw_readl(sdcp->dcp_regs_base + HW_DCP_STAT)); + } + + stat = __raw_readl(sdcp->dcp_regs_base + HW_DCP_CHnSTAT(chan)); + if ((stat & 0xff) != 0) + dev_err(sdcp->dev, "Channel stat error 0x%02x\n", + __raw_readl(sdcp->dcp_regs_base + + HW_DCP_CHnSTAT(chan)) & 0xff); + + /* unmap all src buffers */ + for (descno = 0, hw = input; descno < num_desc; descno++) { + if (descno != 0) + hw = hw->next; + if (hw->src != sdcp->buf1 && hw->src != sdcp->buf2) + dma_unmap_single(sdcp->dev, hw->src_phys, hw->len, + DMA_TO_DEVICE); + } + + return 0; + +} + +static int dcp_sha_init(struct shash_desc *desc) +{ + struct dcp *sdcp = global_sdcp; + struct dcp_hash_op *op = shash_desc_ctx(desc); + struct mutex *mutex = &sdcp->op_mutex[HASH_CHAN]; + + mutex_lock(mutex); + + op->length = 0; + + /* reset the lengths and the pointers of buffer descriptors */ + sdcp->buf1_desc->len = 0; + sdcp->buf1_desc->src = sdcp->buf1; + sdcp->buf2_desc->len = 0; + sdcp->buf2_desc->src = sdcp->buf2; + op->head_desc = sdcp->buf1_desc; + op->tail_desc = sdcp->buf2_desc; + + return 0; +} + +static int dcp_sha_update(struct shash_desc *desc, const u8 *data, + unsigned int length) +{ + struct dcp *sdcp = global_sdcp; + struct dcp_hash_op *op = shash_desc_ctx(desc); + struct dcp_hash_coherent_block *temp; + u32 rem_bytes, bytes_borrowed, hash_sel; + int ret = 0; + + if (strcmp(desc->tfm->base.__crt_alg->cra_name, "sha1") == 0) + hash_sel = BV_DCP_PACKET2_HASH_SELECT__SHA1; + else + hash_sel = BV_DCP_PACKET2_HASH_SELECT__SHA256; + + sdcp->user_buf_desc->src = (void *)data; + sdcp->user_buf_desc->len = length; + + op->tail_desc->len = 0; + + /* check if any pending data from previous updates */ + if (op->head_desc->len) { + + /* borrow from this buffer to make it 64 bytes */ + bytes_borrowed = min(64 - op->head_desc->len, + sdcp->user_buf_desc->len); + + /* copy n bytes to head */ + memcpy(op->head_desc->src + op->head_desc->len, + sdcp->user_buf_desc->src, bytes_borrowed); + op->head_desc->len += bytes_borrowed; + + /* update current buffer's src and len */ + sdcp->user_buf_desc->src += bytes_borrowed; + sdcp->user_buf_desc->len -= bytes_borrowed; + } + + /* Is current buffer unaligned to 64 byte length? + * Each buffer's length must be a multiple of 64 bytes for DCP + */ + rem_bytes = sdcp->user_buf_desc->len % 64; + + /* if length is unaligned, copy remainder to tail */ + if (rem_bytes) { + + memcpy(op->tail_desc->src, (sdcp->user_buf_desc->src + + sdcp->user_buf_desc->len - rem_bytes), + rem_bytes); + + /* update length of current buffer */ + sdcp->user_buf_desc->len -= rem_bytes; + + op->tail_desc->len = rem_bytes; + } + + /* do not send to DCP if length is < 64 */ + if ((op->head_desc->len + sdcp->user_buf_desc->len) >= 64) { + + /* set hash alg to be used (SHA1 or SHA256) */ + op->head_desc->hash_sel = hash_sel; + sdcp->user_buf_desc->hash_sel = hash_sel; + + if (op->head_desc->len) { + op->head_desc->next = sdcp->user_buf_desc; + + ret = dcp_perform_hash_op(op->head_desc, + sdcp->user_buf_desc->len ? 2 : 1, + op->length == 0, false); + } else { + ret = dcp_perform_hash_op(sdcp->user_buf_desc, 1, + op->length == 0, false); + } + + op->length += op->head_desc->len + sdcp->user_buf_desc->len; + op->head_desc->len = 0; + } + + /* if tail has bytes, make it the head for next time */ + if (op->tail_desc->len) { + temp = op->head_desc; + op->head_desc = op->tail_desc; + op->tail_desc = temp; + } + + /* hash_sel to be used by final function */ + op->head_desc->hash_sel = hash_sel; + + return ret; +} + +static int dcp_sha_final(struct shash_desc *desc, u8 *out) +{ + struct dcp_hash_op *op = shash_desc_ctx(desc); + const uint8_t *digest; + struct dcp *sdcp = global_sdcp; + u32 i, digest_len; + struct mutex *mutex = &sdcp->op_mutex[HASH_CHAN]; + int ret = 0; + + /* Send the leftover bytes in head, which can be length 0, + * but DCP still produces hash result in payload ptr. + * Last data bytes need not be 64-byte multiple. + */ + ret = dcp_perform_hash_op(op->head_desc, 1, op->length == 0, true); + + op->length += op->head_desc->len; + + digest_len = (op->head_desc->hash_sel == + BV_DCP_PACKET2_HASH_SELECT__SHA1) ? SHA1_DIGEST_SIZE : + SHA256_DIGEST_SIZE; + + /* hardware reverses the digest (for some unexplicable reason) */ + digest = op->head_desc->digest + digest_len; + for (i = 0; i < digest_len; i++) + *out++ = *--digest; + + mutex_unlock(mutex); + + return ret; +} + +static struct shash_alg dcp_sha1_alg = { + .init = dcp_sha_init, + .update = dcp_sha_update, + .final = dcp_sha_final, + .descsize = sizeof(struct dcp_hash_op), + .digestsize = SHA1_DIGEST_SIZE, + .base = { + .cra_name = "sha1", + .cra_driver_name = "sha1-dcp", + .cra_priority = 300, + .cra_blocksize = SHA1_BLOCK_SIZE, + .cra_ctxsize = + sizeof(struct dcp_hash_op), + .cra_module = THIS_MODULE, + } +}; + +static struct shash_alg dcp_sha256_alg = { + .init = dcp_sha_init, + .update = dcp_sha_update, + .final = dcp_sha_final, + .descsize = sizeof(struct dcp_hash_op), + .digestsize = SHA256_DIGEST_SIZE, + .base = { + .cra_name = "sha256", + .cra_driver_name = "sha256-dcp", + .cra_priority = 300, + .cra_blocksize = SHA256_BLOCK_SIZE, + .cra_ctxsize = + sizeof(struct dcp_hash_op), + .cra_module = THIS_MODULE, + } +}; + +static irqreturn_t dcp_common_irq(int irq, void *context) +{ + struct dcp *sdcp = context; + u32 msk; + + /* check */ + msk = __raw_readl(sdcp->dcp_regs_base + HW_DCP_STAT) & + BF(0x0f, DCP_STAT_IRQ); + if (msk == 0) + return IRQ_NONE; + + /* clear this channel */ + __raw_writel(msk, sdcp->dcp_regs_base + HW_DCP_STAT_CLR); + if (msk & BF(0x01, DCP_STAT_IRQ)) + sdcp->wait[0]++; + if (msk & BF(0x02, DCP_STAT_IRQ)) + sdcp->wait[1]++; + if (msk & BF(0x04, DCP_STAT_IRQ)) + sdcp->wait[2]++; + if (msk & BF(0x08, DCP_STAT_IRQ)) + sdcp->wait[3]++; + return IRQ_HANDLED; +} + +static irqreturn_t dcp_vmi_irq(int irq, void *context) +{ + return dcp_common_irq(irq, context); +} + +static irqreturn_t dcp_irq(int irq, void *context) +{ + return dcp_common_irq(irq, context); +} + +/* DCP bootstream verification interface: uses OTP key for crypto */ +static int dcp_bootstream_ioctl(struct inode *inode, struct file *file, + unsigned int cmd, unsigned long arg) +{ + struct dcp *sdcp = global_sdcp; + struct dcpboot_dma_area *da = sdcp->dcpboot_dma_area; + void __user *argp = (void __user *)arg; + int chan = ROM_DCP_CHAN; + unsigned long timeout; + struct mutex *mutex; + int retVal; + + /* be paranoid */ + if (sdcp == NULL) + return -EBADF; + + if (cmd != DBS_ENC && cmd != DBS_DEC) + return -EINVAL; + + /* copy to (aligned) block */ + if (copy_from_user(da->block, argp, 16)) + return -EFAULT; + + mutex = &sdcp->op_mutex[chan]; + mutex_lock(mutex); + + __raw_writel(-1, sdcp->dcp_regs_base + + HW_DCP_CHnSTAT_CLR(ROM_DCP_CHAN)); + __raw_writel(BF(ROM_DCP_CHAN_MASK, DCP_STAT_IRQ), + sdcp->dcp_regs_base + HW_DCP_STAT_CLR); + + da->hw_packet.pNext = 0; + da->hw_packet.pkt1 = BM_DCP_PACKET1_DECR_SEMAPHORE | + BM_DCP_PACKET1_ENABLE_CIPHER | BM_DCP_PACKET1_OTP_KEY | + BM_DCP_PACKET1_INTERRUPT | + (cmd == DBS_ENC ? BM_DCP_PACKET1_CIPHER_ENCRYPT : 0); + da->hw_packet.pkt2 = BF(0, DCP_PACKET2_CIPHER_CFG) | + BF(0, DCP_PACKET2_KEY_SELECT) | + BF(BV_DCP_PACKET2_CIPHER_MODE__ECB, DCP_PACKET2_CIPHER_MODE) | + BF(BV_DCP_PACKET2_CIPHER_SELECT__AES128, DCP_PACKET2_CIPHER_SELECT); + da->hw_packet.pSrc = sdcp->dcpboot_dma_area_phys + + offsetof(struct dcpboot_dma_area, block); + da->hw_packet.pDst = da->hw_packet.pSrc; /* in-place */ + da->hw_packet.size = 16; + da->hw_packet.pPayload = 0; + da->hw_packet.stat = 0; + + /* Load the work packet pointer and bump the channel semaphore */ + __raw_writel(sdcp->dcpboot_dma_area_phys + + offsetof(struct dcpboot_dma_area, hw_packet), + sdcp->dcp_regs_base + HW_DCP_CHnCMDPTR(ROM_DCP_CHAN)); + + sdcp->wait[chan] = 0; + __raw_writel(BF(1, DCP_CHnSEMA_INCREMENT), + sdcp->dcp_regs_base + HW_DCP_CHnSEMA(ROM_DCP_CHAN)); + + timeout = jiffies + msecs_to_jiffies(100); + + while (time_before(jiffies, timeout) && sdcp->wait[chan] == 0) + cpu_relax(); + + if (!time_before(jiffies, timeout)) { + dev_err(sdcp->dev, + "Timeout while waiting for operation to complete\n"); + retVal = -ETIMEDOUT; + goto exit; + } + + if ((__raw_readl(sdcp->dcp_regs_base + HW_DCP_CHnSTAT(ROM_DCP_CHAN)) + & 0xff) != 0) { + dev_err(sdcp->dev, "Channel stat error 0x%02x\n", + __raw_readl(sdcp->dcp_regs_base + + HW_DCP_CHnSTAT(ROM_DCP_CHAN)) & 0xff); + retVal = -EFAULT; + goto exit; + } + + if (copy_to_user(argp, da->block, 16)) { + retVal = -EFAULT; + goto exit; + } + + retVal = 0; + +exit: + mutex_unlock(mutex); + return retVal; +} + +static const struct file_operations dcp_bootstream_fops = { + .owner = THIS_MODULE, + .ioctl = dcp_bootstream_ioctl, +}; + +static struct miscdevice dcp_bootstream_misc = { + .minor = MISC_DYNAMIC_MINOR, + .name = "dcpboot", + .fops = &dcp_bootstream_fops, +}; + +static int dcp_probe(struct platform_device *pdev) +{ + struct dcp *sdcp = NULL; + struct resource *r; + int i, ret; + dma_addr_t hw_phys; + + if (global_sdcp != NULL) { + dev_err(&pdev->dev, "Only one instance allowed\n"); + ret = -ENODEV; + goto err; + } + + /* allocate memory */ + sdcp = kzalloc(sizeof(*sdcp), GFP_KERNEL); + if (sdcp == NULL) { + dev_err(&pdev->dev, "Failed to allocate structure\n"); + ret = -ENOMEM; + goto err; + } + + sdcp->dev = &pdev->dev; + spin_lock_init(&sdcp->lock); + + for (i = 0; i < DCP_NUM_CHANNELS; i++) { + mutex_init(&sdcp->op_mutex[i]); + init_completion(&sdcp->op_wait[i]); + } + + platform_set_drvdata(pdev, sdcp); + + r = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!r) { + dev_err(&pdev->dev, "failed to get IORESOURCE_MEM\n"); + ret = -ENXIO; + goto err_kfree; + } + sdcp->dcp_regs_base = (u32) IO_ADDRESS(r->start); + + /* Soft reset and remove the clock gate */ + __raw_writel(BM_DCP_CTRL_SFTRST, sdcp->dcp_regs_base + HW_DCP_CTRL_SET); + + /* At 24Mhz, it takes no more than 4 clocks (160 ns) Maximum for + * the part to reset, reading the register twice should + * be sufficient to get 4 clks delay. + */ + __raw_readl(sdcp->dcp_regs_base + HW_DCP_CTRL); + __raw_readl(sdcp->dcp_regs_base + HW_DCP_CTRL); + + __raw_writel(BM_DCP_CTRL_SFTRST | BM_DCP_CTRL_CLKGATE, + sdcp->dcp_regs_base + HW_DCP_CTRL_CLR); + + /* Initialize control registers */ + __raw_writel(DCP_CTRL_INIT, sdcp->dcp_regs_base + HW_DCP_CTRL); + __raw_writel(DCP_CHANNELCTRL_INIT, sdcp->dcp_regs_base + + HW_DCP_CHANNELCTRL); + + /* We do not enable context switching. Give the context + * buffer pointer an illegal address so if context switching is + * inadvertantly enabled, the dcp will return an error instead of + * trashing good memory. The dcp dma cannot access rom, so any rom + * address will do. + */ + __raw_writel(0xFFFF0000, sdcp->dcp_regs_base + HW_DCP_CONTEXT); + + for (i = 0; i < DCP_NUM_CHANNELS; i++) + __raw_writel(-1, sdcp->dcp_regs_base + HW_DCP_CHnSTAT_CLR(i)); + __raw_writel(-1, sdcp->dcp_regs_base + HW_DCP_STAT_CLR); + + r = platform_get_resource(pdev, IORESOURCE_IRQ, 0); + if (!r) { + dev_err(&pdev->dev, "can't get IRQ resource (0)\n"); + ret = -EIO; + goto err_kfree; + } + sdcp->dcp_vmi_irq = r->start; + ret = request_irq(sdcp->dcp_vmi_irq, dcp_vmi_irq, 0, "dcp", + sdcp); + if (ret != 0) { + dev_err(&pdev->dev, "can't request_irq (0)\n"); + goto err_kfree; + } + + r = platform_get_resource(pdev, IORESOURCE_IRQ, 1); + if (!r) { + dev_err(&pdev->dev, "can't get IRQ resource (1)\n"); + ret = -EIO; + goto err_free_irq0; + } + sdcp->dcp_irq = r->start; + ret = request_irq(sdcp->dcp_irq, dcp_irq, 0, "dcp", sdcp); + if (ret != 0) { + dev_err(&pdev->dev, "can't request_irq (1)\n"); + goto err_free_irq0; + } + + global_sdcp = sdcp; + + ret = crypto_register_alg(&dcp_aes_alg); + if (ret != 0) { + dev_err(&pdev->dev, "Failed to register aes crypto\n"); + goto err_kfree; + } + + ret = crypto_register_alg(&dcp_aes_ecb_alg); + if (ret != 0) { + dev_err(&pdev->dev, "Failed to register aes ecb crypto\n"); + goto err_unregister_aes; + } + + ret = crypto_register_alg(&dcp_aes_cbc_alg); + if (ret != 0) { + dev_err(&pdev->dev, "Failed to register aes cbc crypto\n"); + goto err_unregister_aes_ecb; + } + + /* Allocate the descriptor to be used for user buffer + * passed in by the "update" function from Crypto API + */ + sdcp->user_buf_desc = dma_alloc_coherent(sdcp->dev, + sizeof(struct dcp_hash_coherent_block), &hw_phys, + GFP_KERNEL); + if (sdcp->user_buf_desc == NULL) { + printk(KERN_ERR "Error allocating coherent block\n"); + ret = -ENOMEM; + goto err_unregister_aes_cbc; + } + + sdcp->user_buf_desc->my_phys = hw_phys; + + /* Allocate 2 buffers (head & tail) & its descriptors to deal with + * buffer lengths that are not 64 byte aligned, except for the + * last one. + */ + sdcp->buf1 = dma_alloc_coherent(sdcp->dev, + 64, &sdcp->buf1_phys, GFP_KERNEL); + if (sdcp->buf1 == NULL) { + printk(KERN_ERR "Error allocating coherent block\n"); + ret = -ENOMEM; + goto err_unregister_aes_cbc; + } + + sdcp->buf2 = dma_alloc_coherent(sdcp->dev, + 64, &sdcp->buf2_phys, GFP_KERNEL); + if (sdcp->buf2 == NULL) { + printk(KERN_ERR "Error allocating coherent block\n"); + ret = -ENOMEM; + goto err_unregister_aes_cbc; + } + + sdcp->buf1_desc = dma_alloc_coherent(sdcp->dev, + sizeof(struct dcp_hash_coherent_block), &hw_phys, + GFP_KERNEL); + if (sdcp->buf1_desc == NULL) { + printk(KERN_ERR "Error allocating coherent block\n"); + ret = -ENOMEM; + goto err_unregister_aes_cbc; + } + + sdcp->buf1_desc->my_phys = hw_phys; + sdcp->buf1_desc->src = (void *)sdcp->buf1; + sdcp->buf1_desc->src_phys = sdcp->buf1_phys; + + sdcp->buf2_desc = dma_alloc_coherent(sdcp->dev, + sizeof(struct dcp_hash_coherent_block), &hw_phys, + GFP_KERNEL); + if (sdcp->buf2_desc == NULL) { + printk(KERN_ERR "Error allocating coherent block\n"); + ret = -ENOMEM; + goto err_unregister_aes_cbc; + } + + sdcp->buf2_desc->my_phys = hw_phys; + sdcp->buf2_desc->src = (void *)sdcp->buf2; + sdcp->buf2_desc->src_phys = sdcp->buf2_phys; + + + ret = crypto_register_shash(&dcp_sha1_alg); + if (ret != 0) { + dev_err(&pdev->dev, "Failed to register sha1 hash\n"); + goto err_unregister_aes_cbc; + } + + if (__raw_readl(sdcp->dcp_regs_base + HW_DCP_CAPABILITY1) & + BF_DCP_CAPABILITY1_HASH_ALGORITHMS( + BV_DCP_CAPABILITY1_HASH_ALGORITHMS__SHA256)) { + + ret = crypto_register_shash(&dcp_sha256_alg); + if (ret != 0) { + dev_err(&pdev->dev, "Failed to register sha256 hash\n"); + goto err_unregister_sha1; + } + } + + /* register dcpboot interface to allow apps (such as kobs-ng) to + * verify files (such as the bootstream) using the OTP key for crypto */ + ret = misc_register(&dcp_bootstream_misc); + if (ret != 0) { + dev_err(&pdev->dev, "Unable to register misc device\n"); + goto err_unregister_sha1; + } + + sdcp->dcpboot_dma_area = dma_alloc_coherent(&pdev->dev, + sizeof(*sdcp->dcpboot_dma_area), &sdcp->dcpboot_dma_area_phys, + GFP_KERNEL); + if (sdcp->dcpboot_dma_area == NULL) { + dev_err(&pdev->dev, + "Unable to allocate DMAable memory \ + for dcpboot interface\n"); + goto err_dereg; + } + + dev_notice(&pdev->dev, "DCP crypto enabled.!\n"); + return 0; + +err_dereg: + misc_deregister(&dcp_bootstream_misc); +err_unregister_sha1: + crypto_unregister_shash(&dcp_sha1_alg); +err_unregister_aes_cbc: + crypto_unregister_alg(&dcp_aes_cbc_alg); +err_unregister_aes_ecb: + crypto_unregister_alg(&dcp_aes_ecb_alg); +err_unregister_aes: + crypto_unregister_alg(&dcp_aes_alg); +err_free_irq0: + free_irq(sdcp->dcp_vmi_irq, sdcp); +err_kfree: + kfree(sdcp); +err: + + return ret; +} + +static int dcp_remove(struct platform_device *pdev) +{ + struct dcp *sdcp; + + sdcp = platform_get_drvdata(pdev); + platform_set_drvdata(pdev, NULL); + + free_irq(sdcp->dcp_irq, sdcp); + free_irq(sdcp->dcp_vmi_irq, sdcp); + + /* if head and tail buffers were allocated, free them */ + if (sdcp->buf1) { + dma_free_coherent(sdcp->dev, 64, sdcp->buf1, sdcp->buf1_phys); + dma_free_coherent(sdcp->dev, 64, sdcp->buf2, sdcp->buf2_phys); + + dma_free_coherent(sdcp->dev, + sizeof(struct dcp_hash_coherent_block), + sdcp->buf1_desc, sdcp->buf1_desc->my_phys); + + dma_free_coherent(sdcp->dev, + sizeof(struct dcp_hash_coherent_block), + sdcp->buf2_desc, sdcp->buf2_desc->my_phys); + + dma_free_coherent(sdcp->dev, + sizeof(struct dcp_hash_coherent_block), + sdcp->user_buf_desc, sdcp->user_buf_desc->my_phys); + } + + if (sdcp->dcpboot_dma_area) { + dma_free_coherent(&pdev->dev, sizeof(*sdcp->dcpboot_dma_area), + sdcp->dcpboot_dma_area, sdcp->dcpboot_dma_area_phys); + misc_deregister(&dcp_bootstream_misc); + } + + + crypto_unregister_shash(&dcp_sha1_alg); + + if (__raw_readl(sdcp->dcp_regs_base + HW_DCP_CAPABILITY1) & + BF_DCP_CAPABILITY1_HASH_ALGORITHMS( + BV_DCP_CAPABILITY1_HASH_ALGORITHMS__SHA256)) + crypto_unregister_shash(&dcp_sha256_alg); + + crypto_unregister_alg(&dcp_aes_cbc_alg); + crypto_unregister_alg(&dcp_aes_ecb_alg); + crypto_unregister_alg(&dcp_aes_alg); + kfree(sdcp); + global_sdcp = NULL; + + return 0; +} + + +#ifdef CONFIG_PM +static int dcp_suspend(struct platform_device *pdev, + pm_message_t state) +{ + return 0; +} + +static int dcp_resume(struct platform_device *pdev) +{ + return 0; +} +#else +#define dcp_suspend NULL +#define dcp_resume NULL +#endif + +static struct platform_driver dcp_driver = { + .probe = dcp_probe, + .remove = dcp_remove, + .suspend = dcp_suspend, + .resume = dcp_resume, + .driver = { + .name = "dcp", + .owner = THIS_MODULE, + }, +}; + +static int __init +dcp_init(void) +{ + return platform_driver_register(&dcp_driver); +} + +static void __exit +dcp_exit(void) +{ + platform_driver_unregister(&dcp_driver); +} + +MODULE_AUTHOR("Pantelis Antoniou "); +MODULE_DESCRIPTION("DCP Crypto Driver"); +MODULE_LICENSE("GPL"); + +module_init(dcp_init); +module_exit(dcp_exit); diff --git a/drivers/crypto/dcp.h b/drivers/crypto/dcp.h new file mode 100644 index 000000000000..a4db91334d06 --- /dev/null +++ b/drivers/crypto/dcp.h @@ -0,0 +1,717 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#ifndef DCP_H_ +#define DCP_H_ + +#define CIPHER_CHAN 1 +#define CIPHER_MASK (1 << CIPHER_CHAN) + +#define HASH_CHAN 0 +#define HASH_MASK (1 << HASH_CHAN) + +/* DCP boostream interface uses this channel (same as the ROM) */ +#define ROM_DCP_CHAN 3 +#define ROM_DCP_CHAN_MASK (1 << ROM_DCP_CHAN) + + +#define ALL_MASK (CIPHER_MASK | HASH_MASK | ROM_DCP_CHAN_MASK) + +/* Defines the initialization value for the dcp control register */ +#define DCP_CTRL_INIT \ + (BM_DCP_CTRL_GATHER_RESIDUAL_WRITES | \ + BM_DCP_CTRL_ENABLE_CONTEXT_CACHING | \ + BV_DCP_CTRL_CHANNEL_INTERRUPT_ENABLE__CH0 | \ + BV_DCP_CTRL_CHANNEL_INTERRUPT_ENABLE__CH1 | \ + BV_DCP_CTRL_CHANNEL_INTERRUPT_ENABLE__CH2 | \ + BV_DCP_CTRL_CHANNEL_INTERRUPT_ENABLE__CH3) + +/* Defines the initialization value for the dcp channel control register */ +#define DCP_CHANNELCTRL_INIT \ + BF(ALL_MASK, DCP_CHANNELCTRL_ENABLE_CHANNEL) + +/* DCP work packet 1 value for encryption */ +#define DCP_PKT1_ENCRYPT \ + (BM_DCP_PACKET1_DECR_SEMAPHORE | \ + BM_DCP_PACKET1_ENABLE_CIPHER | \ + BM_DCP_PACKET1_CIPHER_ENCRYPT | \ + BM_DCP_PACKET1_CIPHER_INIT) + +/* DCP work packet 1 value for decryption */ +#define DCP_PKT1_DECRYPT \ + (BM_DCP_PACKET1_DECR_SEMAPHORE | \ + BM_DCP_PACKET1_ENABLE_CIPHER | \ + BM_DCP_PACKET1_CIPHER_INIT) + +/* DCP (decryption) work packet definition */ +struct dcp_hw_packet { + uint32_t pNext; /* next dcp work packet address */ + uint32_t pkt1; /* dcp work packet 1 (control 0) */ + uint32_t pkt2; /* dcp work packet 2 (control 1) */ + uint32_t pSrc; /* source buffer address */ + uint32_t pDst; /* destination buffer address */ + uint32_t size; /* buffer size in bytes */ + uint32_t pPayload; /* payload buffer address */ + uint32_t stat; /* dcp status (written by dcp) */ +}; + +#define DCP_NUM_CHANNELS 4 + +/* DCP Register definitions */ + +#ifndef BF +#define BF(value, field) (((value) << BP_##field) & BM_##field) +#endif + +#define REGS_DCP_SIZE 0x00002000 + +#define HW_DCP_CTRL (0x00000000) +#define HW_DCP_CTRL_SET (0x00000004) +#define HW_DCP_CTRL_CLR (0x00000008) +#define HW_DCP_CTRL_TOG (0x0000000c) + +#define BM_DCP_CTRL_SFTRST 0x80000000 +#define BM_DCP_CTRL_CLKGATE 0x40000000 +#define BM_DCP_CTRL_PRESENT_CRYPTO 0x20000000 +#define BV_DCP_CTRL_PRESENT_CRYPTO__Present 0x1 +#define BV_DCP_CTRL_PRESENT_CRYPTO__Absent 0x0 +#define BM_DCP_CTRL_PRESENT_CSC 0x10000000 +#define BV_DCP_CTRL_PRESENT_CSC__Present 0x1 +#define BV_DCP_CTRL_PRESENT_CSC__Absent 0x0 +#define BP_DCP_CTRL_RSVD1 24 +#define BM_DCP_CTRL_RSVD1 0x0F000000 +#define BF_DCP_CTRL_RSVD1(v) \ + (((v) << 24) & BM_DCP_CTRL_RSVD1) +#define BM_DCP_CTRL_GATHER_RESIDUAL_WRITES 0x00800000 +#define BM_DCP_CTRL_ENABLE_CONTEXT_CACHING 0x00400000 +#define BM_DCP_CTRL_ENABLE_CONTEXT_SWITCHING 0x00200000 +#define BP_DCP_CTRL_RSVD0 9 +#define BM_DCP_CTRL_RSVD0 0x001FFE00 +#define BF_DCP_CTRL_RSVD0(v) \ + (((v) << 9) & BM_DCP_CTRL_RSVD0) +#define BM_DCP_CTRL_CSC_INTERRUPT_ENABLE 0x00000100 +#define BP_DCP_CTRL_CHANNEL_INTERRUPT_ENABLE 0 +#define BM_DCP_CTRL_CHANNEL_INTERRUPT_ENABLE 0x000000FF +#define BF_DCP_CTRL_CHANNEL_INTERRUPT_ENABLE(v) \ + (((v) << 0) & BM_DCP_CTRL_CHANNEL_INTERRUPT_ENABLE) +#define BV_DCP_CTRL_CHANNEL_INTERRUPT_ENABLE__CH0 0x01 +#define BV_DCP_CTRL_CHANNEL_INTERRUPT_ENABLE__CH1 0x02 +#define BV_DCP_CTRL_CHANNEL_INTERRUPT_ENABLE__CH2 0x04 +#define BV_DCP_CTRL_CHANNEL_INTERRUPT_ENABLE__CH3 0x08 + +#define HW_DCP_STAT (0x00000010) +#define HW_DCP_STAT_SET (0x00000014) +#define HW_DCP_STAT_CLR (0x00000018) +#define HW_DCP_STAT_TOG (0x0000001c) + +#define BP_DCP_STAT_RSVD2 29 +#define BM_DCP_STAT_RSVD2 0xE0000000 +#define BF_DCP_STAT_RSVD2(v) \ + (((v) << 29) & BM_DCP_STAT_RSVD2) +#define BM_DCP_STAT_OTP_KEY_READY 0x10000000 +#define BP_DCP_STAT_CUR_CHANNEL 24 +#define BM_DCP_STAT_CUR_CHANNEL 0x0F000000 +#define BF_DCP_STAT_CUR_CHANNEL(v) \ + (((v) << 24) & BM_DCP_STAT_CUR_CHANNEL) +#define BV_DCP_STAT_CUR_CHANNEL__None 0x0 +#define BV_DCP_STAT_CUR_CHANNEL__CH0 0x1 +#define BV_DCP_STAT_CUR_CHANNEL__CH1 0x2 +#define BV_DCP_STAT_CUR_CHANNEL__CH2 0x3 +#define BV_DCP_STAT_CUR_CHANNEL__CH3 0x4 +#define BV_DCP_STAT_CUR_CHANNEL__CSC 0x8 +#define BP_DCP_STAT_READY_CHANNELS 16 +#define BM_DCP_STAT_READY_CHANNELS 0x00FF0000 +#define BF_DCP_STAT_READY_CHANNELS(v) \ + (((v) << 16) & BM_DCP_STAT_READY_CHANNELS) +#define BV_DCP_STAT_READY_CHANNELS__CH0 0x01 +#define BV_DCP_STAT_READY_CHANNELS__CH1 0x02 +#define BV_DCP_STAT_READY_CHANNELS__CH2 0x04 +#define BV_DCP_STAT_READY_CHANNELS__CH3 0x08 +#define BP_DCP_STAT_RSVD1 9 +#define BM_DCP_STAT_RSVD1 0x0000FE00 +#define BF_DCP_STAT_RSVD1(v) \ + (((v) << 9) & BM_DCP_STAT_RSVD1) +#define BM_DCP_STAT_CSCIRQ 0x00000100 +#define BP_DCP_STAT_RSVD0 4 +#define BM_DCP_STAT_RSVD0 0x000000F0 +#define BF_DCP_STAT_RSVD0(v) \ + (((v) << 4) & BM_DCP_STAT_RSVD0) +#define BP_DCP_STAT_IRQ 0 +#define BM_DCP_STAT_IRQ 0x0000000F +#define BF_DCP_STAT_IRQ(v) \ + (((v) << 0) & BM_DCP_STAT_IRQ) + +#define HW_DCP_CHANNELCTRL (0x00000020) +#define HW_DCP_CHANNELCTRL_SET (0x00000024) +#define HW_DCP_CHANNELCTRL_CLR (0x00000028) +#define HW_DCP_CHANNELCTRL_TOG (0x0000002c) + +#define BP_DCP_CHANNELCTRL_RSVD 19 +#define BM_DCP_CHANNELCTRL_RSVD 0xFFF80000 +#define BF_DCP_CHANNELCTRL_RSVD(v) \ + (((v) << 19) & BM_DCP_CHANNELCTRL_RSVD) +#define BP_DCP_CHANNELCTRL_CSC_PRIORITY 17 +#define BM_DCP_CHANNELCTRL_CSC_PRIORITY 0x00060000 +#define BF_DCP_CHANNELCTRL_CSC_PRIORITY(v) \ + (((v) << 17) & BM_DCP_CHANNELCTRL_CSC_PRIORITY) +#define BV_DCP_CHANNELCTRL_CSC_PRIORITY__HIGH 0x3 +#define BV_DCP_CHANNELCTRL_CSC_PRIORITY__MED 0x2 +#define BV_DCP_CHANNELCTRL_CSC_PRIORITY__LOW 0x1 +#define BV_DCP_CHANNELCTRL_CSC_PRIORITY__BACKGROUND 0x0 +#define BM_DCP_CHANNELCTRL_CH0_IRQ_MERGED 0x00010000 +#define BP_DCP_CHANNELCTRL_HIGH_PRIORITY_CHANNEL 8 +#define BM_DCP_CHANNELCTRL_HIGH_PRIORITY_CHANNEL 0x0000FF00 +#define BF_DCP_CHANNELCTRL_HIGH_PRIORITY_CHANNEL(v) \ + (((v) << 8) & BM_DCP_CHANNELCTRL_HIGH_PRIORITY_CHANNEL) +#define BV_DCP_CHANNELCTRL_HIGH_PRIORITY_CHANNEL__CH0 0x01 +#define BV_DCP_CHANNELCTRL_HIGH_PRIORITY_CHANNEL__CH1 0x02 +#define BV_DCP_CHANNELCTRL_HIGH_PRIORITY_CHANNEL__CH2 0x04 +#define BV_DCP_CHANNELCTRL_HIGH_PRIORITY_CHANNEL__CH3 0x08 +#define BP_DCP_CHANNELCTRL_ENABLE_CHANNEL 0 +#define BM_DCP_CHANNELCTRL_ENABLE_CHANNEL 0x000000FF +#define BF_DCP_CHANNELCTRL_ENABLE_CHANNEL(v) \ + (((v) << 0) & BM_DCP_CHANNELCTRL_ENABLE_CHANNEL) +#define BV_DCP_CHANNELCTRL_ENABLE_CHANNEL__CH0 0x01 +#define BV_DCP_CHANNELCTRL_ENABLE_CHANNEL__CH1 0x02 +#define BV_DCP_CHANNELCTRL_ENABLE_CHANNEL__CH2 0x04 +#define BV_DCP_CHANNELCTRL_ENABLE_CHANNEL__CH3 0x08 + +#define HW_DCP_CAPABILITY0 (0x00000030) + +#define BM_DCP_CAPABILITY0_DISABLE_DECRYPT 0x80000000 +#define BM_DCP_CAPABILITY0_ENABLE_TZONE 0x40000000 +#define BP_DCP_CAPABILITY0_RSVD 12 +#define BM_DCP_CAPABILITY0_RSVD 0x3FFFF000 +#define BF_DCP_CAPABILITY0_RSVD(v) \ + (((v) << 12) & BM_DCP_CAPABILITY0_RSVD) +#define BP_DCP_CAPABILITY0_NUM_CHANNELS 8 +#define BM_DCP_CAPABILITY0_NUM_CHANNELS 0x00000F00 +#define BF_DCP_CAPABILITY0_NUM_CHANNELS(v) \ + (((v) << 8) & BM_DCP_CAPABILITY0_NUM_CHANNELS) +#define BP_DCP_CAPABILITY0_NUM_KEYS 0 +#define BM_DCP_CAPABILITY0_NUM_KEYS 0x000000FF +#define BF_DCP_CAPABILITY0_NUM_KEYS(v) \ + (((v) << 0) & BM_DCP_CAPABILITY0_NUM_KEYS) + +#define HW_DCP_CAPABILITY1 (0x00000040) + +#define BP_DCP_CAPABILITY1_HASH_ALGORITHMS 16 +#define BM_DCP_CAPABILITY1_HASH_ALGORITHMS 0xFFFF0000 +#define BF_DCP_CAPABILITY1_HASH_ALGORITHMS(v) \ + (((v) << 16) & BM_DCP_CAPABILITY1_HASH_ALGORITHMS) +#define BV_DCP_CAPABILITY1_HASH_ALGORITHMS__SHA1 0x0001 +#define BV_DCP_CAPABILITY1_HASH_ALGORITHMS__CRC32 0x0002 +#define BV_DCP_CAPABILITY1_HASH_ALGORITHMS__SHA256 0x0004 +#define BP_DCP_CAPABILITY1_CIPHER_ALGORITHMS 0 +#define BM_DCP_CAPABILITY1_CIPHER_ALGORITHMS 0x0000FFFF +#define BF_DCP_CAPABILITY1_CIPHER_ALGORITHMS(v) \ + (((v) << 0) & BM_DCP_CAPABILITY1_CIPHER_ALGORITHMS) +#define BV_DCP_CAPABILITY1_CIPHER_ALGORITHMS__AES128 0x0001 + +#define HW_DCP_CONTEXT (0x00000050) + +#define BP_DCP_CONTEXT_ADDR 0 +#define BM_DCP_CONTEXT_ADDR 0xFFFFFFFF +#define BF_DCP_CONTEXT_ADDR(v) (v) + +#define HW_DCP_KEY (0x00000060) + +#define BP_DCP_KEY_RSVD 8 +#define BM_DCP_KEY_RSVD 0xFFFFFF00 +#define BF_DCP_KEY_RSVD(v) \ + (((v) << 8) & BM_DCP_KEY_RSVD) +#define BP_DCP_KEY_RSVD_INDEX 6 +#define BM_DCP_KEY_RSVD_INDEX 0x000000C0 +#define BF_DCP_KEY_RSVD_INDEX(v) \ + (((v) << 6) & BM_DCP_KEY_RSVD_INDEX) +#define BP_DCP_KEY_INDEX 4 +#define BM_DCP_KEY_INDEX 0x00000030 +#define BF_DCP_KEY_INDEX(v) \ + (((v) << 4) & BM_DCP_KEY_INDEX) +#define BP_DCP_KEY_RSVD_SUBWORD 2 +#define BM_DCP_KEY_RSVD_SUBWORD 0x0000000C +#define BF_DCP_KEY_RSVD_SUBWORD(v) \ + (((v) << 2) & BM_DCP_KEY_RSVD_SUBWORD) +#define BP_DCP_KEY_SUBWORD 0 +#define BM_DCP_KEY_SUBWORD 0x00000003 +#define BF_DCP_KEY_SUBWORD(v) \ + (((v) << 0) & BM_DCP_KEY_SUBWORD) + +#define HW_DCP_KEYDATA (0x00000070) + +#define BP_DCP_KEYDATA_DATA 0 +#define BM_DCP_KEYDATA_DATA 0xFFFFFFFF +#define BF_DCP_KEYDATA_DATA(v) (v) + +#define HW_DCP_PACKET0 (0x00000080) + +#define BP_DCP_PACKET0_ADDR 0 +#define BM_DCP_PACKET0_ADDR 0xFFFFFFFF +#define BF_DCP_PACKET0_ADDR(v) (v) + +#define HW_DCP_PACKET1 (0x00000090) + +#define BP_DCP_PACKET1_TAG 24 +#define BM_DCP_PACKET1_TAG 0xFF000000 +#define BF_DCP_PACKET1_TAG(v) \ + (((v) << 24) & BM_DCP_PACKET1_TAG) +#define BM_DCP_PACKET1_OUTPUT_WORDSWAP 0x00800000 +#define BM_DCP_PACKET1_OUTPUT_BYTESWAP 0x00400000 +#define BM_DCP_PACKET1_INPUT_WORDSWAP 0x00200000 +#define BM_DCP_PACKET1_INPUT_BYTESWAP 0x00100000 +#define BM_DCP_PACKET1_KEY_WORDSWAP 0x00080000 +#define BM_DCP_PACKET1_KEY_BYTESWAP 0x00040000 +#define BM_DCP_PACKET1_TEST_SEMA_IRQ 0x00020000 +#define BM_DCP_PACKET1_CONSTANT_FILL 0x00010000 +#define BM_DCP_PACKET1_HASH_OUTPUT 0x00008000 +#define BV_DCP_PACKET1_HASH_OUTPUT__INPUT 0x00 +#define BV_DCP_PACKET1_HASH_OUTPUT__OUTPUT 0x01 +#define BM_DCP_PACKET1_CHECK_HASH 0x00004000 +#define BM_DCP_PACKET1_HASH_TERM 0x00002000 +#define BM_DCP_PACKET1_HASH_INIT 0x00001000 +#define BM_DCP_PACKET1_PAYLOAD_KEY 0x00000800 +#define BM_DCP_PACKET1_OTP_KEY 0x00000400 +#define BM_DCP_PACKET1_CIPHER_INIT 0x00000200 +#define BM_DCP_PACKET1_CIPHER_ENCRYPT 0x00000100 +#define BV_DCP_PACKET1_CIPHER_ENCRYPT__ENCRYPT 0x01 +#define BV_DCP_PACKET1_CIPHER_ENCRYPT__DECRYPT 0x00 +#define BM_DCP_PACKET1_ENABLE_BLIT 0x00000080 +#define BM_DCP_PACKET1_ENABLE_HASH 0x00000040 +#define BM_DCP_PACKET1_ENABLE_CIPHER 0x00000020 +#define BM_DCP_PACKET1_ENABLE_MEMCOPY 0x00000010 +#define BM_DCP_PACKET1_CHAIN_CONTIGUOUS 0x00000008 +#define BM_DCP_PACKET1_CHAIN 0x00000004 +#define BM_DCP_PACKET1_DECR_SEMAPHORE 0x00000002 +#define BM_DCP_PACKET1_INTERRUPT 0x00000001 + +#define HW_DCP_PACKET2 (0x000000a0) + +#define BP_DCP_PACKET2_CIPHER_CFG 24 +#define BM_DCP_PACKET2_CIPHER_CFG 0xFF000000 +#define BF_DCP_PACKET2_CIPHER_CFG(v) \ + (((v) << 24) & BM_DCP_PACKET2_CIPHER_CFG) +#define BP_DCP_PACKET2_RSVD 20 +#define BM_DCP_PACKET2_RSVD 0x00F00000 +#define BF_DCP_PACKET2_RSVD(v) \ + (((v) << 20) & BM_DCP_PACKET2_RSVD) +#define BP_DCP_PACKET2_HASH_SELECT 16 +#define BM_DCP_PACKET2_HASH_SELECT 0x000F0000 +#define BF_DCP_PACKET2_HASH_SELECT(v) \ + (((v) << 16) & BM_DCP_PACKET2_HASH_SELECT) +#define BV_DCP_PACKET2_HASH_SELECT__SHA1 0x00 +#define BV_DCP_PACKET2_HASH_SELECT__CRC32 0x01 +#define BV_DCP_PACKET2_HASH_SELECT__SHA256 0x02 +#define BP_DCP_PACKET2_KEY_SELECT 8 +#define BM_DCP_PACKET2_KEY_SELECT 0x0000FF00 +#define BF_DCP_PACKET2_KEY_SELECT(v) \ + (((v) << 8) & BM_DCP_PACKET2_KEY_SELECT) +#define BP_DCP_PACKET2_CIPHER_MODE 4 +#define BM_DCP_PACKET2_CIPHER_MODE 0x000000F0 +#define BF_DCP_PACKET2_CIPHER_MODE(v) \ + (((v) << 4) & BM_DCP_PACKET2_CIPHER_MODE) +#define BV_DCP_PACKET2_CIPHER_MODE__ECB 0x00 +#define BV_DCP_PACKET2_CIPHER_MODE__CBC 0x01 +#define BP_DCP_PACKET2_CIPHER_SELECT 0 +#define BM_DCP_PACKET2_CIPHER_SELECT 0x0000000F +#define BF_DCP_PACKET2_CIPHER_SELECT(v) \ + (((v) << 0) & BM_DCP_PACKET2_CIPHER_SELECT) +#define BV_DCP_PACKET2_CIPHER_SELECT__AES128 0x00 + +#define HW_DCP_PACKET3 (0x000000b0) + +#define BP_DCP_PACKET3_ADDR 0 +#define BM_DCP_PACKET3_ADDR 0xFFFFFFFF +#define BF_DCP_PACKET3_ADDR(v) (v) + +#define HW_DCP_PACKET4 (0x000000c0) + +#define BP_DCP_PACKET4_ADDR 0 +#define BM_DCP_PACKET4_ADDR 0xFFFFFFFF +#define BF_DCP_PACKET4_ADDR(v) (v) + +#define HW_DCP_PACKET5 (0x000000d0) + +#define BP_DCP_PACKET5_COUNT 0 +#define BM_DCP_PACKET5_COUNT 0xFFFFFFFF +#define BF_DCP_PACKET5_COUNT(v) (v) + +#define HW_DCP_PACKET6 (0x000000e0) + +#define BP_DCP_PACKET6_ADDR 0 +#define BM_DCP_PACKET6_ADDR 0xFFFFFFFF +#define BF_DCP_PACKET6_ADDR(v) (v) + +/* + * multi-register-define name HW_DCP_CHnCMDPTR + * base 0x00000100 + * count 4 + * offset 0x40 + */ +#define HW_DCP_CHnCMDPTR(n) (0x00000100 + (n) * 0x40) + +#define BP_DCP_CHnCMDPTR_ADDR 0 +#define BM_DCP_CHnCMDPTR_ADDR 0xFFFFFFFF +#define BF_DCP_CHnCMDPTR_ADDR(v) (v) + +/* + * multi-register-define name HW_DCP_CHnSEMA + * base 0x00000110 + * count 4 + * offset 0x40 + */ +#define HW_DCP_CHnSEMA(n) (0x00000110 + (n) * 0x40) + +#define BP_DCP_CHnSEMA_RSVD2 24 +#define BM_DCP_CHnSEMA_RSVD2 0xFF000000 +#define BF_DCP_CHnSEMA_RSVD2(v) \ + (((v) << 24) & BM_DCP_CHnSEMA_RSVD2) +#define BP_DCP_CHnSEMA_VALUE 16 +#define BM_DCP_CHnSEMA_VALUE 0x00FF0000 +#define BF_DCP_CHnSEMA_VALUE(v) \ + (((v) << 16) & BM_DCP_CHnSEMA_VALUE) +#define BP_DCP_CHnSEMA_RSVD1 8 +#define BM_DCP_CHnSEMA_RSVD1 0x0000FF00 +#define BF_DCP_CHnSEMA_RSVD1(v) \ + (((v) << 8) & BM_DCP_CHnSEMA_RSVD1) +#define BP_DCP_CHnSEMA_INCREMENT 0 +#define BM_DCP_CHnSEMA_INCREMENT 0x000000FF +#define BF_DCP_CHnSEMA_INCREMENT(v) \ + (((v) << 0) & BM_DCP_CHnSEMA_INCREMENT) + +/* + * multi-register-define name HW_DCP_CHnSTAT + * base 0x00000120 + * count 4 + * offset 0x40 + */ +#define HW_DCP_CHnSTAT(n) (0x00000120 + (n) * 0x40) +#define HW_DCP_CHnSTAT_SET(n) (0x00000124 + (n) * 0x40) +#define HW_DCP_CHnSTAT_CLR(n) (0x00000128 + (n) * 0x40) +#define HW_DCP_CHnSTAT_TOG(n) (0x0000012c + (n) * 0x40) + +#define BP_DCP_CHnSTAT_TAG 24 +#define BM_DCP_CHnSTAT_TAG 0xFF000000 +#define BF_DCP_CHnSTAT_TAG(v) \ + (((v) << 24) & BM_DCP_CHnSTAT_TAG) +#define BP_DCP_CHnSTAT_ERROR_CODE 16 +#define BM_DCP_CHnSTAT_ERROR_CODE 0x00FF0000 +#define BF_DCP_CHnSTAT_ERROR_CODE(v) \ + (((v) << 16) & BM_DCP_CHnSTAT_ERROR_CODE) +#define BV_DCP_CHnSTAT_ERROR_CODE__NEXT_CHAIN_IS_0 0x01 +#define BV_DCP_CHnSTAT_ERROR_CODE__NO_CHAIN 0x02 +#define BV_DCP_CHnSTAT_ERROR_CODE__CONTEXT_ERROR 0x03 +#define BV_DCP_CHnSTAT_ERROR_CODE__PAYLOAD_ERROR 0x04 +#define BV_DCP_CHnSTAT_ERROR_CODE__INVALID_MODE 0x05 +#define BP_DCP_CHnSTAT_RSVD0 7 +#define BM_DCP_CHnSTAT_RSVD0 0x0000FF80 +#define BF_DCP_CHnSTAT_RSVD0(v) \ + (((v) << 7) & BM_DCP_CHnSTAT_RSVD0) +#define BM_DCP_CHnSTAT_ERROR_PAGEFAULT 0x00000040 +#define BM_DCP_CHnSTAT_ERROR_DST 0x00000020 +#define BM_DCP_CHnSTAT_ERROR_SRC 0x00000010 +#define BM_DCP_CHnSTAT_ERROR_PACKET 0x00000008 +#define BM_DCP_CHnSTAT_ERROR_SETUP 0x00000004 +#define BM_DCP_CHnSTAT_HASH_MISMATCH 0x00000002 +#define BM_DCP_CHnSTAT_RSVD_COMPLETE 0x00000001 + +/* + * multi-register-define name HW_DCP_CHnOPTS + * base 0x00000130 + * count 4 + * offset 0x40 + */ +#define HW_DCP_CHnOPTS(n) (0x00000130 + (n) * 0x40) +#define HW_DCP_CHnOPTS_SET(n) (0x00000134 + (n) * 0x40) +#define HW_DCP_CHnOPTS_CLR(n) (0x00000138 + (n) * 0x40) +#define HW_DCP_CHnOPTS_TOG(n) (0x0000013c + (n) * 0x40) + +#define BP_DCP_CHnOPTS_RSVD 16 +#define BM_DCP_CHnOPTS_RSVD 0xFFFF0000 +#define BF_DCP_CHnOPTS_RSVD(v) \ + (((v) << 16) & BM_DCP_CHnOPTS_RSVD) +#define BP_DCP_CHnOPTS_RECOVERY_TIMER 0 +#define BM_DCP_CHnOPTS_RECOVERY_TIMER 0x0000FFFF +#define BF_DCP_CHnOPTS_RECOVERY_TIMER(v) \ + (((v) << 0) & BM_DCP_CHnOPTS_RECOVERY_TIMER) + +#define HW_DCP_CSCCTRL0 (0x00000300) +#define HW_DCP_CSCCTRL0_SET (0x00000304) +#define HW_DCP_CSCCTRL0_CLR (0x00000308) +#define HW_DCP_CSCCTRL0_TOG (0x0000030c) + +#define BP_DCP_CSCCTRL0_RSVD1 16 +#define BM_DCP_CSCCTRL0_RSVD1 0xFFFF0000 +#define BF_DCP_CSCCTRL0_RSVD1(v) \ + (((v) << 16) & BM_DCP_CSCCTRL0_RSVD1) +#define BM_DCP_CSCCTRL0_CLIP 0x00008000 +#define BM_DCP_CSCCTRL0_UPSAMPLE 0x00004000 +#define BM_DCP_CSCCTRL0_SCALE 0x00002000 +#define BM_DCP_CSCCTRL0_ROTATE 0x00001000 +#define BM_DCP_CSCCTRL0_SUBSAMPLE 0x00000800 +#define BM_DCP_CSCCTRL0_DELTA 0x00000400 +#define BP_DCP_CSCCTRL0_RGB_FORMAT 8 +#define BM_DCP_CSCCTRL0_RGB_FORMAT 0x00000300 +#define BF_DCP_CSCCTRL0_RGB_FORMAT(v) \ + (((v) << 8) & BM_DCP_CSCCTRL0_RGB_FORMAT) +#define BV_DCP_CSCCTRL0_RGB_FORMAT__RGB16_565 0x0 +#define BV_DCP_CSCCTRL0_RGB_FORMAT__YCbCrI 0x1 +#define BV_DCP_CSCCTRL0_RGB_FORMAT__RGB24 0x2 +#define BV_DCP_CSCCTRL0_RGB_FORMAT__YUV422I 0x3 +#define BP_DCP_CSCCTRL0_YUV_FORMAT 4 +#define BM_DCP_CSCCTRL0_YUV_FORMAT 0x000000F0 +#define BF_DCP_CSCCTRL0_YUV_FORMAT(v) \ + (((v) << 4) & BM_DCP_CSCCTRL0_YUV_FORMAT) +#define BV_DCP_CSCCTRL0_YUV_FORMAT__YUV420 0x0 +#define BV_DCP_CSCCTRL0_YUV_FORMAT__YUV422 0x2 +#define BP_DCP_CSCCTRL0_RSVD0 1 +#define BM_DCP_CSCCTRL0_RSVD0 0x0000000E +#define BF_DCP_CSCCTRL0_RSVD0(v) \ + (((v) << 1) & BM_DCP_CSCCTRL0_RSVD0) +#define BM_DCP_CSCCTRL0_ENABLE 0x00000001 + +#define HW_DCP_CSCSTAT (0x00000310) +#define HW_DCP_CSCSTAT_SET (0x00000314) +#define HW_DCP_CSCSTAT_CLR (0x00000318) +#define HW_DCP_CSCSTAT_TOG (0x0000031c) + +#define BP_DCP_CSCSTAT_RSVD3 24 +#define BM_DCP_CSCSTAT_RSVD3 0xFF000000 +#define BF_DCP_CSCSTAT_RSVD3(v) \ + (((v) << 24) & BM_DCP_CSCSTAT_RSVD3) +#define BP_DCP_CSCSTAT_ERROR_CODE 16 +#define BM_DCP_CSCSTAT_ERROR_CODE 0x00FF0000 +#define BF_DCP_CSCSTAT_ERROR_CODE(v) \ + (((v) << 16) & BM_DCP_CSCSTAT_ERROR_CODE) +#define BV_DCP_CSCSTAT_ERROR_CODE__LUMA0_FETCH_ERROR_Y0 0x01 +#define BV_DCP_CSCSTAT_ERROR_CODE__LUMA1_FETCH_ERROR_Y1 0x02 +#define BV_DCP_CSCSTAT_ERROR_CODE__CHROMA_FETCH_ERROR_U 0x03 +#define BV_DCP_CSCSTAT_ERROR_CODE__CHROMA_FETCH_ERROR_V 0x04 +#define BP_DCP_CSCSTAT_RSVD2 7 +#define BM_DCP_CSCSTAT_RSVD2 0x0000FF80 +#define BF_DCP_CSCSTAT_RSVD2(v) \ + (((v) << 7) & BM_DCP_CSCSTAT_RSVD2) +#define BM_DCP_CSCSTAT_ERROR_PAGEFAULT 0x00000040 +#define BM_DCP_CSCSTAT_ERROR_DST 0x00000020 +#define BM_DCP_CSCSTAT_ERROR_SRC 0x00000010 +#define BM_DCP_CSCSTAT_RSVD1 0x00000008 +#define BM_DCP_CSCSTAT_ERROR_SETUP 0x00000004 +#define BM_DCP_CSCSTAT_RSVD0 0x00000002 +#define BM_DCP_CSCSTAT_COMPLETE 0x00000001 + +#define HW_DCP_CSCOUTBUFPARAM (0x00000320) + +#define BP_DCP_CSCOUTBUFPARAM_RSVD1 24 +#define BM_DCP_CSCOUTBUFPARAM_RSVD1 0xFF000000 +#define BF_DCP_CSCOUTBUFPARAM_RSVD1(v) \ + (((v) << 24) & BM_DCP_CSCOUTBUFPARAM_RSVD1) +#define BP_DCP_CSCOUTBUFPARAM_FIELD_SIZE 12 +#define BM_DCP_CSCOUTBUFPARAM_FIELD_SIZE 0x00FFF000 +#define BF_DCP_CSCOUTBUFPARAM_FIELD_SIZE(v) \ + (((v) << 12) & BM_DCP_CSCOUTBUFPARAM_FIELD_SIZE) +#define BP_DCP_CSCOUTBUFPARAM_LINE_SIZE 0 +#define BM_DCP_CSCOUTBUFPARAM_LINE_SIZE 0x00000FFF +#define BF_DCP_CSCOUTBUFPARAM_LINE_SIZE(v) \ + (((v) << 0) & BM_DCP_CSCOUTBUFPARAM_LINE_SIZE) + +#define HW_DCP_CSCINBUFPARAM (0x00000330) + +#define BP_DCP_CSCINBUFPARAM_RSVD1 12 +#define BM_DCP_CSCINBUFPARAM_RSVD1 0xFFFFF000 +#define BF_DCP_CSCINBUFPARAM_RSVD1(v) \ + (((v) << 12) & BM_DCP_CSCINBUFPARAM_RSVD1) +#define BP_DCP_CSCINBUFPARAM_LINE_SIZE 0 +#define BM_DCP_CSCINBUFPARAM_LINE_SIZE 0x00000FFF +#define BF_DCP_CSCINBUFPARAM_LINE_SIZE(v) \ + (((v) << 0) & BM_DCP_CSCINBUFPARAM_LINE_SIZE) + +#define HW_DCP_CSCRGB (0x00000340) + +#define BP_DCP_CSCRGB_ADDR 0 +#define BM_DCP_CSCRGB_ADDR 0xFFFFFFFF +#define BF_DCP_CSCRGB_ADDR(v) (v) + +#define HW_DCP_CSCLUMA (0x00000350) + +#define BP_DCP_CSCLUMA_ADDR 0 +#define BM_DCP_CSCLUMA_ADDR 0xFFFFFFFF +#define BF_DCP_CSCLUMA_ADDR(v) (v) + +#define HW_DCP_CSCCHROMAU (0x00000360) + +#define BP_DCP_CSCCHROMAU_ADDR 0 +#define BM_DCP_CSCCHROMAU_ADDR 0xFFFFFFFF +#define BF_DCP_CSCCHROMAU_ADDR(v) (v) + +#define HW_DCP_CSCCHROMAV (0x00000370) + +#define BP_DCP_CSCCHROMAV_ADDR 0 +#define BM_DCP_CSCCHROMAV_ADDR 0xFFFFFFFF +#define BF_DCP_CSCCHROMAV_ADDR(v) (v) + +#define HW_DCP_CSCCOEFF0 (0x00000380) + +#define BP_DCP_CSCCOEFF0_RSVD1 26 +#define BM_DCP_CSCCOEFF0_RSVD1 0xFC000000 +#define BF_DCP_CSCCOEFF0_RSVD1(v) \ + (((v) << 26) & BM_DCP_CSCCOEFF0_RSVD1) +#define BP_DCP_CSCCOEFF0_C0 16 +#define BM_DCP_CSCCOEFF0_C0 0x03FF0000 +#define BF_DCP_CSCCOEFF0_C0(v) \ + (((v) << 16) & BM_DCP_CSCCOEFF0_C0) +#define BP_DCP_CSCCOEFF0_UV_OFFSET 8 +#define BM_DCP_CSCCOEFF0_UV_OFFSET 0x0000FF00 +#define BF_DCP_CSCCOEFF0_UV_OFFSET(v) \ + (((v) << 8) & BM_DCP_CSCCOEFF0_UV_OFFSET) +#define BP_DCP_CSCCOEFF0_Y_OFFSET 0 +#define BM_DCP_CSCCOEFF0_Y_OFFSET 0x000000FF +#define BF_DCP_CSCCOEFF0_Y_OFFSET(v) \ + (((v) << 0) & BM_DCP_CSCCOEFF0_Y_OFFSET) + +#define HW_DCP_CSCCOEFF1 (0x00000390) + +#define BP_DCP_CSCCOEFF1_RSVD1 26 +#define BM_DCP_CSCCOEFF1_RSVD1 0xFC000000 +#define BF_DCP_CSCCOEFF1_RSVD1(v) \ + (((v) << 26) & BM_DCP_CSCCOEFF1_RSVD1) +#define BP_DCP_CSCCOEFF1_C1 16 +#define BM_DCP_CSCCOEFF1_C1 0x03FF0000 +#define BF_DCP_CSCCOEFF1_C1(v) \ + (((v) << 16) & BM_DCP_CSCCOEFF1_C1) +#define BP_DCP_CSCCOEFF1_RSVD0 10 +#define BM_DCP_CSCCOEFF1_RSVD0 0x0000FC00 +#define BF_DCP_CSCCOEFF1_RSVD0(v) \ + (((v) << 10) & BM_DCP_CSCCOEFF1_RSVD0) +#define BP_DCP_CSCCOEFF1_C4 0 +#define BM_DCP_CSCCOEFF1_C4 0x000003FF +#define BF_DCP_CSCCOEFF1_C4(v) \ + (((v) << 0) & BM_DCP_CSCCOEFF1_C4) + +#define HW_DCP_CSCCOEFF2 (0x000003a0) + +#define BP_DCP_CSCCOEFF2_RSVD1 26 +#define BM_DCP_CSCCOEFF2_RSVD1 0xFC000000 +#define BF_DCP_CSCCOEFF2_RSVD1(v) \ + (((v) << 26) & BM_DCP_CSCCOEFF2_RSVD1) +#define BP_DCP_CSCCOEFF2_C2 16 +#define BM_DCP_CSCCOEFF2_C2 0x03FF0000 +#define BF_DCP_CSCCOEFF2_C2(v) \ + (((v) << 16) & BM_DCP_CSCCOEFF2_C2) +#define BP_DCP_CSCCOEFF2_RSVD0 10 +#define BM_DCP_CSCCOEFF2_RSVD0 0x0000FC00 +#define BF_DCP_CSCCOEFF2_RSVD0(v) \ + (((v) << 10) & BM_DCP_CSCCOEFF2_RSVD0) +#define BP_DCP_CSCCOEFF2_C3 0 +#define BM_DCP_CSCCOEFF2_C3 0x000003FF +#define BF_DCP_CSCCOEFF2_C3(v) \ + (((v) << 0) & BM_DCP_CSCCOEFF2_C3) + +#define HW_DCP_CSCCLIP (0x000003d0) + +#define BP_DCP_CSCCLIP_RSVD1 24 +#define BM_DCP_CSCCLIP_RSVD1 0xFF000000 +#define BF_DCP_CSCCLIP_RSVD1(v) \ + (((v) << 24) & BM_DCP_CSCCLIP_RSVD1) +#define BP_DCP_CSCCLIP_HEIGHT 12 +#define BM_DCP_CSCCLIP_HEIGHT 0x00FFF000 +#define BF_DCP_CSCCLIP_HEIGHT(v) \ + (((v) << 12) & BM_DCP_CSCCLIP_HEIGHT) +#define BP_DCP_CSCCLIP_WIDTH 0 +#define BM_DCP_CSCCLIP_WIDTH 0x00000FFF +#define BF_DCP_CSCCLIP_WIDTH(v) \ + (((v) << 0) & BM_DCP_CSCCLIP_WIDTH) + +#define HW_DCP_CSCXSCALE (0x000003e0) + +#define BP_DCP_CSCXSCALE_RSVD1 26 +#define BM_DCP_CSCXSCALE_RSVD1 0xFC000000 +#define BF_DCP_CSCXSCALE_RSVD1(v) \ + (((v) << 26) & BM_DCP_CSCXSCALE_RSVD1) +#define BP_DCP_CSCXSCALE_INT 24 +#define BM_DCP_CSCXSCALE_INT 0x03000000 +#define BF_DCP_CSCXSCALE_INT(v) \ + (((v) << 24) & BM_DCP_CSCXSCALE_INT) +#define BP_DCP_CSCXSCALE_FRAC 12 +#define BM_DCP_CSCXSCALE_FRAC 0x00FFF000 +#define BF_DCP_CSCXSCALE_FRAC(v) \ + (((v) << 12) & BM_DCP_CSCXSCALE_FRAC) +#define BP_DCP_CSCXSCALE_WIDTH 0 +#define BM_DCP_CSCXSCALE_WIDTH 0x00000FFF +#define BF_DCP_CSCXSCALE_WIDTH(v) \ + (((v) << 0) & BM_DCP_CSCXSCALE_WIDTH) + +#define HW_DCP_CSCYSCALE (0x000003f0) + +#define BP_DCP_CSCYSCALE_RSVD1 26 +#define BM_DCP_CSCYSCALE_RSVD1 0xFC000000 +#define BF_DCP_CSCYSCALE_RSVD1(v) \ + (((v) << 26) & BM_DCP_CSCYSCALE_RSVD1) +#define BP_DCP_CSCYSCALE_INT 24 +#define BM_DCP_CSCYSCALE_INT 0x03000000 +#define BF_DCP_CSCYSCALE_INT(v) \ + (((v) << 24) & BM_DCP_CSCYSCALE_INT) +#define BP_DCP_CSCYSCALE_FRAC 12 +#define BM_DCP_CSCYSCALE_FRAC 0x00FFF000 +#define BF_DCP_CSCYSCALE_FRAC(v) \ + (((v) << 12) & BM_DCP_CSCYSCALE_FRAC) +#define BP_DCP_CSCYSCALE_HEIGHT 0 +#define BM_DCP_CSCYSCALE_HEIGHT 0x00000FFF +#define BF_DCP_CSCYSCALE_HEIGHT(v) \ + (((v) << 0) & BM_DCP_CSCYSCALE_HEIGHT) + +#define HW_DCP_DBGSELECT (0x00000400) + +#define BP_DCP_DBGSELECT_RSVD 8 +#define BM_DCP_DBGSELECT_RSVD 0xFFFFFF00 +#define BF_DCP_DBGSELECT_RSVD(v) \ + (((v) << 8) & BM_DCP_DBGSELECT_RSVD) +#define BP_DCP_DBGSELECT_INDEX 0 +#define BM_DCP_DBGSELECT_INDEX 0x000000FF +#define BF_DCP_DBGSELECT_INDEX(v) \ + (((v) << 0) & BM_DCP_DBGSELECT_INDEX) +#define BV_DCP_DBGSELECT_INDEX__CONTROL 0x01 +#define BV_DCP_DBGSELECT_INDEX__OTPKEY0 0x10 +#define BV_DCP_DBGSELECT_INDEX__OTPKEY1 0x11 +#define BV_DCP_DBGSELECT_INDEX__OTPKEY2 0x12 +#define BV_DCP_DBGSELECT_INDEX__OTPKEY3 0x13 + +#define HW_DCP_DBGDATA (0x00000410) + +#define BP_DCP_DBGDATA_DATA 0 +#define BM_DCP_DBGDATA_DATA 0xFFFFFFFF +#define BF_DCP_DBGDATA_DATA(v) (v) + +#define HW_DCP_PAGETABLE (0x00000420) + +#define BP_DCP_PAGETABLE_BASE 2 +#define BM_DCP_PAGETABLE_BASE 0xFFFFFFFC +#define BF_DCP_PAGETABLE_BASE(v) \ + (((v) << 2) & BM_DCP_PAGETABLE_BASE) +#define BM_DCP_PAGETABLE_FLUSH 0x00000002 +#define BM_DCP_PAGETABLE_ENABLE 0x00000001 + +#define HW_DCP_VERSION (0x00000430) + +#define BP_DCP_VERSION_MAJOR 24 +#define BM_DCP_VERSION_MAJOR 0xFF000000 +#define BF_DCP_VERSION_MAJOR(v) \ + (((v) << 24) & BM_DCP_VERSION_MAJOR) +#define BP_DCP_VERSION_MINOR 16 +#define BM_DCP_VERSION_MINOR 0x00FF0000 +#define BF_DCP_VERSION_MINOR(v) \ + (((v) << 16) & BM_DCP_VERSION_MINOR) +#define BP_DCP_VERSION_STEP 0 +#define BM_DCP_VERSION_STEP 0x0000FFFF +#define BF_DCP_VERSION_STEP(v) \ + (((v) << 0) & BM_DCP_VERSION_STEP) + + +#endif diff --git a/drivers/crypto/dcp_bootstream_ioctl.h b/drivers/crypto/dcp_bootstream_ioctl.h new file mode 100644 index 000000000000..7c0c07d5a72d --- /dev/null +++ b/drivers/crypto/dcp_bootstream_ioctl.h @@ -0,0 +1,32 @@ +/* + * Freescale DCP driver for bootstream update. Only handles the OTP KEY + * case and can only encrypt/decrypt. + * + * Author: Pantelis Antoniou + * + * Copyright (C) 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#ifndef DCP_BOOTSTREAM_IOCTL_H +#define DCP_BOOTSTREAM_IOCTL_H + +/* remember to have included the proper _IO definition + * file before hand. + * For user space it's + */ + +#define DBS_IOCTL_BASE 'd' + +#define DBS_ENC _IOW(DBS_IOCTL_BASE, 0x00, uint8_t[16]) +#define DBS_DEC _IOW(DBS_IOCTL_BASE, 0x01, uint8_t[16]) + +#endif diff --git a/drivers/dma/Kconfig b/drivers/dma/Kconfig index 9e01e96fee94..c61e3e305920 100644 --- a/drivers/dma/Kconfig +++ b/drivers/dma/Kconfig @@ -118,6 +118,15 @@ config MX3_IPU_IRQS To avoid bloating the irq_desc[] array we allocate a sufficient number of IRQ slots and map them dynamically to specific sources. +config MXC_PXP + bool "MXC PxP support" + select DMA_ENGINE + +config MXC_PXP_CLIENT_DEVICE + bool "MXC PxP Client Device" + default y + depends on MXC_PXP + config TXX9_DMAC tristate "Toshiba TXx9 SoC DMA support" depends on MACH_TX49XX || MACH_TX39XX diff --git a/drivers/dma/Makefile b/drivers/dma/Makefile index 0fe5ebbfda5d..6b9fadeb9bb1 100644 --- a/drivers/dma/Makefile +++ b/drivers/dma/Makefile @@ -16,6 +16,7 @@ obj-$(CONFIG_MV_XOR) += mv_xor.o obj-$(CONFIG_DW_DMAC) += dw_dmac.o obj-$(CONFIG_AT_HDMAC) += at_hdmac.o obj-$(CONFIG_MX3_IPU) += ipu/ +obj-$(CONFIG_MXC_PXP) += pxp/ obj-$(CONFIG_TXX9_DMAC) += txx9dmac.o obj-$(CONFIG_SH_DMAE) += shdma.o obj-$(CONFIG_COH901318) += coh901318.o coh901318_lli.o diff --git a/drivers/dma/pxp/Makefile b/drivers/dma/pxp/Makefile new file mode 100644 index 000000000000..88e51a7fb1e2 --- /dev/null +++ b/drivers/dma/pxp/Makefile @@ -0,0 +1,2 @@ +obj-$(CONFIG_MXC_PXP) += pxp_dma.o +obj-$(CONFIG_MXC_PXP_CLIENT_DEVICE) += pxp_device.o diff --git a/drivers/dma/pxp/pxp_device.c b/drivers/dma/pxp/pxp_device.c new file mode 100644 index 000000000000..70b751141f1c --- /dev/null +++ b/drivers/dma/pxp/pxp_device.c @@ -0,0 +1,512 @@ +/* + * Copyright (C) 2010 Freescale Semiconductor, Inc. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +static atomic_t open_count = ATOMIC_INIT(0); + +static DEFINE_SPINLOCK(pxp_mem_lock); +static DEFINE_SPINLOCK(pxp_chan_lock); +static LIST_HEAD(head); +static LIST_HEAD(list); +static struct pxp_irq_info irq_info[NR_PXP_VIRT_CHANNEL]; + +struct pxp_chan_handle { + int chan_id; + int hist_status; +}; + +/* To track the allocated memory buffer */ +struct memalloc_record { + struct list_head list; + struct pxp_mem_desc mem; +}; + +struct pxp_chan_info { + int chan_id; + struct dma_chan *dma_chan; + struct list_head list; +}; + +static int pxp_alloc_dma_buffer(struct pxp_mem_desc *mem) +{ + mem->cpu_addr = (unsigned long) + dma_alloc_coherent(NULL, PAGE_ALIGN(mem->size), + (dma_addr_t *) (&mem->phys_addr), + GFP_DMA | GFP_KERNEL); + pr_debug("[ALLOC] mem alloc phys_addr = 0x%x\n", mem->phys_addr); + if ((void *)(mem->cpu_addr) == NULL) { + printk(KERN_ERR "Physical memory allocation error!\n"); + return -1; + } + return 0; +} + +static void pxp_free_dma_buffer(struct pxp_mem_desc *mem) +{ + if (mem->cpu_addr != 0) { + dma_free_coherent(0, PAGE_ALIGN(mem->size), + (void *)mem->cpu_addr, mem->phys_addr); + } +} + +static int pxp_free_buffers(void) +{ + struct memalloc_record *rec, *n; + struct pxp_mem_desc mem; + + list_for_each_entry_safe(rec, n, &head, list) { + mem = rec->mem; + if (mem.cpu_addr != 0) { + pxp_free_dma_buffer(&mem); + pr_debug("[FREE] freed paddr=0x%08X\n", mem.phys_addr); + /* delete from list */ + list_del(&rec->list); + kfree(rec); + } + } + + return 0; +} + +/* Callback function triggered after PxP receives an EOF interrupt */ +static void pxp_dma_done(void *arg) +{ + struct pxp_tx_desc *tx_desc = to_tx_desc(arg); + struct dma_chan *chan = tx_desc->txd.chan; + struct pxp_channel *pxp_chan = to_pxp_channel(chan); + int chan_id = pxp_chan->dma_chan.chan_id; + + pr_debug("DMA Done ISR, chan_id %d\n", chan_id); + + irq_info[chan_id].irq_pending++; + irq_info[chan_id].hist_status = tx_desc->hist_status; + + wake_up_interruptible(&(irq_info[chan_id].waitq)); +} + +static int pxp_ioc_config_chan(unsigned long arg) +{ + struct scatterlist sg[3]; + struct pxp_tx_desc *desc; + struct dma_async_tx_descriptor *txd; + struct pxp_chan_info *info; + struct pxp_config_data pxp_conf; + dma_cookie_t cookie; + int chan_id; + int i, length, ret; + + ret = copy_from_user(&pxp_conf, + (struct pxp_config_data *)arg, + sizeof(struct pxp_config_data)); + if (ret) + return -EFAULT; + + chan_id = pxp_conf.chan_id; + if (chan_id < 0 || chan_id >= NR_PXP_VIRT_CHANNEL) + return -ENODEV; + + init_waitqueue_head(&(irq_info[chan_id].waitq)); + + /* find the channel */ + spin_lock(&pxp_chan_lock); + list_for_each_entry(info, &list, list) { + if (info->dma_chan->chan_id == chan_id) + break; + } + spin_unlock(&pxp_chan_lock); + + sg_init_table(sg, 3); + + txd = + info->dma_chan->device->device_prep_slave_sg(info->dma_chan, + sg, 3, + DMA_TO_DEVICE, + DMA_PREP_INTERRUPT); + if (!txd) { + pr_err("Error preparing a DMA transaction descriptor.\n"); + return -EIO; + } + + txd->callback_param = txd; + txd->callback = pxp_dma_done; + + desc = to_tx_desc(txd); + + length = desc->len; + for (i = 0; i < length; i++) { + if (i == 0) { /* S0 */ + memcpy(&desc->proc_data, + &pxp_conf.proc_data, + sizeof(struct pxp_proc_data)); + memcpy(&desc->layer_param.s0_param, + &pxp_conf.s0_param, + sizeof(struct pxp_layer_param)); + } else if (i == 1) { /* Output */ + memcpy(&desc->layer_param.out_param, + &pxp_conf.out_param, + sizeof(struct pxp_layer_param)); + } else { + /* OverLay */ + memcpy(&desc->layer_param.ol_param, + &pxp_conf.ol_param, + sizeof(struct pxp_layer_param)); + } + + desc = desc->next; + } + + cookie = txd->tx_submit(txd); + if (cookie < 0) { + pr_err("Error tx_submit\n"); + return -EIO; + } + + return 0; +} + +static int pxp_device_open(struct inode *inode, struct file *filp) +{ + atomic_inc(&open_count); + + return 0; +} + +static int pxp_device_release(struct inode *inode, struct file *filp) +{ + if (atomic_dec_and_test(&open_count)) + pxp_free_buffers(); + + return 0; +} + +static int pxp_device_mmap(struct file *file, struct vm_area_struct *vma) +{ + struct memalloc_record *rec, *n; + int request_size, found; + + request_size = vma->vm_end - vma->vm_start; + found = 0; + + pr_debug("start=0x%x, pgoff=0x%x, size=0x%x\n", + (unsigned int)(vma->vm_start), (unsigned int)(vma->vm_pgoff), + request_size); + + spin_lock(&pxp_mem_lock); + list_for_each_entry_safe(rec, n, &head, list) { + if (rec->mem.phys_addr == (vma->vm_pgoff << PAGE_SHIFT) && + (rec->mem.size <= request_size)) { + found = 1; + break; + } + } + spin_unlock(&pxp_mem_lock); + + if (found == 0) + return -ENOMEM; + + vma->vm_flags |= VM_IO | VM_RESERVED; + vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); + + return remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff, + request_size, vma->vm_page_prot) ? -EAGAIN : 0; +} + +static int pxp_device_ioctl(struct inode *inode, struct file *filp, + unsigned int cmd, unsigned long arg) +{ + int ret = 0; + + switch (cmd) { + case PXP_IOC_GET_CHAN: + { + struct pxp_chan_info *info; + dma_cap_mask_t mask; + + pr_debug("drv: PXP_IOC_GET_CHAN Line %d\n", __LINE__); + info = kzalloc(sizeof(*info), GFP_KERNEL); + if (!info) { + pr_err("%d: alloc err\n", __LINE__); + return -ENOMEM; + } + + dma_cap_zero(mask); + dma_cap_set(DMA_SLAVE, mask); + dma_cap_set(DMA_PRIVATE, mask); + info->dma_chan = dma_request_channel(mask, NULL, NULL); + if (!info->dma_chan) { + pr_err("Unsccessfully received channel!\n"); + kfree(info); + return -EBUSY; + } + pr_debug("Successfully received channel." + "chan_id %d\n", info->dma_chan->chan_id); + + spin_lock(&pxp_chan_lock); + list_add_tail(&info->list, &list); + spin_unlock(&pxp_chan_lock); + + if (put_user + (info->dma_chan->chan_id, (u32 __user *) arg)) + return -EFAULT; + + break; + } + case PXP_IOC_PUT_CHAN: + { + int chan_id; + struct pxp_chan_info *info; + + if (get_user(chan_id, (u32 __user *) arg)) + return -EFAULT; + + if (chan_id < 0 || chan_id >= NR_PXP_VIRT_CHANNEL) + return -ENODEV; + + spin_lock(&pxp_chan_lock); + list_for_each_entry(info, &list, list) { + if (info->dma_chan->chan_id == chan_id) + break; + } + spin_unlock(&pxp_chan_lock); + + pr_debug("%d release chan_id %d\n", __LINE__, + info->dma_chan->chan_id); + /* REVISIT */ + dma_release_channel(info->dma_chan); + spin_lock(&pxp_chan_lock); + list_del_init(&info->list); + spin_unlock(&pxp_chan_lock); + kfree(info); + + break; + } + case PXP_IOC_CONFIG_CHAN: + { + + int ret; + + ret = pxp_ioc_config_chan(arg); + if (ret) + return ret; + + break; + } + case PXP_IOC_START_CHAN: + { + struct pxp_chan_info *info; + int chan_id; + + if (get_user(chan_id, (u32 __user *) arg)) + return -EFAULT; + + /* find the channel */ + spin_lock(&pxp_chan_lock); + list_for_each_entry(info, &list, list) { + if (info->dma_chan->chan_id == chan_id) + break; + } + spin_unlock(&pxp_chan_lock); + + dma_async_issue_pending(info->dma_chan); + + break; + } + case PXP_IOC_GET_PHYMEM: + { + struct memalloc_record *rec; + + rec = kzalloc(sizeof(*rec), GFP_KERNEL); + if (!rec) + return -ENOMEM; + + ret = copy_from_user(&(rec->mem), + (struct pxp_mem_desc *)arg, + sizeof(struct pxp_mem_desc)); + if (ret) { + kfree(rec); + return -EFAULT; + } + + pr_debug("[ALLOC] mem alloc size = 0x%x\n", + rec->mem.size); + + ret = pxp_alloc_dma_buffer(&(rec->mem)); + if (ret == -1) { + kfree(rec); + printk(KERN_ERR + "Physical memory allocation error!\n"); + break; + } + ret = copy_to_user((void __user *)arg, &(rec->mem), + sizeof(struct pxp_mem_desc)); + if (ret) { + kfree(rec); + ret = -EFAULT; + break; + } + + spin_lock(&pxp_mem_lock); + list_add(&rec->list, &head); + spin_unlock(&pxp_mem_lock); + + break; + } + case PXP_IOC_PUT_PHYMEM: + { + struct memalloc_record *rec, *n; + struct pxp_mem_desc pxp_mem; + + ret = copy_from_user(&pxp_mem, + (struct pxp_mem_desc *)arg, + sizeof(struct pxp_mem_desc)); + if (ret) + return -EACCES; + + pr_debug("[FREE] mem freed cpu_addr = 0x%x\n", + pxp_mem.cpu_addr); + if ((void *)pxp_mem.cpu_addr != NULL) + pxp_free_dma_buffer(&pxp_mem); + + spin_lock(&pxp_mem_lock); + list_for_each_entry_safe(rec, n, &head, list) { + if (rec->mem.cpu_addr == pxp_mem.cpu_addr) { + /* delete from list */ + list_del(&rec->list); + kfree(rec); + break; + } + } + spin_unlock(&pxp_mem_lock); + + break; + } + case PXP_IOC_WAIT4CMPLT: + { + struct pxp_chan_handle chan_handle; + int ret, chan_id; + + ret = copy_from_user(&chan_handle, + (struct pxp_chan_handle *)arg, + sizeof(struct pxp_chan_handle)); + if (ret) + return -EFAULT; + + chan_id = chan_handle.chan_id; + if (chan_id < 0 || chan_id >= NR_PXP_VIRT_CHANNEL) + return -ENODEV; + + if (!wait_event_interruptible_timeout + (irq_info[chan_id].waitq, + (irq_info[chan_id].irq_pending != 0), 2 * HZ)) { + pr_warning("pxp blocking: timeout.\n"); + return -ETIME; + } else if (signal_pending(current)) { + printk(KERN_WARNING + "pxp interrupt received.\n"); + return -ERESTARTSYS; + } else + irq_info[chan_id].irq_pending--; + + chan_handle.hist_status = irq_info[chan_id].hist_status; + ret = copy_to_user((struct pxp_chan_handle *)arg, + &chan_handle, + sizeof(struct pxp_chan_handle)); + if (ret) + return -EFAULT; + break; + } + default: + break; + } + + return 0; +} + +static const struct file_operations pxp_device_fops = { + .open = pxp_device_open, + .release = pxp_device_release, + .ioctl = pxp_device_ioctl, + .mmap = pxp_device_mmap, +}; + +static struct miscdevice pxp_device_miscdev = { + .minor = MISC_DYNAMIC_MINOR, + .name = "pxp_device", + .fops = &pxp_device_fops, +}; + +static int __devinit pxp_device_probe(struct platform_device *pdev) +{ + int ret; + + /* PxP DMA interface */ + dmaengine_get(); + + ret = misc_register(&pxp_device_miscdev); + if (ret) + return ret; + + pr_debug("PxP_Device Probe Successfully\n"); + return 0; +} + +static int __devexit pxp_device_remove(struct platform_device *pdev) +{ + misc_deregister(&pxp_device_miscdev); + + dmaengine_put(); + + return 0; +} + +static struct platform_driver pxp_client_driver = { + .probe = pxp_device_probe, + .remove = __exit_p(pxp_device_remove), + .driver = { + .name = "pxp-device", + .owner = THIS_MODULE, + }, +}; + +static int __init pxp_device_init(void) +{ + return platform_driver_register(&pxp_client_driver); +} + +static void __exit pxp_device_exit(void) +{ + platform_driver_unregister(&pxp_client_driver); +} + +module_init(pxp_device_init); +module_exit(pxp_device_exit); + +MODULE_DESCRIPTION("i.MX PxP client driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/dma/pxp/pxp_dma.c b/drivers/dma/pxp/pxp_dma.c new file mode 100644 index 000000000000..f80645cbafc6 --- /dev/null +++ b/drivers/dma/pxp/pxp_dma.c @@ -0,0 +1,1383 @@ +/* + * Copyright (C) 2010 Freescale Semiconductor, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ +/* + * Based on STMP378X PxP driver + * Copyright 2008-2009 Embedded Alley Solutions, Inc All Rights Reserved. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "regs-pxp.h" + +#define PXP_DOWNSCALE_THRESHOLD 0x4000 + +static LIST_HEAD(head); + +struct pxp_dma { + struct dma_device dma; +}; + +struct pxps { + struct platform_device *pdev; + struct clk *clk; + void __iomem *base; + int irq; /* PXP IRQ to the CPU */ + + spinlock_t lock; + struct mutex mutex; + + struct device *dev; + struct pxp_dma pxp_dma; + struct pxp_channel channel[NR_PXP_VIRT_CHANNEL]; + struct work_struct work; + struct workqueue_struct *workqueue; + wait_queue_head_t done; + + /* describes most recent processing configuration */ + struct pxp_config_data pxp_conf_state; +}; + +#define to_pxp_dma(d) container_of(d, struct pxp_dma, dma) +#define to_tx_desc(tx) container_of(tx, struct pxp_tx_desc, txd) +#define to_pxp_channel(d) container_of(d, struct pxp_channel, dma_chan) +#define to_pxp(id) container_of(id, struct pxps, pxp_dma) + +#define PXP_DEF_BUFS 2 +#define PXP_MIN_PIX 8 + +#define PXP_WAITCON ((__raw_readl(pxp->base + HW_PXP_STAT) & \ + BM_PXP_STAT_IRQ) != BM_PXP_STAT_IRQ) + +static uint32_t pxp_s0_formats[] = { + PXP_PIX_FMT_RGB24, + PXP_PIX_FMT_RGB565, + PXP_PIX_FMT_RGB555, + PXP_PIX_FMT_YUV420P, + PXP_PIX_FMT_YUV422P, +}; + +/* + * PXP common functions + */ +static void dump_pxp_reg(struct pxps *pxp) +{ + dev_err(pxp->dev, "PXP_CTRL 0x%x", + __raw_readl(pxp->base + HW_PXP_CTRL)); + dev_err(pxp->dev, "PXP_STAT 0x%x", + __raw_readl(pxp->base + HW_PXP_STAT)); + dev_err(pxp->dev, "PXP_OUTBUF 0x%x", + __raw_readl(pxp->base + HW_PXP_OUTBUF)); + dev_err(pxp->dev, "PXP_OUTBUF2 0x%x", + __raw_readl(pxp->base + HW_PXP_OUTBUF2)); + dev_err(pxp->dev, "PXP_OUTSIZE 0x%x", + __raw_readl(pxp->base + HW_PXP_OUTSIZE)); + dev_err(pxp->dev, "PXP_S0BUF 0x%x", + __raw_readl(pxp->base + HW_PXP_S0BUF)); + dev_err(pxp->dev, "PXP_S0UBUF 0x%x", + __raw_readl(pxp->base + HW_PXP_S0UBUF)); + dev_err(pxp->dev, "PXP_S0VBUF 0x%x", + __raw_readl(pxp->base + HW_PXP_S0VBUF)); + dev_err(pxp->dev, "PXP_S0PARAM 0x%x", + __raw_readl(pxp->base + HW_PXP_S0PARAM)); + dev_err(pxp->dev, "PXP_S0BACKGROUND 0x%x", + __raw_readl(pxp->base + HW_PXP_S0BACKGROUND)); + dev_err(pxp->dev, "PXP_S0CROP 0x%x", + __raw_readl(pxp->base + HW_PXP_S0CROP)); + dev_err(pxp->dev, "PXP_S0SCALE 0x%x", + __raw_readl(pxp->base + HW_PXP_S0SCALE)); + dev_err(pxp->dev, "PXP_OLn 0x%x", + __raw_readl(pxp->base + HW_PXP_OLn(0))); + dev_err(pxp->dev, "PXP_OLnSIZE 0x%x", + __raw_readl(pxp->base + HW_PXP_OLnSIZE(0))); + dev_err(pxp->dev, "PXP_OLnPARAM 0x%x", + __raw_readl(pxp->base + HW_PXP_OLnPARAM(0))); + dev_err(pxp->dev, "PXP_CSCCOEF0 0x%x", + __raw_readl(pxp->base + HW_PXP_CSCCOEF0)); + dev_err(pxp->dev, "PXP_CSC2CTRL 0x%x", + __raw_readl(pxp->base + HW_PXP_CSC2CTRL)); + dev_err(pxp->dev, "PXP_CSC2COEF0 0x%x", + __raw_readl(pxp->base + HW_PXP_CSC2COEF0)); + dev_err(pxp->dev, "PXP_CSC2COEF1 0x%x", + __raw_readl(pxp->base + HW_PXP_CSC2COEF1)); + dev_err(pxp->dev, "PXP_CSC2COEF2 0x%x", + __raw_readl(pxp->base + HW_PXP_CSC2COEF2)); + dev_err(pxp->dev, "PXP_CSC2COEF3 0x%x", + __raw_readl(pxp->base + HW_PXP_CSC2COEF3)); + dev_err(pxp->dev, "PXP_CSC2COEF4 0x%x", + __raw_readl(pxp->base + HW_PXP_CSC2COEF4)); + dev_err(pxp->dev, "PXP_CSC2COEF5 0x%x", + __raw_readl(pxp->base + HW_PXP_CSC2COEF5)); + dev_err(pxp->dev, "PXP_LUT_CTRL 0x%x", + __raw_readl(pxp->base + HW_PXP_LUT_CTRL)); + dev_err(pxp->dev, "PXP_LUT 0x%x", __raw_readl(pxp->base + HW_PXP_LUT)); + dev_err(pxp->dev, "PXP_HIST_CTRL 0x%x", + __raw_readl(pxp->base + HW_PXP_HIST_CTRL)); + dev_err(pxp->dev, "PXP_HIST2_PARAM 0x%x", + __raw_readl(pxp->base + HW_PXP_HIST2_PARAM)); + dev_err(pxp->dev, "PXP_HIST4_PARAM 0x%x", + __raw_readl(pxp->base + HW_PXP_HIST4_PARAM)); + dev_err(pxp->dev, "PXP_HIST8_PARAM0 0x%x", + __raw_readl(pxp->base + HW_PXP_HIST8_PARAM0)); + dev_err(pxp->dev, "PXP_HIST8_PARAM1 0x%x", + __raw_readl(pxp->base + HW_PXP_HIST8_PARAM1)); + dev_err(pxp->dev, "PXP_HIST16_PARAM0 0x%x", + __raw_readl(pxp->base + HW_PXP_HIST16_PARAM0)); + dev_err(pxp->dev, "PXP_HIST16_PARAM1 0x%x", + __raw_readl(pxp->base + HW_PXP_HIST16_PARAM1)); + dev_err(pxp->dev, "PXP_HIST16_PARAM2 0x%x", + __raw_readl(pxp->base + HW_PXP_HIST16_PARAM2)); + dev_err(pxp->dev, "PXP_HIST16_PARAM3 0x%x", + __raw_readl(pxp->base + HW_PXP_HIST16_PARAM3)); +} + +static bool is_yuv(pix_fmt) +{ + if ((pix_fmt == PXP_PIX_FMT_YUYV) | + (pix_fmt == PXP_PIX_FMT_UYVY) | + (pix_fmt == PXP_PIX_FMT_Y41P) | + (pix_fmt == PXP_PIX_FMT_YUV444) | + (pix_fmt == PXP_PIX_FMT_NV12) | + (pix_fmt == PXP_PIX_FMT_GREY) | + (pix_fmt == PXP_PIX_FMT_YVU410P) | + (pix_fmt == PXP_PIX_FMT_YUV410P) | + (pix_fmt == PXP_PIX_FMT_YVU420P) | + (pix_fmt == PXP_PIX_FMT_YUV420P) | + (pix_fmt == PXP_PIX_FMT_YUV420P2) | + (pix_fmt == PXP_PIX_FMT_YVU422P) | + (pix_fmt == PXP_PIX_FMT_YUV422P)) { + return true; + } else { + return false; + } +} + +static void pxp_set_ctrl(struct pxps *pxp) +{ + struct pxp_config_data *pxp_conf = &pxp->pxp_conf_state; + struct pxp_proc_data *proc_data = &pxp_conf->proc_data; + u32 ctrl; + u32 fmt_ctrl; + + /* Configure S0 input format */ + switch (pxp_conf->s0_param.pixel_fmt) { + case PXP_PIX_FMT_RGB24: + fmt_ctrl = BV_PXP_CTRL_S0_FORMAT__RGB888; + break; + case PXP_PIX_FMT_RGB565: + fmt_ctrl = BV_PXP_CTRL_S0_FORMAT__RGB565; + break; + case PXP_PIX_FMT_RGB555: + fmt_ctrl = BV_PXP_CTRL_S0_FORMAT__RGB555; + break; + case PXP_PIX_FMT_YUV420P: + case PXP_PIX_FMT_GREY: + fmt_ctrl = BV_PXP_CTRL_S0_FORMAT__YUV420; + break; + case PXP_PIX_FMT_YUV422P: + fmt_ctrl = BV_PXP_CTRL_S0_FORMAT__YUV422; + break; + default: + fmt_ctrl = 0; + } + ctrl = BF_PXP_CTRL_S0_FORMAT(fmt_ctrl); + + /* Configure output format based on out_channel format */ + switch (pxp_conf->out_param.pixel_fmt) { + case PXP_PIX_FMT_RGB24: + fmt_ctrl = BV_PXP_CTRL_OUTBUF_FORMAT__RGB888; + break; + case PXP_PIX_FMT_RGB565: + fmt_ctrl = BV_PXP_CTRL_OUTBUF_FORMAT__RGB565; + break; + case PXP_PIX_FMT_RGB555: + fmt_ctrl = BV_PXP_CTRL_OUTBUF_FORMAT__RGB555; + break; + case PXP_PIX_FMT_YUV420P: + fmt_ctrl = BV_PXP_CTRL_OUTBUF_FORMAT__YUV2P420; + break; + case PXP_PIX_FMT_YUV422P: + fmt_ctrl = BV_PXP_CTRL_OUTBUF_FORMAT__YUV2P422; + break; + case PXP_PIX_FMT_GREY: + fmt_ctrl = BV_PXP_CTRL_OUTBUF_FORMAT__MONOC8; + break; + default: + fmt_ctrl = 0; + } + ctrl |= BF_PXP_CTRL_OUTBUF_FORMAT(fmt_ctrl); + + ctrl |= BM_PXP_CTRL_CROP; + + if (proc_data->scaling) + ctrl |= BM_PXP_CTRL_SCALE; + if (proc_data->vflip) + ctrl |= BM_PXP_CTRL_VFLIP; + if (proc_data->hflip) + ctrl |= BM_PXP_CTRL_HFLIP; + if (proc_data->rotate) + ctrl |= BF_PXP_CTRL_ROTATE(proc_data->rotate / 90); + + __raw_writel(ctrl, pxp->base + HW_PXP_CTRL); +} + +static int pxp_start(struct pxps *pxp) +{ + __raw_writel(BM_PXP_CTRL_IRQ_ENABLE, pxp->base + HW_PXP_CTRL_SET); + __raw_writel(BM_PXP_CTRL_ENABLE, pxp->base + HW_PXP_CTRL_SET); + + return 0; +} + +static void pxp_set_outbuf(struct pxps *pxp) +{ + struct pxp_config_data *pxp_conf = &pxp->pxp_conf_state; + struct pxp_layer_param *out_params = &pxp_conf->out_param; + + __raw_writel(out_params->paddr, pxp->base + HW_PXP_OUTBUF); + + __raw_writel(BF_PXP_OUTSIZE_WIDTH(out_params->width) | + BF_PXP_OUTSIZE_HEIGHT(out_params->height), + pxp->base + HW_PXP_OUTSIZE); +} + +static void pxp_set_s0colorkey(struct pxps *pxp) +{ + struct pxp_config_data *pxp_conf = &pxp->pxp_conf_state; + struct pxp_layer_param *s0_params = &pxp_conf->s0_param; + + /* Low and high are set equal. V4L does not allow a chromakey range */ + if (s0_params->color_key == -1) { + /* disable color key */ + __raw_writel(0xFFFFFF, pxp->base + HW_PXP_S0COLORKEYLOW); + __raw_writel(0, pxp->base + HW_PXP_S0COLORKEYHIGH); + } else { + __raw_writel(s0_params->color_key, + pxp->base + HW_PXP_S0COLORKEYLOW); + __raw_writel(s0_params->color_key, + pxp->base + HW_PXP_S0COLORKEYHIGH); + } +} + +static void pxp_set_olcolorkey(int layer_no, struct pxps *pxp) +{ + struct pxp_config_data *pxp_conf = &pxp->pxp_conf_state; + struct pxp_layer_param *ol_params = &pxp_conf->ol_param[layer_no]; + + /* Low and high are set equal. V4L does not allow a chromakey range */ + if (ol_params->color_key_enable != 0 && ol_params->color_key != -1) { + __raw_writel(ol_params->color_key, + pxp->base + HW_PXP_OLCOLORKEYLOW); + __raw_writel(ol_params->color_key, + pxp->base + HW_PXP_OLCOLORKEYHIGH); + } else { + /* disable color key */ + __raw_writel(0xFFFFFF, pxp->base + HW_PXP_OLCOLORKEYLOW); + __raw_writel(0, pxp->base + HW_PXP_OLCOLORKEYHIGH); + } +} + +static void pxp_set_oln(int layer_no, struct pxps *pxp) +{ + struct pxp_config_data *pxp_conf = &pxp->pxp_conf_state; + struct pxp_layer_param *olparams_data = &pxp_conf->ol_param[layer_no]; + dma_addr_t phys_addr = olparams_data->paddr; + __raw_writel(phys_addr, pxp->base + HW_PXP_OLn(layer_no)); + + /* Fixme */ + __raw_writel(BF_PXP_OLnSIZE_WIDTH(olparams_data->width >> 3) | + BF_PXP_OLnSIZE_HEIGHT(olparams_data->height >> 3), + pxp->base + HW_PXP_OLnSIZE(layer_no)); +} + +static void pxp_set_olparam(int layer_no, struct pxps *pxp) +{ + struct pxp_config_data *pxp_conf = &pxp->pxp_conf_state; + struct pxp_layer_param *olparams_data = &pxp_conf->ol_param[layer_no]; + u32 olparam; + + olparam = BF_PXP_OLnPARAM_ALPHA(olparams_data->global_alpha); + if (olparams_data->pixel_fmt == PXP_PIX_FMT_RGB24) + olparam |= + BF_PXP_OLnPARAM_FORMAT(BV_PXP_OLnPARAM_FORMAT__RGB888); + else + olparam |= + BF_PXP_OLnPARAM_FORMAT(BV_PXP_OLnPARAM_FORMAT__RGB565); + if (olparams_data->global_alpha) + olparam |= + BF_PXP_OLnPARAM_ALPHA_CNTL + (BV_PXP_OLnPARAM_ALPHA_CNTL__Override); + if (olparams_data->color_key_enable) + olparam |= BM_PXP_OLnPARAM_ENABLE_COLORKEY; + if (olparams_data->combine_enable) + olparam |= BM_PXP_OLnPARAM_ENABLE; + __raw_writel(olparam, pxp->base + HW_PXP_OLnPARAM(layer_no)); +} + +static void pxp_set_s0param(struct pxps *pxp) +{ + struct pxp_config_data *pxp_conf = &pxp->pxp_conf_state; + struct pxp_layer_param *s0params_data = &pxp_conf->s0_param; + struct pxp_proc_data *proc_data = &pxp_conf->proc_data; + u32 s0param; + + s0param = BF_PXP_S0PARAM_XBASE(proc_data->drect.left >> 3); + s0param |= BF_PXP_S0PARAM_YBASE(proc_data->drect.top >> 3); + s0param |= BF_PXP_S0PARAM_WIDTH(s0params_data->width >> 3); + s0param |= BF_PXP_S0PARAM_HEIGHT(s0params_data->height >> 3); + __raw_writel(s0param, pxp->base + HW_PXP_S0PARAM); +} + +static void pxp_set_s0crop(struct pxps *pxp) +{ + u32 s0crop; + struct pxp_proc_data *proc_data = &pxp->pxp_conf_state.proc_data; + + s0crop = BF_PXP_S0CROP_XBASE(proc_data->srect.left >> 3); + s0crop |= BF_PXP_S0CROP_YBASE(proc_data->srect.top >> 3); + s0crop |= BF_PXP_S0CROP_WIDTH(proc_data->drect.width >> 3); + s0crop |= BF_PXP_S0CROP_HEIGHT(proc_data->drect.height >> 3); + __raw_writel(s0crop, pxp->base + HW_PXP_S0CROP); +} + +static int pxp_set_scaling(struct pxps *pxp) +{ + int ret = 0; + u32 xscale, yscale, s0scale; + struct pxp_proc_data *proc_data = &pxp->pxp_conf_state.proc_data; + struct pxp_layer_param *s0params_data = &pxp->pxp_conf_state.s0_param; + + if ((s0params_data->pixel_fmt != PXP_PIX_FMT_YUV420P) && + (s0params_data->pixel_fmt != PXP_PIX_FMT_YUV422P)) { + proc_data->scaling = 0; + ret = -EINVAL; + goto out; + } + + if ((proc_data->srect.width == proc_data->drect.width) && + (proc_data->srect.height == proc_data->drect.height)) { + proc_data->scaling = 0; + __raw_writel(0x10001000, pxp->base + HW_PXP_S0SCALE); + goto out; + } + + proc_data->scaling = 1; + xscale = proc_data->srect.width * 0x1000 / proc_data->drect.width; + yscale = proc_data->srect.height * 0x1000 / proc_data->drect.height; + if (xscale > PXP_DOWNSCALE_THRESHOLD) + xscale = PXP_DOWNSCALE_THRESHOLD; + if (yscale > PXP_DOWNSCALE_THRESHOLD) + yscale = PXP_DOWNSCALE_THRESHOLD; + s0scale = BF_PXP_S0SCALE_YSCALE(yscale) | BF_PXP_S0SCALE_XSCALE(xscale); + __raw_writel(s0scale, pxp->base + HW_PXP_S0SCALE); + +out: + pxp_set_ctrl(pxp); + + return ret; +} + +static void pxp_set_bg(struct pxps *pxp) +{ + __raw_writel(pxp->pxp_conf_state.proc_data.bgcolor, + pxp->base + HW_PXP_S0BACKGROUND); +} + +static void pxp_set_lut(struct pxps *pxp) +{ + struct pxp_config_data *pxp_conf = &pxp->pxp_conf_state; + u32 reg_val; + int i; + + if (pxp_conf->proc_data.lut_transform == PXP_LUT_NONE) { + __raw_writel(BM_PXP_LUT_CTRL_BYPASS, + pxp->base + HW_PXP_LUT_CTRL); + } else if (pxp_conf->proc_data.lut_transform == PXP_LUT_INVERT) { + /* Fill out LUT table with 8-bit inverted values */ + + /* Initialize LUT address to 0 and clear bypass bit */ + __raw_writel(0, pxp->base + HW_PXP_LUT_CTRL); + + /* LUT address pointer auto-increments after each data write */ + for (i = 0; i < 256; i++) { + reg_val = + __raw_readl(pxp->base + + HW_PXP_LUT_CTRL) & BM_PXP_LUT_CTRL_ADDR; + reg_val = ~reg_val & BM_PXP_LUT_DATA; + __raw_writel(reg_val, pxp->base + HW_PXP_LUT); + } + } +} + +static void pxp_set_csc(struct pxps *pxp) +{ + struct pxp_config_data *pxp_conf = &pxp->pxp_conf_state; + struct pxp_layer_param *s0_params = &pxp_conf->s0_param; + struct pxp_layer_param *ol_params = &pxp_conf->ol_param[0]; + struct pxp_layer_param *out_params = &pxp_conf->out_param; + + bool input_is_YUV = is_yuv(s0_params->pixel_fmt); + bool output_is_YUV = is_yuv(out_params->pixel_fmt); + + if (input_is_YUV && output_is_YUV) { + /* + * Input = YUV, Output = YUV + * No CSC unless we need to do combining + */ + if (ol_params->combine_enable) { + /* Must convert to RGB for combining with RGB overlay */ + + /* CSC1 - YUV->RGB */ + __raw_writel(0x04030000, pxp->base + HW_PXP_CSCCOEF0); + __raw_writel(0x01230208, pxp->base + HW_PXP_CSCCOEF1); + __raw_writel(0x076b079c, pxp->base + HW_PXP_CSCCOEF2); + + /* CSC2 - RGB->YUV */ + __raw_writel(0x4, pxp->base + HW_PXP_CSC2CTRL); + __raw_writel(0x0096004D, pxp->base + HW_PXP_CSC2COEF0); + __raw_writel(0x05DA001D, pxp->base + HW_PXP_CSC2COEF1); + __raw_writel(0x007005B6, pxp->base + HW_PXP_CSC2COEF2); + __raw_writel(0x057C009E, pxp->base + HW_PXP_CSC2COEF3); + __raw_writel(0x000005E6, pxp->base + HW_PXP_CSC2COEF4); + __raw_writel(0x00000000, pxp->base + HW_PXP_CSC2COEF5); + } else { + /* Input & Output both YUV, so bypass both CSCs */ + + /* CSC1 - Bypass */ + __raw_writel(0x40000000, pxp->base + HW_PXP_CSCCOEF0); + + /* CSC2 - Bypass */ + __raw_writel(0x1, pxp->base + HW_PXP_CSC2CTRL); + } + } else if (input_is_YUV && !output_is_YUV) { + /* + * Input = YUV, Output = RGB + * Use CSC1 to convert to RGB + */ + + /* CSC1 - YUV->RGB */ + __raw_writel(0x04030000, pxp->base + HW_PXP_CSCCOEF0); + __raw_writel(0x01230208, pxp->base + HW_PXP_CSCCOEF1); + __raw_writel(0x076b079c, pxp->base + HW_PXP_CSCCOEF2); + + /* CSC2 - Bypass */ + __raw_writel(0x1, pxp->base + HW_PXP_CSC2CTRL); + } else if (!input_is_YUV && output_is_YUV) { + /* + * Input = RGB, Output = YUV + * Use CSC2 to convert to YUV + */ + + /* CSC1 - Bypass */ + __raw_writel(0x40000000, pxp->base + HW_PXP_CSCCOEF0); + + /* CSC2 - RGB->YUV */ + __raw_writel(0x4, pxp->base + HW_PXP_CSC2CTRL); + __raw_writel(0x0096004D, pxp->base + HW_PXP_CSC2COEF0); + __raw_writel(0x05DA001D, pxp->base + HW_PXP_CSC2COEF1); + __raw_writel(0x007005B6, pxp->base + HW_PXP_CSC2COEF2); + __raw_writel(0x057C009E, pxp->base + HW_PXP_CSC2COEF3); + __raw_writel(0x000005E6, pxp->base + HW_PXP_CSC2COEF4); + __raw_writel(0x00000000, pxp->base + HW_PXP_CSC2COEF5); + } else { + /* + * Input = RGB, Output = RGB + * Input & Output both RGB, so bypass both CSCs + */ + + /* CSC1 - Bypass */ + __raw_writel(0x40000000, pxp->base + HW_PXP_CSCCOEF0); + + /* CSC2 - Bypass */ + __raw_writel(0x1, pxp->base + HW_PXP_CSC2CTRL); + } + + /* YCrCb colorspace */ + /* Not sure when we use this...no YCrCb formats are defined for PxP */ + /* + __raw_writel(0x84ab01f0, HW_PXP_CSCCOEFF0_ADDR); + __raw_writel(0x01230204, HW_PXP_CSCCOEFF1_ADDR); + __raw_writel(0x0730079c, HW_PXP_CSCCOEFF2_ADDR); + */ + +} + +static void pxp_set_s0buf(struct pxps *pxp) +{ + struct pxp_config_data *pxp_conf = &pxp->pxp_conf_state; + struct pxp_layer_param *s0_params = &pxp_conf->s0_param; + dma_addr_t Y, U, V; + + Y = s0_params->paddr; + __raw_writel(Y, pxp->base + HW_PXP_S0BUF); + if ((s0_params->pixel_fmt == PXP_PIX_FMT_YUV420P) || + (s0_params->pixel_fmt == PXP_PIX_FMT_YVU420P) || + (s0_params->pixel_fmt == PXP_PIX_FMT_GREY)) { + /* Set to 1 if YUV format is 4:2:2 rather than 4:2:0 */ + int s = 2; + U = Y + (s0_params->width * s0_params->height); + V = U + ((s0_params->width * s0_params->height) >> s); + __raw_writel(U, pxp->base + HW_PXP_S0UBUF); + __raw_writel(V, pxp->base + HW_PXP_S0VBUF); + } +} + +/** + * pxp_config() - configure PxP for a processing task + * @pxps: PXP context. + * @pxp_chan: PXP channel. + * @return: 0 on success or negative error code on failure. + */ +static int pxp_config(struct pxps *pxp, struct pxp_channel *pxp_chan) +{ + struct pxp_config_data *pxp_conf_data = &pxp->pxp_conf_state; + int ol_nr; + int i; + + /* Configure PxP regs */ + pxp_set_ctrl(pxp); + pxp_set_s0param(pxp); + pxp_set_s0crop(pxp); + pxp_set_scaling(pxp); + ol_nr = pxp_conf_data->layer_nr - 2; + while (ol_nr > 0) { + i = pxp_conf_data->layer_nr - 2 - ol_nr; + pxp_set_oln(i, pxp); + pxp_set_olparam(i, pxp); + /* only the color key in higher overlay will take effect. */ + pxp_set_olcolorkey(i, pxp); + ol_nr--; + } + pxp_set_s0colorkey(pxp); + pxp_set_csc(pxp); + pxp_set_bg(pxp); + pxp_set_lut(pxp); + + pxp_set_s0buf(pxp); + pxp_set_outbuf(pxp); + + return 0; +} + +static struct pxp_tx_desc *pxpdma_first_active(struct pxp_channel *pxp_chan) +{ + return list_entry(pxp_chan->active_list.next, struct pxp_tx_desc, list); +} + +static struct pxp_tx_desc *pxpdma_first_queued(struct pxp_channel *pxp_chan) +{ + return list_entry(pxp_chan->queue.next, struct pxp_tx_desc, list); +} + +/* called with pxp_chan->lock held */ +static void __pxpdma_dostart(struct pxp_channel *pxp_chan) +{ + struct pxp_dma *pxp_dma = to_pxp_dma(pxp_chan->dma_chan.device); + struct pxps *pxp = to_pxp(pxp_dma); + struct pxp_tx_desc *desc; + struct pxp_tx_desc *child; + int i = 0; + + /* so far we presume only one transaction on active_list */ + /* S0 */ + desc = pxpdma_first_active(pxp_chan); + memcpy(&pxp->pxp_conf_state.s0_param, + &desc->layer_param.s0_param, sizeof(struct pxp_layer_param)); + memcpy(&pxp->pxp_conf_state.proc_data, + &desc->proc_data, sizeof(struct pxp_proc_data)); + + /* Save PxP configuration */ + list_for_each_entry(child, &desc->tx_list, list) { + if (i == 0) { /* Output */ + memcpy(&pxp->pxp_conf_state.out_param, + &child->layer_param.out_param, + sizeof(struct pxp_layer_param)); + } else { /* Overlay */ + memcpy(&pxp->pxp_conf_state.ol_param[i - 1], + &child->layer_param.ol_param, + sizeof(struct pxp_layer_param)); + } + + i++; + } + pr_debug("%s:%d S0 w/h %d/%d paddr %08x\n", __func__, __LINE__, + pxp->pxp_conf_state.s0_param.width, + pxp->pxp_conf_state.s0_param.height, + pxp->pxp_conf_state.s0_param.paddr); + pr_debug("%s:%d OUT w/h %d/%d paddr %08x\n", __func__, __LINE__, + pxp->pxp_conf_state.out_param.width, + pxp->pxp_conf_state.out_param.height, + pxp->pxp_conf_state.out_param.paddr); +} + +static void pxpdma_dostart_work(struct work_struct *w) +{ + struct pxps *pxp = container_of(w, struct pxps, work); + struct pxp_channel *pxp_chan = NULL; + unsigned long flags, flags1; + + while (__raw_readl(pxp->base + HW_PXP_CTRL) & BM_PXP_CTRL_ENABLE) + ; + + spin_lock_irqsave(&pxp->lock, flags); + if (list_empty(&head)) { + spin_unlock_irqrestore(&pxp->lock, flags); + return; + } + + pxp_chan = list_entry(head.next, struct pxp_channel, list); + + spin_lock_irqsave(&pxp_chan->lock, flags1); + if (!list_empty(&pxp_chan->active_list)) { + struct pxp_tx_desc *desc; + /* REVISIT */ + desc = pxpdma_first_active(pxp_chan); + __pxpdma_dostart(pxp_chan); + } + spin_unlock_irqrestore(&pxp_chan->lock, flags1); + + /* Configure PxP */ + pxp_config(pxp, pxp_chan); + + pxp_start(pxp); + + spin_unlock_irqrestore(&pxp->lock, flags); +} + +static void pxpdma_dequeue(struct pxp_channel *pxp_chan, struct list_head *list) +{ + struct pxp_tx_desc *desc = NULL; + do { + desc = pxpdma_first_queued(pxp_chan); + list_move_tail(&desc->list, list); + } while (!list_empty(&pxp_chan->queue)); +} + +static dma_cookie_t pxp_tx_submit(struct dma_async_tx_descriptor *tx) +{ + struct pxp_tx_desc *desc = to_tx_desc(tx); + struct pxp_channel *pxp_chan = to_pxp_channel(tx->chan); + dma_cookie_t cookie; + unsigned long flags; + + dev_dbg(&pxp_chan->dma_chan.dev->device, "received TX\n"); + + mutex_lock(&pxp_chan->chan_mutex); + + cookie = pxp_chan->dma_chan.cookie; + + if (++cookie < 0) + cookie = 1; + + /* from dmaengine.h: "last cookie value returned to client" */ + pxp_chan->dma_chan.cookie = cookie; + tx->cookie = cookie; + + /* pxp_chan->lock can be taken under ichan->lock, but not v.v. */ + spin_lock_irqsave(&pxp_chan->lock, flags); + + /* Here we add the tx descriptor to our PxP task queue. */ + list_add_tail(&desc->list, &pxp_chan->queue); + + spin_unlock_irqrestore(&pxp_chan->lock, flags); + + dev_dbg(&pxp_chan->dma_chan.dev->device, "done TX\n"); + + mutex_unlock(&pxp_chan->chan_mutex); + return cookie; +} + +/* Called with pxp_chan->chan_mutex held */ +static int pxp_desc_alloc(struct pxp_channel *pxp_chan, int n) +{ + struct pxp_tx_desc *desc = vmalloc(n * sizeof(struct pxp_tx_desc)); + + if (!desc) + return -ENOMEM; + + pxp_chan->n_tx_desc = n; + pxp_chan->desc = desc; + INIT_LIST_HEAD(&pxp_chan->active_list); + INIT_LIST_HEAD(&pxp_chan->queue); + INIT_LIST_HEAD(&pxp_chan->free_list); + + while (n--) { + struct dma_async_tx_descriptor *txd = &desc->txd; + + memset(txd, 0, sizeof(*txd)); + dma_async_tx_descriptor_init(txd, &pxp_chan->dma_chan); + txd->tx_submit = pxp_tx_submit; + + list_add(&desc->list, &pxp_chan->free_list); + + desc++; + } + + return 0; +} + +/** + * pxp_init_channel() - initialize a PXP channel. + * @pxp_dma: PXP DMA context. + * @pchan: pointer to the channel object. + * @return 0 on success or negative error code on failure. + */ +static int pxp_init_channel(struct pxp_dma *pxp_dma, + struct pxp_channel *pxp_chan) +{ + unsigned long flags; + struct pxps *pxp = to_pxp(pxp_dma); + int ret = 0, n_desc = 0; + + /* + * We are using _virtual_ channel here. + * Each channel contains all parameters of corresponding layers + * for one transaction; each layer is represented as one descriptor + * (i.e., pxp_tx_desc) here. + */ + + spin_lock_irqsave(&pxp->lock, flags); + + /* max desc nr: S0+OL+OUT = 1+8+1 */ + n_desc = 10; + + spin_unlock_irqrestore(&pxp->lock, flags); + + if (n_desc && !pxp_chan->desc) + ret = pxp_desc_alloc(pxp_chan, n_desc); + + return ret; +} + +/** + * pxp_uninit_channel() - uninitialize a PXP channel. + * @pxp_dma: PXP DMA context. + * @pchan: pointer to the channel object. + * @return 0 on success or negative error code on failure. + */ +static int pxp_uninit_channel(struct pxp_dma *pxp_dma, + struct pxp_channel *pxp_chan) +{ + int ret = 0; + + if (pxp_chan->desc) + vfree(pxp_chan->desc); + + pxp_chan->desc = NULL; + + return ret; +} + +static irqreturn_t pxp_irq(int irq, void *dev_id) +{ + struct pxps *pxp = dev_id; + struct pxp_channel *pxp_chan; + struct pxp_tx_desc *desc; + dma_async_tx_callback callback; + void *callback_param; + unsigned long flags, flags1; + u32 hist_status; + + hist_status = + __raw_readl(pxp->base + HW_PXP_HIST_CTRL) & BM_PXP_HIST_CTRL_STATUS; + + __raw_writel(BM_PXP_STAT_IRQ, pxp->base + HW_PXP_STAT_CLR); + + spin_lock_irqsave(&pxp->lock, flags); + + if (list_empty(&head)) { + spin_unlock_irqrestore(&pxp->lock, flags); + return IRQ_NONE; + } + + spin_lock_irqsave(&pxp_chan->lock, flags1); + pxp_chan = list_entry(head.next, struct pxp_channel, list); + list_del_init(&pxp_chan->list); + + if (list_empty(&pxp_chan->active_list)) { + pr_debug("PXP_IRQ pxp_chan->active_list empty. chan_id %d\n", + pxp_chan->dma_chan.chan_id); + spin_unlock_irqrestore(&pxp_chan->lock, flags1); + spin_unlock_irqrestore(&pxp->lock, flags); + return IRQ_NONE; + } + + /* Get descriptor and call callback */ + desc = pxpdma_first_active(pxp_chan); + + pxp_chan->completed = desc->txd.cookie; + + callback = desc->txd.callback; + callback_param = desc->txd.callback_param; + + /* Send histogram status back to caller */ + desc->hist_status = hist_status; + + if ((desc->txd.flags & DMA_PREP_INTERRUPT) && callback) + callback(callback_param); + + pxp_chan->status = PXP_CHANNEL_INITIALIZED; + + list_splice_init(&desc->tx_list, &pxp_chan->free_list); + list_move(&desc->list, &pxp_chan->free_list); + + list_del(&pxp_chan->list); + + wake_up(&pxp->done); + + spin_unlock_irqrestore(&pxp_chan->lock, flags1); + spin_unlock_irqrestore(&pxp->lock, flags); + + return IRQ_HANDLED; +} + +static struct pxp_tx_desc *pxp_desc_get(struct pxp_channel *pxp_chan) +{ + struct pxp_tx_desc *desc, *_desc; + struct pxp_tx_desc *ret = NULL; + unsigned long flags; + + spin_lock_irqsave(&pxp_chan->lock, flags); + list_for_each_entry_safe(desc, _desc, &pxp_chan->free_list, list) { + list_del_init(&desc->list); + ret = desc; + break; + } + spin_unlock_irqrestore(&pxp_chan->lock, flags); + + return ret; +} + +static void pxpdma_desc_put(struct pxp_channel *pxp_chan, + struct pxp_tx_desc *desc) +{ + if (desc) { + struct device *dev = &pxp_chan->dma_chan.dev->device; + struct pxp_tx_desc *child; + unsigned long flags; + + spin_lock_irqsave(&pxp_chan->lock, flags); + list_for_each_entry(child, &desc->tx_list, list) + dev_info(dev, "moving child desc %p to freelist\n", child); + list_splice_init(&desc->tx_list, &pxp_chan->free_list); + dev_info(dev, "moving desc %p to freelist\n", desc); + list_add(&desc->list, &pxp_chan->free_list); + spin_unlock_irqrestore(&pxp_chan->lock, flags); + } +} + +/* Allocate and initialise a transfer descriptor. */ +static struct dma_async_tx_descriptor *pxp_prep_slave_sg(struct dma_chan *chan, + struct scatterlist + *sgl, + unsigned int sg_len, + enum dma_data_direction + direction, + unsigned long tx_flags) +{ + struct pxp_channel *pxp_chan = to_pxp_channel(chan); + struct pxp_dma *pxp_dma = to_pxp_dma(chan->device); + struct pxps *pxp = to_pxp(pxp_dma); + struct pxp_tx_desc *desc = NULL; + struct pxp_tx_desc *first = NULL, *prev = NULL; + struct scatterlist *sg; + unsigned long flags; + dma_addr_t phys_addr; + int i; + + if (direction != DMA_FROM_DEVICE && direction != DMA_TO_DEVICE) { + dev_err(chan->device->dev, "Invalid DMA direction %d!\n", + direction); + return NULL; + } + + if (unlikely(sg_len < 2)) + return NULL; + + spin_lock_irqsave(&pxp_chan->lock, flags); + for_each_sg(sgl, sg, sg_len, i) { + desc = pxp_desc_get(pxp_chan); + if (!desc) { + pxpdma_desc_put(pxp_chan, first); + dev_err(chan->device->dev, "Can't get DMA desc.\n"); + spin_unlock_irqrestore(&pxp_chan->lock, flags); + return NULL; + } + + phys_addr = sg_dma_address(sg); + + if (!first) { + first = desc; + + desc->layer_param.s0_param.paddr = phys_addr; + } else { + list_add_tail(&desc->list, &first->tx_list); + prev->next = desc; + desc->next = NULL; + + if (i == 1) + desc->layer_param.out_param.paddr = phys_addr; + else + desc->layer_param.ol_param.paddr = phys_addr; + } + + prev = desc; + } + spin_unlock_irqrestore(&pxp_chan->lock, flags); + + pxp->pxp_conf_state.layer_nr = sg_len; + first->txd.flags = tx_flags; + first->len = sg_len; + pr_debug("%s:%d first %p, first->len %d, flags %08x\n", + __func__, __LINE__, first, first->len, first->txd.flags); + + return &first->txd; +} + +static void pxp_issue_pending(struct dma_chan *chan) +{ + struct pxp_channel *pxp_chan = to_pxp_channel(chan); + struct pxp_dma *pxp_dma = to_pxp_dma(chan->device); + struct pxps *pxp = to_pxp(pxp_dma); + unsigned long flags0, flags; + + spin_lock_irqsave(&pxp->lock, flags0); + spin_lock_irqsave(&pxp_chan->lock, flags); + + if (!list_empty(&pxp_chan->queue)) { + pxpdma_dequeue(pxp_chan, &pxp_chan->active_list); + pxp_chan->status = PXP_CHANNEL_READY; + list_add_tail(&pxp_chan->list, &head); + } else { + spin_unlock_irqrestore(&pxp_chan->lock, flags); + spin_unlock_irqrestore(&pxp->lock, flags0); + return; + } + spin_unlock_irqrestore(&pxp_chan->lock, flags); + spin_unlock_irqrestore(&pxp->lock, flags0); + + if (!wait_event_interruptible_timeout(pxp->done, PXP_WAITCON, 2 * HZ) || + signal_pending(current)) + return; + + queue_work(pxp->workqueue, &pxp->work); +} + +static void __pxp_terminate_all(struct dma_chan *chan) +{ + struct pxp_channel *pxp_chan = to_pxp_channel(chan); + struct pxp_dma *pxp_dma = to_pxp_dma(chan->device); + unsigned long flags; + + cancel_work_sync(&to_pxp(pxp_dma)->work); + + /* pchan->queue is modified in ISR, have to spinlock */ + spin_lock_irqsave(&pxp_chan->lock, flags); + list_splice_init(&pxp_chan->queue, &pxp_chan->free_list); + list_splice_init(&pxp_chan->active_list, &pxp_chan->free_list); + + spin_unlock_irqrestore(&pxp_chan->lock, flags); + + pxp_chan->status = PXP_CHANNEL_INITIALIZED; +} + +static void pxp_control(struct dma_chan *chan, enum dma_ctrl_cmd cmd) +{ + struct pxp_channel *pxp_chan = to_pxp_channel(chan); + + /* Only supports DMA_TERMINATE_ALL */ + if (cmd != DMA_TERMINATE_ALL) + return -ENXIO; + + mutex_lock(&pxp_chan->chan_mutex); + __pxp_terminate_all(chan); + mutex_unlock(&pxp_chan->chan_mutex); +} + +static int pxp_alloc_chan_resources(struct dma_chan *chan) +{ + struct pxp_channel *pxp_chan = to_pxp_channel(chan); + struct pxp_dma *pxp_dma = to_pxp_dma(chan->device); + int ret; + + /* dmaengine.c now guarantees to only offer free channels */ + BUG_ON(chan->client_count > 1); + WARN_ON(pxp_chan->status != PXP_CHANNEL_FREE); + + chan->cookie = 1; + pxp_chan->completed = -ENXIO; + + pr_debug("%s dma_chan.chan_id %d\n", __func__, chan->chan_id); + ret = pxp_init_channel(pxp_dma, pxp_chan); + if (ret < 0) + goto err_chan; + + pxp_chan->status = PXP_CHANNEL_INITIALIZED; + + dev_dbg(&chan->dev->device, "Found channel 0x%x, irq %d\n", + chan->chan_id, pxp_chan->eof_irq); + + return ret; + +err_chan: + return ret; +} + +static void pxp_free_chan_resources(struct dma_chan *chan) +{ + struct pxp_channel *pxp_chan = to_pxp_channel(chan); + struct pxp_dma *pxp_dma = to_pxp_dma(chan->device); + + mutex_lock(&pxp_chan->chan_mutex); + + __pxp_terminate_all(chan); + + pxp_chan->status = PXP_CHANNEL_FREE; + + pxp_uninit_channel(pxp_dma, pxp_chan); + + mutex_unlock(&pxp_chan->chan_mutex); +} + +static enum dma_status pxp_tx_status(struct dma_chan *chan, + dma_cookie_t cookie, + struct dma_tx_state *txstate) +{ + struct pxp_channel *pxp_chan = to_pxp_channel(chan); + + if (cookie != chan->cookie) + return DMA_ERROR; + + if (txstate) { + txstate->last = pxp_chan->completed; + txstate->used = chan->cookie; + txstate->residue = 0; + } + return DMA_SUCCESS; +} + +static int pxp_hw_init(struct pxps *pxp) +{ + struct pxp_config_data *pxp_conf = &pxp->pxp_conf_state; + struct pxp_proc_data *proc_data = &pxp_conf->proc_data; + u32 reg_val; + int i; + + /* Pull PxP out of reset */ + __raw_writel(0, pxp->base + HW_PXP_CTRL); + + /* Config defaults */ + + /* Initialize non-channel-specific PxP parameters */ + proc_data->drect.left = proc_data->srect.left = 0; + proc_data->drect.top = proc_data->srect.top = 0; + proc_data->drect.width = proc_data->srect.width = 0; + proc_data->drect.height = proc_data->srect.height = 0; + proc_data->scaling = 0; + proc_data->hflip = 0; + proc_data->vflip = 0; + proc_data->rotate = 0; + proc_data->bgcolor = 0; + + /* Initialize S0 channel parameters */ + pxp_conf->s0_param.pixel_fmt = pxp_s0_formats[0]; + pxp_conf->s0_param.width = 0; + pxp_conf->s0_param.height = 0; + pxp_conf->s0_param.color_key = -1; + pxp_conf->s0_param.color_key_enable = false; + + /* Initialize OL channel parameters */ + for (i = 0; i < 8; i++) { + pxp_conf->ol_param[i].combine_enable = false; + pxp_conf->ol_param[i].width = 0; + pxp_conf->ol_param[i].height = 0; + pxp_conf->ol_param[i].pixel_fmt = PXP_PIX_FMT_RGB565; + pxp_conf->ol_param[i].color_key_enable = false; + pxp_conf->ol_param[i].color_key = -1; + pxp_conf->ol_param[i].global_alpha_enable = false; + pxp_conf->ol_param[i].global_alpha = 0; + pxp_conf->ol_param[i].local_alpha_enable = false; + } + + /* Initialize Output channel parameters */ + pxp_conf->out_param.width = 0; + pxp_conf->out_param.height = 0; + pxp_conf->out_param.pixel_fmt = PXP_PIX_FMT_RGB565; + + proc_data->overlay_state = 0; + + /* Write default h/w config */ + pxp_set_ctrl(pxp); + pxp_set_s0param(pxp); + pxp_set_s0crop(pxp); + for (i = 0; i < 8; i++) { + pxp_set_oln(i, pxp); + pxp_set_olparam(i, pxp); + pxp_set_olcolorkey(i, pxp); + } + pxp_set_s0colorkey(pxp); + pxp_set_csc(pxp); + pxp_set_bg(pxp); + pxp_set_lut(pxp); + + /* One-time histogram configuration */ + reg_val = + BF_PXP_HIST_CTRL_PANEL_MODE(BV_PXP_HIST_CTRL_PANEL_MODE__GRAY16); + __raw_writel(reg_val, pxp->base + HW_PXP_HIST_CTRL); + + reg_val = BF_PXP_HIST2_PARAM_VALUE0(0x00) | + BF_PXP_HIST2_PARAM_VALUE1(0x00F); + __raw_writel(reg_val, pxp->base + HW_PXP_HIST2_PARAM); + + reg_val = BF_PXP_HIST4_PARAM_VALUE0(0x00) | + BF_PXP_HIST4_PARAM_VALUE1(0x05) | + BF_PXP_HIST4_PARAM_VALUE2(0x0A) | BF_PXP_HIST4_PARAM_VALUE3(0x0F); + __raw_writel(reg_val, pxp->base + HW_PXP_HIST4_PARAM); + + reg_val = BF_PXP_HIST8_PARAM0_VALUE0(0x00) | + BF_PXP_HIST8_PARAM0_VALUE1(0x02) | + BF_PXP_HIST8_PARAM0_VALUE2(0x04) | BF_PXP_HIST8_PARAM0_VALUE3(0x06); + __raw_writel(reg_val, pxp->base + HW_PXP_HIST8_PARAM0); + reg_val = BF_PXP_HIST8_PARAM1_VALUE4(0x09) | + BF_PXP_HIST8_PARAM1_VALUE5(0x0B) | + BF_PXP_HIST8_PARAM1_VALUE6(0x0D) | BF_PXP_HIST8_PARAM1_VALUE7(0x0F); + __raw_writel(reg_val, pxp->base + HW_PXP_HIST8_PARAM1); + + reg_val = BF_PXP_HIST16_PARAM0_VALUE0(0x00) | + BF_PXP_HIST16_PARAM0_VALUE1(0x01) | + BF_PXP_HIST16_PARAM0_VALUE2(0x02) | + BF_PXP_HIST16_PARAM0_VALUE3(0x03); + __raw_writel(reg_val, pxp->base + HW_PXP_HIST16_PARAM0); + reg_val = BF_PXP_HIST16_PARAM1_VALUE4(0x04) | + BF_PXP_HIST16_PARAM1_VALUE5(0x05) | + BF_PXP_HIST16_PARAM1_VALUE6(0x06) | + BF_PXP_HIST16_PARAM1_VALUE7(0x07); + __raw_writel(reg_val, pxp->base + HW_PXP_HIST16_PARAM1); + reg_val = BF_PXP_HIST16_PARAM2_VALUE8(0x08) | + BF_PXP_HIST16_PARAM2_VALUE9(0x09) | + BF_PXP_HIST16_PARAM2_VALUE10(0x0A) | + BF_PXP_HIST16_PARAM2_VALUE11(0x0B); + __raw_writel(reg_val, pxp->base + HW_PXP_HIST16_PARAM2); + reg_val = BF_PXP_HIST16_PARAM3_VALUE12(0x0C) | + BF_PXP_HIST16_PARAM3_VALUE13(0x0D) | + BF_PXP_HIST16_PARAM3_VALUE14(0x0E) | + BF_PXP_HIST16_PARAM3_VALUE15(0x0F); + __raw_writel(reg_val, pxp->base + HW_PXP_HIST16_PARAM3); + + return 0; +} + +static int pxp_dma_init(struct pxps *pxp) +{ + struct pxp_dma *pxp_dma = &pxp->pxp_dma; + struct dma_device *dma = &pxp_dma->dma; + int i; + + dma_cap_set(DMA_SLAVE, dma->cap_mask); + dma_cap_set(DMA_PRIVATE, dma->cap_mask); + + /* Compulsory common fields */ + dma->dev = pxp->dev; + dma->device_alloc_chan_resources = pxp_alloc_chan_resources; + dma->device_free_chan_resources = pxp_free_chan_resources; + dma->device_tx_status = pxp_tx_status; + dma->device_issue_pending = pxp_issue_pending; + + /* Compulsory for DMA_SLAVE fields */ + dma->device_prep_slave_sg = pxp_prep_slave_sg; + dma->device_control = pxp_control; + + /* Initialize PxP Channels */ + INIT_LIST_HEAD(&dma->channels); + for (i = 0; i < NR_PXP_VIRT_CHANNEL; i++) { + struct pxp_channel *pxp_chan = pxp->channel + i; + struct dma_chan *dma_chan = &pxp_chan->dma_chan; + + spin_lock_init(&pxp_chan->lock); + mutex_init(&pxp_chan->chan_mutex); + + /* Only one EOF IRQ for PxP, shared by all channels */ + pxp_chan->eof_irq = pxp->irq; + pxp_chan->status = PXP_CHANNEL_FREE; + pxp_chan->completed = -ENXIO; + snprintf(pxp_chan->eof_name, sizeof(pxp_chan->eof_name), + "PXP EOF %d", i); + + dma_chan->device = &pxp_dma->dma; + dma_chan->cookie = 1; + dma_chan->chan_id = i; + list_add_tail(&dma_chan->device_node, &dma->channels); + } + + return dma_async_device_register(&pxp_dma->dma); +} + +static int pxp_probe(struct platform_device *pdev) +{ + struct pxps *pxp; + struct resource *res; + int irq; + int err = 0; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + irq = platform_get_irq(pdev, 0); + if (!res || irq < 0) { + err = -ENODEV; + goto exit; + } + + pxp = kzalloc(sizeof(*pxp), GFP_KERNEL); + if (!pxp) { + dev_err(&pdev->dev, "failed to allocate control object\n"); + err = -ENOMEM; + goto exit; + } + + pxp->dev = &pdev->dev; + + platform_set_drvdata(pdev, pxp); + pxp->irq = irq; + + spin_lock_init(&pxp->lock); + mutex_init(&pxp->mutex); + + if (!request_mem_region(res->start, resource_size(res), "pxp-mem")) { + err = -EBUSY; + goto freepxp; + } + + pxp->base = ioremap(res->start, SZ_4K); + pxp->pdev = pdev; + + pxp->clk = clk_get(NULL, "pxp_axi"); + clk_enable(pxp->clk); + + err = pxp_hw_init(pxp); + if (err) { + dev_err(&pdev->dev, "failed to initialize hardware\n"); + goto release; + } + + err = request_irq(pxp->irq, pxp_irq, 0, "pxp-irq", pxp); + if (err) + goto release; + /* Initialize DMA engine */ + err = pxp_dma_init(pxp); + if (err < 0) + goto err_dma_init; + + init_waitqueue_head(&pxp->done); + INIT_WORK(&pxp->work, pxpdma_dostart_work); + pxp->workqueue = create_singlethread_workqueue("pxp_dma"); +exit: + return err; +err_dma_init: + free_irq(pxp->irq, pxp); + clk_disable(pxp->clk); +release: + release_mem_region(res->start, resource_size(res)); +freepxp: + kfree(pxp); + dev_err(&pdev->dev, "Exiting (unsuccessfully) pxp_probe function\n"); + return err; +} + +static int __devexit pxp_remove(struct platform_device *pdev) +{ + struct pxps *pxp = platform_get_drvdata(pdev); + + cancel_work_sync(&pxp->work); + kfree(pxp); + + free_irq(pxp->irq, pxp); + clk_disable(pxp->clk); + clk_put(pxp->clk); + iounmap(pxp->base); + + kfree(pxp); + + return 0; +} + +#ifdef CONFIG_PM +static int pxp_suspend(struct platform_device *pdev, pm_message_t state) +{ + struct pxps *pxp = platform_get_drvdata(pdev); + + while (__raw_readl(pxp->base + HW_PXP_CTRL) & BM_PXP_CTRL_ENABLE) + ; + + __raw_writel(BM_PXP_CTRL_SFTRST, pxp->base + HW_PXP_CTRL); + clk_disable(pxp->clk); + + return 0; +} + +static int pxp_resume(struct platform_device *pdev) +{ + struct pxps *pxp = platform_get_drvdata(pdev); + + clk_enable(pxp->clk); + /* Pull PxP out of reset */ + __raw_writel(0, pxp->base + HW_PXP_CTRL); + + return 0; +} +#else +#define pxp_suspend NULL +#define pxp_resume NULL +#endif + +static struct platform_driver pxp_driver = { + .driver = { + .name = "mxc-pxp", + }, + .probe = pxp_probe, + .remove = __exit_p(pxp_remove), + .suspend = pxp_suspend, + .resume = pxp_resume, +}; + +static int __init pxp_init(void) +{ + return platform_driver_register(&pxp_driver); +} + +subsys_initcall(pxp_init); + +static void __exit pxp_exit(void) +{ + platform_driver_unregister(&pxp_driver); +} + +module_exit(pxp_exit); + +MODULE_DESCRIPTION("i.MX PxP driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/dma/pxp/regs-pxp.h b/drivers/dma/pxp/regs-pxp.h new file mode 100644 index 000000000000..b0c1b00fdfa0 --- /dev/null +++ b/drivers/dma/pxp/regs-pxp.h @@ -0,0 +1,949 @@ +/* + * Freescale PXP Register Definitions + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * This file is created by xml file. Don't Edit it. + * + * Xml Revision: 1.6 + * Template revision: 1.3 + */ + +#ifndef __ARCH_ARM___PXP_H +#define __ARCH_ARM___PXP_H + + +#define HW_PXP_CTRL (0x00000000) +#define HW_PXP_CTRL_SET (0x00000004) +#define HW_PXP_CTRL_CLR (0x00000008) +#define HW_PXP_CTRL_TOG (0x0000000c) + +#define BM_PXP_CTRL_SFTRST 0x80000000 +#define BM_PXP_CTRL_CLKGATE 0x40000000 +#define BM_PXP_CTRL_RSVD 0x20000000 +#define BM_PXP_CTRL_EN_REPEAT 0x10000000 +#define BP_PXP_CTRL_INTERLACED_OUTPUT 26 +#define BM_PXP_CTRL_INTERLACED_OUTPUT 0x0C000000 +#define BF_PXP_CTRL_INTERLACED_OUTPUT(v) \ + (((v) << 26) & BM_PXP_CTRL_INTERLACED_OUTPUT) +#define BV_PXP_CTRL_INTERLACED_OUTPUT__PROGRESSIVE 0x0 +#define BV_PXP_CTRL_INTERLACED_OUTPUT__FIELD0 0x1 +#define BV_PXP_CTRL_INTERLACED_OUTPUT__FIELD1 0x2 +#define BV_PXP_CTRL_INTERLACED_OUTPUT__INTERLACED 0x3 +#define BP_PXP_CTRL_INTERLACED_INPUT 24 +#define BM_PXP_CTRL_INTERLACED_INPUT 0x03000000 +#define BF_PXP_CTRL_INTERLACED_INPUT(v) \ + (((v) << 24) & BM_PXP_CTRL_INTERLACED_INPUT) +#define BV_PXP_CTRL_INTERLACED_INPUT__PROGRESSIVE 0x0 +#define BV_PXP_CTRL_INTERLACED_INPUT__FIELD0 0x2 +#define BV_PXP_CTRL_INTERLACED_INPUT__FIELD1 0x3 +#define BM_PXP_CTRL_BLOCK_SIZE 0x00800000 +#define BV_PXP_CTRL_BLOCK_SIZE__8X8 0x0 +#define BV_PXP_CTRL_BLOCK_SIZE__16X16 0x1 +#define BM_PXP_CTRL_ALPHA_OUTPUT 0x00400000 +#define BM_PXP_CTRL_IN_PLACE 0x00200000 +#define BM_PXP_CTRL_DELTA 0x00100000 +#define BM_PXP_CTRL_CROP 0x00080000 +#define BM_PXP_CTRL_SCALE 0x00040000 +#define BM_PXP_CTRL_UPSAMPLE 0x00020000 +#define BM_PXP_CTRL_SUBSAMPLE 0x00010000 +#define BP_PXP_CTRL_S0_FORMAT 12 +#define BM_PXP_CTRL_S0_FORMAT 0x0000F000 +#define BF_PXP_CTRL_S0_FORMAT(v) \ + (((v) << 12) & BM_PXP_CTRL_S0_FORMAT) +#define BV_PXP_CTRL_S0_FORMAT__RGB888 0x1 +#define BV_PXP_CTRL_S0_FORMAT__RGB565 0x4 +#define BV_PXP_CTRL_S0_FORMAT__RGB555 0x5 +#define BV_PXP_CTRL_S0_FORMAT__YUV422 0x8 +#define BV_PXP_CTRL_S0_FORMAT__YUV420 0x9 +#define BV_PXP_CTRL_S0_FORMAT__UYVY1P422 0xA +#define BV_PXP_CTRL_S0_FORMAT__VYUY1P422 0xB +#define BV_PXP_CTRL_S0_FORMAT__YUV2P422 0xC +#define BV_PXP_CTRL_S0_FORMAT__YUV2P420 0xD +#define BV_PXP_CTRL_S0_FORMAT__YVU2P422 0xE +#define BV_PXP_CTRL_S0_FORMAT__YVU2P420 0xF +#define BM_PXP_CTRL_VFLIP 0x00000800 +#define BM_PXP_CTRL_HFLIP 0x00000400 +#define BP_PXP_CTRL_ROTATE 8 +#define BM_PXP_CTRL_ROTATE 0x00000300 +#define BF_PXP_CTRL_ROTATE(v) \ + (((v) << 8) & BM_PXP_CTRL_ROTATE) +#define BV_PXP_CTRL_ROTATE__ROT_0 0x0 +#define BV_PXP_CTRL_ROTATE__ROT_90 0x1 +#define BV_PXP_CTRL_ROTATE__ROT_180 0x2 +#define BV_PXP_CTRL_ROTATE__ROT_270 0x3 +#define BP_PXP_CTRL_OUTBUF_FORMAT 4 +#define BM_PXP_CTRL_OUTBUF_FORMAT 0x000000F0 +#define BF_PXP_CTRL_OUTBUF_FORMAT(v) \ + (((v) << 4) & BM_PXP_CTRL_OUTBUF_FORMAT) +#define BV_PXP_CTRL_OUTBUF_FORMAT__ARGB8888 0x0 +#define BV_PXP_CTRL_OUTBUF_FORMAT__RGB888 0x1 +#define BV_PXP_CTRL_OUTBUF_FORMAT__RGB888P 0x2 +#define BV_PXP_CTRL_OUTBUF_FORMAT__ARGB1555 0x3 +#define BV_PXP_CTRL_OUTBUF_FORMAT__RGB565 0x4 +#define BV_PXP_CTRL_OUTBUF_FORMAT__RGB555 0x5 +#define BV_PXP_CTRL_OUTBUF_FORMAT__YUV444 0x7 +#define BV_PXP_CTRL_OUTBUF_FORMAT__MONOC8 0x8 +#define BV_PXP_CTRL_OUTBUF_FORMAT__MONOC4 0x9 +#define BV_PXP_CTRL_OUTBUF_FORMAT__UYVY1P422 0xA +#define BV_PXP_CTRL_OUTBUF_FORMAT__VYUY1P422 0xB +#define BV_PXP_CTRL_OUTBUF_FORMAT__YUV2P422 0xC +#define BV_PXP_CTRL_OUTBUF_FORMAT__YUV2P420 0xD +#define BV_PXP_CTRL_OUTBUF_FORMAT__YVU2P422 0xE +#define BV_PXP_CTRL_OUTBUF_FORMAT__YVU2P420 0xF +#define BM_PXP_CTRL_ENABLE_LCD_HANDSHAKE 0x00000008 +#define BM_PXP_CTRL_NEXT_IRQ_ENABLE 0x00000004 +#define BM_PXP_CTRL_IRQ_ENABLE 0x00000002 +#define BM_PXP_CTRL_ENABLE 0x00000001 + +#define HW_PXP_STAT (0x00000010) +#define HW_PXP_STAT_SET (0x00000014) +#define HW_PXP_STAT_CLR (0x00000018) +#define HW_PXP_STAT_TOG (0x0000001c) + +#define BP_PXP_STAT_BLOCKX 24 +#define BM_PXP_STAT_BLOCKX 0xFF000000 +#define BF_PXP_STAT_BLOCKX(v) \ + (((v) << 24) & BM_PXP_STAT_BLOCKX) +#define BP_PXP_STAT_BLOCKY 16 +#define BM_PXP_STAT_BLOCKY 0x00FF0000 +#define BF_PXP_STAT_BLOCKY(v) \ + (((v) << 16) & BM_PXP_STAT_BLOCKY) +#define BP_PXP_STAT_RSVD2 8 +#define BM_PXP_STAT_RSVD2 0x0000FF00 +#define BF_PXP_STAT_RSVD2(v) \ + (((v) << 8) & BM_PXP_STAT_RSVD2) +#define BP_PXP_STAT_AXI_ERROR_ID 4 +#define BM_PXP_STAT_AXI_ERROR_ID 0x000000F0 +#define BF_PXP_STAT_AXI_ERROR_ID(v) \ + (((v) << 4) & BM_PXP_STAT_AXI_ERROR_ID) +#define BM_PXP_STAT_NEXT_IRQ 0x00000008 +#define BM_PXP_STAT_AXI_READ_ERROR 0x00000004 +#define BM_PXP_STAT_AXI_WRITE_ERROR 0x00000002 +#define BM_PXP_STAT_IRQ 0x00000001 + +#define HW_PXP_OUTBUF (0x00000020) + +#define BP_PXP_OUTBUF_ADDR 0 +#define BM_PXP_OUTBUF_ADDR 0xFFFFFFFF +#define BF_PXP_OUTBUF_ADDR(v) (v) + +#define HW_PXP_OUTBUF2 (0x00000030) + +#define BP_PXP_OUTBUF2_ADDR 0 +#define BM_PXP_OUTBUF2_ADDR 0xFFFFFFFF +#define BF_PXP_OUTBUF2_ADDR(v) (v) + +#define HW_PXP_OUTSIZE (0x00000040) + +#define BP_PXP_OUTSIZE_ALPHA 24 +#define BM_PXP_OUTSIZE_ALPHA 0xFF000000 +#define BF_PXP_OUTSIZE_ALPHA(v) \ + (((v) << 24) & BM_PXP_OUTSIZE_ALPHA) +#define BP_PXP_OUTSIZE_WIDTH 12 +#define BM_PXP_OUTSIZE_WIDTH 0x00FFF000 +#define BF_PXP_OUTSIZE_WIDTH(v) \ + (((v) << 12) & BM_PXP_OUTSIZE_WIDTH) +#define BP_PXP_OUTSIZE_HEIGHT 0 +#define BM_PXP_OUTSIZE_HEIGHT 0x00000FFF +#define BF_PXP_OUTSIZE_HEIGHT(v) \ + (((v) << 0) & BM_PXP_OUTSIZE_HEIGHT) + +#define HW_PXP_S0BUF (0x00000050) + +#define BP_PXP_S0BUF_ADDR 0 +#define BM_PXP_S0BUF_ADDR 0xFFFFFFFF +#define BF_PXP_S0BUF_ADDR(v) (v) + +#define HW_PXP_S0UBUF (0x00000060) + +#define BP_PXP_S0UBUF_ADDR 0 +#define BM_PXP_S0UBUF_ADDR 0xFFFFFFFF +#define BF_PXP_S0UBUF_ADDR(v) (v) + +#define HW_PXP_S0VBUF (0x00000070) + +#define BP_PXP_S0VBUF_ADDR 0 +#define BM_PXP_S0VBUF_ADDR 0xFFFFFFFF +#define BF_PXP_S0VBUF_ADDR(v) (v) + +#define HW_PXP_S0PARAM (0x00000080) + +#define BP_PXP_S0PARAM_XBASE 24 +#define BM_PXP_S0PARAM_XBASE 0xFF000000 +#define BF_PXP_S0PARAM_XBASE(v) \ + (((v) << 24) & BM_PXP_S0PARAM_XBASE) +#define BP_PXP_S0PARAM_YBASE 16 +#define BM_PXP_S0PARAM_YBASE 0x00FF0000 +#define BF_PXP_S0PARAM_YBASE(v) \ + (((v) << 16) & BM_PXP_S0PARAM_YBASE) +#define BP_PXP_S0PARAM_WIDTH 8 +#define BM_PXP_S0PARAM_WIDTH 0x0000FF00 +#define BF_PXP_S0PARAM_WIDTH(v) \ + (((v) << 8) & BM_PXP_S0PARAM_WIDTH) +#define BP_PXP_S0PARAM_HEIGHT 0 +#define BM_PXP_S0PARAM_HEIGHT 0x000000FF +#define BF_PXP_S0PARAM_HEIGHT(v) \ + (((v) << 0) & BM_PXP_S0PARAM_HEIGHT) + +#define HW_PXP_S0BACKGROUND (0x00000090) + +#define BP_PXP_S0BACKGROUND_COLOR 0 +#define BM_PXP_S0BACKGROUND_COLOR 0xFFFFFFFF +#define BF_PXP_S0BACKGROUND_COLOR(v) (v) + +#define HW_PXP_S0CROP (0x000000a0) + +#define BP_PXP_S0CROP_XBASE 24 +#define BM_PXP_S0CROP_XBASE 0xFF000000 +#define BF_PXP_S0CROP_XBASE(v) \ + (((v) << 24) & BM_PXP_S0CROP_XBASE) +#define BP_PXP_S0CROP_YBASE 16 +#define BM_PXP_S0CROP_YBASE 0x00FF0000 +#define BF_PXP_S0CROP_YBASE(v) \ + (((v) << 16) & BM_PXP_S0CROP_YBASE) +#define BP_PXP_S0CROP_WIDTH 8 +#define BM_PXP_S0CROP_WIDTH 0x0000FF00 +#define BF_PXP_S0CROP_WIDTH(v) \ + (((v) << 8) & BM_PXP_S0CROP_WIDTH) +#define BP_PXP_S0CROP_HEIGHT 0 +#define BM_PXP_S0CROP_HEIGHT 0x000000FF +#define BF_PXP_S0CROP_HEIGHT(v) \ + (((v) << 0) & BM_PXP_S0CROP_HEIGHT) + +#define HW_PXP_S0SCALE (0x000000b0) + +#define BM_PXP_S0SCALE_RSVD2 0x80000000 +#define BP_PXP_S0SCALE_YSCALE 16 +#define BM_PXP_S0SCALE_YSCALE 0x7FFF0000 +#define BF_PXP_S0SCALE_YSCALE(v) \ + (((v) << 16) & BM_PXP_S0SCALE_YSCALE) +#define BM_PXP_S0SCALE_RSVD1 0x00008000 +#define BP_PXP_S0SCALE_XSCALE 0 +#define BM_PXP_S0SCALE_XSCALE 0x00007FFF +#define BF_PXP_S0SCALE_XSCALE(v) \ + (((v) << 0) & BM_PXP_S0SCALE_XSCALE) + +#define HW_PXP_S0OFFSET (0x000000c0) + +#define BP_PXP_S0OFFSET_RSVD2 28 +#define BM_PXP_S0OFFSET_RSVD2 0xF0000000 +#define BF_PXP_S0OFFSET_RSVD2(v) \ + (((v) << 28) & BM_PXP_S0OFFSET_RSVD2) +#define BP_PXP_S0OFFSET_YOFFSET 16 +#define BM_PXP_S0OFFSET_YOFFSET 0x0FFF0000 +#define BF_PXP_S0OFFSET_YOFFSET(v) \ + (((v) << 16) & BM_PXP_S0OFFSET_YOFFSET) +#define BP_PXP_S0OFFSET_RSVD1 12 +#define BM_PXP_S0OFFSET_RSVD1 0x0000F000 +#define BF_PXP_S0OFFSET_RSVD1(v) \ + (((v) << 12) & BM_PXP_S0OFFSET_RSVD1) +#define BP_PXP_S0OFFSET_XOFFSET 0 +#define BM_PXP_S0OFFSET_XOFFSET 0x00000FFF +#define BF_PXP_S0OFFSET_XOFFSET(v) \ + (((v) << 0) & BM_PXP_S0OFFSET_XOFFSET) + +#define HW_PXP_CSCCOEF0 (0x000000d0) + +#define BM_PXP_CSCCOEF0_YCBCR_MODE 0x80000000 +#define BM_PXP_CSCCOEF0_BYPASS 0x40000000 +#define BM_PXP_CSCCOEF0_RSVD1 0x20000000 +#define BP_PXP_CSCCOEF0_C0 18 +#define BM_PXP_CSCCOEF0_C0 0x1FFC0000 +#define BF_PXP_CSCCOEF0_C0(v) \ + (((v) << 18) & BM_PXP_CSCCOEF0_C0) +#define BP_PXP_CSCCOEF0_UV_OFFSET 9 +#define BM_PXP_CSCCOEF0_UV_OFFSET 0x0003FE00 +#define BF_PXP_CSCCOEF0_UV_OFFSET(v) \ + (((v) << 9) & BM_PXP_CSCCOEF0_UV_OFFSET) +#define BP_PXP_CSCCOEF0_Y_OFFSET 0 +#define BM_PXP_CSCCOEF0_Y_OFFSET 0x000001FF +#define BF_PXP_CSCCOEF0_Y_OFFSET(v) \ + (((v) << 0) & BM_PXP_CSCCOEF0_Y_OFFSET) + +#define HW_PXP_CSCCOEF1 (0x000000e0) + +#define BP_PXP_CSCCOEF1_RSVD1 27 +#define BM_PXP_CSCCOEF1_RSVD1 0xF8000000 +#define BF_PXP_CSCCOEF1_RSVD1(v) \ + (((v) << 27) & BM_PXP_CSCCOEF1_RSVD1) +#define BP_PXP_CSCCOEF1_C1 16 +#define BM_PXP_CSCCOEF1_C1 0x07FF0000 +#define BF_PXP_CSCCOEF1_C1(v) \ + (((v) << 16) & BM_PXP_CSCCOEF1_C1) +#define BP_PXP_CSCCOEF1_RSVD0 11 +#define BM_PXP_CSCCOEF1_RSVD0 0x0000F800 +#define BF_PXP_CSCCOEF1_RSVD0(v) \ + (((v) << 11) & BM_PXP_CSCCOEF1_RSVD0) +#define BP_PXP_CSCCOEF1_C4 0 +#define BM_PXP_CSCCOEF1_C4 0x000007FF +#define BF_PXP_CSCCOEF1_C4(v) \ + (((v) << 0) & BM_PXP_CSCCOEF1_C4) + +#define HW_PXP_CSCCOEF2 (0x000000f0) + +#define BP_PXP_CSCCOEF2_RSVD1 27 +#define BM_PXP_CSCCOEF2_RSVD1 0xF8000000 +#define BF_PXP_CSCCOEF2_RSVD1(v) \ + (((v) << 27) & BM_PXP_CSCCOEF2_RSVD1) +#define BP_PXP_CSCCOEF2_C2 16 +#define BM_PXP_CSCCOEF2_C2 0x07FF0000 +#define BF_PXP_CSCCOEF2_C2(v) \ + (((v) << 16) & BM_PXP_CSCCOEF2_C2) +#define BP_PXP_CSCCOEF2_RSVD0 11 +#define BM_PXP_CSCCOEF2_RSVD0 0x0000F800 +#define BF_PXP_CSCCOEF2_RSVD0(v) \ + (((v) << 11) & BM_PXP_CSCCOEF2_RSVD0) +#define BP_PXP_CSCCOEF2_C3 0 +#define BM_PXP_CSCCOEF2_C3 0x000007FF +#define BF_PXP_CSCCOEF2_C3(v) \ + (((v) << 0) & BM_PXP_CSCCOEF2_C3) + +#define HW_PXP_NEXT (0x00000100) +#define HW_PXP_NEXT_SET (0x00000104) +#define HW_PXP_NEXT_CLR (0x00000108) +#define HW_PXP_NEXT_TOG (0x0000010c) + +#define BP_PXP_NEXT_POINTER 2 +#define BM_PXP_NEXT_POINTER 0xFFFFFFFC +#define BF_PXP_NEXT_POINTER(v) \ + (((v) << 2) & BM_PXP_NEXT_POINTER) +#define BM_PXP_NEXT_RSVD 0x00000002 +#define BM_PXP_NEXT_ENABLED 0x00000001 + +#define HW_PXP_S0COLORKEYLOW (0x00000180) + +#define BP_PXP_S0COLORKEYLOW_RSVD1 24 +#define BM_PXP_S0COLORKEYLOW_RSVD1 0xFF000000 +#define BF_PXP_S0COLORKEYLOW_RSVD1(v) \ + (((v) << 24) & BM_PXP_S0COLORKEYLOW_RSVD1) +#define BP_PXP_S0COLORKEYLOW_PIXEL 0 +#define BM_PXP_S0COLORKEYLOW_PIXEL 0x00FFFFFF +#define BF_PXP_S0COLORKEYLOW_PIXEL(v) \ + (((v) << 0) & BM_PXP_S0COLORKEYLOW_PIXEL) + +#define HW_PXP_S0COLORKEYHIGH (0x00000190) + +#define BP_PXP_S0COLORKEYHIGH_RSVD1 24 +#define BM_PXP_S0COLORKEYHIGH_RSVD1 0xFF000000 +#define BF_PXP_S0COLORKEYHIGH_RSVD1(v) \ + (((v) << 24) & BM_PXP_S0COLORKEYHIGH_RSVD1) +#define BP_PXP_S0COLORKEYHIGH_PIXEL 0 +#define BM_PXP_S0COLORKEYHIGH_PIXEL 0x00FFFFFF +#define BF_PXP_S0COLORKEYHIGH_PIXEL(v) \ + (((v) << 0) & BM_PXP_S0COLORKEYHIGH_PIXEL) + +#define HW_PXP_OLCOLORKEYLOW (0x000001a0) + +#define BP_PXP_OLCOLORKEYLOW_RSVD1 24 +#define BM_PXP_OLCOLORKEYLOW_RSVD1 0xFF000000 +#define BF_PXP_OLCOLORKEYLOW_RSVD1(v) \ + (((v) << 24) & BM_PXP_OLCOLORKEYLOW_RSVD1) +#define BP_PXP_OLCOLORKEYLOW_PIXEL 0 +#define BM_PXP_OLCOLORKEYLOW_PIXEL 0x00FFFFFF +#define BF_PXP_OLCOLORKEYLOW_PIXEL(v) \ + (((v) << 0) & BM_PXP_OLCOLORKEYLOW_PIXEL) + +#define HW_PXP_OLCOLORKEYHIGH (0x000001b0) + +#define BP_PXP_OLCOLORKEYHIGH_RSVD1 24 +#define BM_PXP_OLCOLORKEYHIGH_RSVD1 0xFF000000 +#define BF_PXP_OLCOLORKEYHIGH_RSVD1(v) \ + (((v) << 24) & BM_PXP_OLCOLORKEYHIGH_RSVD1) +#define BP_PXP_OLCOLORKEYHIGH_PIXEL 0 +#define BM_PXP_OLCOLORKEYHIGH_PIXEL 0x00FFFFFF +#define BF_PXP_OLCOLORKEYHIGH_PIXEL(v) \ + (((v) << 0) & BM_PXP_OLCOLORKEYHIGH_PIXEL) + +#define HW_PXP_DEBUGCTRL (0x000001d0) + +#define BP_PXP_DEBUGCTRL_RSVD 8 +#define BM_PXP_DEBUGCTRL_RSVD 0xFFFFFF00 +#define BF_PXP_DEBUGCTRL_RSVD(v) \ + (((v) << 8) & BM_PXP_DEBUGCTRL_RSVD) +#define BP_PXP_DEBUGCTRL_SELECT 0 +#define BM_PXP_DEBUGCTRL_SELECT 0x000000FF +#define BF_PXP_DEBUGCTRL_SELECT(v) \ + (((v) << 0) & BM_PXP_DEBUGCTRL_SELECT) +#define BV_PXP_DEBUGCTRL_SELECT__NONE 0x0 +#define BV_PXP_DEBUGCTRL_SELECT__CTRL 0x1 +#define BV_PXP_DEBUGCTRL_SELECT__S0REGS 0x2 +#define BV_PXP_DEBUGCTRL_SELECT__S0BAX 0x3 +#define BV_PXP_DEBUGCTRL_SELECT__S0BAY 0x4 +#define BV_PXP_DEBUGCTRL_SELECT__PXBUF 0x5 +#define BV_PXP_DEBUGCTRL_SELECT__ROTATION 0x6 +#define BV_PXP_DEBUGCTRL_SELECT__ROTBUF0 0x7 +#define BV_PXP_DEBUGCTRL_SELECT__ROTBUF1 0x8 + +#define HW_PXP_DEBUG (0x000001e0) + +#define BP_PXP_DEBUG_DATA 0 +#define BM_PXP_DEBUG_DATA 0xFFFFFFFF +#define BF_PXP_DEBUG_DATA(v) (v) + +#define HW_PXP_VERSION (0x000001f0) + +#define BP_PXP_VERSION_MAJOR 24 +#define BM_PXP_VERSION_MAJOR 0xFF000000 +#define BF_PXP_VERSION_MAJOR(v) \ + (((v) << 24) & BM_PXP_VERSION_MAJOR) +#define BP_PXP_VERSION_MINOR 16 +#define BM_PXP_VERSION_MINOR 0x00FF0000 +#define BF_PXP_VERSION_MINOR(v) \ + (((v) << 16) & BM_PXP_VERSION_MINOR) +#define BP_PXP_VERSION_STEP 0 +#define BM_PXP_VERSION_STEP 0x0000FFFF +#define BF_PXP_VERSION_STEP(v) \ + (((v) << 0) & BM_PXP_VERSION_STEP) + +/* + * multi-register-define name HW_PXP_OLn + * base 0x00000200 + * count 8 + * offset 0x40 + */ +#define HW_PXP_OLn(n) (0x00000200 + (n) * 0x40) +#define BP_PXP_OLn_ADDR 0 +#define BM_PXP_OLn_ADDR 0xFFFFFFFF +#define BF_PXP_OLn_ADDR(v) (v) + +/* + * multi-register-define name HW_PXP_OLnSIZE + * base 0x00000210 + * count 8 + * offset 0x40 + */ +#define HW_PXP_OLnSIZE(n) (0x00000210 + (n) * 0x40) +#define BP_PXP_OLnSIZE_XBASE 24 +#define BM_PXP_OLnSIZE_XBASE 0xFF000000 +#define BF_PXP_OLnSIZE_XBASE(v) \ + (((v) << 24) & BM_PXP_OLnSIZE_XBASE) +#define BP_PXP_OLnSIZE_YBASE 16 +#define BM_PXP_OLnSIZE_YBASE 0x00FF0000 +#define BF_PXP_OLnSIZE_YBASE(v) \ + (((v) << 16) & BM_PXP_OLnSIZE_YBASE) +#define BP_PXP_OLnSIZE_WIDTH 8 +#define BM_PXP_OLnSIZE_WIDTH 0x0000FF00 +#define BF_PXP_OLnSIZE_WIDTH(v) \ + (((v) << 8) & BM_PXP_OLnSIZE_WIDTH) +#define BP_PXP_OLnSIZE_HEIGHT 0 +#define BM_PXP_OLnSIZE_HEIGHT 0x000000FF +#define BF_PXP_OLnSIZE_HEIGHT(v) \ + (((v) << 0) & BM_PXP_OLnSIZE_HEIGHT) + +/* + * multi-register-define name HW_PXP_OLnPARAM + * base 0x00000220 + * count 8 + * offset 0x40 + */ +#define HW_PXP_OLnPARAM(n) (0x00000220 + (n) * 0x40) +#define BP_PXP_OLnPARAM_RSVD1 20 +#define BM_PXP_OLnPARAM_RSVD1 0xFFF00000 +#define BF_PXP_OLnPARAM_RSVD1(v) \ + (((v) << 20) & BM_PXP_OLnPARAM_RSVD1) +#define BP_PXP_OLnPARAM_ROP 16 +#define BM_PXP_OLnPARAM_ROP 0x000F0000 +#define BF_PXP_OLnPARAM_ROP(v) \ + (((v) << 16) & BM_PXP_OLnPARAM_ROP) +#define BV_PXP_OLnPARAM_ROP__MASKOL 0x0 +#define BV_PXP_OLnPARAM_ROP__MASKNOTOL 0x1 +#define BV_PXP_OLnPARAM_ROP__MASKOLNOT 0x2 +#define BV_PXP_OLnPARAM_ROP__MERGEOL 0x3 +#define BV_PXP_OLnPARAM_ROP__MERGENOTOL 0x4 +#define BV_PXP_OLnPARAM_ROP__MERGEOLNOT 0x5 +#define BV_PXP_OLnPARAM_ROP__NOTCOPYOL 0x6 +#define BV_PXP_OLnPARAM_ROP__NOT 0x7 +#define BV_PXP_OLnPARAM_ROP__NOTMASKOL 0x8 +#define BV_PXP_OLnPARAM_ROP__NOTMERGEOL 0x9 +#define BV_PXP_OLnPARAM_ROP__XOROL 0xA +#define BV_PXP_OLnPARAM_ROP__NOTXOROL 0xB +#define BP_PXP_OLnPARAM_ALPHA 8 +#define BM_PXP_OLnPARAM_ALPHA 0x0000FF00 +#define BF_PXP_OLnPARAM_ALPHA(v) \ + (((v) << 8) & BM_PXP_OLnPARAM_ALPHA) +#define BP_PXP_OLnPARAM_FORMAT 4 +#define BM_PXP_OLnPARAM_FORMAT 0x000000F0 +#define BF_PXP_OLnPARAM_FORMAT(v) \ + (((v) << 4) & BM_PXP_OLnPARAM_FORMAT) +#define BV_PXP_OLnPARAM_FORMAT__ARGB8888 0x0 +#define BV_PXP_OLnPARAM_FORMAT__RGB888 0x1 +#define BV_PXP_OLnPARAM_FORMAT__ARGB1555 0x3 +#define BV_PXP_OLnPARAM_FORMAT__RGB565 0x4 +#define BV_PXP_OLnPARAM_FORMAT__RGB555 0x5 +#define BM_PXP_OLnPARAM_ENABLE_COLORKEY 0x00000008 +#define BP_PXP_OLnPARAM_ALPHA_CNTL 1 +#define BM_PXP_OLnPARAM_ALPHA_CNTL 0x00000006 +#define BF_PXP_OLnPARAM_ALPHA_CNTL(v) \ + (((v) << 1) & BM_PXP_OLnPARAM_ALPHA_CNTL) +#define BV_PXP_OLnPARAM_ALPHA_CNTL__Embedded 0x0 +#define BV_PXP_OLnPARAM_ALPHA_CNTL__Override 0x1 +#define BV_PXP_OLnPARAM_ALPHA_CNTL__Multiply 0x2 +#define BV_PXP_OLnPARAM_ALPHA_CNTL__ROPs 0x3 +#define BM_PXP_OLnPARAM_ENABLE 0x00000001 + +/* + * multi-register-define name HW_PXP_OLnPARAM2 + * base 0x00000230 + * count 8 + * offset 0x40 + */ +#define HW_PXP_OLnPARAM2(n) (0x00000230 + (n) * 0x40) +#define BP_PXP_OLnPARAM2_RSVD 0 +#define BM_PXP_OLnPARAM2_RSVD 0xFFFFFFFF +#define BF_PXP_OLnPARAM2_RSVD(v) (v) + +#define HW_PXP_CSC2CTRL (0x00000400) + +#define BP_PXP_CSC2CTRL_RSVD 3 +#define BM_PXP_CSC2CTRL_RSVD 0xFFFFFFF8 +#define BF_PXP_CSC2CTRL_RSVD(v) \ + (((v) << 3) & BM_PXP_CSC2CTRL_RSVD) +#define BP_PXP_CSC2CTRL_CSC_MODE 1 +#define BM_PXP_CSC2CTRL_CSC_MODE 0x00000006 +#define BF_PXP_CSC2CTRL_CSC_MODE(v) \ + (((v) << 1) & BM_PXP_CSC2CTRL_CSC_MODE) +#define BV_PXP_CSC2CTRL_CSC_MODE__YUV2RGB 0x0 +#define BV_PXP_CSC2CTRL_CSC_MODE__YCbCr2RGB 0x1 +#define BV_PXP_CSC2CTRL_CSC_MODE__RGB2YUV 0x2 +#define BV_PXP_CSC2CTRL_CSC_MODE__RGB2YCbCr 0x3 +#define BM_PXP_CSC2CTRL_BYPASS 0x00000001 + +#define HW_PXP_CSC2COEF0 (0x00000410) + +#define BP_PXP_CSC2COEF0_RSVD1 27 +#define BM_PXP_CSC2COEF0_RSVD1 0xF8000000 +#define BF_PXP_CSC2COEF0_RSVD1(v) \ + (((v) << 27) & BM_PXP_CSC2COEF0_RSVD1) +#define BP_PXP_CSC2COEF0_A2 16 +#define BM_PXP_CSC2COEF0_A2 0x07FF0000 +#define BF_PXP_CSC2COEF0_A2(v) \ + (((v) << 16) & BM_PXP_CSC2COEF0_A2) +#define BP_PXP_CSC2COEF0_RSVD0 11 +#define BM_PXP_CSC2COEF0_RSVD0 0x0000F800 +#define BF_PXP_CSC2COEF0_RSVD0(v) \ + (((v) << 11) & BM_PXP_CSC2COEF0_RSVD0) +#define BP_PXP_CSC2COEF0_A1 0 +#define BM_PXP_CSC2COEF0_A1 0x000007FF +#define BF_PXP_CSC2COEF0_A1(v) \ + (((v) << 0) & BM_PXP_CSC2COEF0_A1) + +#define HW_PXP_CSC2COEF1 (0x00000420) + +#define BP_PXP_CSC2COEF1_RSVD1 27 +#define BM_PXP_CSC2COEF1_RSVD1 0xF8000000 +#define BF_PXP_CSC2COEF1_RSVD1(v) \ + (((v) << 27) & BM_PXP_CSC2COEF1_RSVD1) +#define BP_PXP_CSC2COEF1_B1 16 +#define BM_PXP_CSC2COEF1_B1 0x07FF0000 +#define BF_PXP_CSC2COEF1_B1(v) \ + (((v) << 16) & BM_PXP_CSC2COEF1_B1) +#define BP_PXP_CSC2COEF1_RSVD0 11 +#define BM_PXP_CSC2COEF1_RSVD0 0x0000F800 +#define BF_PXP_CSC2COEF1_RSVD0(v) \ + (((v) << 11) & BM_PXP_CSC2COEF1_RSVD0) +#define BP_PXP_CSC2COEF1_A3 0 +#define BM_PXP_CSC2COEF1_A3 0x000007FF +#define BF_PXP_CSC2COEF1_A3(v) \ + (((v) << 0) & BM_PXP_CSC2COEF1_A3) + +#define HW_PXP_CSC2COEF2 (0x00000430) + +#define BP_PXP_CSC2COEF2_RSVD1 27 +#define BM_PXP_CSC2COEF2_RSVD1 0xF8000000 +#define BF_PXP_CSC2COEF2_RSVD1(v) \ + (((v) << 27) & BM_PXP_CSC2COEF2_RSVD1) +#define BP_PXP_CSC2COEF2_B3 16 +#define BM_PXP_CSC2COEF2_B3 0x07FF0000 +#define BF_PXP_CSC2COEF2_B3(v) \ + (((v) << 16) & BM_PXP_CSC2COEF2_B3) +#define BP_PXP_CSC2COEF2_RSVD0 11 +#define BM_PXP_CSC2COEF2_RSVD0 0x0000F800 +#define BF_PXP_CSC2COEF2_RSVD0(v) \ + (((v) << 11) & BM_PXP_CSC2COEF2_RSVD0) +#define BP_PXP_CSC2COEF2_B2 0 +#define BM_PXP_CSC2COEF2_B2 0x000007FF +#define BF_PXP_CSC2COEF2_B2(v) \ + (((v) << 0) & BM_PXP_CSC2COEF2_B2) + +#define HW_PXP_CSC2COEF3 (0x00000440) + +#define BP_PXP_CSC2COEF3_RSVD1 27 +#define BM_PXP_CSC2COEF3_RSVD1 0xF8000000 +#define BF_PXP_CSC2COEF3_RSVD1(v) \ + (((v) << 27) & BM_PXP_CSC2COEF3_RSVD1) +#define BP_PXP_CSC2COEF3_C2 16 +#define BM_PXP_CSC2COEF3_C2 0x07FF0000 +#define BF_PXP_CSC2COEF3_C2(v) \ + (((v) << 16) & BM_PXP_CSC2COEF3_C2) +#define BP_PXP_CSC2COEF3_RSVD0 11 +#define BM_PXP_CSC2COEF3_RSVD0 0x0000F800 +#define BF_PXP_CSC2COEF3_RSVD0(v) \ + (((v) << 11) & BM_PXP_CSC2COEF3_RSVD0) +#define BP_PXP_CSC2COEF3_C1 0 +#define BM_PXP_CSC2COEF3_C1 0x000007FF +#define BF_PXP_CSC2COEF3_C1(v) \ + (((v) << 0) & BM_PXP_CSC2COEF3_C1) + +#define HW_PXP_CSC2COEF4 (0x00000450) + +#define BP_PXP_CSC2COEF4_RSVD1 25 +#define BM_PXP_CSC2COEF4_RSVD1 0xFE000000 +#define BF_PXP_CSC2COEF4_RSVD1(v) \ + (((v) << 25) & BM_PXP_CSC2COEF4_RSVD1) +#define BP_PXP_CSC2COEF4_D1 16 +#define BM_PXP_CSC2COEF4_D1 0x01FF0000 +#define BF_PXP_CSC2COEF4_D1(v) \ + (((v) << 16) & BM_PXP_CSC2COEF4_D1) +#define BP_PXP_CSC2COEF4_RSVD0 11 +#define BM_PXP_CSC2COEF4_RSVD0 0x0000F800 +#define BF_PXP_CSC2COEF4_RSVD0(v) \ + (((v) << 11) & BM_PXP_CSC2COEF4_RSVD0) +#define BP_PXP_CSC2COEF4_C3 0 +#define BM_PXP_CSC2COEF4_C3 0x000007FF +#define BF_PXP_CSC2COEF4_C3(v) \ + (((v) << 0) & BM_PXP_CSC2COEF4_C3) + +#define HW_PXP_CSC2COEF5 (0x00000460) + +#define BP_PXP_CSC2COEF5_RSVD1 25 +#define BM_PXP_CSC2COEF5_RSVD1 0xFE000000 +#define BF_PXP_CSC2COEF5_RSVD1(v) \ + (((v) << 25) & BM_PXP_CSC2COEF5_RSVD1) +#define BP_PXP_CSC2COEF5_D3 16 +#define BM_PXP_CSC2COEF5_D3 0x01FF0000 +#define BF_PXP_CSC2COEF5_D3(v) \ + (((v) << 16) & BM_PXP_CSC2COEF5_D3) +#define BP_PXP_CSC2COEF5_RSVD0 9 +#define BM_PXP_CSC2COEF5_RSVD0 0x0000FE00 +#define BF_PXP_CSC2COEF5_RSVD0(v) \ + (((v) << 9) & BM_PXP_CSC2COEF5_RSVD0) +#define BP_PXP_CSC2COEF5_D2 0 +#define BM_PXP_CSC2COEF5_D2 0x000001FF +#define BF_PXP_CSC2COEF5_D2(v) \ + (((v) << 0) & BM_PXP_CSC2COEF5_D2) + +#define HW_PXP_LUT_CTRL (0x00000470) + +#define BM_PXP_LUT_CTRL_BYPASS 0x80000000 +#define BP_PXP_LUT_CTRL_RSVD 8 +#define BM_PXP_LUT_CTRL_RSVD 0x7FFFFF00 +#define BF_PXP_LUT_CTRL_RSVD(v) \ + (((v) << 8) & BM_PXP_LUT_CTRL_RSVD) +#define BP_PXP_LUT_CTRL_ADDR 0 +#define BM_PXP_LUT_CTRL_ADDR 0x000000FF +#define BF_PXP_LUT_CTRL_ADDR(v) \ + (((v) << 0) & BM_PXP_LUT_CTRL_ADDR) + +#define HW_PXP_LUT (0x00000480) + +#define BP_PXP_LUT_RSVD 8 +#define BM_PXP_LUT_RSVD 0xFFFFFF00 +#define BF_PXP_LUT_RSVD(v) \ + (((v) << 8) & BM_PXP_LUT_RSVD) +#define BP_PXP_LUT_DATA 0 +#define BM_PXP_LUT_DATA 0x000000FF +#define BF_PXP_LUT_DATA(v) \ + (((v) << 0) & BM_PXP_LUT_DATA) + +#define HW_PXP_HIST_CTRL (0x00000490) + +#define BP_PXP_HIST_CTRL_RSVD 6 +#define BM_PXP_HIST_CTRL_RSVD 0xFFFFFFC0 +#define BF_PXP_HIST_CTRL_RSVD(v) \ + (((v) << 6) & BM_PXP_HIST_CTRL_RSVD) +#define BP_PXP_HIST_CTRL_PANEL_MODE 4 +#define BM_PXP_HIST_CTRL_PANEL_MODE 0x00000030 +#define BF_PXP_HIST_CTRL_PANEL_MODE(v) \ + (((v) << 4) & BM_PXP_HIST_CTRL_PANEL_MODE) +#define BV_PXP_HIST_CTRL_PANEL_MODE__GRAY4 0x0 +#define BV_PXP_HIST_CTRL_PANEL_MODE__GRAY8 0x1 +#define BV_PXP_HIST_CTRL_PANEL_MODE__GRAY16 0x2 +#define BV_PXP_HIST_CTRL_PANEL_MODE__GRAY32 0x3 +#define BP_PXP_HIST_CTRL_STATUS 0 +#define BM_PXP_HIST_CTRL_STATUS 0x0000000F +#define BF_PXP_HIST_CTRL_STATUS(v) \ + (((v) << 0) & BM_PXP_HIST_CTRL_STATUS) + +#define HW_PXP_HIST2_PARAM (0x000004a0) + +#define BP_PXP_HIST2_PARAM_RSVD 16 +#define BM_PXP_HIST2_PARAM_RSVD 0xFFFF0000 +#define BF_PXP_HIST2_PARAM_RSVD(v) \ + (((v) << 16) & BM_PXP_HIST2_PARAM_RSVD) +#define BP_PXP_HIST2_PARAM_RSVD1 13 +#define BM_PXP_HIST2_PARAM_RSVD1 0x0000E000 +#define BF_PXP_HIST2_PARAM_RSVD1(v) \ + (((v) << 13) & BM_PXP_HIST2_PARAM_RSVD1) +#define BP_PXP_HIST2_PARAM_VALUE1 8 +#define BM_PXP_HIST2_PARAM_VALUE1 0x00001F00 +#define BF_PXP_HIST2_PARAM_VALUE1(v) \ + (((v) << 8) & BM_PXP_HIST2_PARAM_VALUE1) +#define BP_PXP_HIST2_PARAM_RSVD0 5 +#define BM_PXP_HIST2_PARAM_RSVD0 0x000000E0 +#define BF_PXP_HIST2_PARAM_RSVD0(v) \ + (((v) << 5) & BM_PXP_HIST2_PARAM_RSVD0) +#define BP_PXP_HIST2_PARAM_VALUE0 0 +#define BM_PXP_HIST2_PARAM_VALUE0 0x0000001F +#define BF_PXP_HIST2_PARAM_VALUE0(v) \ + (((v) << 0) & BM_PXP_HIST2_PARAM_VALUE0) + +#define HW_PXP_HIST4_PARAM (0x000004b0) + +#define BP_PXP_HIST4_PARAM_RSVD3 29 +#define BM_PXP_HIST4_PARAM_RSVD3 0xE0000000 +#define BF_PXP_HIST4_PARAM_RSVD3(v) \ + (((v) << 29) & BM_PXP_HIST4_PARAM_RSVD3) +#define BP_PXP_HIST4_PARAM_VALUE3 24 +#define BM_PXP_HIST4_PARAM_VALUE3 0x1F000000 +#define BF_PXP_HIST4_PARAM_VALUE3(v) \ + (((v) << 24) & BM_PXP_HIST4_PARAM_VALUE3) +#define BP_PXP_HIST4_PARAM_RSVD2 21 +#define BM_PXP_HIST4_PARAM_RSVD2 0x00E00000 +#define BF_PXP_HIST4_PARAM_RSVD2(v) \ + (((v) << 21) & BM_PXP_HIST4_PARAM_RSVD2) +#define BP_PXP_HIST4_PARAM_VALUE2 16 +#define BM_PXP_HIST4_PARAM_VALUE2 0x001F0000 +#define BF_PXP_HIST4_PARAM_VALUE2(v) \ + (((v) << 16) & BM_PXP_HIST4_PARAM_VALUE2) +#define BP_PXP_HIST4_PARAM_RSVD1 13 +#define BM_PXP_HIST4_PARAM_RSVD1 0x0000E000 +#define BF_PXP_HIST4_PARAM_RSVD1(v) \ + (((v) << 13) & BM_PXP_HIST4_PARAM_RSVD1) +#define BP_PXP_HIST4_PARAM_VALUE1 8 +#define BM_PXP_HIST4_PARAM_VALUE1 0x00001F00 +#define BF_PXP_HIST4_PARAM_VALUE1(v) \ + (((v) << 8) & BM_PXP_HIST4_PARAM_VALUE1) +#define BP_PXP_HIST4_PARAM_RSVD0 5 +#define BM_PXP_HIST4_PARAM_RSVD0 0x000000E0 +#define BF_PXP_HIST4_PARAM_RSVD0(v) \ + (((v) << 5) & BM_PXP_HIST4_PARAM_RSVD0) +#define BP_PXP_HIST4_PARAM_VALUE0 0 +#define BM_PXP_HIST4_PARAM_VALUE0 0x0000001F +#define BF_PXP_HIST4_PARAM_VALUE0(v) \ + (((v) << 0) & BM_PXP_HIST4_PARAM_VALUE0) + +#define HW_PXP_HIST8_PARAM0 (0x000004c0) + +#define BP_PXP_HIST8_PARAM0_RSVD3 29 +#define BM_PXP_HIST8_PARAM0_RSVD3 0xE0000000 +#define BF_PXP_HIST8_PARAM0_RSVD3(v) \ + (((v) << 29) & BM_PXP_HIST8_PARAM0_RSVD3) +#define BP_PXP_HIST8_PARAM0_VALUE3 24 +#define BM_PXP_HIST8_PARAM0_VALUE3 0x1F000000 +#define BF_PXP_HIST8_PARAM0_VALUE3(v) \ + (((v) << 24) & BM_PXP_HIST8_PARAM0_VALUE3) +#define BP_PXP_HIST8_PARAM0_RSVD2 21 +#define BM_PXP_HIST8_PARAM0_RSVD2 0x00E00000 +#define BF_PXP_HIST8_PARAM0_RSVD2(v) \ + (((v) << 21) & BM_PXP_HIST8_PARAM0_RSVD2) +#define BP_PXP_HIST8_PARAM0_VALUE2 16 +#define BM_PXP_HIST8_PARAM0_VALUE2 0x001F0000 +#define BF_PXP_HIST8_PARAM0_VALUE2(v) \ + (((v) << 16) & BM_PXP_HIST8_PARAM0_VALUE2) +#define BP_PXP_HIST8_PARAM0_RSVD1 13 +#define BM_PXP_HIST8_PARAM0_RSVD1 0x0000E000 +#define BF_PXP_HIST8_PARAM0_RSVD1(v) \ + (((v) << 13) & BM_PXP_HIST8_PARAM0_RSVD1) +#define BP_PXP_HIST8_PARAM0_VALUE1 8 +#define BM_PXP_HIST8_PARAM0_VALUE1 0x00001F00 +#define BF_PXP_HIST8_PARAM0_VALUE1(v) \ + (((v) << 8) & BM_PXP_HIST8_PARAM0_VALUE1) +#define BP_PXP_HIST8_PARAM0_RSVD0 5 +#define BM_PXP_HIST8_PARAM0_RSVD0 0x000000E0 +#define BF_PXP_HIST8_PARAM0_RSVD0(v) \ + (((v) << 5) & BM_PXP_HIST8_PARAM0_RSVD0) +#define BP_PXP_HIST8_PARAM0_VALUE0 0 +#define BM_PXP_HIST8_PARAM0_VALUE0 0x0000001F +#define BF_PXP_HIST8_PARAM0_VALUE0(v) \ + (((v) << 0) & BM_PXP_HIST8_PARAM0_VALUE0) + +#define HW_PXP_HIST8_PARAM1 (0x000004d0) + +#define BP_PXP_HIST8_PARAM1_RSVD7 29 +#define BM_PXP_HIST8_PARAM1_RSVD7 0xE0000000 +#define BF_PXP_HIST8_PARAM1_RSVD7(v) \ + (((v) << 29) & BM_PXP_HIST8_PARAM1_RSVD7) +#define BP_PXP_HIST8_PARAM1_VALUE7 24 +#define BM_PXP_HIST8_PARAM1_VALUE7 0x1F000000 +#define BF_PXP_HIST8_PARAM1_VALUE7(v) \ + (((v) << 24) & BM_PXP_HIST8_PARAM1_VALUE7) +#define BP_PXP_HIST8_PARAM1_RSVD6 21 +#define BM_PXP_HIST8_PARAM1_RSVD6 0x00E00000 +#define BF_PXP_HIST8_PARAM1_RSVD6(v) \ + (((v) << 21) & BM_PXP_HIST8_PARAM1_RSVD6) +#define BP_PXP_HIST8_PARAM1_VALUE6 16 +#define BM_PXP_HIST8_PARAM1_VALUE6 0x001F0000 +#define BF_PXP_HIST8_PARAM1_VALUE6(v) \ + (((v) << 16) & BM_PXP_HIST8_PARAM1_VALUE6) +#define BP_PXP_HIST8_PARAM1_RSVD5 13 +#define BM_PXP_HIST8_PARAM1_RSVD5 0x0000E000 +#define BF_PXP_HIST8_PARAM1_RSVD5(v) \ + (((v) << 13) & BM_PXP_HIST8_PARAM1_RSVD5) +#define BP_PXP_HIST8_PARAM1_VALUE5 8 +#define BM_PXP_HIST8_PARAM1_VALUE5 0x00001F00 +#define BF_PXP_HIST8_PARAM1_VALUE5(v) \ + (((v) << 8) & BM_PXP_HIST8_PARAM1_VALUE5) +#define BP_PXP_HIST8_PARAM1_RSVD4 5 +#define BM_PXP_HIST8_PARAM1_RSVD4 0x000000E0 +#define BF_PXP_HIST8_PARAM1_RSVD4(v) \ + (((v) << 5) & BM_PXP_HIST8_PARAM1_RSVD4) +#define BP_PXP_HIST8_PARAM1_VALUE4 0 +#define BM_PXP_HIST8_PARAM1_VALUE4 0x0000001F +#define BF_PXP_HIST8_PARAM1_VALUE4(v) \ + (((v) << 0) & BM_PXP_HIST8_PARAM1_VALUE4) + +#define HW_PXP_HIST16_PARAM0 (0x000004e0) + +#define BP_PXP_HIST16_PARAM0_RSVD3 29 +#define BM_PXP_HIST16_PARAM0_RSVD3 0xE0000000 +#define BF_PXP_HIST16_PARAM0_RSVD3(v) \ + (((v) << 29) & BM_PXP_HIST16_PARAM0_RSVD3) +#define BP_PXP_HIST16_PARAM0_VALUE3 24 +#define BM_PXP_HIST16_PARAM0_VALUE3 0x1F000000 +#define BF_PXP_HIST16_PARAM0_VALUE3(v) \ + (((v) << 24) & BM_PXP_HIST16_PARAM0_VALUE3) +#define BP_PXP_HIST16_PARAM0_RSVD2 21 +#define BM_PXP_HIST16_PARAM0_RSVD2 0x00E00000 +#define BF_PXP_HIST16_PARAM0_RSVD2(v) \ + (((v) << 21) & BM_PXP_HIST16_PARAM0_RSVD2) +#define BP_PXP_HIST16_PARAM0_VALUE2 16 +#define BM_PXP_HIST16_PARAM0_VALUE2 0x001F0000 +#define BF_PXP_HIST16_PARAM0_VALUE2(v) \ + (((v) << 16) & BM_PXP_HIST16_PARAM0_VALUE2) +#define BP_PXP_HIST16_PARAM0_RSVD1 13 +#define BM_PXP_HIST16_PARAM0_RSVD1 0x0000E000 +#define BF_PXP_HIST16_PARAM0_RSVD1(v) \ + (((v) << 13) & BM_PXP_HIST16_PARAM0_RSVD1) +#define BP_PXP_HIST16_PARAM0_VALUE1 8 +#define BM_PXP_HIST16_PARAM0_VALUE1 0x00001F00 +#define BF_PXP_HIST16_PARAM0_VALUE1(v) \ + (((v) << 8) & BM_PXP_HIST16_PARAM0_VALUE1) +#define BP_PXP_HIST16_PARAM0_RSVD0 5 +#define BM_PXP_HIST16_PARAM0_RSVD0 0x000000E0 +#define BF_PXP_HIST16_PARAM0_RSVD0(v) \ + (((v) << 5) & BM_PXP_HIST16_PARAM0_RSVD0) +#define BP_PXP_HIST16_PARAM0_VALUE0 0 +#define BM_PXP_HIST16_PARAM0_VALUE0 0x0000001F +#define BF_PXP_HIST16_PARAM0_VALUE0(v) \ + (((v) << 0) & BM_PXP_HIST16_PARAM0_VALUE0) + +#define HW_PXP_HIST16_PARAM1 (0x000004f0) + +#define BP_PXP_HIST16_PARAM1_RSVD7 29 +#define BM_PXP_HIST16_PARAM1_RSVD7 0xE0000000 +#define BF_PXP_HIST16_PARAM1_RSVD7(v) \ + (((v) << 29) & BM_PXP_HIST16_PARAM1_RSVD7) +#define BP_PXP_HIST16_PARAM1_VALUE7 24 +#define BM_PXP_HIST16_PARAM1_VALUE7 0x1F000000 +#define BF_PXP_HIST16_PARAM1_VALUE7(v) \ + (((v) << 24) & BM_PXP_HIST16_PARAM1_VALUE7) +#define BP_PXP_HIST16_PARAM1_RSVD6 21 +#define BM_PXP_HIST16_PARAM1_RSVD6 0x00E00000 +#define BF_PXP_HIST16_PARAM1_RSVD6(v) \ + (((v) << 21) & BM_PXP_HIST16_PARAM1_RSVD6) +#define BP_PXP_HIST16_PARAM1_VALUE6 16 +#define BM_PXP_HIST16_PARAM1_VALUE6 0x001F0000 +#define BF_PXP_HIST16_PARAM1_VALUE6(v) \ + (((v) << 16) & BM_PXP_HIST16_PARAM1_VALUE6) +#define BP_PXP_HIST16_PARAM1_RSVD5 13 +#define BM_PXP_HIST16_PARAM1_RSVD5 0x0000E000 +#define BF_PXP_HIST16_PARAM1_RSVD5(v) \ + (((v) << 13) & BM_PXP_HIST16_PARAM1_RSVD5) +#define BP_PXP_HIST16_PARAM1_VALUE5 8 +#define BM_PXP_HIST16_PARAM1_VALUE5 0x00001F00 +#define BF_PXP_HIST16_PARAM1_VALUE5(v) \ + (((v) << 8) & BM_PXP_HIST16_PARAM1_VALUE5) +#define BP_PXP_HIST16_PARAM1_RSVD4 5 +#define BM_PXP_HIST16_PARAM1_RSVD4 0x000000E0 +#define BF_PXP_HIST16_PARAM1_RSVD4(v) \ + (((v) << 5) & BM_PXP_HIST16_PARAM1_RSVD4) +#define BP_PXP_HIST16_PARAM1_VALUE4 0 +#define BM_PXP_HIST16_PARAM1_VALUE4 0x0000001F +#define BF_PXP_HIST16_PARAM1_VALUE4(v) \ + (((v) << 0) & BM_PXP_HIST16_PARAM1_VALUE4) + +#define HW_PXP_HIST16_PARAM2 (0x00000500) + +#define BP_PXP_HIST16_PARAM2_RSVD11 29 +#define BM_PXP_HIST16_PARAM2_RSVD11 0xE0000000 +#define BF_PXP_HIST16_PARAM2_RSVD11(v) \ + (((v) << 29) & BM_PXP_HIST16_PARAM2_RSVD11) +#define BP_PXP_HIST16_PARAM2_VALUE11 24 +#define BM_PXP_HIST16_PARAM2_VALUE11 0x1F000000 +#define BF_PXP_HIST16_PARAM2_VALUE11(v) \ + (((v) << 24) & BM_PXP_HIST16_PARAM2_VALUE11) +#define BP_PXP_HIST16_PARAM2_RSVD10 21 +#define BM_PXP_HIST16_PARAM2_RSVD10 0x00E00000 +#define BF_PXP_HIST16_PARAM2_RSVD10(v) \ + (((v) << 21) & BM_PXP_HIST16_PARAM2_RSVD10) +#define BP_PXP_HIST16_PARAM2_VALUE10 16 +#define BM_PXP_HIST16_PARAM2_VALUE10 0x001F0000 +#define BF_PXP_HIST16_PARAM2_VALUE10(v) \ + (((v) << 16) & BM_PXP_HIST16_PARAM2_VALUE10) +#define BP_PXP_HIST16_PARAM2_RSVD9 13 +#define BM_PXP_HIST16_PARAM2_RSVD9 0x0000E000 +#define BF_PXP_HIST16_PARAM2_RSVD9(v) \ + (((v) << 13) & BM_PXP_HIST16_PARAM2_RSVD9) +#define BP_PXP_HIST16_PARAM2_VALUE9 8 +#define BM_PXP_HIST16_PARAM2_VALUE9 0x00001F00 +#define BF_PXP_HIST16_PARAM2_VALUE9(v) \ + (((v) << 8) & BM_PXP_HIST16_PARAM2_VALUE9) +#define BP_PXP_HIST16_PARAM2_RSVD8 5 +#define BM_PXP_HIST16_PARAM2_RSVD8 0x000000E0 +#define BF_PXP_HIST16_PARAM2_RSVD8(v) \ + (((v) << 5) & BM_PXP_HIST16_PARAM2_RSVD8) +#define BP_PXP_HIST16_PARAM2_VALUE8 0 +#define BM_PXP_HIST16_PARAM2_VALUE8 0x0000001F +#define BF_PXP_HIST16_PARAM2_VALUE8(v) \ + (((v) << 0) & BM_PXP_HIST16_PARAM2_VALUE8) + +#define HW_PXP_HIST16_PARAM3 (0x00000510) + +#define BP_PXP_HIST16_PARAM3_RSVD15 29 +#define BM_PXP_HIST16_PARAM3_RSVD15 0xE0000000 +#define BF_PXP_HIST16_PARAM3_RSVD15(v) \ + (((v) << 29) & BM_PXP_HIST16_PARAM3_RSVD15) +#define BP_PXP_HIST16_PARAM3_VALUE15 24 +#define BM_PXP_HIST16_PARAM3_VALUE15 0x1F000000 +#define BF_PXP_HIST16_PARAM3_VALUE15(v) \ + (((v) << 24) & BM_PXP_HIST16_PARAM3_VALUE15) +#define BP_PXP_HIST16_PARAM3_RSVD14 21 +#define BM_PXP_HIST16_PARAM3_RSVD14 0x00E00000 +#define BF_PXP_HIST16_PARAM3_RSVD14(v) \ + (((v) << 21) & BM_PXP_HIST16_PARAM3_RSVD14) +#define BP_PXP_HIST16_PARAM3_VALUE14 16 +#define BM_PXP_HIST16_PARAM3_VALUE14 0x001F0000 +#define BF_PXP_HIST16_PARAM3_VALUE14(v) \ + (((v) << 16) & BM_PXP_HIST16_PARAM3_VALUE14) +#define BP_PXP_HIST16_PARAM3_RSVD13 13 +#define BM_PXP_HIST16_PARAM3_RSVD13 0x0000E000 +#define BF_PXP_HIST16_PARAM3_RSVD13(v) \ + (((v) << 13) & BM_PXP_HIST16_PARAM3_RSVD13) +#define BP_PXP_HIST16_PARAM3_VALUE13 8 +#define BM_PXP_HIST16_PARAM3_VALUE13 0x00001F00 +#define BF_PXP_HIST16_PARAM3_VALUE13(v) \ + (((v) << 8) & BM_PXP_HIST16_PARAM3_VALUE13) +#define BP_PXP_HIST16_PARAM3_RSVD12 5 +#define BM_PXP_HIST16_PARAM3_RSVD12 0x000000E0 +#define BF_PXP_HIST16_PARAM3_RSVD12(v) \ + (((v) << 5) & BM_PXP_HIST16_PARAM3_RSVD12) +#define BP_PXP_HIST16_PARAM3_VALUE12 0 +#define BM_PXP_HIST16_PARAM3_VALUE12 0x0000001F +#define BF_PXP_HIST16_PARAM3_VALUE12(v) \ + (((v) << 0) & BM_PXP_HIST16_PARAM3_VALUE12) +#endif /* __ARCH_ARM___PXP_H */ diff --git a/drivers/hwmon/Kconfig b/drivers/hwmon/Kconfig index e19cf8eb6ccf..b5d3a46085ea 100644 --- a/drivers/hwmon/Kconfig +++ b/drivers/hwmon/Kconfig @@ -1166,4 +1166,14 @@ config SENSORS_LIS3LV02D endif # ACPI +config MXC_MMA7450 + tristate "MMA7450 device driver" + depends on MACH_MX31_3DS || MACH_MX23EVK + default n + +config SENSORS_ISL29003 + tristate "ISL29003 Light Sensor" + depends on MACH_MX37_3DS || MACH_MX51_3DS + default y + endif # HWMON diff --git a/drivers/hwmon/Makefile b/drivers/hwmon/Makefile index 2138ceb1a713..1f5dccc660b7 100644 --- a/drivers/hwmon/Makefile +++ b/drivers/hwmon/Makefile @@ -103,6 +103,8 @@ obj-$(CONFIG_SENSORS_W83L785TS) += w83l785ts.o obj-$(CONFIG_SENSORS_W83L786NG) += w83l786ng.o obj-$(CONFIG_SENSORS_WM831X) += wm831x-hwmon.o obj-$(CONFIG_SENSORS_WM8350) += wm8350-hwmon.o +obj-$(CONFIG_SENSORS_ISL29003) += isl29003.o +obj-$(CONFIG_MXC_MMA7450) += mxc_mma7450.o ifeq ($(CONFIG_HWMON_DEBUG_CHIP),y) EXTRA_CFLAGS += -DDEBUG diff --git a/drivers/hwmon/isl29003.c b/drivers/hwmon/isl29003.c new file mode 100644 index 000000000000..18c9947b3cd8 --- /dev/null +++ b/drivers/hwmon/isl29003.c @@ -0,0 +1,439 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file drivers/hwmon/isl29003.c + * + * @brief ISL29003 light sensor Driver + * + * @ingroup + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +enum isl29003_width { + ISL29003_WIDTH_16 = 0, + ISL29003_WIDTH_12, + ISL29003_WIDTH_8, + ISL29003_WIDTH_4, +}; + +enum isl29003_gain { + ISL29003_GAIN_1000 = 0, + ISL29003_GAIN_4000, + ISL29003_GAIN_16000, + ISL29003_GAIN_64000, +}; + +enum isl29003_mode { + ISL29003_MODE_DIODE1 = 0, + ISL29003_MODE_DIODE2, + ISL29003_MODE_DIODE1_2, +}; + +struct isl29003_param { + enum isl29003_width width; + enum isl29003_gain gain; + enum isl29003_mode mode; +}; + +/* bit definition for ISL29003_CMD reg */ +#define ENABLE 7 +#define ADCPD 6 +#define TIMEING_MODE 5 +#define MODE 2 +#define WIDTH 0 + +/* bit definition for ISL29003_CTRL reg */ +#define INT_FLAG 5 +#define GAIN 2 +#define INT_PERSIST 0 + +enum isl29003_reg { + ISL29003_CMD = 0, + ISL29003_CTRL, + ISL29003_THRS_HI, + ISL29003_THRS_LO, + ISL29003_LSB_S, + ISL29003_MSB_S, + ISL29003_LSB_T, + ISL29003_MSB_T, + ISL29003_SYNC_IIC = 0x80, + ISL29003_CLAR_INT = 0x40 +}; + +/* default configure for ISL29003 */ +#define ISL29003_WIDTH_DEFAULT ISL29003_WIDTH_16 +#define ISL29003_GAIN_DEFAULT ISL29003_GAIN_16000 +#define ISL29003_MODE_DEFAULT ISL29003_MODE_DIODE1 + +/* range table for different GAIN settings */ +int range[4] = { 973, 3892, 15568, 62272 }; + +/* width table for different WIDTH settings */ +int width[4] = { 16, 1, 256, 16 }; + +struct isl29003_data { + struct i2c_client *client; + struct device *hwmon_dev; + struct regulator *vdd_reg; + struct isl29003_param param; + int lux_coeff; + unsigned char enable; +}; + +static struct i2c_client *isl29003_client; + +/*! + * This function do the isl29003 register read. + */ +int isl29003_read(struct i2c_client *client, u8 reg) +{ + return i2c_smbus_read_byte_data(client, reg); +} + +/*! + * This function do the isl29003 register write. + */ +int isl29003_write(struct i2c_client *client, u8 reg, char value) +{ + return i2c_smbus_write_byte_data(client, reg, value); +} + +/*! + * This function do the isl29003 config and enable. + */ +static int isl29003_on(void) +{ + unsigned char cmd; + int err = 0; + struct mxc_lightsensor_platform_data *ls_data; + struct isl29003_data *data = i2c_get_clientdata(isl29003_client); + + if (data->enable) + goto exit; + + ls_data = (struct mxc_lightsensor_platform_data *) + (isl29003_client->dev).platform_data; + + /* coeff=range*100k/rext/2^n */ + data->lux_coeff = range[data->param.gain] * 100 / + ls_data->rext / width[data->param.width]; + + if (data->vdd_reg) + regulator_enable(data->vdd_reg); + msleep(100); + + cmd = data->param.gain << GAIN; + if (isl29003_write(isl29003_client, ISL29003_CTRL, cmd)) { + err = -ENODEV; + goto exit; + } + + cmd = (data->param.width << WIDTH) | (data->param.mode << MODE) | + (1 << ENABLE); + if (isl29003_write(isl29003_client, ISL29003_CMD, cmd)) { + err = -ENODEV; + goto exit; + } + + data->enable = 1; + + pr_info("isl29003 on\n"); + return 0; +exit: + return err; +} + +/*! + * This function shut down the isl29003. + */ +static int isl29003_off(void) +{ + struct isl29003_data *data = i2c_get_clientdata(isl29003_client); + int cmd; + + if (!data->enable) + return 0; + + cmd = isl29003_read(isl29003_client, ISL29003_CMD); + if (cmd < 0) + return -ENODEV; + + cmd = ((cmd | (1 << ADCPD)) & (~(1 << ENABLE))); + if (isl29003_write(isl29003_client, ISL29003_CMD, (char)cmd)) + return -ENODEV; + + if (data->vdd_reg) + regulator_disable(data->vdd_reg); + + data->enable = 0; + + pr_info("isl29003 off\n"); + return 0; +} + +/*! + * This function read the isl29003 lux registers and convert them to the lux + * value. + * + * @output buffer this param holds the lux value, when =-1, read fail + * + * @return 0 + */ +static int isl29003_read_lux(void) +{ + int d; + int lux; + struct isl29003_data *data = i2c_get_clientdata(isl29003_client); + + d = isl29003_read(isl29003_client, ISL29003_MSB_S); + if (d < 0) + goto err; + + lux = d; + d = isl29003_read(isl29003_client, ISL29003_LSB_S); + if (d < 0) + goto err; + + lux = (lux << 8) + d; + + if (data->param.width < ISL29003_WIDTH_8) + lux = (data->lux_coeff * lux) >> 12; + else + lux = data->lux_coeff * lux; + + return lux; +err: + return -1; +} + +static ssize_t ls_enable(struct device *dev, struct device_attribute *attr, + const char *buf, size_t count) +{ + char *endp; + int enable = simple_strtoul(buf, &endp, 0); + size_t size = endp - buf; + + if (*endp && isspace(*endp)) + size++; + if (size != count) + return -EINVAL; + + if (enable == 1) { + if (isl29003_on()) + pr_info("device open fail\n"); + } + if (enable == 0) { + if (isl29003_off()) + pr_info("device powerdown fail\n"); + } + + return count; +} + +static SENSOR_DEVICE_ATTR(enable, S_IWUGO, NULL, ls_enable, 0); + +static ssize_t show_lux(struct device *dev, struct device_attribute *attr, + char *buf) +{ + return snprintf(buf, PAGE_SIZE, "%u\n", isl29003_read_lux()); +} + +static SENSOR_DEVICE_ATTR(lux, S_IRUGO, show_lux, NULL, 0); + +static int isl29003_i2c_probe(struct i2c_client *client, + const struct i2c_device_id *did) +{ + int err = 0; + struct isl29003_data *data; + struct regulator *vdd_reg; + struct mxc_lightsensor_platform_data *ls_data; + + ls_data = (struct mxc_lightsensor_platform_data *) + (client->dev).platform_data; + + if (ls_data && ls_data->vdd_reg) + vdd_reg = regulator_get(&client->dev, ls_data->vdd_reg); + else + vdd_reg = NULL; + + /* check the existence of the device */ + if (vdd_reg) + regulator_enable(vdd_reg); + msleep(100); + + if (isl29003_write(client, ISL29003_CMD, 0)) + err = -ENODEV; + + if (!err) + if (isl29003_read(client, ISL29003_CMD)) + err = -ENODEV; + + if (vdd_reg) + regulator_disable(vdd_reg); + if (err < 0) + goto exit1; + + isl29003_client = client; + data = kzalloc(sizeof(struct isl29003_data), GFP_KERNEL); + if (data == NULL) { + err = -ENOMEM; + goto exit1; + } + + i2c_set_clientdata(client, data); + data->client = client; + + data->param.width = ISL29003_WIDTH_DEFAULT; + data->param.gain = ISL29003_GAIN_DEFAULT; + data->param.mode = ISL29003_MODE_DEFAULT; + + data->enable = 0; + + err = device_create_file(&client->dev, + &sensor_dev_attr_enable.dev_attr); + if (err) + goto exit2; + + err = device_create_file(&client->dev, &sensor_dev_attr_lux.dev_attr); + if (err) + goto exit_remove1; + + /* Register sysfs hooks */ + data->hwmon_dev = hwmon_device_register(&client->dev); + if (IS_ERR(data->hwmon_dev)) { + err = PTR_ERR(data->hwmon_dev); + goto exit_remove2; + } + + data->vdd_reg = vdd_reg; + return 0; + +exit_remove2: + device_remove_file(&client->dev, &sensor_dev_attr_lux.dev_attr); +exit_remove1: + device_remove_file(&client->dev, &sensor_dev_attr_enable.dev_attr); +exit2: + kfree(data); +exit1: + if (vdd_reg) { + regulator_put(vdd_reg); + vdd_reg = NULL; + } + isl29003_client = NULL; + return err; +} + +static int isl29003_i2c_remove(struct i2c_client *client) +{ + struct isl29003_data *data = i2c_get_clientdata(client); + + if (data->vdd_reg) { + regulator_put(data->vdd_reg); + data->vdd_reg = NULL; + } + hwmon_device_unregister(data->hwmon_dev); + device_remove_file(&client->dev, &sensor_dev_attr_enable.dev_attr); + device_remove_file(&client->dev, &sensor_dev_attr_lux.dev_attr); + kfree(data); + return 0; +} + +static int isl29003_suspend(struct i2c_client *client, pm_message_t message) +{ + int cmd; + + struct isl29003_data *data = i2c_get_clientdata(client); + + if (!data->enable) + goto exit; + + cmd = isl29003_read(client, ISL29003_CMD); + if (cmd < 0) + goto err; + + cmd = (cmd | (1 << ADCPD)); + if (isl29003_write(client, ISL29003_CMD, (char)cmd)) + goto err; +exit: + return 0; +err: + return -ENODEV; +} + +static int isl29003_resume(struct i2c_client *client) +{ + int cmd; + + struct isl29003_data *data = i2c_get_clientdata(client); + + if (!data->enable) + goto exit; + + cmd = isl29003_read(client, ISL29003_CMD); + if (cmd < 0) + goto err; + + cmd = (cmd & (~(1 << ADCPD))); + if (isl29003_write(client, ISL29003_CMD, (char)cmd)) + goto err; +exit: + return 0; +err: + return -ENODEV; +} + +static const struct i2c_device_id isl29003_id[] = { + {"isl29003", 0}, + {} +}; +MODULE_DEVICE_TABLE(i2c, isl29003_id); + +static struct i2c_driver isl29003_driver = { + .driver = { + .name = "isl29003", + }, + .probe = isl29003_i2c_probe, + .remove = isl29003_i2c_remove, + .suspend = isl29003_suspend, + .resume = isl29003_resume, + .id_table = isl29003_id, +}; + +static int __init isl29003_init(void) +{ + return i2c_add_driver(&isl29003_driver);; +} + +static void __exit isl29003_cleanup(void) +{ + i2c_del_driver(&isl29003_driver); +} + +module_init(isl29003_init); +module_exit(isl29003_cleanup); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("ISL29003 light sensor driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/hwmon/mxc_mma7450.c b/drivers/hwmon/mxc_mma7450.c new file mode 100644 index 000000000000..fa1dd41267eb --- /dev/null +++ b/drivers/hwmon/mxc_mma7450.c @@ -0,0 +1,788 @@ +/* + * linux/drivers/hwmon/mma7450.c + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*include file*/ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/*macro define*/ +#define MMA7450_I2C_ADDR 0x1D +#define DEVICE_NAME "mma7450" +#define POLL_INTERVAL 100 +#define DEBUG + +#define INPUT_FUZZ 4 +#define INPUT_FLAT 4 + +enum { + REG_XOUTL = 0x00, + REG_XOUTH, + REG_YOUTL, + REG_YOUTH, + REG_ZOUTL, + REG_ZOUTH, + REG_XOUT8, + REG_YOUT8, + REG_ZOUT8, + REG_STATUS, + REG_DETSRC, + REG_TOUT, + REG_RESERVED_0, + REG_I2CAD, + REG_USRINF, + REG_WHOAMI, + REG_XOFFL, + REG_XOFFH, + REG_YOFFL, + REG_YOFFH, + REG_ZOFFL, + REG_ZOFFH, + REG_MCTL, + REG_INTRST, + REG_CTL1, + REG_CTL2, + REG_LDTH, + REG_PDTH, + REG_PD, + REG_LT, + REG_TW, + REG_REVERVED_1, +}; + +enum { + MOD_STANDBY = 0, + MOD_MEASURE, + MOD_LEVEL_D, + MOD_PULSE_D, +}; + +enum { + INT_1L_2P = 0, + INT_1P_2L, + INT_1SP_2P, +}; + +struct mma7450_status { + u8 mod; + u8 ctl1; + u8 ctl2; +}; + +/*forward declear*/ +static ssize_t mma7450_show(struct device *dev, + struct device_attribute *attr, char *buf); +static ssize_t mma7450_store(struct device *dev, + struct device_attribute *attr, const char *buf, + size_t count); +static int mma7450_probe(struct i2c_client *client, + const struct i2c_device_id *id); +static int mma7450_remove(struct i2c_client *client); +static int mma7450_suspend(struct i2c_client *client, pm_message_t state); +static int mma7450_resume(struct i2c_client *client); +static void mma_bh_handler(struct work_struct *work); + +/*definition*/ +static struct regulator *reg_dvdd_io; +static struct regulator *reg_avdd; +static struct i2c_client *mma7450_client; +static struct device *hwmon_dev; +static struct input_polled_dev *mma7450_idev; +static struct mxc_mma7450_platform_data *plat_data; +static u8 mma7450_mode; +static struct device_attribute mma7450_dev_attr = { + .attr = { + .name = "mma7450_ctl", + .mode = S_IRUSR | S_IWUSR, + }, + .show = mma7450_show, + .store = mma7450_store, +}; + +static const struct i2c_device_id mma7450_id[] = { + {"mma7450", 0}, + {}, +}; + +MODULE_DEVICE_TABLE(i2c, mma7450_id); + +static struct i2c_driver i2c_mma7450_driver = { + .driver = { + .name = "mma7450", + }, + .probe = mma7450_probe, + .remove = mma7450_remove, + .suspend = mma7450_suspend, + .resume = mma7450_resume, + .id_table = mma7450_id, +}; + +static struct mma7450_status mma_status = { + .mod = 0, + .ctl1 = 0, + .ctl2 = 0, +}; + +DECLARE_WORK(mma_work, mma_bh_handler); + +#ifdef DEBUG +enum { + MMA_REG_R = 0, + MMA_REG_W, + MMA_SET_MOD, + MMA_SET_L_THR, + MMA_SET_P_THR, + MMA_SET_INTP, + MMA_SET_INTB, + MMA_SET_G, + MMA_I2C_EABLE, + MMA_OFF_X, + MMA_OFF_Y, + MMA_OFF_Z, + MMA_SELF_TEST, + MMA_SET_LDPL, + MMA_SET_PDPL, + MMA_SET_PDV, + MMA_SET_LTV, + MMA_SET_TW, + MMA_CMD_MAX +}; + +static char *command[MMA_CMD_MAX] = { + [MMA_REG_R] = "readreg", + [MMA_REG_W] = "writereg", + [MMA_SET_MOD] = "setmod", + [MMA_SET_L_THR] = "setlt", + [MMA_SET_P_THR] = "setpt", + [MMA_SET_INTP] = "setintp", + [MMA_SET_INTB] = "setintb", + [MMA_SET_G] = "setg", + [MMA_I2C_EABLE] = "setie", + [MMA_OFF_X] = "setxo", + [MMA_OFF_Y] = "setyo", + [MMA_OFF_Z] = "setzo", + [MMA_SELF_TEST] = "selft", + [MMA_SET_LDPL] = "setldp", + [MMA_SET_PDPL] = "setpdp", + [MMA_SET_PDV] = "setpdv", + [MMA_SET_LTV] = "setltv", + [MMA_SET_TW] = "settw", +}; + +static void set_mod(u8 mode) +{ + int ret; + + ret = i2c_smbus_read_byte_data(mma7450_client, REG_MCTL); + /* shall I test the ret value? */ + ret = (ret & ~0x3) | (mode & 0x3); + mma_status.mod = ret; + i2c_smbus_write_byte_data(mma7450_client, REG_MCTL, ret); +} + +static void set_level_thr(u8 lth) +{ + i2c_smbus_write_byte_data(mma7450_client, REG_LDTH, lth); +} + +static void set_pulse_thr(u8 pth) +{ + i2c_smbus_write_byte_data(mma7450_client, REG_PDTH, pth); +} + +static void set_int_pin(u8 pin) +{ + int ret; + + ret = i2c_smbus_read_byte_data(mma7450_client, REG_CTL1); + ret = (ret & ~0x1) | (pin & 0x1); + mma_status.ctl1 = ret; + i2c_smbus_write_byte_data(mma7450_client, REG_CTL1, ret); +} + +static void set_int_bit(u8 bit) +{ + int ret; + + ret = i2c_smbus_read_byte_data(mma7450_client, REG_CTL1); + ret = (ret & ~0x6) | ((bit << 1) & 0x6); + mma_status.ctl1 = ret; + i2c_smbus_write_byte_data(mma7450_client, REG_CTL1, ret); +} + +static void set_g_level(u8 gl) +{ + int ret; + + ret = i2c_smbus_read_byte_data(mma7450_client, REG_MCTL); + ret = (ret & ~0xC) | ((gl << 2) & 0xC); + i2c_smbus_write_byte_data(mma7450_client, REG_MCTL, ret); +} + +static void set_i2c_enable(u8 i2c_e) +{ + int ret; + + ret = i2c_smbus_read_byte_data(mma7450_client, REG_I2CAD); + ret = (ret & ~0x80) | ((i2c_e << 7) & 0x80); + i2c_smbus_write_byte_data(mma7450_client, REG_I2CAD, ret); +} + +static void set_x_offset(u16 xo) +{ + u8 data; + + data = (xo & 0xFF); + i2c_smbus_write_byte_data(mma7450_client, REG_XOFFL, data); + data = (xo & 0xFF00) >> 8; + i2c_smbus_write_byte_data(mma7450_client, REG_XOFFH, data); +} + +static void set_y_offset(u16 yo) +{ + u8 data; + + data = (yo & 0xFF); + i2c_smbus_write_byte_data(mma7450_client, REG_YOFFL, data); + data = (yo & 0xFF00) >> 8; + i2c_smbus_write_byte_data(mma7450_client, REG_YOFFH, data); +} + +static void set_z_offset(u16 zo) +{ + u8 data; + + data = (zo & 0xFF); + i2c_smbus_write_byte_data(mma7450_client, REG_ZOFFL, data); + data = (zo & 0xFF00) >> 8; + i2c_smbus_write_byte_data(mma7450_client, REG_ZOFFH, data); +} + +static void selftest(u8 st) +{ + int ret; + + ret = i2c_smbus_read_byte_data(mma7450_client, REG_MCTL); + ret = (ret & ~0x10) | ((st << 4) & 0x10); + i2c_smbus_write_byte_data(mma7450_client, REG_MCTL, ret); +} + +static void set_level_det_p(u8 ldp) +{ + int ret; + + ret = i2c_smbus_read_byte_data(mma7450_client, REG_CTL2); + ret = (ret & ~0x1) | ((ldp << 0) & 0x1); + mma_status.ctl2 = ret; + i2c_smbus_write_byte_data(mma7450_client, REG_CTL2, ret); +} + +static void set_pulse_det_p(u8 pdp) +{ + int ret; + + ret = i2c_smbus_read_byte_data(mma7450_client, REG_CTL2); + ret = (ret & ~0x2) | ((pdp << 1) & 0x2); + mma_status.ctl2 = ret; + i2c_smbus_write_byte_data(mma7450_client, REG_CTL2, ret); +} + +static void set_pulse_duration(u8 pd) +{ + i2c_smbus_write_byte_data(mma7450_client, REG_PD, pd); +} + +static void set_latency_time(u8 lt) +{ + i2c_smbus_write_byte_data(mma7450_client, REG_LT, lt); +} + +static void set_time_window(u8 tw) +{ + i2c_smbus_write_byte_data(mma7450_client, REG_TW, tw); +} + +static void parse_arg(const char *arg, int *reg, int *value) +{ + const char *p; + + for (p = arg;; p++) { + if (*p == ' ' || *p == '\0') + break; + } + + p++; + + *reg = simple_strtoul(arg, NULL, 16); + *value = simple_strtoul(p, NULL, 16); +} + +static void cmd_read_reg(const char *arg) +{ + int reg, value, ret; + + parse_arg(arg, ®, &value); + ret = i2c_smbus_read_byte_data(mma7450_client, reg); + dev_info(&mma7450_client->dev, "read reg0x%x = %x\n", reg, ret); +} + +static void cmd_write_reg(const char *arg) +{ + int reg, value, ret; + + parse_arg(arg, ®, &value); + ret = i2c_smbus_write_byte_data(mma7450_client, reg, value); + dev_info(&mma7450_client->dev, "write reg result %s\n", + ret ? "failed" : "success"); +} + +static int exec_command(const char *buf, size_t count) +{ + const char *p, *s; + const char *arg; + int i, value = 0; + + for (p = buf;; p++) { + if (*p == ' ' || *p == '\0' || p - buf >= count) + break; + } + arg = p + 1; + + for (i = MMA_REG_R; i < MMA_CMD_MAX; i++) { + s = command[i]; + if (s && !strncmp(buf, s, p - buf)) { + dev_info(&mma7450_client->dev, "command %s\n", s); + goto mma_exec_command; + } + } + + dev_err(&mma7450_client->dev, "command is not found\n"); + return -1; + + mma_exec_command: + if (i != MMA_REG_R && i != MMA_REG_W) + value = simple_strtoul(arg, NULL, 16); + + switch (i) { + case MMA_REG_R: + cmd_read_reg(arg); + break; + case MMA_REG_W: + cmd_write_reg(arg); + break; + case MMA_SET_MOD: + set_mod(value); + break; + case MMA_SET_L_THR: + set_level_thr(value); + break; + case MMA_SET_P_THR: + set_pulse_thr(value); + break; + case MMA_SET_INTP: + set_int_pin(value); + break; + case MMA_SET_INTB: + set_int_bit(value); + break; + case MMA_SET_G: + set_g_level(value); + break; + case MMA_I2C_EABLE: + set_i2c_enable(value); + break; + case MMA_OFF_X: + set_x_offset(value); + break; + case MMA_OFF_Y: + set_y_offset(value); + break; + case MMA_OFF_Z: + set_z_offset(value); + break; + case MMA_SELF_TEST: + selftest(value); + break; + case MMA_SET_LDPL: + set_level_det_p(value); + break; + case MMA_SET_PDPL: + set_pulse_det_p(value); + break; + case MMA_SET_PDV: + set_pulse_duration(value); + break; + case MMA_SET_LTV: + set_latency_time(value); + break; + case MMA_SET_TW: + set_time_window(value); + break; + default: + dev_err(&mma7450_client->dev, "command is not found\n"); + break; + } + + return 0; +} + +static ssize_t mma7450_show(struct device *dev, + struct device_attribute *attr, char *buf) +{ + int ret, reg; + + for (reg = REG_XOUTL; reg < REG_REVERVED_1; reg++) { + ret = i2c_smbus_read_byte_data(mma7450_client, reg); + dev_info(&mma7450_client->dev, "reg0x%02x:\t%03d\t0x%02x\n", + reg, (s8) ret, ret); + } + + return 0; +} + +static ssize_t mma7450_store(struct device *dev, + struct device_attribute *attr, const char *buf, + size_t count) +{ + exec_command(buf, count); + + return count; +} + +#else + +static ssize_t mma7450_show(struct device *dev, + struct device_attribute *attr, char *buf) +{ + return 0; +} + +static ssize_t mma7450_store(struct device *dev, + struct device_attribute *attr, const char *buf, + size_t count) +{ + return count; +} + +#endif + +static void report_abs(void) +{ + u8 status, mod = mma_status.mod; + s16 x, y, z; + + status = i2c_smbus_read_byte_data(mma7450_client, REG_STATUS); + if (!(status & 0x01)) { /* data ready in measurement mode? */ + return; + } + if ((mod & 0x0c) == 0) { /* 8g range */ + x = 0xFF & i2c_smbus_read_byte_data(mma7450_client, REG_XOUTL); + x |= 0xFF00 & + (i2c_smbus_read_byte_data(mma7450_client, REG_XOUTH) << 8); + y = 0xFF & i2c_smbus_read_byte_data(mma7450_client, REG_YOUTL); + y |= 0xFF00 & + (i2c_smbus_read_byte_data(mma7450_client, REG_YOUTH) << 8); + z = 0xFF & i2c_smbus_read_byte_data(mma7450_client, REG_ZOUTL); + z |= 0xFF00 & + (i2c_smbus_read_byte_data(mma7450_client, REG_ZOUTH) << 8); + } else { /* 2g/4g range */ + x = 0xFF & i2c_smbus_read_byte_data(mma7450_client, REG_XOUT8); + y = 0xFF & i2c_smbus_read_byte_data(mma7450_client, REG_YOUT8); + z = 0xFF & i2c_smbus_read_byte_data(mma7450_client, REG_ZOUT8); + } + + status = i2c_smbus_read_byte_data(mma7450_client, REG_STATUS); + if (status & 0x02) { /* data is overwrite */ + return; + } + + /* convert signed 10bits to signed 16bits */ + x = (short)(x << 6) >> 6; + y = (short)(y << 6) >> 6; + z = (short)(z << 6) >> 6; + + input_report_abs(mma7450_idev->input, ABS_X, x); + input_report_abs(mma7450_idev->input, ABS_Y, y); + input_report_abs(mma7450_idev->input, ABS_Z, z); + input_sync(mma7450_idev->input); +} + +static void mma_bh_handler(struct work_struct *work) +{ +} + +static void mma7450_dev_poll(struct input_polled_dev *dev) +{ + report_abs(); +} + +static irqreturn_t mma7450_interrupt(int irq, void *dev_id) +{ + struct input_dev *input_dev = dev_id; + u8 int_bit, int_pin; + + int_bit = mma_status.ctl1 & 0x6; + int_pin = mma_status.ctl1 & 0x1; + + switch (mma_status.mod & 0x03) { + case 1: + /*only int1 report data ready int */ + if (plat_data->int1 != irq) + goto error_bad_int; + schedule_work(&mma_work); + break; + case 2: + /* for level and pulse detection mode, + * choice tasklet to handle interrupt quickly. + * Currently, leave it doing nothing*/ + if (plat_data->int1 == irq) { + if ((int_bit == 0) && (int_pin != 0)) + goto error_bad_int; + if ((int_bit == 0x2) && (int_pin != 0x1)) + goto error_bad_int; + if (int_bit == 0x4) + goto error_bad_int; + } + if (plat_data->int2 == irq) { + if ((int_bit == 0) && (int_pin != 0x1)) + goto error_bad_int; + if ((int_bit == 0x2) && (int_pin != 0)) + goto error_bad_int; + if (int_bit == 0x4) + goto error_bad_int; + } + + dev_info(&input_dev->dev, "motion detected in level mod\n"); + + break; + case 3: + if (plat_data->int1 == irq) { + if ((int_bit == 0) && (int_pin != 0x1)) + goto error_bad_int; + if ((int_bit == 0x2) && (int_pin != 0)) + goto error_bad_int; + if ((int_bit == 0x4) && (int_pin != 0x1)) + goto error_bad_int; + } + if (plat_data->int2 == irq) { + if ((int_bit == 0) && (int_pin != 0)) + goto error_bad_int; + if ((int_bit == 0x2) && (int_pin != 0x1)) + goto error_bad_int; + if ((int_bit == 0x4) && (int_pin != 0)) + goto error_bad_int; + } + + if (mma_status.ctl2 & 0x02) + dev_info(&input_dev->dev, + "freefall detected in pulse mod\n"); + else + dev_info(&input_dev->dev, + "motion detected in pulse mod\n"); + + break; + case 0: + default: + break; + } + error_bad_int: + return IRQ_RETVAL(1); +} + +static int mma7450_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + int ret; + struct input_dev *idev; + + plat_data = + (struct mxc_mma7450_platform_data *)client->dev.platform_data; + if (plat_data == NULL) { + dev_err(&client->dev, "lack of platform data!\n"); + return -ENODEV; + } + + /*enable power supply */ + /*when to power on/off the power is to be considered later */ + /*shall I check the return value */ + reg_dvdd_io = regulator_get(&client->dev, plat_data->reg_dvdd_io); + if (reg_dvdd_io != ERR_PTR(-ENOENT)) + regulator_enable(reg_dvdd_io); + else + return -EINVAL; + + reg_avdd = regulator_get(&client->dev, plat_data->reg_avdd); + if (reg_avdd != ERR_PTR(-ENOENT)) + regulator_enable(reg_avdd); + else { + regulator_put(reg_dvdd_io); + return -EINVAL; + } + + /*bind the right device to the driver */ + ret = i2c_smbus_read_byte_data(client, REG_I2CAD); + if (MMA7450_I2C_ADDR != (0x7F & ret)) { /*compare the address value */ + dev_err(&client->dev, + "read chip ID 0x%x is not equal to 0x%x!\n", ret, + MMA7450_I2C_ADDR); + goto error_disable_power; + } + mma7450_client = client; + + /*interrupt register */ + /*when to register interrupt is to be considered later */ + + /*create device file in sysfs as user interface */ + ret = device_create_file(&client->dev, &mma7450_dev_attr); + if (ret) { + dev_err(&client->dev, "create device file failed!\n"); + goto error_disable_power; + } + + /*register to hwmon device */ + hwmon_dev = hwmon_device_register(&client->dev); + if (IS_ERR(hwmon_dev)) { + dev_err(&client->dev, "hwmon register failed!\n"); + ret = PTR_ERR(hwmon_dev); + goto error_rm_dev_file; + } + + /*input poll device register */ + mma7450_idev = input_allocate_polled_device(); + if (!mma7450_idev) { + dev_err(&client->dev, "alloc poll device failed!\n"); + ret = -ENOMEM; + goto error_rm_hwmon_dev; + } + mma7450_idev->poll = mma7450_dev_poll; + mma7450_idev->poll_interval = POLL_INTERVAL; + idev = mma7450_idev->input; + idev->name = DEVICE_NAME; + idev->id.bustype = BUS_I2C; + idev->dev.parent = &client->dev; + idev->evbit[0] = BIT_MASK(EV_ABS); + + input_set_abs_params(idev, ABS_X, -512, 512, INPUT_FUZZ, INPUT_FLAT); + input_set_abs_params(idev, ABS_Y, -512, 512, INPUT_FUZZ, INPUT_FLAT); + input_set_abs_params(idev, ABS_Z, -512, 512, INPUT_FUZZ, INPUT_FLAT); + ret = input_register_polled_device(mma7450_idev); + if (ret) { + dev_err(&client->dev, "register poll device failed!\n"); + goto error_free_poll_dev; + } + + /* configure gpio as input for interrupt monitor */ + plat_data->gpio_pin_get(); + + set_irq_type(plat_data->int1, IRQF_TRIGGER_RISING); + /* register interrupt handle */ + ret = request_irq(plat_data->int1, mma7450_interrupt, + IRQF_TRIGGER_RISING, DEVICE_NAME, idev); + + if (ret) { + dev_err(&client->dev, "request_irq(%d) returned error %d\n", + plat_data->int1, ret); + goto error_rm_poll_dev; + } + + set_irq_type(plat_data->int2, IRQF_TRIGGER_RISING); + ret = request_irq(plat_data->int2, mma7450_interrupt, + IRQF_TRIGGER_RISING, DEVICE_NAME, idev); + if (ret) { + dev_err(&client->dev, "request_irq(%d) returned error %d\n", + plat_data->int2, ret); + goto error_free_irq1; + } + + dev_info(&client->dev, "mma7450 device is probed successfully.\n"); + + set_mod(1); + return 0; /*what value shall be return */ + + /*error handle */ + error_free_irq1: + free_irq(plat_data->int1, 0); + error_rm_poll_dev: + input_unregister_polled_device(mma7450_idev); + error_free_poll_dev: + input_free_polled_device(mma7450_idev); + error_rm_hwmon_dev: + hwmon_device_unregister(hwmon_dev); + error_rm_dev_file: + device_remove_file(&client->dev, &mma7450_dev_attr); + error_disable_power: + regulator_disable(reg_dvdd_io); /*shall I check the return value */ + regulator_disable(reg_avdd); + regulator_put(reg_dvdd_io); + regulator_put(reg_avdd); + + return ret; +} + +static int mma7450_remove(struct i2c_client *client) +{ + free_irq(plat_data->int2, mma7450_idev->input); + free_irq(plat_data->int1, mma7450_idev->input); + plat_data->gpio_pin_put(); + input_unregister_polled_device(mma7450_idev); + input_free_polled_device(mma7450_idev); + hwmon_device_unregister(hwmon_dev); + device_remove_file(&client->dev, &mma7450_dev_attr); + regulator_disable(reg_dvdd_io); /*shall I check the return value */ + regulator_disable(reg_avdd); + regulator_put(reg_dvdd_io); + regulator_put(reg_avdd); + return 0; +} + +static int mma7450_suspend(struct i2c_client *client, pm_message_t state) +{ + mma7450_mode = i2c_smbus_read_byte_data(mma7450_client, REG_MCTL); + i2c_smbus_write_byte_data(mma7450_client, REG_MCTL, + mma7450_mode & ~0x3); + return 0; +} + +static int mma7450_resume(struct i2c_client *client) +{ + i2c_smbus_write_byte_data(mma7450_client, REG_MCTL, mma7450_mode); + return 0; +} + +static int __init init_mma7450(void) +{ + /*register driver */ + printk(KERN_INFO "add mma i2c driver\n"); + return i2c_add_driver(&i2c_mma7450_driver); +} + +static void __exit exit_mma7450(void) +{ + printk(KERN_INFO "del mma i2c driver.\n"); + return i2c_del_driver(&i2c_mma7450_driver); +} + +module_init(init_mma7450); +module_exit(exit_mma7450); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MMA7450 sensor driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/i2c-slave/Kconfig b/drivers/i2c-slave/Kconfig new file mode 100644 index 000000000000..89717e15e784 --- /dev/null +++ b/drivers/i2c-slave/Kconfig @@ -0,0 +1,39 @@ +# +# I2C slave subsystem configuration +# + +menuconfig I2C_SLAVE + bool "I2C Slave support" + depends on HAS_IOMEM + ---help--- + I2C (pronounce: I-square-C) is a slow serial bus protocol used in + many micro controller applications and developed by Philips. + + If you want I2C Slave support, you should say Y here. + + This I2C Slave support can also be built as a module. If so, the module + will be called i2c-slave. + +if I2C_SLAVE + +config I2C_SLAVE_CORE + tristate "I2C SLAVE CORE" + default y + ---help--- + i2c slave core. + +config MXC_I2C_SLAVE + tristate "MXC I2C SLAVE" + depends on I2C_SLAVE_CORE + default y + ---help--- + mxc i2c slave support. + +config I2C_SLAVE_CLIENT + tristate "I2C SLAVE CLIENT" + default y + ---help--- + i2c slave client that used when the master is on the same board. + this is for i2c master which is on the same board with the slave. + +endif # I2C_SLAVE diff --git a/drivers/i2c-slave/Makefile b/drivers/i2c-slave/Makefile new file mode 100644 index 000000000000..a7b08c919af9 --- /dev/null +++ b/drivers/i2c-slave/Makefile @@ -0,0 +1,8 @@ +# +# Makefile for the i2c slave. +# + +i2c_slave-objs := i2c_slave_ring_buffer.o i2c_slave_device.o i2c_slave_core.o +obj-$(CONFIG_I2C_SLAVE_CORE) += i2c_slave.o +obj-$(CONFIG_MXC_I2C_SLAVE) += mxc_i2c_slave.o +obj-$(CONFIG_I2C_SLAVE_CLIENT) += i2c_slave_client.o diff --git a/drivers/i2c-slave/i2c_slave_client.c b/drivers/i2c-slave/i2c_slave_client.c new file mode 100644 index 000000000000..05bed361f5ca --- /dev/null +++ b/drivers/i2c-slave/i2c_slave_client.c @@ -0,0 +1,81 @@ +/* + * Copyright 2007-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#include +#include +#include +#include +#include +#include +#include +#include + +struct i2c_client *i2c_slave_client; +static int i2c_slave_client_probe(struct i2c_client *adapter); +static int i2c_slave_client_remove(struct i2c_client *client); +static struct i2c_driver i2c_slave_client_driver = { + .driver = { + .owner = THIS_MODULE, + .name = "i2c-slave-client", + }, + .probe = i2c_slave_client_probe, + .remove = i2c_slave_client_remove, +}; + +/*! + * ov2640 I2C attach function + * + * @param adapter struct i2c_adapter * + * @return Error code indicating success or failure + */ +static int i2c_slave_client_probe(struct i2c_client *client) +{ + i2c_slave_client = client; + return 0; +} + +/*! + * ov2640 I2C detach function + * + * @param client struct i2c_client * + * @return Error code indicating success or failure + */ +static int i2c_slave_client_remove(struct i2c_client *client) +{ + return 0; +} + +/*! + * ov2640 init function + * + * @return Error code indicating success or failure + */ +static __init int i2c_slave_client_init(void) +{ + return i2c_add_driver(&i2c_slave_client_driver); +} + +/*! + * OV2640 cleanup function + * + * @return Error code indicating success or failure + */ +static void __exit i2c_slave_client_clean(void) +{ + i2c_del_driver(&i2c_slave_client_driver); +} + +module_init(i2c_slave_client_init); +module_exit(i2c_slave_client_clean); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("I2c Slave Client Driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/i2c-slave/i2c_slave_core.c b/drivers/i2c-slave/i2c_slave_core.c new file mode 100644 index 000000000000..4d3a21a5f45f --- /dev/null +++ b/drivers/i2c-slave/i2c_slave_core.c @@ -0,0 +1,359 @@ +/* + * Copyright 2007-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include "i2c_slave_device.h" + +int i2c_slave_major; + +static ssize_t i2c_slave_read(struct file *fd, char __user *buf, size_t len, + loff_t *ptr) +{ + i2c_slave_device_t *dev; + void *kbuf; + int ret; + + if (len == 0) + return 0; + + kbuf = kmalloc(len, GFP_KERNEL); + if (!kbuf) { + ret = -ENOMEM; + goto error0; + } + + dev = (i2c_slave_device_t *) fd->private_data; + if (!dev) { + ret = -ENODEV; + goto error1; + } + + ret = i2c_slave_device_read(dev, len, kbuf); + if (ret <= 0 || copy_to_user(buf, kbuf, len)) { + ret = -EFAULT; + } + + error1: + kfree(kbuf); + error0: + return ret; +} + +static ssize_t i2c_slave_write(struct file *fd, const char __user *buf, + size_t len, loff_t *ptr) +{ + i2c_slave_device_t *dev; + void *kbuf; + int ret; + + if (len == 0) + return 0; + + kbuf = kmalloc(len, GFP_KERNEL); + if (!kbuf) { + ret = -ENOMEM; + goto error0; + } + if (copy_from_user(kbuf, buf, len)) { + ret = -EFAULT; + goto error1; + } + + dev = (i2c_slave_device_t *) fd->private_data; + if (!dev) { + ret = -ENODEV; + goto error1; + } + + ret = i2c_slave_device_write(dev, len, (u8 *) kbuf); + + error1: + kfree(kbuf); + error0: + return ret; +} + +static int i2c_slave_ioctl(struct inode *inode, struct file *fd, + unsigned code, unsigned long value) +{ + /*todo */ + return 0; +} + +static int i2c_slave_open(struct inode *inode, struct file *fd) +{ + int ret; + unsigned int id; + i2c_slave_device_t *dev; + id = iminor(inode); + + if (id >= I2C_SLAVE_DEVICE_MAX) { + ret = -ENODEV; + goto error; + } + + dev = i2c_slave_device_find(id); + if (!dev) { + ret = -ENODEV; + goto error; + } + + i2c_slave_rb_clear(dev->receive_buffer); + i2c_slave_rb_clear(dev->send_buffer); + + if (i2c_slave_device_start(dev)) { + ret = -EBUSY; + goto error; + } + + fd->private_data = (void *)dev; + ret = 0; + + error: + return ret; +} + +static int i2c_slave_release(struct inode *inode, struct file *fd) +{ + int ret; + unsigned int id; + i2c_slave_device_t *dev; + id = iminor(inode); + + if (id >= I2C_SLAVE_DEVICE_MAX) { + ret = -ENODEV; + goto error; + } + + dev = i2c_slave_device_find(id); + if (!dev) { + ret = -ENODEV; + goto error; + } + + if (i2c_slave_device_stop(dev)) { + ret = -EBUSY; + goto error; + } + + ret = 0; + + error: + return ret; +} + +static const struct file_operations i2c_slave_fops = { + .owner = THIS_MODULE, + .llseek = no_llseek, + .read = i2c_slave_read, + .write = i2c_slave_write, + .ioctl = i2c_slave_ioctl, + .open = i2c_slave_open, + .release = i2c_slave_release, +}; + +static int i2c_slave_bus_match(struct device *dev, struct device_driver *drv) +{ + return 0; +} + +/* +static int i2c_slave_bus_probe(struct device *dev) +{ + struct device_driver *driver = dev->driver; + + if (driver) { + return driver->probe(dev); + } else { + dev_err(dev, "%s: no driver\n", __func__); + return -ENODEV; + } +} +*/ + +static int i2c_slave_bus_remove(struct device *dev) +{ + struct device_driver *driver = dev->driver; + + if (driver) { + if (!driver->remove) { + return 0; + } else { + return driver->remove(dev); + } + } else { + + dev_err(dev, "%s: no driver\n", __func__); + return -ENODEV; + } +} + +static void i2c_slave_bus_shutdown(struct device *dev) +{ + struct device_driver *driver = dev->driver; + + if (driver) { + + driver->shutdown(dev); + } else { + + dev_err(dev, "%s: no driver\n", __func__); + return; + } +} +static int i2c_slave_bus_suspend(struct device *dev, pm_message_t state) +{ + struct device_driver *driver = dev->driver; + + if (driver) { + + if (!driver->suspend) { + return 0; + } else { + return driver->suspend(dev, state); + } + } else { + + dev_err(dev, "%s: no driver\n", __func__); + return -ENODEV; + } +} + +static int i2c_slave_bus_resume(struct device *dev) +{ + struct device_driver *driver = dev->driver; + + if (driver) { + + if (!driver->resume) { + return 0; + } else { + return driver->resume(dev); + } + } else { + + dev_err(dev, "%s: no driver\n", __func__); + return -ENODEV; + } +} + +struct bus_type i2c_slave_bus_type = { + .name = "i2c-slave", + .match = i2c_slave_bus_match, + .remove = i2c_slave_bus_remove, + .shutdown = i2c_slave_bus_shutdown, + .suspend = i2c_slave_bus_suspend, + .resume = i2c_slave_bus_resume, +}; + +EXPORT_SYMBOL_GPL(i2c_slave_bus_type); + +static int i2c_slave_driver_probe(struct device *dev) +{ + return 0; +} + +static int i2c_slave_driver_remove(struct device *dev) +{ + return 0; +} + +static int i2c_slave_driver_shutdown(struct device *dev) +{ + return 0; +} + +static int i2c_slave_driver_suspend(struct device *dev, pm_message_t state) +{ + return 0; +} + +static int i2c_slave_driver_resume(struct device *dev) +{ + return 0; +} + +extern struct class *i2c_slave_class; + +static struct device_driver i2c_slave_driver = { + .name = "i2c-slave", + .owner = THIS_MODULE, + .bus = &i2c_slave_bus_type, + .probe = i2c_slave_driver_probe, + .remove = i2c_slave_driver_remove, + .shutdown = i2c_slave_driver_shutdown, + .suspend = i2c_slave_driver_suspend, + .resume = i2c_slave_driver_resume, +}; + +static int __init i2c_slave_dev_init(void) +{ + int ret; + + printk(KERN_INFO "i2c slave /dev entries driver\n"); + + ret = bus_register(&i2c_slave_bus_type); + if (ret) { + printk(KERN_ERR "%s: bus_register error\n", __func__); + goto out; + } + + i2c_slave_class = class_create(THIS_MODULE, "i2c-slave"); + if (IS_ERR(i2c_slave_class)) { + pr_err("%s: class_create error\n", __func__); + goto out_unreg_bus; + } + + i2c_slave_major = register_chrdev(0, "i2c-slave", &i2c_slave_fops); + if (i2c_slave_major <= 0) { + pr_err("%s: register_chrdev error\n", __func__); + goto out_unreg_class; + } + + ret = driver_register(&i2c_slave_driver); + if (ret) { + pr_err("%s: driver_register error\n", __func__); + goto out_unreg_chrdev; + } + + return 0; + + out_unreg_chrdev: + unregister_chrdev(i2c_slave_major, "i2c-slave"); + out_unreg_class: + class_destroy(i2c_slave_class); + out_unreg_bus: + bus_unregister(&i2c_slave_bus_type); + out: + pr_err("%s: init error\n", __func__); + return ret; +} + +static void __exit i2c_dev_exit(void) +{ + driver_unregister(&i2c_slave_driver); + class_destroy(i2c_slave_class); + unregister_chrdev(i2c_slave_major, "i2c-slave"); + bus_unregister(&i2c_slave_bus_type); +} + +module_init(i2c_slave_dev_init); +module_exit(i2c_dev_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("I2C Slave Driver Core"); +MODULE_LICENSE("GPL"); diff --git a/drivers/i2c-slave/i2c_slave_device.c b/drivers/i2c-slave/i2c_slave_device.c new file mode 100644 index 000000000000..1968a00aa693 --- /dev/null +++ b/drivers/i2c-slave/i2c_slave_device.c @@ -0,0 +1,271 @@ +/* + * Copyright 2007-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include +#include +#include "i2c_slave_device.h" +static i2c_slave_device_t *i2c_slave_devices[I2C_SLAVE_DEVICE_MAX]; +struct class *i2c_slave_class; +static int i2c_slave_device_get_id(void) +{ + int i; + for (i = 0; i < I2C_SLAVE_DEVICE_MAX; i++) { + if (!i2c_slave_devices[i]) + return i; + } + return -1; +} + +i2c_slave_device_t *i2c_slave_device_find(int id) +{ + if (id >= 0 && id < I2C_SLAVE_DEVICE_MAX) + return i2c_slave_devices[id]; + + else + return NULL; +} +void i2c_slave_device_set_name(i2c_slave_device_t *device, char *name) +{ + device->name = name; +} + +void i2c_slave_device_set_address(i2c_slave_device_t *device, u8 address) +{ + device->address = address; +} + +u8 i2c_slave_device_get_addr(i2c_slave_device_t *device) +{ + return device->address; +} + +int i2c_slave_device_set_freq(i2c_slave_device_t *device, u32 freq) +{ + /*TODO: freq check */ + device->scl_freq = freq; + return 0; +} + +u32 i2c_slave_device_get_freq(i2c_slave_device_t *device) +{ + return device->scl_freq; +} + +/*used by the specific i2c device to register itself to the core.*/ +i2c_slave_device_t *i2c_slave_device_alloc(void) +{ + int id; + i2c_slave_device_t *device; + id = i2c_slave_device_get_id(); + if (id < 0) { + goto error; + } + device = + (i2c_slave_device_t *) kzalloc(sizeof(i2c_slave_device_t), + GFP_KERNEL); + if (!device) { + printk(KERN_ERR "%s: alloc device error\n", __func__); + goto error_device; + } + device->receive_buffer = i2c_slave_rb_alloc(PAGE_SIZE); + if (!device->receive_buffer) { + printk(KERN_ERR "%s: alloc receive buffer error\n", __func__); + goto error_receive_buffer; + } + device->send_buffer = i2c_slave_rb_alloc(PAGE_SIZE); + if (!device->send_buffer) { + printk(KERN_ERR "%s: alloc send buffer error\n", __func__); + goto error_send_buffer; + } + device->id = id; + return device; + + error_send_buffer: + kfree(device->receive_buffer); + error_receive_buffer: + kfree((void *)device); + error_device: + pr_debug(KERN_ERR "%s: no memory\n", __func__); + error: + return 0; +} + +void i2c_slave_device_free(i2c_slave_device_t *dev) +{ + i2c_slave_rb_release(dev->receive_buffer); + i2c_slave_rb_release(dev->send_buffer); + kfree(dev); +} + +int i2c_slave_device_register(i2c_slave_device_t *device) +{ + device->dev = device_create(i2c_slave_class, NULL, + MKDEV(i2c_slave_major, device->id), + NULL, "slave-i2c-%d", device->id); + if (!device->dev) { + return -1; + } + i2c_slave_devices[device->id] = device; + return 0; +} + +void i2c_slave_device_unregister(i2c_slave_device_t *device) +{ + device_destroy(i2c_slave_class, MKDEV(i2c_slave_major, device->id)); + i2c_slave_devices[device->id] = 0; + i2c_slave_device_free(device); +} + +/* + this two functions are used by i2c slave core to start or stop the specific i2c device. +*/ +int i2c_slave_device_start(i2c_slave_device_t *device) +{ + return device->start(device); +} + +int i2c_slave_device_stop(i2c_slave_device_t *device) +{ + return device->stop(device); +} + +/* + this two functions are used by i2c slave core to get data by the specific i2c slave device + or send data to it to feed i2c master's need. + + @mod: async(1) or sync(0) mode. +*/ +int i2c_slave_device_read(i2c_slave_device_t *device, int num, u8 *data) +{ + int read_num, read_total = 0; + int step = 1000; + u8 *read_buf = data; + printk(KERN_INFO "%s: device id=%d, num=%d\n", __func__, device->id, + num); + read_num = i2c_slave_rb_consume(device->receive_buffer, num, read_buf); + read_total += read_num; + read_buf += read_num; + step--; + while ((read_total < num) && step) { + set_current_state(TASK_INTERRUPTIBLE); + schedule_timeout(HZ / 10); + if (!signal_pending(current)) { + } else { + /*TODO*/ break; + } + read_num = + i2c_slave_rb_consume(device->receive_buffer, + num - read_total, read_buf); + num -= read_num; + read_buf += read_num; + step--; + } + return read_total; +} +int i2c_slave_device_write(i2c_slave_device_t *device, int num, u8 *data) +{ + int write_num, write_total = 0; + int step = 1000; + u8 *buf_index = data; + write_num = i2c_slave_rb_produce(device->send_buffer, num, buf_index); + write_total += write_num; + buf_index += write_num; + step--; + while (write_total < num && step) { + set_current_state(TASK_INTERRUPTIBLE); + schedule_timeout(HZ / 10); + if (!signal_pending(current)) { + } else { + /*TODO*/ step = 0; + break; + } + write_num = + i2c_slave_rb_produce(device->send_buffer, num - write_total, + buf_index); + write_total += write_num; + buf_index += write_num; + step--; + } + while (step && i2c_slave_rb_num(device->send_buffer)) { + set_current_state(TASK_INTERRUPTIBLE); + schedule_timeout(HZ / 10); + if (!signal_pending(current)) { + step--; + } else { + /*TODO*/ step = 0; + break; + } + } + if (!step) { + write_total -= i2c_slave_rb_num(device->send_buffer); + i2c_slave_rb_clear(device->send_buffer); + } + return write_total; +} + +/* + * this 2 functions used by the specific i2c slave device when they got data from master(produce), + * or is request by master(consume). + */ +int i2c_slave_device_produce(i2c_slave_device_t *device, int num, u8 *data) +{ + int ret; + ret = i2c_slave_rb_produce(device->receive_buffer, num, data); + return ret; +} +int i2c_slave_device_consume(i2c_slave_device_t *device, int num, u8 *data) +{ + return i2c_slave_rb_consume(device->send_buffer, num, data); +} + +EXPORT_SYMBOL(i2c_slave_device_set_name); +EXPORT_SYMBOL(i2c_slave_device_set_address); +EXPORT_SYMBOL(i2c_slave_device_get_addr); +EXPORT_SYMBOL(i2c_slave_device_find); +EXPORT_SYMBOL(i2c_slave_device_set_freq); +EXPORT_SYMBOL(i2c_slave_device_get_freq); + +/* +* used by the specific i2c device to register itself to the core. +*/ +EXPORT_SYMBOL(i2c_slave_device_alloc); +EXPORT_SYMBOL(i2c_slave_device_free); +EXPORT_SYMBOL(i2c_slave_device_register); +EXPORT_SYMBOL(i2c_slave_device_unregister); + +/* + this two functions are used by i2c slave core to start or stop the specific i2c device. +*/ +EXPORT_SYMBOL(i2c_slave_device_start); +EXPORT_SYMBOL(i2c_slave_device_stop); + +/* + this two functions are used by i2c slave core to get data by the specific i2c slave device + or send data to it for it to feed i2c master's need. + + @mod: async(1) or sync(0) mode. +*/ +EXPORT_SYMBOL(i2c_slave_device_read); +EXPORT_SYMBOL(i2c_slave_device_write); + +/* +* this 2 functions used by the specific i2c slave device when they got data from master, +* or is request by master. +*/ +EXPORT_SYMBOL(i2c_slave_device_produce); +EXPORT_SYMBOL(i2c_slave_device_consume); diff --git a/drivers/i2c-slave/i2c_slave_device.h b/drivers/i2c-slave/i2c_slave_device.h new file mode 100644 index 000000000000..472782cd230d --- /dev/null +++ b/drivers/i2c-slave/i2c_slave_device.h @@ -0,0 +1,79 @@ +/* + * Copyright 2007-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#ifndef __I2C_SLAVE_H__ +#define __I2C_SLAVE_H__ + +#include +#include "i2c_slave_ring_buffer.h" + +#define I2C_SLAVE_DEVICE_MAX 256 +extern int i2c_slave_major; + +typedef struct i2c_slave_device { + struct list_head list; + u8 address; + u32 scl_freq; + char *name; + i2c_slave_ring_buffer_t *receive_buffer; + i2c_slave_ring_buffer_t *send_buffer; + int (*start) (struct i2c_slave_device *); + int (*stop) (struct i2c_slave_device *); + /*int (*set_freq)(struct i2c_slave_device*); + int (*set_addr)(struct i2c_slave_device*);*/ + void *private_data; + struct device *dev; + int id; +} i2c_slave_device_t; + +/* + used by the specific device to set some infomations. +*/ +void i2c_slave_device_set_name(i2c_slave_device_t *device, char *name); +void i2c_slave_device_set_address(i2c_slave_device_t *device, u8 address); +i2c_slave_device_t *i2c_slave_device_find(int id); +u8 i2c_slave_device_get_addr(i2c_slave_device_t *device); +int i2c_slave_device_set_freq(i2c_slave_device_t *device, u32 freq); +u32 i2c_slave_device_get_freq(i2c_slave_device_t *device); + +/* +**used by the specific i2c device to register itself to the core. +*/ +i2c_slave_device_t *i2c_slave_device_alloc(void); +void i2c_slave_device_free(i2c_slave_device_t *); +int i2c_slave_device_register(i2c_slave_device_t *device); +void i2c_slave_device_unregister(i2c_slave_device_t *device); + +/* + this two functions are used by i2c slave core to start or stop the specific i2c device. +*/ +int i2c_slave_device_start(i2c_slave_device_t *device); +int i2c_slave_device_stop(i2c_slave_device_t *device); + +/* + this two functions are used by i2c slave core to get data by the specific i2c slave device + or send data to it for it to feed i2c master's need. + + @mod: async(1) or sync(0) mode. +*/ +int i2c_slave_device_read(i2c_slave_device_t *device, int num, u8 *data); +int i2c_slave_device_write(i2c_slave_device_t *device, int num, u8 *data); + +/* +*this 2 functions used by the specific i2c slave device when they got data from master, +*or is requested by master. +*/ +int i2c_slave_device_produce(i2c_slave_device_t *device, int num, u8 *data); +int i2c_slave_device_consume(i2c_slave_device_t *device, int num, u8 *data); + +#endif diff --git a/drivers/i2c-slave/i2c_slave_ring_buffer.c b/drivers/i2c-slave/i2c_slave_ring_buffer.c new file mode 100644 index 000000000000..2f7be580c197 --- /dev/null +++ b/drivers/i2c-slave/i2c_slave_ring_buffer.c @@ -0,0 +1,185 @@ +/* + * Copyright 2007-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#include +#include +#include "i2c_slave_ring_buffer.h" + +i2c_slave_ring_buffer_t *i2c_slave_rb_alloc(int size) +{ + i2c_slave_ring_buffer_t *ring_buf; + + ring_buf = + (i2c_slave_ring_buffer_t *) kzalloc(sizeof(i2c_slave_ring_buffer_t), + GFP_KERNEL); + if (!ring_buf) { + pr_debug("%s: alloc ring_buf error\n", __func__); + goto error; + } + + ring_buf->buffer = kmalloc(size, GFP_KERNEL); + if (!ring_buf->buffer) { + pr_debug("%s: alloc buffer error\n", __func__); + goto error1; + } + + ring_buf->total = size; + + ring_buf->lock = __SPIN_LOCK_UNLOCKED(ring_buf->lock); + return ring_buf; + + error1: + kfree(ring_buf); + error: + return NULL; +} + +void i2c_slave_rb_release(i2c_slave_ring_buffer_t *ring) +{ + unsigned long flags; + + spin_lock_irqsave(ring->lock, flags); + kfree(ring->buffer); + spin_unlock_irqrestore(ring->lock, flags); + kfree(ring); +} + +int i2c_slave_rb_produce(i2c_slave_ring_buffer_t *ring, int num, char *data) +{ + int ret = 0; + unsigned long flags; + + spin_lock_irqsave(ring->lock, flags); + + if (ring->start < ring->end) { + if ((ring->start + num) < ring->end) { /*have enough space */ + memcpy(&ring->buffer[ring->start], data, num); + ring->start += num; + ret = num; + } else { /*space not enough, just copy part of it. */ + ret = ring->end - ring->start; + memcpy(&ring->buffer[ring->start], data, ret); + ring->start += ret; + ring->full = 1; + } + } else if (ring->start >= ring->end && !ring->full) { + if (ring->start + num <= ring->total) { /*space enough */ + ret = num; + memcpy(&ring->buffer[ring->start], data, ret); + ring->start += ret; + } else { /*turn ring->start around */ + ret = ring->total - ring->start; + memcpy(&ring->buffer[ring->start], data, ret); + ring->start = 0; + num -= ret; + data += ret; + if (num < ring->end) { /*space enough */ + ret += num; + memcpy(&ring->buffer[ring->start], data, num); + } else { /*space not enough, just copy part of it. */ + ret += ring->end; + memcpy(&ring->buffer[ring->start], data, + ring->end); + ring->start = ring->end; + ring->full = 1; + } + } + } else { /*(ring->data == ring->end) && ring->full ) : full */ + ret = 0; + } + + spin_unlock_irqrestore(ring->lock, flags); + return ret; +} + +int i2c_slave_rb_consume(i2c_slave_ring_buffer_t *ring, int num, char *data) +{ + int ret; + unsigned long flags; + spin_lock_irqsave(ring->lock, flags); + if (num <= 0) { + ret = 0; + goto out; + } + + if (ring->start > ring->end) { + if (num <= ring->start - ring->end) { /*enough */ + ret = num; + memcpy(data, &ring->buffer[ring->end], ret); + ring->end += ret; + } else { /*not enough */ + ret = ring->start - ring->end; + memcpy(data, &ring->buffer[ring->end], ret); + ring->end += ret; + } + } else if (ring->start < ring->end || ring->full) { + if (num <= ring->total - ring->end) { + ret = ring->total - ring->end; + memcpy(data, &ring->buffer[ring->end], ret); + ring->end += ret; + } else if (num <= ring->total - ring->end + ring->start) { + ret = ring->total - ring->end; + memcpy(data, &ring->buffer[ring->end], ret); + ring->end = 0; + data += ret; + num -= ret; + memcpy(data, &ring->buffer[ring->end], num); + ring->end = num; + ret += num; + } else { + ret = ring->total - ring->end; + memcpy(data, &ring->buffer[ring->end], ret); + ring->end = 0; + data += ret; + num -= ret; + memcpy(data, &ring->buffer[ring->end], ring->start); + ring->end = ring->start; + ret += ring->start; + } + ring->full = 0; + } else { /*empty */ + ret = 0; + } + + out: + spin_unlock_irqrestore(ring->lock, flags); + + return ret; +} + +int i2c_slave_rb_num(i2c_slave_ring_buffer_t *ring) +{ + int ret; + unsigned long flags; + spin_lock_irqsave(ring->lock, flags); + if (ring->start > ring->end) { + ret = ring->start - ring->end; + } else if (ring->start < ring->end) { + ret = ring->total - ring->end + ring->start; + } else if (ring->full) { + ret = ring->total; + } else { + ret = 0; + } + spin_unlock_irqrestore(ring->lock, flags); + return ret; +} + +void i2c_slave_rb_clear(i2c_slave_ring_buffer_t *ring) +{ + unsigned long flags; + spin_lock_irqsave(ring->lock, flags); + + ring->start = ring->end = 0; + ring->full = 0; + spin_unlock_irqrestore(ring->lock, flags); +} diff --git a/drivers/i2c-slave/i2c_slave_ring_buffer.h b/drivers/i2c-slave/i2c_slave_ring_buffer.h new file mode 100644 index 000000000000..32fc21b618ed --- /dev/null +++ b/drivers/i2c-slave/i2c_slave_ring_buffer.h @@ -0,0 +1,39 @@ +#ifndef __BUFFER_MANAGER_H__ +#define __BUFFER_MANAGER_H__ +/* + * Copyright 2007-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#include +#include + +typedef struct i2c_slave_ring_buffer { + int start; + int end; + int total; + bool full; + char *buffer; + spinlock_t lock; +} i2c_slave_ring_buffer_t; + +i2c_slave_ring_buffer_t *i2c_slave_rb_alloc(int size); + +void i2c_slave_rb_release(i2c_slave_ring_buffer_t *ring); + +int i2c_slave_rb_produce(i2c_slave_ring_buffer_t *ring, int num, char *data); + +int i2c_slave_rb_consume(i2c_slave_ring_buffer_t *ring, int num, char *data); + +int i2c_slave_rb_num(i2c_slave_ring_buffer_t *ring); + +void i2c_slave_rb_clear(i2c_slave_ring_buffer_t *ring); + +#endif diff --git a/drivers/i2c-slave/mxc_i2c_slave.c b/drivers/i2c-slave/mxc_i2c_slave.c new file mode 100644 index 000000000000..347c015afd22 --- /dev/null +++ b/drivers/i2c-slave/mxc_i2c_slave.c @@ -0,0 +1,335 @@ +/* + * Copyright (C) 2007-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "i2c_slave_device.h" +#include "mxc_i2c_slave.h" +#include "mxc_i2c_slave_reg.h" + +struct mxc_i2c_slave_clk { + int reg_value; + int div; +}; + +static const struct mxc_i2c_slave_clk i2c_clk_table[] = { + {0x20, 22}, {0x21, 24}, {0x22, 26}, {0x23, 28}, + {0, 30}, {1, 32}, {0x24, 32}, {2, 36}, + {0x25, 36}, {0x26, 40}, {3, 42}, {0x27, 44}, + {4, 48}, {0x28, 48}, {5, 52}, {0x29, 56}, + {6, 60}, {0x2A, 64}, {7, 72}, {0x2B, 72}, + {8, 80}, {0x2C, 80}, {9, 88}, {0x2D, 96}, + {0xA, 104}, {0x2E, 112}, {0xB, 128}, {0x2F, 128}, + {0xC, 144}, {0xD, 160}, {0x30, 160}, {0xE, 192}, + {0x31, 192}, {0x32, 224}, {0xF, 240}, {0x33, 256}, + {0x10, 288}, {0x11, 320}, {0x34, 320}, {0x12, 384}, + {0x35, 384}, {0x36, 448}, {0x13, 480}, {0x37, 512}, + {0x14, 576}, {0x15, 640}, {0x38, 640}, {0x16, 768}, + {0x39, 768}, {0x3A, 896}, {0x17, 960}, {0x3B, 1024}, + {0x18, 1152}, {0x19, 1280}, {0x3C, 1280}, {0x1A, 1536}, + {0x3D, 1536}, {0x3E, 1792}, {0x1B, 1920}, {0x3F, 2048}, + {0x1C, 2304}, {0x1D, 2560}, {0x1E, 3072}, {0x1F, 3840}, + {0, 0} +}; + +extern void gpio_i2c_active(int i2c_num); +extern void gpio_i2c_inactive(int i2c_num); + +static irqreturn_t interrupt_handler(int irq, void *dev_id) +{ + u16 status, ctl; + int num; + u16 data; + struct mxc_i2c_slave_device *mxc_i2c = + (struct mxc_i2c_slave_device *)dev_id; + + status = readw(mxc_i2c->reg_base + MXC_I2SR); + ctl = readw(mxc_i2c->reg_base + MXC_I2CR); + + dev_dbg(mxc_i2c->dev->dev, "status=%x, ctl=%x\n", status, ctl); + + if (status & MXC_I2SR_IAAS) { + if (status & MXC_I2SR_SRW) { + /*slave send */ + num = + i2c_slave_device_consume(mxc_i2c->dev, 1, + (u8 *) &data); + if (num < 1) { + /*FIXME:not ready to send data */ + printk(KERN_ERR + " i2c-slave:%s:data not ready\n", + __func__); + } else { + ctl |= MXC_I2CR_MTX; + writew(ctl, mxc_i2c->reg_base + MXC_I2CR); + /*send data */ + writew(data, mxc_i2c->reg_base + MXC_I2DR); + } + + } else { + /*slave receive */ + ctl &= ~MXC_I2CR_MTX; + writew(ctl, mxc_i2c->reg_base + MXC_I2CR); + + /*dummy read */ + data = readw(mxc_i2c->reg_base + MXC_I2DR); + } + } else { + /*slave send */ + if (ctl & MXC_I2CR_MTX) { + if (!(status & MXC_I2SR_RXAK)) { /*ACK received */ + num = + i2c_slave_device_consume(mxc_i2c->dev, 1, + (u8 *) &data); + if (num < 1) { + /*FIXME:not ready to send data */ + printk(KERN_ERR + " i2c-slave:%s:data not ready\n", + __func__); + } else { + ctl |= MXC_I2CR_MTX; + writew(ctl, + mxc_i2c->reg_base + MXC_I2CR); + writew(data, + mxc_i2c->reg_base + MXC_I2DR); + } + } else { + /*no ACK. */ + /*dummy read */ + ctl &= ~MXC_I2CR_MTX; + writew(ctl, mxc_i2c->reg_base + MXC_I2CR); + data = readw(mxc_i2c->reg_base + MXC_I2DR); + } + } else { /*read */ + ctl &= ~MXC_I2CR_MTX; + writew(ctl, mxc_i2c->reg_base + MXC_I2CR); + + /*read */ + data = readw(mxc_i2c->reg_base + MXC_I2DR); + i2c_slave_device_produce(mxc_i2c->dev, 1, + (u8 *) &data); + } + + } + + writew(0x0, mxc_i2c->reg_base + MXC_I2SR); + + return IRQ_HANDLED; +} + +static int start(i2c_slave_device_t *device) +{ + volatile unsigned int cr; + unsigned int addr; + struct mxc_i2c_slave_device *mxc_dev; + + mxc_dev = (struct mxc_i2c_slave_device *)device->private_data; + if (!mxc_dev) { + dev_err(device->dev, "%s: get mxc_dev error\n", __func__); + return -ENODEV; + } + + clk_enable(mxc_dev->clk); + /* Set the frequency divider */ + writew(mxc_dev->clkdiv, mxc_dev->reg_base + MXC_IFDR); + + /* Set the Slave bit */ + cr = readw(mxc_dev->reg_base + MXC_I2CR); + cr &= (!MXC_I2CR_MSTA); + writew(cr, mxc_dev->reg_base + MXC_I2CR); + + /*Set Slave Address */ + addr = mxc_dev->dev->address << 1; + writew(addr, mxc_dev->reg_base + MXC_IADR); + + /* Clear the status register */ + writew(0x0, mxc_dev->reg_base + MXC_I2SR); + + /* Enable I2C and its interrupts */ + writew(MXC_I2CR_IEN, mxc_dev->reg_base + MXC_I2CR); + writew(MXC_I2CR_IEN | MXC_I2CR_IIEN, mxc_dev->reg_base + MXC_I2CR); + + return 0; + +} + +static int stop(i2c_slave_device_t *device) +{ + struct mxc_i2c_slave_device *mxc_dev; + + mxc_dev = (struct mxc_i2c_slave_device *)device->private_data; + + writew(0x0, mxc_dev->reg_base + MXC_I2CR); + clk_disable(mxc_dev->clk); + + return 0; +} + +static int mxc_i2c_slave_probe(struct platform_device *pdev) +{ + int i; + u32 clk_freq; + struct resource *res; + struct mxc_i2c_slave_device *mxc_dev; + + mxc_dev = kzalloc(sizeof(struct mxc_i2c_slave_device), GFP_KERNEL); + if (!mxc_dev) { + goto error0; + } + mxc_dev->dev = i2c_slave_device_alloc(); + if (mxc_dev->dev == 0) { + dev_err(&pdev->dev, "%s: i2c_slave_device_alloc error\n", + __func__); + goto error1; + } + + i2c_slave_device_set_address(mxc_dev->dev, MXC_I2C_SLAVE_ADDRESS); + i2c_slave_device_set_freq(mxc_dev->dev, MXC_I2C_SLAVE_FREQ); + i2c_slave_device_set_name(mxc_dev->dev, MXC_I2C_SLAVE_NAME); + mxc_dev->dev->start = start; + mxc_dev->dev->stop = stop; + + mxc_dev->dev->private_data = mxc_dev; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (res == NULL) { + dev_err(&pdev->dev, "%s: get resource error\n", __func__); + goto error2; + } + mxc_dev->reg_base = ioremap(res->start, res->end - res->start + 1); + + mxc_dev->irq = platform_get_irq(pdev, 0); + if (mxc_dev->irq < 0) { + dev_err(&pdev->dev, "%s: get irq error\n", __func__); + goto error3; + } + if (request_irq(mxc_dev->irq, interrupt_handler, + 0, mxc_dev->dev->name, mxc_dev) < 0) { + dev_err(&pdev->dev, "%s: request_irq error\n", __func__); + goto error3; + } + + /*i2c id on soc */ + mxc_dev->id = pdev->id; + + gpio_i2c_active(mxc_dev->id); + + /*clock */ + mxc_dev->clk = clk_get(&pdev->dev, "i2c_clk"); + clk_freq = clk_get_rate(mxc_dev->clk); + mxc_dev->clkdiv = -1; + if (mxc_dev->dev->scl_freq) { + /* Calculate divider and round up any fractional part */ + int div = (clk_freq + mxc_dev->dev->scl_freq - 1) / + mxc_dev->dev->scl_freq; + for (i = 0; i2c_clk_table[i].div != 0; i++) { + if (i2c_clk_table[i].div >= div) { + mxc_dev->clkdiv = i2c_clk_table[i].reg_value; + break; + } + } + } + if (mxc_dev->clkdiv == -1) { + i--; + mxc_dev->clkdiv = 0x1F; /* Use max divider */ + } + dev_dbg(&pdev->dev, + "i2c slave speed is %d/%d = %d bps, reg val = 0x%02X\n", + clk_freq, i2c_clk_table[i].div, clk_freq / i2c_clk_table[i].div, + mxc_dev->clkdiv); + + if (i2c_slave_device_register(mxc_dev->dev) < 0) { + dev_err(&pdev->dev, "%s: i2c_slave_device_register error\n", + __func__); + goto error4; + } + + platform_set_drvdata(pdev, (void *)mxc_dev); + + /*start(mxc_dev->dev); */ + return 0; + + error4: + free_irq(mxc_dev->irq, mxc_dev); + error3: + iounmap(mxc_dev->reg_base); + error2: + i2c_slave_device_free(mxc_dev->dev); + error1: + kfree(mxc_dev); + error0: + return -ENODEV; +} + +static int mxc_i2c_slave_remove(struct platform_device *pdev) +{ + struct mxc_i2c_slave_device *mxc_dev; + mxc_dev = (struct mxc_i2c_slave_device *)platform_get_drvdata(pdev); + + i2c_slave_device_unregister(mxc_dev->dev); + free_irq(mxc_dev->irq, mxc_dev); + iounmap(mxc_dev->reg_base); + kfree((void *)mxc_dev); + + return 0; +} + +static int mxc_i2c_slave_suspend(struct platform_device *pdev, + pm_message_t state) +{ + return 0; +} + +static int mxc_i2c_slave_resume(struct platform_device *pdev) +{ + return 0; +} + +static struct platform_driver mxci2c_slave_driver = { + .driver = { + .name = "mxc_i2c_slave", + .owner = THIS_MODULE, + }, + .probe = mxc_i2c_slave_probe, + .remove = mxc_i2c_slave_remove, + .suspend = mxc_i2c_slave_suspend, + .resume = mxc_i2c_slave_resume, +}; + +static int __init mxc_i2c_slave_init(void) +{ + /* Register the device driver structure. */ + return platform_driver_register(&mxci2c_slave_driver); +} + +/*! + * This function is used to cleanup all resources before the driver exits. + */ +static void __exit mxc_i2c_slave_exit(void) +{ + platform_driver_unregister(&mxci2c_slave_driver); +} + +module_init(mxc_i2c_slave_init); +module_exit(mxc_i2c_slave_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MXC I2C Slave Driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/i2c-slave/mxc_i2c_slave.h b/drivers/i2c-slave/mxc_i2c_slave.h new file mode 100644 index 000000000000..b3045dc4a2c5 --- /dev/null +++ b/drivers/i2c-slave/mxc_i2c_slave.h @@ -0,0 +1,44 @@ +/* + * Copyright 2007-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#ifndef __MXC_I2C_SLAVE_H__ +#define __MXC_I2C_SLAVE_H__ + +#include +#include "i2c_slave_device.h" + +#define MXC_I2C_SLAVE_NAME "MXC_I2C_SLAVE" +#define MXC_I2C_SLAVE_ADDRESS 0x55 +#define MXC_I2C_SLAVE_FREQ (1000*100) + +struct mxc_i2c_slave_device { + /*! + * The default clock divider value to be used. + */ + unsigned int clkdiv; + + /*! + * The clock source for the device. + */ + struct clk *clk; + + /*i2c id on soc */ + int id; + + int irq; + unsigned long reg_base; + bool state; /*0:stop, 1:start */ + i2c_slave_device_t *dev; +}; + +#endif diff --git a/drivers/i2c-slave/mxc_i2c_slave_reg.h b/drivers/i2c-slave/mxc_i2c_slave_reg.h new file mode 100644 index 000000000000..52a04e06f810 --- /dev/null +++ b/drivers/i2c-slave/mxc_i2c_slave_reg.h @@ -0,0 +1,41 @@ +/* + * Copyright 2007-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#ifndef __MXC_I2C_SLAVE_REG_H__ +#define __MXC_I2C_SLAVE_REG_H__ + +/* Address offsets of the I2C registers */ +#define MXC_IADR 0x00 /* Address Register */ +#define MXC_IFDR 0x04 /* Freq div register */ +#define MXC_I2CR 0x08 /* Control regsiter */ +#define MXC_I2SR 0x0C /* Status register */ +#define MXC_I2DR 0x10 /* Data I/O register */ + +/* Bit definitions of I2CR */ +#define MXC_I2CR_IEN 0x0080 +#define MXC_I2CR_IIEN 0x0040 +#define MXC_I2CR_MSTA 0x0020 +#define MXC_I2CR_MTX 0x0010 +#define MXC_I2CR_TXAK 0x0008 +#define MXC_I2CR_RSTA 0x0004 + +/* Bit definitions of I2SR */ +#define MXC_I2SR_ICF 0x0080 +#define MXC_I2SR_IAAS 0x0040 +#define MXC_I2SR_IBB 0x0020 +#define MXC_I2SR_IAL 0x0010 +#define MXC_I2SR_SRW 0x0004 +#define MXC_I2SR_IIF 0x0002 +#define MXC_I2SR_RXAK 0x0001 + +#endif /* __MXC_I2C_REG_H__ */ diff --git a/drivers/i2c/busses/Kconfig b/drivers/i2c/busses/Kconfig index bceafbfa7268..d72d0f0ccb44 100644 --- a/drivers/i2c/busses/Kconfig +++ b/drivers/i2c/busses/Kconfig @@ -431,6 +431,64 @@ config I2C_MPC This driver can also be built as a module. If so, the module will be called i2c-mpc. +config I2C_MXC + tristate "MXC I2C support" + depends on I2C && ARCH_MXC + help + If you say yes to this option, support will be included for Freescale + MXC I2C modules. + + This driver can also be built as a module. + +config I2C_MXC_HS + tristate "MXC HIGH SPEED I2C support" + depends on I2C && ARCH_MXC + help + If you say yes to this option, support will be included for Freescale + MXC HIGH SPEED I2C modules. + + This driver can also be built as a module. + +config I2C_MXS + tristate "MXS I2C Support" + depends on I2C && ARCH_MXS + help + If you say yes to this option, support will be included for Freescale + MXS I2C modules. + +config I2C_MXS_SELECT0 + bool "Enable I2C0 module" + default y + depends on I2C_MXS + help + Enable MXS I2C0 Module + +config I2C_MXS_SELECT0_PIOQUEUE_MODE + tristate "MXS I2C0 PIOQUEUE MODE Support" + depends on (I2C_MXS_SELECT0 && !ARCH_MX23) + help + say yes if you are sure transfer length is eqaul to or less than 24 bytes. + Otherwise say no to use DMA mode by default. + +config I2C_MXS_SELECT1 + bool "Enable I2C1 module" + depends on (I2C_MXS && !ARCH_MX23) + help + Enable MXS I2C1 Module + +config I2C_MXS_SELECT1_PIOQUEUE_MODE + tristate "MXS I2C1 PIOQUEUE MODE Support" + depends on I2C_MXS_SELECT1 + help + say yes if you are sure transfer length is eqaul to or less than 24 bytes. + Otherwise say no to use DMA mode by default. + +config I2C_STMP378X + tristate "STMP378x I2C adapter" + depends on MACH_STMP378X + help + TBD + config I2C_MV64XXX tristate "Marvell mv64xxx I2C Controller" depends on (MV64X60 || PLAT_ORION) && EXPERIMENTAL diff --git a/drivers/i2c/busses/Makefile b/drivers/i2c/busses/Makefile index 936880bd1dc5..0b25b7baa449 100644 --- a/drivers/i2c/busses/Makefile +++ b/drivers/i2c/busses/Makefile @@ -74,6 +74,10 @@ obj-$(CONFIG_I2C_SIBYTE) += i2c-sibyte.o obj-$(CONFIG_I2C_STUB) += i2c-stub.o obj-$(CONFIG_SCx200_ACB) += scx200_acb.o obj-$(CONFIG_SCx200_I2C) += scx200_i2c.o +obj-$(CONFIG_I2C_MXC) += mxc_i2c.o +obj-$(CONFIG_I2C_MXC_HS) += mxc_i2c_hs.o +obj-$(CONFIG_I2C_STMP378X) += i2c-stmp378x.o +obj-$(CONFIG_I2C_MXS) += i2c-mxs.o ifeq ($(CONFIG_I2C_DEBUG_BUS),y) EXTRA_CFLAGS += -DDEBUG diff --git a/drivers/i2c/busses/i2c-mxs.c b/drivers/i2c/busses/i2c-mxs.c new file mode 100644 index 000000000000..1834bc7ec35e --- /dev/null +++ b/drivers/i2c/busses/i2c-mxs.c @@ -0,0 +1,598 @@ +/* + * Freescale MX28 I2C bus driver + * Copyright (C) 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "i2c-mxs.h" + +/* 2 for read, 1 for write */ +#define NR_DESC 3 +static struct mxs_dma_desc *desc[NR_DESC]; +static dma_addr_t i2c_buf_phys; +static u8 *i2c_buf_virt; + +#define CMD_I2C_SELECT (BM_I2C_CTRL0_RETAIN_CLOCK | \ + BM_I2C_CTRL0_PRE_SEND_START | \ + BM_I2C_CTRL0_MASTER_MODE | \ + BM_I2C_CTRL0_DIRECTION | \ + BF_I2C_CTRL0_XFER_COUNT(1)) +#define CMD_I2C_WRITE (BM_I2C_CTRL0_PRE_SEND_START | \ + BM_I2C_CTRL0_MASTER_MODE | \ + BM_I2C_CTRL0_DIRECTION) +#define CMD_I2C_READ (BM_I2C_CTRL0_SEND_NAK_ON_LAST | \ + BM_I2C_CTRL0_MASTER_MODE) + +/* Hack for platform which does not support PioQueue Mode */ +#if !defined(HW_I2C_QUEUECMD) || \ + !defined(HW_I2C_QUEUEDATA) || \ + !defined(HW_I2C_QUEUECTRL_CLR) || \ + !defined(HW_I2C_QUEUECTRL_SET) +#warning "Pio Queue Mode *NOT* Support!" +#define HW_I2C_QUEUECMD HW_I2C_VERSION +#define HW_I2C_QUEUEDATA HW_I2C_VERSION +#define HW_I2C_QUEUECTRL_SET HW_I2C_VERSION +#define HW_I2C_QUEUECTRL_CLR HW_I2C_VERSION +#endif + +static void hw_i2c_dmachan_reset(struct mxs_i2c_dev *dev) +{ + mxs_dma_reset(dev->dma_chan); + mxs_dma_ack_irq(dev->dma_chan); +} + +static int hw_i2c_dma_init(struct platform_device *pdev) +{ + struct mxs_i2c_dev *mxs_i2c = platform_get_drvdata(pdev); + int i, ret; + + ret = mxs_dma_request(mxs_i2c->dma_chan, &pdev->dev, "i2c"); + if (ret) + return ret; + + for (i = 0; i < NR_DESC; i++) { + desc[i] = mxs_dma_alloc_desc(); + if (desc[i] == NULL) + goto err; + } + + i2c_buf_virt = dma_alloc_coherent(&pdev->dev, + PAGE_SIZE, &i2c_buf_phys, GFP_KERNEL); + if (i2c_buf_virt == NULL) + goto err; + + hw_i2c_dmachan_reset(mxs_i2c); + mxs_dma_enable_irq(mxs_i2c->dma_chan, 1); + + return 0; + +err: + while (--i >= 0) + mxs_dma_free_desc(desc[i]); + + return -ENOMEM; +} + +static void hw_i2c_dma_uninit(struct platform_device *pdev) +{ + struct mxs_i2c_dev *mxs_i2c = platform_get_drvdata(pdev); + int i; + LIST_HEAD(list); + + mxs_dma_enable_irq(mxs_i2c->dma_chan, 0); + mxs_dma_get_cooked(mxs_i2c->dma_chan, &list); + mxs_dma_disable(mxs_i2c->dma_chan); + + for (i = 0; i < NR_DESC; i++) + mxs_dma_free_desc(desc[i]); + + hw_i2c_dmachan_reset(mxs_i2c); + + dma_free_coherent(&pdev->dev, PAGE_SIZE, i2c_buf_virt, i2c_buf_phys); + + mxs_dma_release(mxs_i2c->dma_chan, &pdev->dev); +} + +static void hw_i2c_pioq_setup_read(struct mxs_i2c_dev *dev, + u8 addr, void *buff, int len, int flags) +{ + u32 queuecmd; + u32 queuedata; + + WARN_ONCE(len > 24, "choose DMA mode if xfer len > 24 bytes\n"); + + /* fill queue cmd */ + queuecmd = CMD_I2C_SELECT; + __raw_writel(queuecmd, dev->regbase + HW_I2C_QUEUECMD); + + /* fill data (slave addr) */ + queuedata = addr | I2C_READ; + __raw_writel(queuedata, dev->regbase + HW_I2C_DATA); + + /* fill queue cmd */ + queuecmd = CMD_I2C_READ | flags; + queuecmd |= BF_I2C_CTRL0_XFER_COUNT(len) | flags; + __raw_writel(queuecmd, dev->regbase + HW_I2C_QUEUECMD); + +} + +static void hw_i2c_dma_setup_read(u8 addr, void *buff, int len, int flags) +{ + if (len > (PAGE_SIZE - 4)) + BUG(); + + memset(&desc[0]->cmd, 0, sizeof(desc[0]->cmd)); + memset(&desc[1]->cmd, 0, sizeof(desc[1]->cmd)); + + desc[0]->cmd.cmd.bits.bytes = 1; + desc[0]->cmd.cmd.bits.pio_words = 1; + desc[0]->cmd.cmd.bits.wait4end = 1; + desc[0]->cmd.cmd.bits.dec_sem = 1; + desc[0]->cmd.cmd.bits.irq = 1; + desc[0]->cmd.cmd.bits.chain = 1; + desc[0]->cmd.cmd.bits.command = DMA_READ; + desc[0]->cmd.address = i2c_buf_phys; + desc[0]->cmd.pio_words[0] = CMD_I2C_SELECT; + i2c_buf_virt[0] = addr | I2C_READ; + + desc[1]->cmd.cmd.bits.bytes = len; + desc[1]->cmd.cmd.bits.pio_words = 1; + desc[1]->cmd.cmd.bits.wait4end = 1; + desc[1]->cmd.cmd.bits.dec_sem = 1; + desc[1]->cmd.cmd.bits.irq = 1; + desc[1]->cmd.cmd.bits.command = DMA_WRITE; + desc[1]->cmd.address = (u32) i2c_buf_phys + 1; + desc[1]->cmd.pio_words[0] = CMD_I2C_READ; + desc[1]->cmd.pio_words[0] |= BF_I2C_CTRL0_XFER_COUNT(len) | flags; +} + +static void hw_i2c_pioq_setup_write(struct mxs_i2c_dev *dev, + u8 addr, void *buff, int len, int flags) +{ + int align_len, i; + u8 slaveaddr; + u32 queuecmd; + u8 *buf1; + u32 *buf2; + + WARN_ONCE(len > 24, "choose DMA mode if xfer len > 24 bytes\n"); + + align_len = (len + 1 + 3) & ~3; + + buf1 = (u8 *) dev->buf; + buf2 = (u32 *) dev->buf; + + /* fill queue cmd */ + queuecmd = CMD_I2C_WRITE; + queuecmd |= BF_I2C_CTRL0_XFER_COUNT(len + 1) | flags; + __raw_writel(queuecmd, dev->regbase + HW_I2C_QUEUECMD); + + /* fill data (slave addr) */ + slaveaddr = addr | I2C_WRITE; + memcpy(buf1, &slaveaddr, 1); + + memcpy(&buf1[1], buff, len); + + /* fill data */ + for (i = 0; i < align_len / 4; i++) + __raw_writel(*buf2++, dev->regbase + HW_I2C_DATA); +} + +static void hw_i2c_dma_setup_write(u8 addr, void *buff, int len, int flags) +{ + memset(&desc[2]->cmd, 0, sizeof(desc[2]->cmd)); + + desc[2]->cmd.cmd.bits.bytes = len + 1; + desc[2]->cmd.cmd.bits.pio_words = 1; + desc[2]->cmd.cmd.bits.wait4end = 1; + desc[2]->cmd.cmd.bits.dec_sem = 1; + desc[2]->cmd.cmd.bits.irq = 1; + desc[2]->cmd.cmd.bits.command = DMA_READ; + desc[2]->cmd.address = i2c_buf_phys; + desc[2]->cmd.pio_words[0] = CMD_I2C_WRITE; + desc[2]->cmd.pio_words[0] |= BM_I2C_CTRL0_POST_SEND_STOP; + desc[2]->cmd.pio_words[0] |= BF_I2C_CTRL0_XFER_COUNT(len + 1) | flags; + + i2c_buf_virt[0] = addr | I2C_WRITE; + memcpy(&i2c_buf_virt[1], buff, len); +} + +static void hw_i2c_pioq_run(struct mxs_i2c_dev *dev) +{ + __raw_writel(0x20, dev->regbase + HW_I2C_QUEUECTRL_SET); +} + +static void hw_i2c_dma_run(struct mxs_i2c_dev *dev, int dir) +{ + if (dir == I2C_READ) { + mxs_dma_desc_append(dev->dma_chan, desc[0]); + mxs_dma_desc_append(dev->dma_chan, desc[1]); + } else + mxs_dma_desc_append(dev->dma_chan, desc[2]); + + mxs_dma_enable(dev->dma_chan); +} + +static void hw_i2c_pioq_stop(struct mxs_i2c_dev *dev) +{ + __raw_writel(0x20, dev->regbase + HW_I2C_QUEUECTRL_CLR); +} + +static void hw_i2c_finish_read(struct mxs_i2c_dev *dev, void *buff, int len) +{ + int i, align_len; + u8 *buf1; + u32 *buf2; + + if (dev->flags & MXS_I2C_PIOQUEUE_MODE) { + align_len = (len + 3) & ~3; + + buf1 = (u8 *) dev->buf; + buf2 = (u32 *) dev->buf; + + for (i = 0; i < align_len / 4; i++) + *buf2++ = __raw_readl(dev->regbase + HW_I2C_QUEUEDATA); + + memcpy(buff, buf1, len); + } else + memcpy(buff, &i2c_buf_virt[1], len); +} + +/* + * Low level master read/write transaction. + */ +static int mxs_i2c_xfer_msg(struct i2c_adapter *adap, + struct i2c_msg *msg, int stop) +{ + struct mxs_i2c_dev *dev = i2c_get_adapdata(adap); + int err; + int flags; + + init_completion(&dev->cmd_complete); + dev->cmd_err = 0; + + dev_dbg(dev->dev, "addr: 0x%04x, len: %d, flags: 0x%x, stop: %d\n", + msg->addr, msg->len, msg->flags, stop); + + if ((msg->len == 0) || (msg->len > (PAGE_SIZE - 1))) + return -EINVAL; + + flags = stop ? BM_I2C_CTRL0_POST_SEND_STOP : 0; + + if (msg->flags & I2C_M_RD) { + if (dev->flags & MXS_I2C_PIOQUEUE_MODE) { + hw_i2c_pioq_setup_read(dev, + msg->addr, + msg->buf, msg->len, flags); + hw_i2c_pioq_run(dev); + } else { + hw_i2c_dma_setup_read(msg->addr, + msg->buf, msg->len, flags); + + hw_i2c_dma_run(dev, I2C_READ); + } + } else { + if (dev->flags & MXS_I2C_PIOQUEUE_MODE) { + hw_i2c_pioq_setup_write(dev, + msg->addr, + msg->buf, msg->len, flags); + hw_i2c_pioq_run(dev); + } else { + hw_i2c_dma_setup_write(msg->addr, + msg->buf, msg->len, flags); + hw_i2c_dma_run(dev, I2C_WRITE); + } + } + + err = wait_for_completion_interruptible_timeout(&dev->cmd_complete, + msecs_to_jiffies(1000) + ); + if (err <= 0) { + dev_dbg(dev->dev, "controller is timed out\n"); + return -ETIMEDOUT; + } + + if ((!dev->cmd_err) && (msg->flags & I2C_M_RD)) + hw_i2c_finish_read(dev, msg->buf, msg->len); + + dev_dbg(dev->dev, "Done with err=%d\n", dev->cmd_err); + + return dev->cmd_err; +} + +static int +mxs_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg msgs[], int num) +{ + int i; + int err; + + if (!msgs->len) + return -EINVAL; + + for (i = 0; i < num; i++) { + err = mxs_i2c_xfer_msg(adap, &msgs[i], (i == (num - 1))); + if (err) + break; + } + + if (err == 0) + err = num; + + return err; +} + +static u32 mxs_i2c_func(struct i2c_adapter *adap) +{ + return I2C_FUNC_I2C | (I2C_FUNC_SMBUS_EMUL & ~I2C_FUNC_SMBUS_QUICK); +} + +static irqreturn_t mxs_i2c_dma_isr(int this_irq, void *dev_id) +{ + struct mxs_i2c_dev *mxs_i2c = dev_id; + + LIST_HEAD(list); + mxs_dma_ack_irq(mxs_i2c->dma_chan); + mxs_dma_cooked(mxs_i2c->dma_chan, &list); + + return IRQ_HANDLED; +} + +#define I2C_IRQ_MASK 0x000000FF +static irqreturn_t mxs_i2c_isr(int this_irq, void *dev_id) +{ + struct mxs_i2c_dev *mxs_i2c = dev_id; + u32 stat; + u32 done_mask = + BM_I2C_CTRL1_DATA_ENGINE_CMPLT_IRQ | BM_I2C_CTRL1_BUS_FREE_IRQ; + + stat = __raw_readl(mxs_i2c->regbase + HW_I2C_CTRL1) & I2C_IRQ_MASK; + if (!stat) + return IRQ_NONE; + + if (stat & BM_I2C_CTRL1_NO_SLAVE_ACK_IRQ) { + mxs_i2c->cmd_err = -EREMOTEIO; + + /* + * Stop DMA + * Clear NAK + */ + __raw_writel(BM_I2C_CTRL1_CLR_GOT_A_NAK, + mxs_i2c->regbase + HW_I2C_CTRL1_SET); + hw_i2c_dmachan_reset(mxs_i2c); + mxs_reset_block((void __iomem *)mxs_i2c->regbase, 1); + /* Will catch all error (IRQ mask) */ + __raw_writel(0x0000FF00, mxs_i2c->regbase + HW_I2C_CTRL1_SET); + + complete(&mxs_i2c->cmd_complete); + + goto done; + } + + /* Don't care about BM_I2C_CTRL1_OVERSIZE_XFER_TERM_IRQ */ + if (stat & (BM_I2C_CTRL1_EARLY_TERM_IRQ | + BM_I2C_CTRL1_MASTER_LOSS_IRQ | + BM_I2C_CTRL1_SLAVE_STOP_IRQ | BM_I2C_CTRL1_SLAVE_IRQ)) { + mxs_i2c->cmd_err = -EIO; + complete(&mxs_i2c->cmd_complete); + goto done; + } + if ((stat & done_mask) == done_mask) + complete(&mxs_i2c->cmd_complete); + +done: + __raw_writel(stat, mxs_i2c->regbase + HW_I2C_CTRL1_CLR); + return IRQ_HANDLED; +} + +static const struct i2c_algorithm mxs_i2c_algo = { + .master_xfer = mxs_i2c_xfer, + .functionality = mxs_i2c_func, +}; + +static int mxs_i2c_probe(struct platform_device *pdev) +{ + struct mxs_i2c_dev *mxs_i2c; + struct mxs_i2c_plat_data *pdata; + struct i2c_adapter *adap; + struct resource *res; + int err = 0; + + mxs_i2c = kzalloc(sizeof(struct mxs_i2c_dev), GFP_KERNEL); + if (!mxs_i2c) { + dev_err(&pdev->dev, "no mem \n"); + return -ENOMEM; + } + + pdata = pdev->dev.platform_data; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!res) { + dev_err(&pdev->dev, "no register base resource\n"); + err = -ENODEV; + goto nores; + } + mxs_i2c->regbase = (unsigned long)IO_ADDRESS(res->start); + + res = platform_get_resource(pdev, IORESOURCE_DMA, 0); + if (!res) { + dev_err(&pdev->dev, "no dma channel resource\n"); + err = -ENODEV; + goto nores; + } + mxs_i2c->dma_chan = res->start; + + res = platform_get_resource(pdev, IORESOURCE_IRQ, 0); + if (!res) { + dev_err(&pdev->dev, "no err_irq resource\n"); + err = -ENODEV; + goto nores; + } + mxs_i2c->irq_err = res->start; + + res = platform_get_resource(pdev, IORESOURCE_IRQ, 1); + if (!res) { + dev_err(&pdev->dev, "no dma_irq resource\n"); + err = -ENODEV; + goto nores; + } + mxs_i2c->irq_dma = res->start; + + mxs_i2c->dev = &pdev->dev; + mxs_i2c->flags = pdata->pioqueue_mode ? + MXS_I2C_PIOQUEUE_MODE : MXS_I2C_DMA_MODE; + + err = + request_irq(mxs_i2c->irq_err, mxs_i2c_isr, 0, pdev->name, mxs_i2c); + if (err) { + dev_err(&pdev->dev, "Can't get IRQ\n"); + goto no_err_irq; + } + + err = + request_irq(mxs_i2c->irq_dma, mxs_i2c_dma_isr, 0, pdev->name, + mxs_i2c); + if (err) { + dev_err(&pdev->dev, "Can't get IRQ\n"); + goto no_dma_irq; + } + + /* reset I2C module */ + mxs_reset_block((void __iomem *)mxs_i2c->regbase, 1); + platform_set_drvdata(pdev, mxs_i2c); + + if (mxs_i2c->flags & MXS_I2C_PIOQUEUE_MODE) + __raw_writel(0x04, mxs_i2c->regbase + HW_I2C_QUEUECTRL_SET); + + mxs_i2c->buf = kzalloc(PAGE_SIZE, GFP_KERNEL); + if (mxs_i2c->buf == NULL) { + dev_err(&pdev->dev, "HW Init failed\n"); + goto init_failed; + } else { + err = hw_i2c_dma_init(pdev); + if (err) { + dev_err(&pdev->dev, "HW Init failed\n"); + goto init_failed; + } + } + + /* Will catch all error (IRQ mask) */ + __raw_writel(0x0000FF00, mxs_i2c->regbase + HW_I2C_CTRL1_SET); + + adap = &mxs_i2c->adapter; + strncpy(adap->name, "MXS I2C adapter", sizeof(adap->name)); + adap->owner = THIS_MODULE; + adap->class = I2C_CLASS_HWMON; + adap->algo = &mxs_i2c_algo; + adap->dev.parent = &pdev->dev; + adap->nr = pdev->id; + i2c_set_adapdata(adap, mxs_i2c); + err = i2c_add_numbered_adapter(adap); + if (err) { + dev_err(&pdev->dev, "Failed to add adapter\n"); + goto no_i2c_adapter; + + } + + return 0; + +no_i2c_adapter: + __raw_writel(BM_I2C_CTRL0_SFTRST, mxs_i2c->regbase + HW_I2C_CTRL0_SET); + + if (mxs_i2c->flags & MXS_I2C_DMA_MODE) + hw_i2c_dma_uninit(pdev); + else + kfree(mxs_i2c->buf); +init_failed: + free_irq(mxs_i2c->irq_dma, mxs_i2c); +no_dma_irq: + free_irq(mxs_i2c->irq_err, mxs_i2c); +no_err_irq: +nores: + kfree(mxs_i2c); + return err; +} + +static int mxs_i2c_remove(struct platform_device *pdev) +{ + struct mxs_i2c_dev *mxs_i2c = platform_get_drvdata(pdev); + int res; + + res = i2c_del_adapter(&mxs_i2c->adapter); + if (res) + return -EBUSY; + + __raw_writel(BM_I2C_CTRL0_SFTRST, mxs_i2c->regbase + HW_I2C_CTRL0_SET); + + if (mxs_i2c->flags & MXS_I2C_DMA_MODE) + hw_i2c_dma_uninit(pdev); + if (mxs_i2c->flags & MXS_I2C_PIOQUEUE_MODE) + hw_i2c_pioq_stop(mxs_i2c); + + platform_set_drvdata(pdev, NULL); + + free_irq(mxs_i2c->irq_err, mxs_i2c); + free_irq(mxs_i2c->irq_dma, mxs_i2c); + + kfree(mxs_i2c->buf); + kfree(mxs_i2c); + return 0; +} + +static struct platform_driver mxs_i2c_driver = { + .driver = { + .name = "mxs-i2c", + .owner = THIS_MODULE, + }, + .probe = mxs_i2c_probe, + .remove = __devexit_p(mxs_i2c_remove), +}; + +static int __init mxs_i2c_init(void) +{ + return platform_driver_register(&mxs_i2c_driver); +} + +subsys_initcall(mxs_i2c_init); + +static void __exit mxs_i2c_exit(void) +{ + platform_driver_unregister(&mxs_i2c_driver); +} + +module_exit(mxs_i2c_exit); + +MODULE_AUTHOR("Embedded Alley Solutions, Inc/Freescale Inc"); +MODULE_DESCRIPTION("MXS I2C Bus Driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/i2c/busses/i2c-mxs.h b/drivers/i2c/busses/i2c-mxs.h new file mode 100644 index 000000000000..4ddca007624a --- /dev/null +++ b/drivers/i2c/busses/i2c-mxs.h @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#ifndef _I2C_H +#define _I2C_H + +#define I2C_READ 1 +#define I2C_WRITE 0 + +struct mxs_i2c_dev { + struct device *dev; + void *buf; + unsigned long regbase; + u32 flags; +#define MXS_I2C_DMA_MODE 0x1 +#define MXS_I2C_PIOQUEUE_MODE 0x2 + int dma_chan; + int irq_dma; + int irq_err; + struct completion cmd_complete; + u32 cmd_err; + struct i2c_adapter adapter; + spinlock_t lock; + wait_queue_head_t queue; +}; +#endif diff --git a/drivers/i2c/busses/mxc_i2c.c b/drivers/i2c/busses/mxc_i2c.c new file mode 100644 index 000000000000..b47f9db4b476 --- /dev/null +++ b/drivers/i2c/busses/mxc_i2c.c @@ -0,0 +1,808 @@ +/* + * Copyright (C) 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mxc_i2c.c + * + * @brief Driver for the Freescale Semiconductor MXC I2C buses. + * + * Based on i2c driver algorithm for PCF8584 adapters + * + * @ingroup MXCI2C + */ + +/* + * Include Files + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "mxc_i2c_reg.h" + +/*! + * In case the MXC device has multiple I2C modules, this structure is used to + * store information specific to each I2C module. + */ +typedef struct { + /*! + * This structure is used to identify the physical i2c bus along with + * the access algorithms necessary to access it. + */ + struct i2c_adapter adap; + + /*! + * This waitqueue is used to wait for the data transfer to complete. + */ + wait_queue_head_t wq; + + /*! + * The base address of the I2C device. + */ + void __iomem *membase; + + /*! + * The interrupt number used by the I2C device. + */ + int irq; + + /*! + * The default clock divider value to be used. + */ + unsigned int clkdiv; + + /*! + * The clock source for the device. + */ + struct clk *clk; + + /*! + * The current power state of the device + */ + bool low_power; + + /*! + * Boolean to indicate if data was transferred + */ + bool transfer_done; + + /*! + * Boolean to indicate if we received an ACK for the data transmitted + */ + bool tx_success; +} mxc_i2c_device; + +struct clk_div_table { + int reg_value; + int div; +}; + +static const struct clk_div_table i2c_clk_table[] = { + {0x20, 22}, {0x21, 24}, {0x22, 26}, {0x23, 28}, + {0, 30}, {1, 32}, {0x24, 32}, {2, 36}, + {0x25, 36}, {0x26, 40}, {3, 42}, {0x27, 44}, + {4, 48}, {0x28, 48}, {5, 52}, {0x29, 56}, + {6, 60}, {0x2A, 64}, {7, 72}, {0x2B, 72}, + {8, 80}, {0x2C, 80}, {9, 88}, {0x2D, 96}, + {0xA, 104}, {0x2E, 112}, {0xB, 128}, {0x2F, 128}, + {0xC, 144}, {0xD, 160}, {0x30, 160}, {0xE, 192}, + {0x31, 192}, {0x32, 224}, {0xF, 240}, {0x33, 256}, + {0x10, 288}, {0x11, 320}, {0x34, 320}, {0x12, 384}, + {0x35, 384}, {0x36, 448}, {0x13, 480}, {0x37, 512}, + {0x14, 576}, {0x15, 640}, {0x38, 640}, {0x16, 768}, + {0x39, 768}, {0x3A, 896}, {0x17, 960}, {0x3B, 1024}, + {0x18, 1152}, {0x19, 1280}, {0x3C, 1280}, {0x1A, 1536}, + {0x3D, 1536}, {0x3E, 1792}, {0x1B, 1920}, {0x3F, 2048}, + {0x1C, 2304}, {0x1D, 2560}, {0x1E, 3072}, {0x1F, 3840}, + {0, 0} +}; + +extern void gpio_i2c_active(int i2c_num); +extern void gpio_i2c_inactive(int i2c_num); + +/*! + * Transmit a \b STOP signal to the slave device. + * + * @param dev the mxc i2c structure used to get to the right i2c device + */ +static void mxc_i2c_stop(mxc_i2c_device *dev) +{ + unsigned int cr, sr; + int retry = 16; + + cr = readw(dev->membase + MXC_I2CR); + cr &= ~(MXC_I2CR_MSTA | MXC_I2CR_MTX); + writew(cr, dev->membase + MXC_I2CR); + + /* Wait till the Bus Busy bit is reset */ + sr = readw(dev->membase + MXC_I2SR); + while (retry-- && ((sr & MXC_I2SR_IBB))) { + udelay(3); + sr = readw(dev->membase + MXC_I2SR); + } + if (retry <= 0) + dev_err(&dev->adap.dev, "Could not set I2C Bus Busy bit" + " to zero.\n"); +} + +/*! + * Wait for the transmission of the data byte to complete. This function waits + * till we get a signal from the interrupt service routine indicating completion + * of the address cycle or we time out. + * + * @param dev the mxc i2c structure used to get to the right i2c device + * @param trans_flag transfer flag + * + * + * @return The function returns 0 on success or -1 if an ack was not received + */ + +static int mxc_i2c_wait_for_tc(mxc_i2c_device *dev, int trans_flag) +{ + int retry = 16; + + while (retry-- && !dev->transfer_done) { + wait_event_interruptible_timeout(dev->wq, + dev->transfer_done, + dev->adap.timeout); + } + dev->transfer_done = false; + + if (retry <= 0) { + /* Unable to send data */ + dev_err(&dev->adap.dev, "Data not transmitted\n"); + return -1; + } + + if (!dev->tx_success) { + /* An ACK was not received for transmitted byte */ + dev_err(&dev->adap.dev, "ACK not received \n"); + return -1; + } + + return 0; +} + +/*! + * Transmit a \b START signal to the slave device. + * + * @param dev the mxc i2c structure used to get to the right i2c device + * @param *msg pointer to a message structure that contains the slave + * address + * + * @return The function returns EBUSY on failure, 0 on success. + */ +static int mxc_i2c_start(mxc_i2c_device *dev, struct i2c_msg *msg) +{ + volatile unsigned int cr, sr; + unsigned int addr_trans; + int retry = 16; + + /* + * Set the slave address and the requested transfer mode + * in the data register + */ + addr_trans = msg->addr << 1; + if (msg->flags & I2C_M_RD) { + addr_trans |= 0x01; + } + + /* Set the Master bit */ + cr = readw(dev->membase + MXC_I2CR); + cr |= MXC_I2CR_MSTA; + writew(cr, dev->membase + MXC_I2CR); + + /* Wait till the Bus Busy bit is set */ + sr = readw(dev->membase + MXC_I2SR); + while (retry-- && (!(sr & MXC_I2SR_IBB))) { + udelay(3); + sr = readw(dev->membase + MXC_I2SR); + } + if (retry <= 0) { + dev_err(&dev->adap.dev, "Could not grab Bus ownership\n"); + return -EBUSY; + } + + /* Set the Transmit bit */ + cr = readw(dev->membase + MXC_I2CR); + cr |= MXC_I2CR_MTX; + writew(cr, dev->membase + MXC_I2CR); + + writew(addr_trans, dev->membase + MXC_I2DR); + return 0; +} + +/*! + * Transmit a \b REPEAT START to the slave device + * + * @param dev the mxc i2c structure used to get to the right i2c device + * @param *msg pointer to a message structure that contains the slave + * address + */ +static int mxc_i2c_repstart(mxc_i2c_device *dev, struct i2c_msg *msg) +{ + volatile unsigned int cr, sr; + unsigned int addr_trans; + int retry = 16; + + /* + * Set the slave address and the requested transfer mode + * in the data register + */ + addr_trans = msg->addr << 1; + if (msg->flags & I2C_M_RD) { + addr_trans |= 0x01; + } + cr = readw(dev->membase + MXC_I2CR); + cr |= MXC_I2CR_RSTA; + writew(cr, dev->membase + MXC_I2CR); + /* Wait till the Bus Busy bit is set */ + sr = readw(dev->membase + MXC_I2SR); + while (retry-- && (!(sr & MXC_I2SR_IBB))) { + udelay(3); + sr = readw(dev->membase + MXC_I2SR); + } + if (retry <= 0) { + dev_err(&dev->adap.dev, "Could not grab Bus ownership\n"); + return -EBUSY; + } + writew(addr_trans, dev->membase + MXC_I2DR); + return 0; +} + +/*! + * Read the received data. The function waits till data is available or times + * out. Generates a stop signal if this is the last message to be received. + * Sends an ack for all the bytes received except the last byte. + * + * @param dev the mxc i2c structure used to get to the right i2c device + * @param *msg pointer to a message structure that contains the slave + * address and a pointer to the receive buffer + * @param last indicates that this is the last message to be received + * @param addr_comp flag indicates that we just finished the address cycle + * + * @return The function returns the number of bytes read or -1 on time out. + */ +static int mxc_i2c_readbytes(mxc_i2c_device *dev, struct i2c_msg *msg, + int last, int addr_comp) +{ + int i; + char *buf = msg->buf; + int len = msg->len; + volatile unsigned int cr; + + cr = readw(dev->membase + MXC_I2CR); + /* + * Clear MTX to switch to receive mode. + */ + cr &= ~MXC_I2CR_MTX; + /* + * Clear the TXAK bit to gen an ack when receiving only one byte. + */ + if (len == 1) { + cr |= MXC_I2CR_TXAK; + } else { + cr &= ~MXC_I2CR_TXAK; + } + writew(cr, dev->membase + MXC_I2CR); + /* + * Dummy read only at the end of an address cycle + */ + if (addr_comp > 0) { + readw(dev->membase + MXC_I2DR); + } + + for (i = 0; i < len; i++) { + /* + * Wait for data transmission to complete + */ + if (mxc_i2c_wait_for_tc(dev, msg->flags)) { + mxc_i2c_stop(dev); + return -1; + } + /* + * Do not generate an ACK for the last byte + */ + if (i == (len - 2)) { + cr = readw(dev->membase + MXC_I2CR); + cr |= MXC_I2CR_TXAK; + writew(cr, dev->membase + MXC_I2CR); + } else if (i == (len - 1)) { + if (last) { + mxc_i2c_stop(dev); + } + } + /* Read the data */ + *buf++ = readw(dev->membase + MXC_I2DR); + } + + return i; +} + +/*! + * Write the data to the data register. Generates a stop signal if this is + * the last message to be sent or if no ack was received for the data sent. + * + * @param dev the mxc i2c structure used to get to the right i2c device + * @param *msg pointer to a message structure that contains the slave + * address and data to be sent + * @param last indicates that this is the last message to be received + * + * @return The function returns the number of bytes written or -1 on time out + * or if no ack was received for the data that was sent. + */ +static int mxc_i2c_writebytes(mxc_i2c_device *dev, struct i2c_msg *msg, + int last) +{ + int i; + char *buf = msg->buf; + int len = msg->len; + volatile unsigned int cr; + + cr = readw(dev->membase + MXC_I2CR); + /* Set MTX to switch to transmit mode */ + cr |= MXC_I2CR_MTX; + writew(cr, dev->membase + MXC_I2CR); + + for (i = 0; i < len; i++) { + /* + * Write the data + */ + writew(*buf++, dev->membase + MXC_I2DR); + if (mxc_i2c_wait_for_tc(dev, msg->flags)) { + mxc_i2c_stop(dev); + return -1; + } + } + if (last > 0) { + mxc_i2c_stop(dev); + } + + return i; +} + +/*! + * Function enables the I2C module and initializes the registers. + * + * @param dev the mxc i2c structure used to get to the right i2c device + * @param trans_flag transfer flag + */ +static void mxc_i2c_module_en(mxc_i2c_device *dev, int trans_flag) +{ + clk_enable(dev->clk); + /* Set the frequency divider */ + writew(dev->clkdiv, dev->membase + MXC_IFDR); + /* Clear the status register */ + writew(0x0, dev->membase + MXC_I2SR); + /* Enable I2C and its interrupts */ + writew(MXC_I2CR_IEN, dev->membase + MXC_I2CR); + writew(MXC_I2CR_IEN | MXC_I2CR_IIEN, dev->membase + MXC_I2CR); +} + +/*! + * Disables the I2C module. + * + * @param dev the mxc i2c structure used to get to the right i2c device + */ +static void mxc_i2c_module_dis(mxc_i2c_device *dev) +{ + writew(0x0, dev->membase + MXC_I2CR); + clk_disable(dev->clk); +} + +/*! + * The function is registered in the adapter structure. It is called when an MXC + * driver wishes to transfer data to a device connected to the I2C device. + * + * @param adap adapter structure for the MXC i2c device + * @param msgs[] array of messages to be transferred to the device + * @param num number of messages to be transferred to the device + * + * @return The function returns the number of messages transferred, + * \b -EREMOTEIO on I2C failure and a 0 if the num argument is + * less than 0. + */ +static int mxc_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg msgs[], + int num) +{ + mxc_i2c_device *dev = (mxc_i2c_device *) (i2c_get_adapdata(adap)); + int i, ret = 0, addr_comp = 0; + volatile unsigned int sr; + int retry = 5; + + if (dev->low_power) { + dev_err(&dev->adap.dev, "I2C Device in low power mode\n"); + return -EREMOTEIO; + } + + if (num < 1) { + return 0; + } + + mxc_i2c_module_en(dev, msgs[0].flags); + sr = readw(dev->membase + MXC_I2SR); + /* + * Check bus state + */ + + while ((sr & MXC_I2SR_IBB) && retry--) { + udelay(5); + sr = readw(dev->membase + MXC_I2SR); + } + + if ((sr & MXC_I2SR_IBB) && retry < 0) { + mxc_i2c_module_dis(dev); + dev_err(&dev->adap.dev, "Bus busy\n"); + return -EREMOTEIO; + } + + dev->transfer_done = false; + dev->tx_success = false; + for (i = 0; i < num && ret >= 0; i++) { + addr_comp = 0; + /* + * Send the slave address and transfer direction in the + * address cycle + */ + if (i == 0) { + /* + * Send a start or repeat start signal + */ + if (mxc_i2c_start(dev, &msgs[0])) + return -EREMOTEIO; + /* Wait for the address cycle to complete */ + if (mxc_i2c_wait_for_tc(dev, msgs[0].flags)) { + mxc_i2c_stop(dev); + mxc_i2c_module_dis(dev); + return -EREMOTEIO; + } + addr_comp = 1; + } else { + /* + * Generate repeat start only if required i.e the address + * changed or the transfer direction changed + */ + if ((msgs[i].addr != msgs[i - 1].addr) || + ((msgs[i].flags & I2C_M_RD) != + (msgs[i - 1].flags & I2C_M_RD))) { + mxc_i2c_repstart(dev, &msgs[i]); + /* Wait for the address cycle to complete */ + if (mxc_i2c_wait_for_tc(dev, msgs[i].flags)) { + mxc_i2c_stop(dev); + mxc_i2c_module_dis(dev); + return -EREMOTEIO; + } + addr_comp = 1; + } + } + + /* Transfer the data */ + if (msgs[i].flags & I2C_M_RD) { + /* Read the data */ + ret = mxc_i2c_readbytes(dev, &msgs[i], (i + 1 == num), + addr_comp); + if (ret < 0) { + dev_err(&dev->adap.dev, "mxc_i2c_readbytes:" + " fail.\n"); + break; + } + } else { + /* Write the data */ + ret = mxc_i2c_writebytes(dev, &msgs[i], (i + 1 == num)); + if (ret < 0) { + dev_err(&dev->adap.dev, "mxc_i2c_writebytes:" + " fail.\n"); + break; + } + } + } + + mxc_i2c_module_dis(dev); + /* + * Decrease by 1 as we do not want Start message to be included in + * the count + */ + return (i < 0 ? ret : i); +} + +/*! + * Returns the i2c functionality supported by this driver. + * + * @param adap adapter structure for this i2c device + * + * @return Returns the functionality that is supported. + */ +static u32 mxc_i2c_func(struct i2c_adapter *adap) +{ + return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL; +} + +/*! + * Stores the pointers for the i2c algorithm functions. The algorithm functions + * is used by the i2c bus driver to talk to the i2c bus + */ +static struct i2c_algorithm mxc_i2c_algorithm = { + .master_xfer = mxc_i2c_xfer, + .functionality = mxc_i2c_func +}; + +/*! + * Interrupt Service Routine. It signals to the process about the data transfer + * completion. Also sets a flag if bus arbitration is lost. + * @param irq the interrupt number + * @param dev_id driver private data + * + * @return The function returns \b IRQ_HANDLED. + */ +static irqreturn_t mxc_i2c_handler(int irq, void *dev_id) +{ + mxc_i2c_device *dev = dev_id; + volatile unsigned int sr, cr; + + sr = readw(dev->membase + MXC_I2SR); + cr = readw(dev->membase + MXC_I2CR); + + /* + * Clear the interrupt bit + */ + writew(0x0, dev->membase + MXC_I2SR); + + if (sr & MXC_I2SR_IAL) { + dev_err(&dev->adap.dev, "Bus Arbitration lost\n"); + } else { + /* Interrupt due byte transfer completion */ + dev->tx_success = true; + /* Check if RXAK is received in Transmit mode */ + if ((cr & MXC_I2CR_MTX) && (sr & MXC_I2SR_RXAK)) { + dev->tx_success = false; + } + dev->transfer_done = true; + wake_up_interruptible(&dev->wq); + } + + return IRQ_HANDLED; +} + +/*! + * This function is called to put the I2C adapter in a low power state. Refer to the + * document driver-model/driver.txt in the kernel source tree for more + * information. + * + * @param pdev the device structure used to give information on which I2C + * to suspend + * @param state the power state the device is entering + * + * @return The function returns 0 on success and -1 on failure. + */ +static int mxci2c_suspend_noirq(struct device *dev) +{ + struct platform_device *pdev = to_platform_device(dev); + mxc_i2c_device *mxcdev = platform_get_drvdata(pdev); + volatile unsigned int sr = 0; + + if (mxcdev == NULL) { + return -1; + } + + /* Prevent further calls to be processed */ + mxcdev->low_power = true; + /* Wait till we finish the current transfer */ + sr = readw(mxcdev->membase + MXC_I2SR); + while (sr & MXC_I2SR_IBB) { + msleep(10); + sr = readw(mxcdev->membase + MXC_I2SR); + } + gpio_i2c_inactive(mxcdev->adap.id); + + return 0; +} + +/*! + * This function is called to bring the I2C adapter back from a low power state. Refer + * to the document driver-model/driver.txt in the kernel source tree for more + * information. + * + * @param pdev the device structure used to give information on which I2C + * to resume + * + * @return The function returns 0 on success and -1 on failure + */ +static int mxci2c_resume_noirq(struct device *dev) +{ + struct platform_device *pdev = to_platform_device(dev); + mxc_i2c_device *mxcdev = platform_get_drvdata(pdev); + + if (mxcdev == NULL) + return -1; + + mxcdev->low_power = false; + gpio_i2c_active(mxcdev->adap.id); + + return 0; +} + +/*! + * This function is called during the driver binding process. + * + * @param pdev the device structure used to store device specific + * information that is used by the suspend, resume and remove + * functions + * + * @return The function always returns 0. + */ +static int mxci2c_probe(struct platform_device *pdev) +{ + mxc_i2c_device *mxc_i2c; + struct mxc_i2c_platform_data *i2c_plat_data = pdev->dev.platform_data; + struct resource *res; + int id = pdev->id; + u32 clk_freq; + int ret = 0; + int i; + + mxc_i2c = kzalloc(sizeof(mxc_i2c_device), GFP_KERNEL); + if (!mxc_i2c) { + return -ENOMEM; + } + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (res == NULL) { + ret = -ENODEV; + goto err1; + } + mxc_i2c->membase = ioremap(res->start, res->end - res->start + 1); + + /* + * Request the I2C interrupt + */ + mxc_i2c->irq = platform_get_irq(pdev, 0); + if (mxc_i2c->irq < 0) { + ret = mxc_i2c->irq; + goto err2; + } + + ret = request_irq(mxc_i2c->irq, mxc_i2c_handler, + 0, pdev->name, mxc_i2c); + if (ret < 0) { + goto err2; + } + + init_waitqueue_head(&mxc_i2c->wq); + + mxc_i2c->low_power = false; + + gpio_i2c_active(id); + + mxc_i2c->clk = clk_get(&pdev->dev, "i2c_clk"); + clk_freq = clk_get_rate(mxc_i2c->clk); + mxc_i2c->clkdiv = -1; + if (i2c_plat_data->i2c_clk) { + /* Calculate divider and round up any fractional part */ + int div = (clk_freq + i2c_plat_data->i2c_clk - 1) / + i2c_plat_data->i2c_clk; + for (i = 0; i2c_clk_table[i].div != 0; i++) { + if (i2c_clk_table[i].div >= div) { + mxc_i2c->clkdiv = i2c_clk_table[i].reg_value; + break; + } + } + } + if (mxc_i2c->clkdiv == -1) { + i--; + mxc_i2c->clkdiv = 0x1F; /* Use max divider */ + } + dev_dbg(&pdev->dev, "i2c speed is %d/%d = %d bps, reg val = 0x%02X\n", + clk_freq, i2c_clk_table[i].div, + clk_freq / i2c_clk_table[i].div, mxc_i2c->clkdiv); + + /* + * Set the adapter information + */ + strlcpy(mxc_i2c->adap.name, pdev->name, 48); + mxc_i2c->adap.id = mxc_i2c->adap.nr = id; + mxc_i2c->adap.algo = &mxc_i2c_algorithm; + mxc_i2c->adap.timeout = 1; + platform_set_drvdata(pdev, mxc_i2c); + i2c_set_adapdata(&mxc_i2c->adap, mxc_i2c); + ret = i2c_add_numbered_adapter(&mxc_i2c->adap); + if (ret < 0) + goto err3; + + printk(KERN_INFO "MXC I2C driver\n"); + return 0; + + err3: + free_irq(mxc_i2c->irq, mxc_i2c); + gpio_i2c_inactive(id); + err2: + iounmap(mxc_i2c->membase); + err1: + dev_err(&pdev->dev, "failed to probe i2c adapter\n"); + kfree(mxc_i2c); + return ret; +} + +/*! + * Dissociates the driver from the I2C device. + * + * @param pdev the device structure used to give information on which I2C + * to remove + * + * @return The function always returns 0. + */ +static int mxci2c_remove(struct platform_device *pdev) +{ + mxc_i2c_device *mxc_i2c = platform_get_drvdata(pdev); + int id = pdev->id; + + free_irq(mxc_i2c->irq, mxc_i2c); + i2c_del_adapter(&mxc_i2c->adap); + gpio_i2c_inactive(id); + clk_put(mxc_i2c->clk); + platform_set_drvdata(pdev, NULL); + iounmap(mxc_i2c->membase); + kfree(mxc_i2c); + return 0; +} + +static struct dev_pm_ops mxci2c_dev_pm_ops = { + .suspend_noirq = mxci2c_suspend_noirq, + .resume_noirq = mxci2c_resume_noirq, +}; + +/*! + * This structure contains pointers to the power management callback functions. + */ +static struct platform_driver mxci2c_driver = { + .driver = { + .name = "mxc_i2c", + .owner = THIS_MODULE, + .pm = &mxci2c_dev_pm_ops, + }, + .probe = mxci2c_probe, + .remove = mxci2c_remove, +}; + +/*! + * Function requests the interrupts and registers the i2c adapter structures. + * + * @return The function returns 0 on success and a non-zero value on failure. + */ +static int __init mxc_i2c_init(void) +{ + /* Register the device driver structure. */ + return platform_driver_register(&mxci2c_driver); +} + +/*! + * This function is used to cleanup all resources before the driver exits. + */ +static void __exit mxc_i2c_exit(void) +{ + platform_driver_unregister(&mxci2c_driver); +} + +subsys_initcall(mxc_i2c_init); +module_exit(mxc_i2c_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MXC I2C driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/i2c/busses/mxc_i2c_hs.c b/drivers/i2c/busses/mxc_i2c_hs.c new file mode 100644 index 000000000000..60262741cd54 --- /dev/null +++ b/drivers/i2c/busses/mxc_i2c_hs.c @@ -0,0 +1,553 @@ +/* + * Copyright (C) 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "mxc_i2c_hs_reg.h" + +typedef struct { + struct device *dev; + + void __iomem *reg_base_virt; + unsigned long reg_base_phy; + int irq; + unsigned int speed; + struct clk *ipg_clk; + struct clk *serial_clk; + bool low_power; + + struct i2c_msg *msg; + int index; +} mxc_i2c_hs; + +struct clk_div_table { + int reg_value; + int div; +}; + +static const struct clk_div_table i2c_clk_table[] = { + {0x0, 16}, {0x1, 18}, {0x2, 20}, {0x3, 22}, + {0x20, 24}, {0x21, 26}, {0x22, 28}, {0x23, 30}, + {0x4, 32}, {0x5, 36}, {0x6, 40}, {0x7, 44}, + {0x24, 48}, {0x25, 52}, {0x26, 56}, {0x27, 60}, + {0x8, 64}, {0x9, 72}, {0xa, 80}, {0xb, 88}, + {0x28, 96}, {0x29, 104}, {0x2a, 112}, {0x2b, 120}, + {0xc, 128}, {0xd, 144}, {0xe, 160}, {0xf, 176}, + {0x2c, 192}, {0x2d, 208}, {0x2e, 224}, {0x2f, 240}, + {0x10, 256}, {0x11, 288}, {0x12, 320}, {0x13, 352}, + {0x30, 384}, {0x31, 416}, {0x32, 448}, {0x33, 480}, + {0x14, 512}, {0x15, 576}, {0x16, 640}, {0x17, 704}, + {0x34, 768}, {0x35, 832}, {0x36, 896}, {0x37, 960}, + {0x18, 1024}, {0x19, 1152}, {0x1a, 1280}, {0x1b, 1408}, + {0x38, 1536}, {0x39, 1664}, {0x3a, 1792}, {0x3b, 1920}, + {0x1c, 2048}, {0x1d, 2304}, {0x1e, 2560}, {0x1f, 2816}, + {0x3c, 3072}, {0x3d, 3328}, {0x3E, 3584}, {0x3F, 3840}, + {-1, -1} +}; + +static struct i2c_adapter *adap; + +extern void gpio_i2c_hs_inactive(void); +extern void gpio_i2c_hs_active(void); + +static u16 reg_read(mxc_i2c_hs *i2c_hs, u32 reg_offset) +{ + return __raw_readw(i2c_hs->reg_base_virt + reg_offset); +} + +static void reg_write(mxc_i2c_hs *i2c_hs, u32 reg_offset, u16 data) +{ + __raw_writew(data, i2c_hs->reg_base_virt + reg_offset); +} + +static void reg_set_mask(mxc_i2c_hs *i2c_hs, u32 reg_offset, u16 mask) +{ + u16 value; + + value = reg_read(i2c_hs, reg_offset); + value |= mask; + reg_write(i2c_hs, reg_offset, value); +} +static void reg_clear_mask(mxc_i2c_hs *i2c_hs, u32 reg_offset, u16 mask) +{ + u16 value; + + value = reg_read(i2c_hs, reg_offset); + value &= ~mask; + reg_write(i2c_hs, reg_offset, value); +} + +static void mxci2c_hs_set_div(mxc_i2c_hs *i2c_hs) +{ + unsigned long clk_freq; + int i; + int div = -1;; + + clk_freq = clk_get_rate(i2c_hs->serial_clk); + if (i2c_hs->speed) { + div = (clk_freq + i2c_hs->speed - 1) / i2c_hs->speed; + for (i = 0; i2c_clk_table[i].div >= 0; i++) { + if (i2c_clk_table[i].div >= div) { + div = i2c_clk_table[i].reg_value; + reg_write(i2c_hs, HIFSFDR, div); + break; + } + } + } +} + +static int mxci2c_hs_enable(mxc_i2c_hs *i2c_hs) +{ + gpio_i2c_hs_active(); + clk_enable(i2c_hs->ipg_clk); + clk_enable(i2c_hs->serial_clk); + mxci2c_hs_set_div(i2c_hs); + reg_write(i2c_hs, HICR, reg_read(i2c_hs, HICR) | HICR_HIEN); + + return 0; +} + +static int mxci2c_hs_disable(mxc_i2c_hs *i2c_hs) +{ + reg_write(i2c_hs, HICR, reg_read(i2c_hs, HICR) & (~HICR_HIEN)); + clk_disable(i2c_hs->ipg_clk); + clk_disable(i2c_hs->serial_clk); + + return 0; +} + +static int mxci2c_hs_bus_busy(mxc_i2c_hs *i2c_hs) +{ + u16 value; + int retry = 1000; + + while (retry--) { + value = reg_read(i2c_hs, HISR); + if (value & HISR_HIBB) { + udelay(1); + } else { + break; + } + } + + if (retry <= 0) { + dev_dbg(NULL, "%s: Bus Busy!\n", __func__); + return 1; + } else { + return 0; + } +} + +static int mxci2c_hs_start(mxc_i2c_hs *i2c_hs, int repeat_start, u16 address) +{ + u16 mask; + int ret = 0; + + mxci2c_hs_bus_busy(i2c_hs); + + /*7 bit address */ + reg_clear_mask(i2c_hs, HICR, HICR_ADDR_MODE); + + /*send start */ + if (repeat_start) + mask = HICR_RSTA; + else + mask = HICR_MSTA; + reg_set_mask(i2c_hs, HICR, mask); + + return ret; +} + +static int mxci2c_hs_stop(mxc_i2c_hs *i2c_hs) +{ + reg_clear_mask(i2c_hs, HICR, HICR_MSTA); + reg_clear_mask(i2c_hs, HICR, HICR_HIIEN); + + return 0; +} + +static int mxci2c_wait_writefifo(mxc_i2c_hs *i2c_hs) +{ + int i, num, left; + int retry, ret = 0; + + retry = 10000; + while (retry--) { + udelay(10); + if (reg_read(i2c_hs, HISR) & (HISR_TDE | HISR_TDC_ZERO)) { + if (i2c_hs->index < i2c_hs->msg->len) { + left = i2c_hs->msg->len - i2c_hs->index; + num = + (left > + HITFR_MAX_COUNT) ? HITFR_MAX_COUNT : left; + for (i = 0; i < num; i++) { + reg_write(i2c_hs, HITDR, + i2c_hs->msg->buf[i2c_hs-> + index + i]); + } + i2c_hs->index += num; + } else { + if (reg_read(i2c_hs, HISR) & HISR_TDC_ZERO) { + msleep(1); + break; + } + } + } + } + + if (retry <= 0) { + printk(KERN_ERR "%s:wait error\n", __func__); + ret = -1; + } + + return ret; +} + +static int mxci2c_wait_readfifo(mxc_i2c_hs *i2c_hs) +{ + int i, num, left; + int retry, ret = 0; + u16 value; + + retry = 10000; + while (retry--) { + udelay(10); + value = reg_read(i2c_hs, HISR); + if (value & (HISR_RDF | HISR_RDC_ZERO)) { + if (i2c_hs->index < i2c_hs->msg->len) { + left = i2c_hs->msg->len - i2c_hs->index; + num = + (left > + HITFR_MAX_COUNT) ? HITFR_MAX_COUNT : left; + for (i = 0; i < num; i++) { + i2c_hs->msg->buf[i2c_hs->index + i] = + reg_read(i2c_hs, HIRDR); + } + i2c_hs->index += num; + } else { + if (value & HISR_RDC_ZERO) { + break; + } + } + } + } + + if (retry <= 0) { + printk(KERN_ERR "%s:wait error\n", __func__); + ret = -1; + } + + return ret; +} + +static int mxci2c_hs_read(mxc_i2c_hs *i2c_hs, int repeat_start, + struct i2c_msg *msg) +{ + int ret; + + if (msg->len > HIRDCR_MAX_COUNT) { + printk(KERN_ERR "%s: error: msg too long, max longth 256\n", + __func__); + return -1; + } + + ret = 0; + i2c_hs->msg = msg; + i2c_hs->index = 0; + + /*set address */ + reg_write(i2c_hs, HIMADR, HIMADR_LSB_ADR(msg->addr)); + + /*receive mode */ + reg_clear_mask(i2c_hs, HICR, HICR_MTX); + + reg_clear_mask(i2c_hs, HICR, HICR_HIIEN); + + /*FIFO*/ reg_set_mask(i2c_hs, HIRFR, HIRFR_RFEN | HIRFR_RFWM(7)); + reg_set_mask(i2c_hs, HIRFR, HIRFR_RFLSH); + + /*TDCR*/ + reg_write(i2c_hs, HIRDCR, HIRDCR_RDC_EN | HIRDCR_RDC(msg->len)); + + mxci2c_hs_start(i2c_hs, repeat_start, msg->addr); + + ret = mxci2c_wait_readfifo(i2c_hs); + + if (ret < 0) + return ret; + else + return msg->len; +} + +static int mxci2c_hs_write(mxc_i2c_hs *i2c_hs, int repeat_start, + struct i2c_msg *msg) +{ + int ret, i; + + if (msg->len > HITDCR_MAX_COUNT) { + printk(KERN_ERR "%s: error: msg too long, max longth 256\n", + __func__); + return -1; + } + + ret = 0; + i2c_hs->msg = msg; + i2c_hs->index = 0; + + /*set address */ + reg_write(i2c_hs, HIMADR, HIMADR_LSB_ADR(msg->addr)); + + /*transmit mode */ + reg_set_mask(i2c_hs, HICR, HICR_MTX); + + reg_clear_mask(i2c_hs, HICR, HICR_HIIEN); + + /* TDCR */ + reg_write(i2c_hs, HITDCR, HITDCR_TDC_EN | HITDCR_TDC(msg->len)); + + /* FIFO */ + reg_set_mask(i2c_hs, HITFR, HITFR_TFEN); + reg_set_mask(i2c_hs, HITFR, HITFR_TFLSH); + + if (msg->len > HITFR_MAX_COUNT) + i2c_hs->index = HITFR_MAX_COUNT; + else { + i2c_hs->index = msg->len; + } + + for (i = 0; i < i2c_hs->index; i++) { + reg_write(i2c_hs, HITDR, msg->buf[i]); + } + + mxci2c_hs_start(i2c_hs, repeat_start, msg->addr); + + ret = mxci2c_wait_writefifo(i2c_hs); + + if (ret < 0) + return ret; + else + return msg->len; +} + +static int mxci2c_hs_xfer(struct i2c_adapter *adap, struct i2c_msg msgs[], + int num) +{ + int i; + int ret = -EIO; + + mxc_i2c_hs *i2c_hs = (mxc_i2c_hs *) (i2c_get_adapdata(adap)); + + if (i2c_hs->low_power) { + dev_err(&adap->dev, "I2C Device in low power mode\n"); + return -EREMOTEIO; + } + + if (num < 1) { + return 0; + } + + mxci2c_hs_enable(i2c_hs); + + for (i = 0; i < num; i++) { + if (msgs[i].flags & I2C_M_RD) { + ret = mxci2c_hs_read(i2c_hs, 0, &msgs[i]); + if (ret < 0) + break; + } else { + ret = mxci2c_hs_write(i2c_hs, 0, &msgs[i]); + if (ret < 0) + break; + } + mxci2c_hs_stop(i2c_hs); + } + mxci2c_hs_stop(i2c_hs); + + mxci2c_hs_disable(i2c_hs); + + if (ret < 0) + return ret; + + return i; +} + +static u32 mxci2c_hs_func(struct i2c_adapter *adap) +{ + return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL; +} + +/*! + * Stores the pointers for the i2c algorithm functions. The algorithm functions + * is used by the i2c bus driver to talk to the i2c bus + */ +static struct i2c_algorithm mxci2c_hs_algorithm = { + .master_xfer = mxci2c_hs_xfer, + .functionality = mxci2c_hs_func +}; + +static int mxci2c_hs_probe(struct platform_device *pdev) +{ + mxc_i2c_hs *i2c_hs; + struct mxc_i2c_platform_data *i2c_plat_data = pdev->dev.platform_data; + struct resource *res; + int id = pdev->id; + int ret = 0; + + i2c_hs = kzalloc(sizeof(mxc_i2c_hs), GFP_KERNEL); + if (!i2c_hs) { + return -ENOMEM; + } + + i2c_hs->dev = &pdev->dev; + + i2c_hs->speed = i2c_plat_data->i2c_clk; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (res == NULL) { + ret = -ENODEV; + goto err1; + } + i2c_hs->reg_base_virt = ioremap(res->start, res->end - res->start + 1); + i2c_hs->reg_base_phy = res->start; + + i2c_hs->ipg_clk = clk_get(&pdev->dev, "hsi2c_clk"); + i2c_hs->serial_clk = clk_get(&pdev->dev, "hsi2c_serial_clk"); + + /* + * Request the I2C interrupt + */ + i2c_hs->irq = platform_get_irq(pdev, 0); + if (i2c_hs->irq < 0) { + ret = i2c_hs->irq; + goto err1; + } + + i2c_hs->low_power = false; + + /* + * Set the adapter information + */ + adap = kzalloc(sizeof(struct i2c_adapter), GFP_KERNEL); + if (!adap) { + ret = -ENODEV; + goto err1; + } + strlcpy(adap->name, pdev->name, 48); + adap->id = adap->nr = id; + adap->algo = &mxci2c_hs_algorithm; + adap->timeout = 1; + platform_set_drvdata(pdev, i2c_hs); + i2c_set_adapdata(adap, i2c_hs); + ret = i2c_add_numbered_adapter(adap); + if (ret < 0) { + goto err2; + } + + printk(KERN_INFO "MXC HS I2C driver\n"); + return 0; + + err2: + kfree(adap); + err1: + dev_err(&pdev->dev, "failed to probe high speed i2c adapter\n"); + iounmap(i2c_hs->reg_base_virt); + kfree(i2c_hs); + return ret; +} + +static int mxci2c_hs_suspend(struct platform_device *pdev, pm_message_t state) +{ + mxc_i2c_hs *i2c_hs = platform_get_drvdata(pdev); + + if (i2c_hs == NULL) { + return -1; + } + + /* Prevent further calls to be processed */ + i2c_hs->low_power = true; + + gpio_i2c_hs_inactive(); + + return 0; +} + +static int mxci2c_hs_resume(struct platform_device *pdev) +{ + mxc_i2c_hs *i2c_hs = platform_get_drvdata(pdev); + + if (i2c_hs == NULL) + return -1; + + i2c_hs->low_power = false; + gpio_i2c_hs_active(); + + return 0; +} + +static int mxci2c_hs_remove(struct platform_device *pdev) +{ + mxc_i2c_hs *i2c_hs = platform_get_drvdata(pdev); + + i2c_del_adapter(adap); + gpio_i2c_hs_inactive(); + platform_set_drvdata(pdev, NULL); + iounmap(i2c_hs->reg_base_virt); + kfree(i2c_hs); + return 0; +} + +static struct platform_driver mxci2c_hs_driver = { + .driver = { + .name = "mxc_i2c_hs", + .owner = THIS_MODULE, + }, + .probe = mxci2c_hs_probe, + .remove = mxci2c_hs_remove, + .suspend = mxci2c_hs_suspend, + .resume = mxci2c_hs_resume, +}; + +/*! + * Function requests the interrupts and registers the i2c adapter structures. + * + * @return The function returns 0 on success and a non-zero value on failure. + */ +static int __init mxci2c_hs_init(void) +{ + /* Register the device driver structure. */ + return platform_driver_register(&mxci2c_hs_driver); +} + +/*! + * This function is used to cleanup all resources before the driver exits. + */ +static void __exit mxci2c_hs_exit(void) +{ + platform_driver_unregister(&mxci2c_hs_driver); +} + +subsys_initcall(mxci2c_hs_init); +module_exit(mxci2c_hs_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MXC HIGH SPEED I2C driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/i2c/busses/mxc_i2c_hs_reg.h b/drivers/i2c/busses/mxc_i2c_hs_reg.h new file mode 100644 index 000000000000..5a017cb17765 --- /dev/null +++ b/drivers/i2c/busses/mxc_i2c_hs_reg.h @@ -0,0 +1,97 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#ifndef __MXC_I2C_HS_REG_H__ +#define __MXC_I2C_HS_REG_H__ + +#define HISADR 0x00 + +#define HIMADR 0x04 +#define HIMADR_LSB_ADR(x) ((x) << 1) +#define HIMADR_MSB_ADR(x) (((x) & 0x7) << 8) + +#define HICR 0x08 +#define HICR_HIEN 0x1 +#define HICR_DMA_EN_RX 0x2 +#define HICR_DMA_EN_TR 0x4 +#define HICR_RSTA 0x8 +#define HICR_TXAK 0x10 +#define HICR_MTX 0x20 +#define HICR_MSTA 0x40 +#define HICR_HIIEN 0x80 +#define HICR_ADDR_MODE 0x100 +#define HICR_MST_CODE(x) (((x)&0x7) << 9) +#define HICR_HSM_EN 0x1000 +#define HICR_SAMC(x) (((x)&0x3) << 13) +#define SAMC_7_10 0 +#define SMAC_7 1 +#define SMAC_10 2 + +#define HISR 0x0c +#define HISR_RDF 0x1 +#define HISR_TDE 0x2 +#define HISR_HIAAS 0x4 +#define HISR_HIAL 0x8 +#define HISR_BTD 0x10 +#define HISR_RDC_ZERO 0x20 +#define HISR_TDC_ZERO 0x40 +#define HISR_RXAK 0x80 +#define HISR_HIBB 0x100 +#define HISR_SRW 0x200 +#define HISR_SADDR_MODE 0x400 +#define HISR_SHS_MODE 0x800 + +#define HIIMR 0x10 +#define HIIMR_RDF 0x1 +#define HIIMR_TDE 0x2 +#define HIIMR_AAS 0x4 +#define HIIMR_AL 0x8 +#define HIIMR_BTD 0x10 +#define HIIMR_RDC 0x20 +#define HIIMR_TDC 0x40 +#define HIIMR_RXAK 0x80 + +#define HITDR 0x14 + +#define HIRDR 0x18 + +#define HIFSFDR 0x1c + +#define HIHSFDR 0x20 + +#define HITFR 0x24 +#define HITFR_TFEN 0x1 +#define HITFR_TFLSH 0x2 +#define HITFR_TFWM(x) (((x) & 0x7) << 2) +#define HITFR_TFC(x) (((x) >> 8) & 0xF) +#define HITFR_MAX_COUNT 8 + +#define HIRFR 0x28 +#define HIRFR_RFEN 0x1 +#define HIRFR_RFLSH 0x2 +#define HIRFR_RFWM(x) (((x) & 0x7) << 2) +#define HIRFR_RFC(x) (((x) >> 8) & 0xF) +#define HIRFR_MAX_COUNT 8 + +#define HITDCR 0x2c +#define HITDCR_TDC(x) ((x) & 0xFF) +#define HITDCR_TDC_EN 0x100 +#define HITDCR_TDC_RSTA 0x200 +#define HITDCR_MAX_COUNT 0xFF + +#define HIRDCR 0x30 +#define HIRDCR_RDC(x) ((x) & 0xFF) +#define HIRDCR_RDC_EN 0x100 +#define HIRDCR_RDC_RSTA 0x200 +#define HIRDCR_MAX_COUNT 0xFF + +#endif diff --git a/drivers/i2c/busses/mxc_i2c_reg.h b/drivers/i2c/busses/mxc_i2c_reg.h new file mode 100644 index 000000000000..2f81036c6626 --- /dev/null +++ b/drivers/i2c/busses/mxc_i2c_reg.h @@ -0,0 +1,40 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#ifndef __MXC_I2C_REG_H__ +#define __MXC_I2C_REG_H__ + +/* Address offsets of the I2C registers */ +#define MXC_IADR 0x00 /* Address Register */ +#define MXC_IFDR 0x04 /* Freq div register */ +#define MXC_I2CR 0x08 /* Control regsiter */ +#define MXC_I2SR 0x0C /* Status register */ +#define MXC_I2DR 0x10 /* Data I/O register */ + +/* Bit definitions of I2CR */ +#define MXC_I2CR_IEN 0x0080 +#define MXC_I2CR_IIEN 0x0040 +#define MXC_I2CR_MSTA 0x0020 +#define MXC_I2CR_MTX 0x0010 +#define MXC_I2CR_TXAK 0x0008 +#define MXC_I2CR_RSTA 0x0004 + +/* Bit definitions of I2SR */ +#define MXC_I2SR_ICF 0x0080 +#define MXC_I2SR_IAAS 0x0040 +#define MXC_I2SR_IBB 0x0020 +#define MXC_I2SR_IAL 0x0010 +#define MXC_I2SR_SRW 0x0004 +#define MXC_I2SR_IIF 0x0002 +#define MXC_I2SR_RXAK 0x0001 + +#endif /* __MXC_I2C_REG_H__ */ diff --git a/drivers/input/keyboard/Kconfig b/drivers/input/keyboard/Kconfig index 1ba25145b333..48a072a0bac9 100644 --- a/drivers/input/keyboard/Kconfig +++ b/drivers/input/keyboard/Kconfig @@ -426,4 +426,31 @@ config KEYBOARD_W90P910 To compile this driver as a module, choose M here: the module will be called w90p910_keypad. +config KEYBOARD_MXC + tristate "MXC Keypad Driver" + depends on ARCH_MXC + help + This is the Keypad driver for the Freescale MXC application + processors. + +config KEYBOARD_MXS + tristate "MXS keyboard" + depends on ARCH_MXS + help + This is the Keypad driver for the Freescale mxs soc + + +config KEYBOARD_MC9S08DZ60 + tristate "mc9s08dz60 keyboard" + depends on MXC_PMIC_MC9S08DZ60 + help + -to be written- + +config KEYBOARD_MPR084 + tristate "Freescale MPR084 Touch Keypad Driver" + depends on ARCH_MX37 + help + This is the Keypad driver for the Freescale Proximity Capacitive + Touch Sensor controller chip. + endif diff --git a/drivers/input/keyboard/Makefile b/drivers/input/keyboard/Makefile index 4596d0c6f922..ce93d014483d 100644 --- a/drivers/input/keyboard/Makefile +++ b/drivers/input/keyboard/Makefile @@ -38,3 +38,7 @@ obj-$(CONFIG_KEYBOARD_SUNKBD) += sunkbd.o obj-$(CONFIG_KEYBOARD_TWL4030) += twl4030_keypad.o obj-$(CONFIG_KEYBOARD_XTKBD) += xtkbd.o obj-$(CONFIG_KEYBOARD_W90P910) += w90p910_keypad.o +obj-$(CONFIG_KEYBOARD_MXC) += mxc_keyb.o +obj-$(CONFIG_KEYBOARD_MPR084) += mpr084.o +obj-$(CONFIG_KEYBOARD_MXS) += mxs-kbd.o +obj-$(CONFIG_KEYBOARD_MC9S08DZ60) += mc9s08dz60_keyb.o diff --git a/drivers/input/keyboard/mc9s08dz60_keyb.c b/drivers/input/keyboard/mc9s08dz60_keyb.c new file mode 100644 index 000000000000..87ab5d3eda0a --- /dev/null +++ b/drivers/input/keyboard/mc9s08dz60_keyb.c @@ -0,0 +1,248 @@ +/* + * Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mc9s08dz60keyb.c + * + * @brief Driver for the Freescale Semiconductor MXC keypad port. + * + * The keypad driver is designed as a standard Input driver which interacts + * with low level keypad port hardware. Upon opening, the Keypad driver + * initializes the keypad port. When the keypad interrupt happens the driver + * calles keypad polling timer and scans the keypad matrix for key + * press/release. If all key press/release happened it comes out of timer and + * waits for key press interrupt. The scancode for key press and release events + * are passed to Input subsytem. + * + * @ingroup keypad + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MOD_NAME "mc9s08dz60-keyb" +/* + * Module header file + */ + +/*! Input device structure. */ +static struct input_dev *mc9s08dz60kbd_dev; +static unsigned int key_status; +static int keypad_irq; +static unsigned int key_code_map[8] = { + KEY_LEFT, + KEY_DOWN, + 0, + 0, + KEY_UP, + KEY_RIGHT, + 0, + 0, +}; +static unsigned int keycodes_size = 8; + +static void read_key_handler(struct work_struct *work); +static DECLARE_WORK(key_pad_event, read_key_handler); + + +static void read_key_handler(struct work_struct *work) +{ + unsigned int val1, val2; + int pre_val, curr_val, i; + val1 = val2 = 0xff; + mcu_pmic_read_reg(REG_MCU_KPD_1, &val1, 0xff); + mcu_pmic_read_reg(REG_MCU_KPD_2, &val2, 0xff); + pr_debug("key pressed, 0x%02x%02x\n", val2, val1); + for (i = 0; i < 8; i++) { + curr_val = (val1 >> i) & 0x1; + if (curr_val > 0) + input_event(mc9s08dz60kbd_dev, EV_KEY, + key_code_map[i], 1); + else { + pre_val = (key_status >> i) & 0x1; + if (pre_val > 0) + input_event(mc9s08dz60kbd_dev, EV_KEY, + key_code_map[i], 0); + } + } + key_status = val1; + +} + +static irqreturn_t mc9s08dz60kpp_interrupt(int irq, void *dev_id) +{ + schedule_work(&key_pad_event); + return IRQ_RETVAL(1); +} + +/*! + * This function is called when the keypad driver is opened. + * Since keypad initialization is done in __init, nothing is done in open. + * + * @param dev Pointer to device inode + * + * @result The function always return 0 + */ +static int mc9s08dz60kpp_open(struct input_dev *dev) +{ + return 0; +} + +/*! + * This function is called close the keypad device. + * Nothing is done in this function, since every thing is taken care in + * __exit function. + * + * @param dev Pointer to device inode + * + */ +static void mc9s08dz60kpp_close(struct input_dev *dev) +{ +} + + +/*! + * This function is called during the driver binding process. + * + * @param pdev the device structure used to store device specific + * information that is used by the suspend, resume and remove + * functions. + * + * @return The function returns 0 on successful registration. Otherwise returns + * specific error code. + */ +static int mc9s08dz60kpp_probe(struct platform_device *pdev) +{ + int i, irq; + int retval; + + retval = mcu_pmic_write_reg(REG_MCU_KPD_CONTROL, 0x1, 0x1); + if (retval != 0) { + pr_info("mc9s08dz60 keypad: mcu not detected!\n"); + return retval; + } + + irq = platform_get_irq(pdev, 0); + retval = request_irq(irq, mc9s08dz60kpp_interrupt, + 0, MOD_NAME, MOD_NAME); + if (retval) { + pr_debug("KPP: request_irq(%d) returned error %d\n", + irq, retval); + return retval; + } + keypad_irq = irq; + + mc9s08dz60kbd_dev = input_allocate_device(); + if (!mc9s08dz60kbd_dev) { + pr_info(KERN_ERR "mc9s08dz60kbd_dev: \ + not enough memory for input device\n"); + retval = -ENOMEM; + goto err1; + } + + mc9s08dz60kbd_dev->name = "mc9s08dz60kpd"; + mc9s08dz60kbd_dev->id.bustype = BUS_HOST; + mc9s08dz60kbd_dev->open = mc9s08dz60kpp_open; + mc9s08dz60kbd_dev->close = mc9s08dz60kpp_close; + + retval = input_register_device(mc9s08dz60kbd_dev); + if (retval < 0) { + pr_info(KERN_ERR + "mc9s08dz60kbd_dev: failed to register input device\n"); + goto err2; + } + + __set_bit(EV_KEY, mc9s08dz60kbd_dev->evbit); + + for (i = 0; i < keycodes_size; i++) + __set_bit(key_code_map[i], mc9s08dz60kbd_dev->keybit); + + device_init_wakeup(&pdev->dev, 1); + + pr_info("mc9s08dz60 keypad probed\n"); + + return 0; + +err2: + input_free_device(mc9s08dz60kbd_dev); +err1: + free_irq(irq, MOD_NAME); + return retval; +} + +/*! + * Dissociates the driver from the kpp device. + * + * @param pdev the device structure used to give information on which SDHC + * to remove + * + * @return The function always returns 0. + */ +static int mc9s08dz60kpp_remove(struct platform_device *pdev) +{ + free_irq(keypad_irq, MOD_NAME); + input_unregister_device(mc9s08dz60kbd_dev); + + if (mc9s08dz60kbd_dev) + input_free_device(mc9s08dz60kbd_dev); + + return 0; +} + +/*! + * This structure contains pointers to the power management callback functions. + */ +static struct platform_driver mc9s08dz60kpd_driver = { + .driver = { + .name = "mc9s08dz60keypad", + .bus = &platform_bus_type, + }, + .probe = mc9s08dz60kpp_probe, + .remove = mc9s08dz60kpp_remove +}; + +static int __init mc9s08dz60kpp_init(void) +{ + pr_info(KERN_INFO "mc9s08dz60 keypad loaded\n"); + platform_driver_register(&mc9s08dz60kpd_driver); + return 0; +} + +static void __exit mc9s08dz60kpp_cleanup(void) +{ + platform_driver_unregister(&mc9s08dz60kpd_driver); +} + +module_init(mc9s08dz60kpp_init); +module_exit(mc9s08dz60kpp_cleanup); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MXC Keypad Controller Driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/input/keyboard/mpr084.c b/drivers/input/keyboard/mpr084.c new file mode 100644 index 000000000000..d0d5a9fb0809 --- /dev/null +++ b/drivers/input/keyboard/mpr084.c @@ -0,0 +1,500 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file linux/drivers/input/keyboard/mpr084.c + * + * @brief Driver for the Freescale MPR084 I2C Touch Sensor KeyPad module. + * + * + * + * @ingroup Keypad + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Definitions + */ +#define DEBUG 0 + +#define KEY_COUNT 8 + +/* + *Registers in MPR084 + */ +#define MPR084_FIFO_ADDR 0x00 +#define MPR084_FAULT_ADDR 0x01 +#define MPR084_TPS_ADDR 0x02 +#define MPR084_TPC_ADDR 0x03 +#define MPR084_STR1_ADDR 0x04 +#define MPR084_STR2_ADDR 0x05 +#define MPR084_STR3_ADDR 0x06 +#define MPR084_STR4_ADDR 0x07 +#define MPR084_STR5_ADDR 0x08 +#define MPR084_STR6_ADDR 0x09 +#define MPR084_STR7_ADDR 0x0A +#define MPR084_STR8_ADDR 0x0B +#define MPR084_ECEM_ADDR 0x0C +#define MPR084_MNTP_ADDR 0x0D +#define MPR084_MTC_ADDR 0x0E +#define MPR084_TASP_ADDR 0x0F +#define MPR084_SC_ADDR 0x10 +#define MPR084_LPC_ADDR 0x11 +#define MPR084_SKT_ADDR 0x12 +#define MPR084_CONFIG_ADDR 0x13 +#define MPR084_SI_ADDR 0x14 +#define MPR084_ADDR_MINI MPR084_FIFO_ADDR +#define MPR084_ADDR_MAX MPR084_SI_ADDR + +/* FIFO registers */ +#define MPR084_FIFO_MORE_DATA_FLAG 0x80 +#define MPR084_FIFO_NO_DATA_FLAG 0x40 +#define MPR084_FIFO_OVERFLOW_FLAG 0x20 +#define MPR084_FIFO_PAD_IS_TOUCHED 0x10 +#define MPR084_FIFO_POSITION_MASK 0x0F + +#define DRIVER_NAME "mpr084" + +struct mpr084_data { + struct i2c_client *client; + struct device_driver driver; + struct input_dev *idev; + struct task_struct *tstask; + struct completion kpirq_completion; + int kpirq; + int kp_thread_cnt; + int opened; +}; + +static int kpstatus[KEY_COUNT]; +static struct mxc_keyp_platform_data *keypad; +static const unsigned short *mxckpd_keycodes; +static struct regulator *vdd_reg; + +static int mpr084_read_register(struct mpr084_data *data, + unsigned char regaddr, int *value) +{ + int ret = 0; + unsigned char regvalue; + + ret = i2c_master_send(data->client, ®addr, 1); + if (ret < 0) + goto err; + udelay(20); + ret = i2c_master_recv(data->client, ®value, 1); + if (ret < 0) + goto err; + *value = regvalue; + + return ret; +err: + return -ENODEV; +} + +static int mpr084_write_register(struct mpr084_data *data, + u8 regaddr, u8 regvalue) +{ + int ret = 0; + unsigned char msgbuf[2]; + + msgbuf[0] = regaddr; + msgbuf[1] = regvalue; + ret = i2c_master_send(data->client, msgbuf, 2); + if (ret < 0) { + printk(KERN_ERR "%s - Error in writing to I2C Register %d \n", + __func__, regaddr); + return ret; + } + + return ret; +} + + +static irqreturn_t mpr084_keypadirq(int irq, void *v) +{ + struct mpr084_data *d = v; + + disable_irq(d->kpirq); + complete(&d->kpirq_completion); + return IRQ_HANDLED; +} + +static int mpr084ts_thread(void *v) +{ + struct mpr084_data *d = v; + int ret = 0, fifo = 0; + int index = 0, currentstatus = 0; + + if (d->kp_thread_cnt) + return -EINVAL; + d->kp_thread_cnt = 1; + while (1) { + + if (kthread_should_stop()) + break; + /* Wait for keypad interrupt */ + if (wait_for_completion_interruptible_timeout + (&d->kpirq_completion, HZ) <= 0) + continue; + + ret = mpr084_read_register(d, MPR084_FIFO_ADDR, &fifo); + if (ret < 0) { + printk(KERN_ERR + "%s: Err in reading keypad FIFO register \n\n", + __func__); + } else { + if (fifo & MPR084_FIFO_OVERFLOW_FLAG) + printk(KERN_ERR + "%s: FIFO overflow \n\n", __func__); + while (!(fifo & MPR084_FIFO_NO_DATA_FLAG)) { + index = fifo & MPR084_FIFO_POSITION_MASK; + currentstatus = + fifo & MPR084_FIFO_PAD_IS_TOUCHED; + /*Scan key map for changes */ + if ((currentstatus) ^ (kpstatus[index])) { + if (!(currentstatus)) { + /*Key released. */ + input_event(d->idev, EV_KEY, + mxckpd_keycodes + [index], 0); + } else { + /* Key pressed. */ + input_event(d->idev, EV_KEY, + mxckpd_keycodes + [index], 1); + } + /*Store current keypad status */ + kpstatus[index] = currentstatus; + } + mpr084_read_register(d, MPR084_FIFO_ADDR, + &fifo); + if (fifo & MPR084_FIFO_OVERFLOW_FLAG) + printk(KERN_ERR + "%s: FIFO overflow \n\n", + __func__); + } + } + /* Re-enable interrupts */ + enable_irq(d->kpirq); + } + + d->kp_thread_cnt = 0; + return 0; +} + +/*! + * This function puts the Keypad controller in low-power mode/state. + * + * @param pdev the device structure used to give information on Keypad + * to suspend + * @param state the power state the device is entering + * + * @return The function always returns 0. + */ +static int mpr084_suspend(struct i2c_client *client, pm_message_t state) +{ + struct mpr084_data *d = i2c_get_clientdata(client); + + if (!IS_ERR(d->tstask) && d->opened) + kthread_stop(d->tstask); + + return 0; +} + +/*! + * This function brings the Keypad controller back from low-power state. + * + * @param pdev the device structure used to give information on Keypad + * to resume + * + * @return The function always returns 0. + */ +static int mpr084_resume(struct i2c_client *client) +{ + struct mpr084_data *d = i2c_get_clientdata(client); + + if (d->opened) + d->tstask = kthread_run(mpr084ts_thread, d, DRIVER_NAME "kpd"); + + return 0; +} + +static int mpr084_idev_open(struct input_dev *idev) +{ + struct mpr084_data *d = input_get_drvdata(idev); + int ret = 0; + + d->tstask = kthread_run(mpr084ts_thread, d, DRIVER_NAME "kpd"); + if (IS_ERR(d->tstask)) + ret = PTR_ERR(d->tstask); + else + d->opened++; + return ret; +} + +static void mpr084_idev_close(struct input_dev *idev) +{ + struct mpr084_data *d = input_get_drvdata(idev); + + if (!IS_ERR(d->tstask)) + kthread_stop(d->tstask); + if (d->opened > 0) + d->opened--; +} + +static int mpr084_driver_register(struct mpr084_data *data) +{ + struct input_dev *idev; + int ret = 0; + + if (data->kpirq) { + ret = + request_irq(data->kpirq, mpr084_keypadirq, + IRQF_TRIGGER_FALLING, DRIVER_NAME, data); + if (!ret) { + init_completion(&data->kpirq_completion); + set_irq_wake(data->kpirq, 1); + } else { + printk(KERN_ERR "%s: cannot grab irq %d\n", + __func__, data->kpirq); + } + + } + idev = input_allocate_device(); + data->idev = idev; + input_set_drvdata(idev, data); + idev->name = DRIVER_NAME; + idev->open = mpr084_idev_open; + idev->close = mpr084_idev_close; + if (!ret) + ret = input_register_device(idev); + + return ret; +} + +static int mpr084_i2c_remove(struct i2c_client *client) +{ + struct mpr084_data *d = i2c_get_clientdata(client); + + free_irq(d->kpirq, d); + input_unregister_device(d->idev); + if (keypad->inactive) + keypad->inactive(); + + /*Disable the Regulator*/ + if (keypad->vdd_reg) { + regulator_disable(vdd_reg); + regulator_put(vdd_reg); + } + + return 0; +} + +static int mpr084_configure(struct mpr084_data *data) +{ + int ret = 0, regValue = 0; + + ret = mpr084_write_register(data, MPR084_TPC_ADDR, 0x1d); + if (ret < 0) + goto err; + ret = mpr084_write_register(data, MPR084_STR1_ADDR, 0x10); + if (ret < 0) + goto err; + ret = mpr084_write_register(data, MPR084_STR2_ADDR, 0x10); + if (ret < 0) + goto err; + ret = mpr084_write_register(data, MPR084_STR3_ADDR, 0x10); + if (ret < 0) + goto err; + ret = mpr084_write_register(data, MPR084_STR4_ADDR, 0x10); + if (ret < 0) + goto err; + ret = mpr084_write_register(data, MPR084_STR5_ADDR, 0x10); + if (ret < 0) + goto err; + ret = mpr084_write_register(data, MPR084_STR6_ADDR, 0x10); + if (ret < 0) + goto err; + ret = mpr084_write_register(data, MPR084_STR7_ADDR, 0x10); + if (ret < 0) + goto err; + ret = mpr084_write_register(data, MPR084_STR8_ADDR, 0x10); + if (ret < 0) + goto err; + /* channel enable mask: enable all */ + ret = mpr084_write_register(data, MPR084_ECEM_ADDR, 0xff); + if (ret < 0) + goto err; + /*two conccurrent touch position allowed */ + ret = mpr084_write_register(data, MPR084_MNTP_ADDR, 0x02); + if (ret < 0) + goto err; + + /* master tick period*/ + ret = mpr084_write_register(data, MPR084_MTC_ADDR, 0x05); + if (ret < 0) + goto err; + + + /*Sample period */ + ret = mpr084_write_register(data, MPR084_TASP_ADDR, 0x02); + if (ret < 0) + goto err; + + + /* disable sournder*/ + ret = mpr084_write_register(data, MPR084_SC_ADDR, 0x00); + if (ret < 0) + goto err; + + /* stuck key timeout */ + ret = mpr084_write_register(data, MPR084_SKT_ADDR, 0x01); + if (ret < 0) + goto err; + + /*enabled IRQEN, RUNE, IRQR */ + ret = mpr084_read_register(data, MPR084_CONFIG_ADDR, ®Value); + if (ret < 0) { + printk(KERN_ERR + "%s: Err in reading keypad CONFIGADDR register \n\n", + __func__); + goto err; + } + regValue |= 0x03; + ret = mpr084_write_register(data, MPR084_CONFIG_ADDR, regValue); + if (ret < 0) + goto err; + return ret; +err: + return -ENODEV; +} + +static int mpr084_i2c_probe(struct i2c_client *client, const struct i2c_device_id *id) +{ + struct mpr084_data *data; + int err = 0, i = 0; +#if DEBUG + int regValue = 0; +#endif + data = kzalloc(sizeof(struct mpr084_data), GFP_KERNEL); + if (data == NULL) + return -ENOMEM; + i2c_set_clientdata(client, data); + data->client = client; + data->kpirq = client->irq; + err = mpr084_driver_register(data); + if (err < 0) + goto exit_free; + keypad = (struct mxc_keyp_platform_data *)(client->dev).platform_data; + if (keypad->active) + keypad->active(); + + /*Enable the Regulator*/ + if (keypad && keypad->vdd_reg) { + vdd_reg = regulator_get(&client->dev, keypad->vdd_reg); + if (!IS_ERR(vdd_reg)) + regulator_enable(vdd_reg); + else + vdd_reg = NULL; + } else + vdd_reg = NULL; + + mxckpd_keycodes = keypad->matrix; + data->idev->keycode = &mxckpd_keycodes; + data->idev->keycodesize = sizeof(unsigned char); + data->idev->keycodemax = KEY_COUNT; + data->idev->id.bustype = BUS_I2C; + __set_bit(EV_KEY, data->idev->evbit); + for (i = 0; i < 8; i++) + __set_bit(mxckpd_keycodes[i], data->idev->keybit); + err = mpr084_configure(data); + if (err == -ENODEV) { + free_irq(data->kpirq, data); + input_unregister_device(data->idev); + goto exit_free; + } + +#if DEBUG + for (i = MPR084_ADDR_MINI; i <= MPR084_ADDR_MAX; i++) { + err = mpr084_read_register(data, i, ®Value); + if (err < 0) { + printk(KERN_ERR + "%s: Err in reading keypad CONFIGADDR register \n\n", + __func__); + goto exit_free; + } + printk("MPR084 Register id: %d, Value:%d \n", i, regValue); + + } +#endif + memset(kpstatus, 0, sizeof(kpstatus)); + printk(KERN_INFO "%s: Device Attached\n", __func__); + return 0; +exit_free: + /*disable the Regulator*/ + if (vdd_reg) { + regulator_disable(vdd_reg); + regulator_put(vdd_reg); + vdd_reg = NULL; + } + kfree(data); + return err; +} + +static const struct i2c_device_id mpr084_id[] = { + { "mpr084", 0 }, + {}, +}; +MODULE_DEVICE_TABLE(i2c, mpr084_id); + +static struct i2c_driver mpr084_driver = { + .driver = { + .name = DRIVER_NAME, + }, + .probe = mpr084_i2c_probe, + .remove = mpr084_i2c_remove, + .suspend = mpr084_suspend, + .resume = mpr084_resume, + .command = NULL, + .id_table = mpr084_id, +}; +static int __init mpr084_init(void) +{ + return i2c_add_driver(&mpr084_driver); +} + +static void __exit mpr084_exit(void) +{ + i2c_del_driver(&mpr084_driver); +} + +MODULE_AUTHOR("Freescale Semiconductor Inc"); +MODULE_DESCRIPTION("MPR084 Touch KeyPad Controller driver"); +MODULE_LICENSE("GPL"); +module_init(mpr084_init); +module_exit(mpr084_exit); diff --git a/drivers/input/keyboard/mxc_keyb.c b/drivers/input/keyboard/mxc_keyb.c new file mode 100644 index 000000000000..740140f3f0e2 --- /dev/null +++ b/drivers/input/keyboard/mxc_keyb.c @@ -0,0 +1,1203 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mxc_keyb.c + * + * @brief Driver for the Freescale Semiconductor MXC keypad port. + * + * The keypad driver is designed as a standard Input driver which interacts + * with low level keypad port hardware. Upon opening, the Keypad driver + * initializes the keypad port. When the keypad interrupt happens the driver + * calles keypad polling timer and scans the keypad matrix for key + * press/release. If all key press/release happened it comes out of timer and + * waits for key press interrupt. The scancode for key press and release events + * are passed to Input subsytem. + * + * @ingroup keypad + */ + +/*! + * Comment KPP_DEBUG to disable debug messages + */ +#define KPP_DEBUG 0 + +#if KPP_DEBUG +#define DEBUG +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/*! + * Keypad Module Name + */ +#define MOD_NAME "mxckpd" + +/*! + * XLATE mode selection + */ +#define KEYPAD_XLATE 0 + +/*! + * RAW mode selection + */ +#define KEYPAD_RAW 1 + +/*! + * Maximum number of keys. + */ +#define MAXROW 8 +#define MAXCOL 8 +#define MXC_MAXKEY (MAXROW * MAXCOL) + +/*! + * This define indicates break scancode for every key release. A constant + * of 128 is added to the key press scancode. + */ +#define MXC_KEYRELEASE 128 + +/* + * _reg_KPP_KPCR _reg_KPP_KPSR _reg_KPP_KDDR _reg_KPP_KPDR + * The offset of Keypad Control Register Address + */ +#define KPCR 0x00 + +/* + * The offset of Keypad Status Register Address + */ +#define KPSR 0x02 + +/* + * The offset of Keypad Data Direction Address + */ +#define KDDR 0x04 + +/* + * The offset of Keypad Data Register + */ +#define KPDR 0x06 + +/* + * Key Press Interrupt Status bit + */ +#define KBD_STAT_KPKD 0x01 + +/* + * Key Release Interrupt Status bit + */ +#define KBD_STAT_KPKR 0x02 + +/* + * Key Depress Synchronizer Chain Status bit + */ +#define KBD_STAT_KDSC 0x04 + +/* + * Key Release Synchronizer Status bit + */ +#define KBD_STAT_KRSS 0x08 + +/* + * Key Depress Interrupt Enable Status bit + */ +#define KBD_STAT_KDIE 0x100 + +/* + * Key Release Interrupt Enable + */ +#define KBD_STAT_KRIE 0x200 + +/* + * Keypad Clock Enable + */ +#define KBD_STAT_KPPEN 0x400 + +/*! + * Buffer size of keypad queue. Should be a power of 2. + */ +#define KPP_BUF_SIZE 128 + +/*! + * Test whether bit is set for integer c + */ +#define TEST_BIT(c, n) ((c) & (0x1 << (n))) + +/*! + * Set nth bit in the integer c + */ +#define BITSET(c, n) ((c) | (1 << (n))) + +/*! + * Reset nth bit in the integer c + */ +#define BITRESET(c, n) ((c) & ~(1 << (n))) + +/*! + * This enum represents the keypad state machine to maintain debounce logic + * for key press/release. + */ +enum KeyState { + + /*! + * Key press state. + */ + KStateUp, + + /*! + * Key press debounce state. + */ + KStateFirstDown, + + /*! + * Key release state. + */ + KStateDown, + + /*! + * Key release debounce state. + */ + KStateFirstUp +}; + +/*! + * Keypad Private Data Structure + */ +struct keypad_priv { + + /*! + * Keypad state machine. + */ + enum KeyState iKeyState; + + /*! + * Number of rows configured in the keypad matrix + */ + unsigned long kpp_rows; + + /*! + * Number of Columns configured in the keypad matrix + */ + unsigned long kpp_cols; + + /*! + * Timer used for Keypad polling. + */ + struct timer_list poll_timer; + + /*! + * The base address + */ + void __iomem *base; +}; +/*! + * This structure holds the keypad private data structure. + */ +static struct keypad_priv kpp_dev; + +/*! Indicates if the key pad device is enabled. */ +static unsigned int key_pad_enabled; + +/*! Input device structure. */ +static struct input_dev *mxckbd_dev; + +/*! KPP clock handle. */ +static struct clk *kpp_clk; + +/*! This static variable indicates whether a key event is pressed/released. */ +static unsigned short KPress; + +/*! cur_rcmap and prev_rcmap array is used to detect key press and release. */ +static unsigned short *cur_rcmap; /* max 64 bits (8x8 matrix) */ +static unsigned short *prev_rcmap; + +/*! + * Debounce polling period(10ms) in system ticks. + */ +static unsigned short KScanRate = (10 * HZ) / 1000; + +static struct keypad_data *keypad; + +static int has_leaning_key; +/*! + * These arrays are used to store press and release scancodes. + */ +static short **press_scancode; +static short **release_scancode; + +static const unsigned short *mxckpd_keycodes; +static unsigned short mxckpd_keycodes_size; + +#define press_left_code 30 +#define press_right_code 29 +#define press_up_code 28 +#define press_down_code 27 + +#define rel_left_code 158 +#define rel_right_code 157 +#define rel_up_code 156 +#define rel_down_code 155 +/*! + * These functions are used to configure and the GPIO pins for keypad to + * activate and deactivate it. + */ +extern void gpio_keypad_active(void); +extern void gpio_keypad_inactive(void); + +/*! + * This function is called for generating scancodes for key press and + * release on keypad for the board. + * + * @param row Keypad row pressed on the keypad matrix. + * @param col Keypad col pressed on the keypad matrix. + * @param press Indicated key press/release. + * + * @return Key press/release Scancode. + */ +static signed short mxc_scan_matrix_leaning_key(int row, int col, int press) +{ + static unsigned first_row; + static unsigned first_set, flag; + signed short scancode = -1; + + if (press) { + if ((3 == col) && ((3 == row) || + (4 == row) || (5 == row) || (6 == row))) { + if (first_set == 0) { + first_set = 1; + first_row = row; + } else { + first_set = 0; + if (((first_row == 6) || (first_row == 3)) + && ((row == 6) || (row == 3))) + scancode = press_down_code; + else if (((first_row == 3) || (first_row == 5)) + && ((row == 3) || (row == 5))) + scancode = press_left_code; + else if (((first_row == 6) || (first_row == 4)) + && ((row == 6) || (row == 4))) + scancode = press_right_code; + else if (((first_row == 4) || (first_row == 5)) + && ((row == 4) || (row == 5))) + scancode = press_up_code; + KPress = 1; + kpp_dev.iKeyState = KStateUp; + pr_debug("Press (%d, %d) scan=%d Kpress=%d\n", + row, col, scancode, KPress); + } + } else { + /* + * check for other keys only + * if the cursor key presses + * are not detected may be + * this needs better logic + */ + if ((0 == (cur_rcmap[3] & BITSET(0, 3))) && + (0 == (cur_rcmap[4] & BITSET(0, 3))) && + (0 == (cur_rcmap[5] & BITSET(0, 3))) && + (0 == (cur_rcmap[6] & BITSET(0, 3)))) { + scancode = ((col * kpp_dev.kpp_rows) + row); + KPress = 1; + kpp_dev.iKeyState = KStateUp; + flag = 1; + pr_debug("Press (%d, %d) scan=%d Kpress=%d\n", + row, col, scancode, KPress); + } + } + } else { + if ((flag == 0) && (3 == col) + && ((3 == row) || (4 == row) || (5 == row) + || (6 == row))) { + if (first_set == 0) { + first_set = 1; + first_row = row; + } else { + first_set = 0; + if (((first_row == 6) || (first_row == 3)) + && ((row == 6) || (row == 3))) + scancode = rel_down_code; + else if (((first_row == 3) || (first_row == 5)) + && ((row == 3) || (row == 5))) + scancode = rel_left_code; + else if (((first_row == 6) || (first_row == 4)) + && ((row == 6) || (row == 4))) + scancode = rel_right_code; + else if (((first_row == 4) || (first_row == 5)) + && ((row == 4) || (row == 5))) + scancode = rel_up_code; + KPress = 0; + kpp_dev.iKeyState = KStateDown; + pr_debug("Release (%d, %d) scan=%d Kpress=%d\n", + row, col, scancode, KPress); + } + } else { + /* + * check for other keys only + * if the cursor key presses + * are not detected may be + * this needs better logic + */ + if ((0 == (prev_rcmap[3] & BITSET(0, 3))) && + (0 == (prev_rcmap[4] & BITSET(0, 3))) && + (0 == (cur_rcmap[5] & BITSET(0, 3))) && + (0 == (cur_rcmap[6] & BITSET(0, 3)))) { + scancode = ((col * kpp_dev.kpp_rows) + row) + + MXC_KEYRELEASE; + KPress = 0; + flag = 0; + kpp_dev.iKeyState = KStateDown; + pr_debug("Release (%d, %d) scan=%d Kpress=%d\n", + row, col, scancode, KPress); + } + } + } + return scancode; +} + +/*! + * This function is called to scan the keypad matrix to find out the key press + * and key release events. Make scancode and break scancode are generated for + * key press and key release events. + * + * The following scanning sequence are done for + * keypad row and column scanning, + * -# Write 1's to KPDR[15:8], setting column data to 1's + * -# Configure columns as totem pole outputs(for quick discharging of keypad + * capacitance) + * -# Configure columns as open-drain + * -# Write a single column to 0, others to 1. + * -# Sample row inputs and save data. Multiple key presses can be detected on + * a single column. + * -# Repeat steps the above steps for remaining columns. + * -# Return all columns to 0 in preparation for standby mode. + * -# Clear KPKD and KPKR status bit(s) by writing to a 1, + * Set the KPKR synchronizer chain by writing "1" to KRSS register, + * Clear the KPKD synchronizer chain by writing "1" to KDSC register + * + * @result Number of key pressed/released. + */ +static int mxc_kpp_scan_matrix(void) +{ + unsigned short reg_val; + int col, row; + short scancode = 0; + int keycnt = 0; /* How many keys are still pressed */ + + /* + * wmb() linux kernel function which guarantees orderings in write + * operations + */ + wmb(); + + /* save cur keypad matrix to prev */ + + memcpy(prev_rcmap, cur_rcmap, kpp_dev.kpp_rows * sizeof(prev_rcmap[0])); + memset(cur_rcmap, 0, kpp_dev.kpp_rows * sizeof(cur_rcmap[0])); + + for (col = 0; col < kpp_dev.kpp_cols; col++) { /* Col */ + /* 2. Write 1.s to KPDR[15:8] setting column data to 1.s */ + reg_val = __raw_readw(kpp_dev.base + KPDR); + reg_val |= 0xff00; + __raw_writew(reg_val, kpp_dev.base + KPDR); + + /* + * 3. Configure columns as totem pole outputs(for quick + * discharging of keypad capacitance) + */ + reg_val = __raw_readw(kpp_dev.base + KPCR); + reg_val &= 0x00ff; + __raw_writew(reg_val, kpp_dev.base + KPCR); + + udelay(2); + + /* + * 4. Configure columns as open-drain + */ + reg_val = __raw_readw(kpp_dev.base + KPCR); + reg_val |= ((1 << kpp_dev.kpp_cols) - 1) << 8; + __raw_writew(reg_val, kpp_dev.base + KPCR); + + /* + * 5. Write a single column to 0, others to 1. + * 6. Sample row inputs and save data. Multiple key presses + * can be detected on a single column. + * 7. Repeat steps 2 - 6 for remaining columns. + */ + + /* Col bit starts at 8th bit in KPDR */ + reg_val = __raw_readw(kpp_dev.base + KPDR); + reg_val &= ~(1 << (8 + col)); + __raw_writew(reg_val, kpp_dev.base + KPDR); + + /* Delay added to avoid propagating the 0 from column to row + * when scanning. */ + + udelay(5); + + /* Read row input */ + reg_val = __raw_readw(kpp_dev.base + KPDR); + for (row = 0; row < kpp_dev.kpp_rows; row++) { /* sample row */ + if (TEST_BIT(reg_val, row) == 0) { + cur_rcmap[row] = BITSET(cur_rcmap[row], col); + keycnt++; + } + } + } + + /* + * 8. Return all columns to 0 in preparation for standby mode. + * 9. Clear KPKD and KPKR status bit(s) by writing to a .1., + * set the KPKR synchronizer chain by writing "1" to KRSS register, + * clear the KPKD synchronizer chain by writing "1" to KDSC register + */ + reg_val = 0x00; + __raw_writew(reg_val, kpp_dev.base + KPDR); + reg_val = __raw_readw(kpp_dev.base + KPDR); + reg_val = __raw_readw(kpp_dev.base + KPSR); + reg_val |= KBD_STAT_KPKD | KBD_STAT_KPKR | KBD_STAT_KRSS | + KBD_STAT_KDSC; + __raw_writew(reg_val, kpp_dev.base + KPSR); + + /* Check key press status change */ + + /* + * prev_rcmap array will contain the previous status of the keypad + * matrix. cur_rcmap array will contains the present status of the + * keypad matrix. If a bit is set in the array, that (row, col) bit is + * pressed, else it is not pressed. + * + * XORing these two variables will give us the change in bit for + * particular row and column. If a bit is set in XOR output, then that + * (row, col) has a change of status from the previous state. From + * the diff variable the key press and key release of row and column + * are found out. + * + * If the key press is determined then scancode for key pressed + * can be generated using the following statement: + * scancode = ((row * 8) + col); + * + * If the key release is determined then scancode for key release + * can be generated using the following statement: + * scancode = ((row * 8) + col) + MXC_KEYRELEASE; + */ + for (row = 0; row < kpp_dev.kpp_rows; row++) { + unsigned char diff; + + /* + * Calculate the change in the keypad row status + */ + diff = prev_rcmap[row] ^ cur_rcmap[row]; + + for (col = 0; col < kpp_dev.kpp_cols; col++) { + if ((diff >> col) & 0x1) { + /* There is a status change on col */ + if ((prev_rcmap[row] & BITSET(0, col)) == 0) { + /* + * Previous state is 0, so now + * a key is pressed + */ + if (has_leaning_key) { + scancode = + mxc_scan_matrix_leaning_key + (row, col, 1); + } else { + scancode = + ((row * kpp_dev.kpp_cols) + + col); + KPress = 1; + kpp_dev.iKeyState = KStateUp; + } + pr_debug("Press (%d, %d) scan=%d " + "Kpress=%d\n", + row, col, scancode, KPress); + press_scancode[row][col] = + (short)scancode; + } else { + /* + * Previous state is not 0, so + * now a key is released + */ + if (has_leaning_key) { + scancode = + mxc_scan_matrix_leaning_key + (row, col, 0); + } else { + scancode = + (row * kpp_dev.kpp_cols) + + col + MXC_KEYRELEASE; + KPress = 0; + kpp_dev.iKeyState = KStateDown; + } + + pr_debug + ("Release (%d, %d) scan=%d Kpress=%d\n", + row, col, scancode, KPress); + release_scancode[row][col] = + (short)scancode; + keycnt++; + } + } + } + } + + /* + * This switch case statement is the + * implementation of state machine of debounce + * logic for key press/release. + * The explaination of state machine is as + * follows: + * + * KStateUp State: + * This is in intial state of the state machine + * this state it checks for any key presses. + * The key press can be checked using the + * variable KPress. If KPress is set, then key + * press is identified and switches the to + * KStateFirstDown state for key press to + * debounce. + * + * KStateFirstDown: + * After debounce delay(10ms), if the KPress is + * still set then pass scancode generated to + * input device and change the state to + * KStateDown, else key press debounce is not + * satisfied so change the state to KStateUp. + * + * KStateDown: + * In this state it checks for any key release. + * If KPress variable is cleared, then key + * release is indicated and so, switch the + * state to KStateFirstUp else to state + * KStateDown. + * + * KStateFirstUp: + * After debounce delay(10ms), if the KPress is + * still reset then pass the key release + * scancode to input device and change + * the state to KStateUp else key release is + * not satisfied so change the state to + * KStateDown. + */ + switch (kpp_dev.iKeyState) { + case KStateUp: + if (KPress) { + /* First Down (must debounce). */ + kpp_dev.iKeyState = KStateFirstDown; + } else { + /* Still UP.(NO Changes) */ + kpp_dev.iKeyState = KStateUp; + } + break; + + case KStateFirstDown: + if (KPress) { + for (row = 0; row < kpp_dev.kpp_rows; row++) { + for (col = 0; col < kpp_dev.kpp_cols; col++) { + if ((press_scancode[row][col] != -1)) { + /* Still Down, so add scancode */ + scancode = + press_scancode[row][col]; + input_event(mxckbd_dev, EV_KEY, + mxckpd_keycodes + [scancode], 1); + if (mxckpd_keycodes[scancode] == + KEY_LEFTSHIFT) { + input_event(mxckbd_dev, + EV_KEY, + KEY_3, 1); + } + kpp_dev.iKeyState = KStateDown; + press_scancode[row][col] = -1; + } + } + } + } else { + /* Just a bounce */ + kpp_dev.iKeyState = KStateUp; + } + break; + + case KStateDown: + if (KPress) { + /* Still down (no change) */ + kpp_dev.iKeyState = KStateDown; + } else { + /* First Up. Must debounce */ + kpp_dev.iKeyState = KStateFirstUp; + } + break; + + case KStateFirstUp: + if (KPress) { + /* Just a bounce */ + kpp_dev.iKeyState = KStateDown; + } else { + for (row = 0; row < kpp_dev.kpp_rows; row++) { + for (col = 0; col < kpp_dev.kpp_cols; col++) { + if ((release_scancode[row][col] != -1)) { + scancode = + release_scancode[row][col]; + scancode = + scancode - MXC_KEYRELEASE; + input_event(mxckbd_dev, EV_KEY, + mxckpd_keycodes + [scancode], 0); + if (mxckpd_keycodes[scancode] == + KEY_LEFTSHIFT) { + input_event(mxckbd_dev, + EV_KEY, + KEY_3, 0); + } + kpp_dev.iKeyState = KStateUp; + release_scancode[row][col] = -1; + } + } + } + } + break; + + default: + return -EBADRQC; + break; + } + + return keycnt; +} + +/*! + * This function is called to start the timer for scanning the keypad if there + * is any key press. Currently this interval is set to 10 ms. When there are + * no keys pressed on the keypad we return back, waiting for a keypad key + * press interrupt. + * + * @param data Opaque data passed back by kernel. Not used. + */ +static void mxc_kpp_handle_timer(unsigned long data) +{ + unsigned short reg_val; + int i; + + if (key_pad_enabled == 0) { + return; + } + if (mxc_kpp_scan_matrix() == 0) { + /* + * Stop scanning and wait for interrupt. + * Enable press interrupt and disable release interrupt. + */ + __raw_writew(0x00FF, kpp_dev.base + KPDR); + reg_val = __raw_readw(kpp_dev.base + KPSR); + reg_val |= (KBD_STAT_KPKR | KBD_STAT_KPKD); + reg_val |= KBD_STAT_KRSS | KBD_STAT_KDSC; + __raw_writew(reg_val, kpp_dev.base + KPSR); + reg_val |= KBD_STAT_KDIE; + reg_val &= ~KBD_STAT_KRIE; + __raw_writew(reg_val, kpp_dev.base + KPSR); + + /* + * No more keys pressed... make sure unwanted key codes are + * not given upstairs + */ + for (i = 0; i < kpp_dev.kpp_rows; i++) { + memset(press_scancode[i], -1, + sizeof(press_scancode[0][0]) * kpp_dev.kpp_cols); + memset(release_scancode[i], -1, + sizeof(release_scancode[0][0]) * + kpp_dev.kpp_cols); + } + return; + } + + /* + * There are still some keys pressed, continue to scan. + * We shall scan again in 10 ms. This has to be tuned according + * to the requirement. + */ + kpp_dev.poll_timer.expires = jiffies + KScanRate; + kpp_dev.poll_timer.function = mxc_kpp_handle_timer; + add_timer(&kpp_dev.poll_timer); +} + +/*! + * This function is the keypad Interrupt handler. + * This function checks for keypad status register (KPSR) for key press + * and interrupt. If key press interrupt has occurred, then the key + * press interrupt in the KPSR are disabled. + * It then calls mxc_kpp_scan_matrix to check for any key pressed/released. + * If any key is found to be pressed, then a timer is set to call + * mxc_kpp_scan_matrix function for every 10 ms. + * + * @param irq The Interrupt number + * @param dev_id Driver private data + * + * @result The function returns \b IRQ_RETVAL(1) if interrupt was handled, + * returns \b IRQ_RETVAL(0) if the interrupt was not handled. + * \b IRQ_RETVAL is defined in include/linux/interrupt.h. + */ +static irqreturn_t mxc_kpp_interrupt(int irq, void *dev_id) +{ + unsigned short reg_val; + + /* Delete the polling timer */ + del_timer(&kpp_dev.poll_timer); + reg_val = __raw_readw(kpp_dev.base + KPSR); + + /* Check if it is key press interrupt */ + if (reg_val & KBD_STAT_KPKD) { + /* + * Disable key press(KDIE status bit) interrupt + */ + reg_val &= ~KBD_STAT_KDIE; + __raw_writew(reg_val, kpp_dev.base + KPSR); + } else { + /* spurious interrupt */ + return IRQ_RETVAL(0); + } + /* + * Check if any keys are pressed, if so start polling. + */ + mxc_kpp_handle_timer(0); + + return IRQ_RETVAL(1); +} + +/*! + * This function is called when the keypad driver is opened. + * Since keypad initialization is done in __init, nothing is done in open. + * + * @param dev Pointer to device inode + * + * @result The function always return 0 + */ +static int mxc_kpp_open(struct input_dev *dev) +{ + return 0; +} + +/*! + * This function is called close the keypad device. + * Nothing is done in this function, since every thing is taken care in + * __exit function. + * + * @param dev Pointer to device inode + * + */ +static void mxc_kpp_close(struct input_dev *dev) +{ +} + +#ifdef CONFIG_PM +/*! + * This function puts the Keypad controller in low-power mode/state. + * If Keypad is enabled as a wake source(i.e. it can resume the system + * from suspend mode), the Keypad controller doesn't enter low-power state. + * + * @param pdev the device structure used to give information on Keypad + * to suspend + * @param state the power state the device is entering + * + * @return return -1 when the keypad is pressed. Otherwise, return 0 + */ +static int mxc_kpp_suspend(struct platform_device *pdev, pm_message_t state) +{ + /* When the keypad is still pressed, clean up registers and timers */ + if (timer_pending(&kpp_dev.poll_timer)) + return -1; + + if (device_may_wakeup(&pdev->dev)) { + enable_irq_wake(keypad->irq); + } else { + disable_irq(keypad->irq); + key_pad_enabled = 0; + clk_disable(kpp_clk); + gpio_keypad_inactive(); + } + + return 0; +} + +/*! + * This function brings the Keypad controller back from low-power state. + * If Keypad is enabled as a wake source(i.e. it can resume the system + * from suspend mode), the Keypad controller doesn't enter low-power state. + * + * @param pdev the device structure used to give information on Keypad + * to resume + * + * @return The function always returns 0. + */ +static int mxc_kpp_resume(struct platform_device *pdev) +{ + if (device_may_wakeup(&pdev->dev)) { + disable_irq_wake(keypad->irq); + } else { + gpio_keypad_active(); + clk_enable(kpp_clk); + key_pad_enabled = 1; + enable_irq(keypad->irq); + } + + return 0; +} + +#else +#define mxc_kpp_suspend NULL +#define mxc_kpp_resume NULL +#endif /* CONFIG_PM */ + +/*! + * This function is called to free the allocated memory for local arrays + */ +static void mxc_kpp_free_allocated(void) +{ + + int i; + + if (press_scancode) { + for (i = 0; i < kpp_dev.kpp_rows; i++) { + if (press_scancode[i]) + kfree(press_scancode[i]); + } + kfree(press_scancode); + } + + if (release_scancode) { + for (i = 0; i < kpp_dev.kpp_rows; i++) { + if (release_scancode[i]) + kfree(release_scancode[i]); + } + kfree(release_scancode); + } + + if (cur_rcmap) + kfree(cur_rcmap); + + if (prev_rcmap) + kfree(prev_rcmap); + + if (mxckbd_dev) + input_free_device(mxckbd_dev); +} + +/*! + * This function is called during the driver binding process. + * + * @param pdev the device structure used to store device specific + * information that is used by the suspend, resume and remove + * functions. + * + * @return The function returns 0 on successful registration. Otherwise returns + * specific error code. + */ +static int mxc_kpp_probe(struct platform_device *pdev) +{ + int i, irq; + int retval; + unsigned int reg_val; + struct resource *res; + + keypad = (struct keypad_data *)pdev->dev.platform_data; + + kpp_dev.kpp_cols = keypad->colmax; + kpp_dev.kpp_rows = keypad->rowmax; + key_pad_enabled = 0; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!res) + return -ENODEV; + + kpp_dev.base = ioremap(res->start, res->end - res->start + 1); + if (!kpp_dev.base) + return -ENOMEM; + + irq = platform_get_irq(pdev, 0); + keypad->irq = irq; + + /* Enable keypad clock */ + kpp_clk = clk_get(&pdev->dev, "kpp_clk"); + clk_enable(kpp_clk); + + /* IOMUX configuration for keypad */ + gpio_keypad_active(); + + /* Configure keypad */ + + /* Enable number of rows in keypad (KPCR[7:0]) + * Configure keypad columns as open-drain (KPCR[15:8]) + * + * Configure the rows/cols in KPP + * LSB nibble in KPP is for 8 rows + * MSB nibble in KPP is for 8 cols + */ + reg_val = __raw_readw(kpp_dev.base + KPCR); + reg_val |= (1 << keypad->rowmax) - 1; /* LSB */ + reg_val |= ((1 << keypad->colmax) - 1) << 8; /* MSB */ + __raw_writew(reg_val, kpp_dev.base + KPCR); + + /* Write 0's to KPDR[15:8] */ + reg_val = __raw_readw(kpp_dev.base + KPDR); + reg_val &= 0x00ff; + __raw_writew(reg_val, kpp_dev.base + KPDR); + + /* Configure columns as output, rows as input (KDDR[15:0]) */ + reg_val = __raw_readw(kpp_dev.base + KDDR); + reg_val |= 0xff00; + reg_val &= 0xff00; + __raw_writew(reg_val, kpp_dev.base + KDDR); + + reg_val = __raw_readw(kpp_dev.base + KPSR); + reg_val &= ~(KBD_STAT_KPKR | KBD_STAT_KPKD); + reg_val |= KBD_STAT_KPKD; + reg_val |= KBD_STAT_KRSS | KBD_STAT_KDSC; + __raw_writew(reg_val, kpp_dev.base + KPSR); + reg_val |= KBD_STAT_KDIE; + reg_val &= ~KBD_STAT_KRIE; + __raw_writew(reg_val, kpp_dev.base + KPSR); + + has_leaning_key = keypad->learning; + mxckpd_keycodes = keypad->matrix; + mxckpd_keycodes_size = keypad->rowmax * keypad->colmax; + + if ((keypad->matrix == (void *)0) + || (mxckpd_keycodes_size == 0)) { + retval = -ENODEV; + goto err1; + } + + mxckbd_dev = input_allocate_device(); + if (!mxckbd_dev) { + printk(KERN_ERR + "mxckbd_dev: not enough memory for input device\n"); + retval = -ENOMEM; + goto err1; + } + + mxckbd_dev->keycode = (void *)mxckpd_keycodes; + mxckbd_dev->keycodesize = sizeof(mxckpd_keycodes[0]); + mxckbd_dev->keycodemax = mxckpd_keycodes_size; + mxckbd_dev->name = "mxckpd"; + mxckbd_dev->id.bustype = BUS_HOST; + mxckbd_dev->open = mxc_kpp_open; + mxckbd_dev->close = mxc_kpp_close; + + retval = input_register_device(mxckbd_dev); + if (retval < 0) { + printk(KERN_ERR + "mxckbd_dev: failed to register input device\n"); + goto err2; + } + + /* allocate required memory */ + press_scancode = kmalloc(kpp_dev.kpp_rows * sizeof(press_scancode[0]), + GFP_KERNEL); + release_scancode = + kmalloc(kpp_dev.kpp_rows * sizeof(release_scancode[0]), GFP_KERNEL); + + if (!press_scancode || !release_scancode) { + retval = -ENOMEM; + goto err3; + } + + for (i = 0; i < kpp_dev.kpp_rows; i++) { + press_scancode[i] = kmalloc(kpp_dev.kpp_cols + * sizeof(press_scancode[0][0]), + GFP_KERNEL); + release_scancode[i] = + kmalloc(kpp_dev.kpp_cols * sizeof(release_scancode[0][0]), + GFP_KERNEL); + + if (!press_scancode[i] || !release_scancode[i]) { + retval = -ENOMEM; + goto err3; + } + } + + cur_rcmap = + kmalloc(kpp_dev.kpp_rows * sizeof(cur_rcmap[0]), GFP_KERNEL); + prev_rcmap = + kmalloc(kpp_dev.kpp_rows * sizeof(prev_rcmap[0]), GFP_KERNEL); + + if (!cur_rcmap || !prev_rcmap) { + retval = -ENOMEM; + goto err3; + } + + __set_bit(EV_KEY, mxckbd_dev->evbit); + + for (i = 0; i < mxckpd_keycodes_size; i++) + __set_bit(mxckpd_keycodes[i], mxckbd_dev->keybit); + + for (i = 0; i < kpp_dev.kpp_rows; i++) { + memset(press_scancode[i], -1, + sizeof(press_scancode[0][0]) * kpp_dev.kpp_cols); + memset(release_scancode[i], -1, + sizeof(release_scancode[0][0]) * kpp_dev.kpp_cols); + } + memset(cur_rcmap, 0, kpp_dev.kpp_rows * sizeof(cur_rcmap[0])); + memset(prev_rcmap, 0, kpp_dev.kpp_rows * sizeof(prev_rcmap[0])); + + key_pad_enabled = 1; + /* Initialize the polling timer */ + init_timer(&kpp_dev.poll_timer); + + /* + * Request for IRQ number for keypad port. The Interrupt handler + * function (mxc_kpp_interrupt) is called when ever interrupt occurs on + * keypad port. + */ + retval = request_irq(irq, mxc_kpp_interrupt, 0, MOD_NAME, MOD_NAME); + if (retval) { + pr_debug("KPP: request_irq(%d) returned error %d\n", + irq, retval); + goto err3; + } + + /* By default, devices should wakeup if they can */ + /* So keypad is set as "should wakeup" as it can */ + device_init_wakeup(&pdev->dev, 1); + + return 0; + + err3: + mxc_kpp_free_allocated(); + err2: + input_free_device(mxckbd_dev); + err1: + free_irq(irq, MOD_NAME); + clk_disable(kpp_clk); + clk_put(kpp_clk); + return retval; +} + +/*! + * Dissociates the driver from the kpp device. + * + * @param pdev the device structure used to give information on which SDHC + * to remove + * + * @return The function always returns 0. + */ +static int mxc_kpp_remove(struct platform_device *pdev) +{ + unsigned short reg_val; + + /* + * Clear the KPKD status flag (write 1 to it) and synchronizer chain. + * Set KDIE control bit, clear KRIE control bit (avoid false release + * events. Disable the keypad GPIO pins. + */ + __raw_writew(0x00, kpp_dev.base + KPCR); + __raw_writew(0x00, kpp_dev.base + KPDR); + __raw_writew(0x00, kpp_dev.base + KDDR); + + reg_val = __raw_readw(kpp_dev.base + KPSR); + reg_val |= KBD_STAT_KPKD; + reg_val &= ~KBD_STAT_KRSS; + reg_val |= KBD_STAT_KDIE; + reg_val &= ~KBD_STAT_KRIE; + __raw_writew(reg_val, kpp_dev.base + KPSR); + + gpio_keypad_inactive(); + clk_disable(kpp_clk); + clk_put(kpp_clk); + + KPress = 0; + + del_timer(&kpp_dev.poll_timer); + + free_irq(keypad->irq, MOD_NAME); + input_unregister_device(mxckbd_dev); + + mxc_kpp_free_allocated(); + + return 0; +} + +/*! + * This structure contains pointers to the power management callback functions. + */ +static struct platform_driver mxc_kpd_driver = { + .driver = { + .name = "mxc_keypad", + .bus = &platform_bus_type, + }, + .suspend = mxc_kpp_suspend, + .resume = mxc_kpp_resume, + .probe = mxc_kpp_probe, + .remove = mxc_kpp_remove +}; + +/*! + * This function is called for module initialization. + * It registers keypad char driver and requests for KPP irq number. This + * function does the initialization of the keypad device. + * + * The following steps are used for keypad configuration,\n + * -# Enable number of rows in the keypad control register (KPCR[7:0}).\n + * -# Write 0's to KPDR[15:8]\n + * -# Configure keypad columns as open-drain (KPCR[15:8])\n + * -# Configure columns as output, rows as input (KDDR[15:0])\n + * -# Clear the KPKD status flag (write 1 to it) and synchronizer chain\n + * -# Set KDIE control bit, clear KRIE control bit\n + * In this function the keypad queue initialization is done. + * The keypad IOMUX configuration are done here.* + + * + * @return 0 on success and a non-zero value on failure. + */ +static int __init mxc_kpp_init(void) +{ + printk(KERN_INFO "MXC keypad loaded\n"); + platform_driver_register(&mxc_kpd_driver); + return 0; +} + +/*! + * This function is called whenever the module is removed from the kernel. It + * unregisters the keypad driver from kernel and frees the irq number. + * This function puts the keypad to standby mode. The keypad interrupts are + * disabled. It calls gpio_keypad_inactive function to switch gpio + * configuration into default state. + * + */ +static void __exit mxc_kpp_cleanup(void) +{ + platform_driver_unregister(&mxc_kpd_driver); +} + +module_init(mxc_kpp_init); +module_exit(mxc_kpp_cleanup); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MXC Keypad Controller Driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/input/keyboard/mxs-kbd.c b/drivers/input/keyboard/mxs-kbd.c new file mode 100644 index 000000000000..20daee01aae4 --- /dev/null +++ b/drivers/input/keyboard/mxs-kbd.c @@ -0,0 +1,365 @@ +/* + * Keypad ladder driver for Freescale MXS boards + * + * Author: dmitry pervushin + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. + * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#define BUTTON_PRESS_THRESHOLD 3300 +#define LRADC_NOISE_MARGIN 100 + +/* this value represents the the lradc value at 3.3V ( 3.3V / 0.000879 V/b ) */ +#define TARGET_VDDIO_LRADC_VALUE 3754 + +struct mxskbd_data { + struct input_dev *input; + int last_button; + int irq; + int btn_irq; + struct mxskbd_keypair *keycodes; + unsigned int base; + int chan; + unsigned int btn_enable; /* detect enable bits */ + unsigned int btn_irq_stat; /* detect irq status bits */ + unsigned int btn_irq_ctrl; /* detect irq enable bits */ +}; + +static int delay1 = 500; +static int delay2 = 200; + +static int mxskbd_open(struct input_dev *dev); +static void mxskbd_close(struct input_dev *dev); + +static struct mxskbd_data *mxskbd_data_alloc(struct platform_device *pdev, + struct mxskbd_keypair *keys) +{ + struct mxskbd_data *d = kzalloc(sizeof(*d), GFP_KERNEL); + + if (!d) + return NULL; + + if (!keys) { + dev_err(&pdev->dev, + "No keycodes in platform_data, bailing out.\n"); + kfree(d); + return NULL; + } + d->keycodes = keys; + + d->input = input_allocate_device(); + if (!d->input) { + kfree(d); + return NULL; + } + + d->input->phys = "onboard"; + d->input->uniq = "0000'0000"; + d->input->name = pdev->name; + d->input->id.bustype = BUS_HOST; + d->input->open = mxskbd_open; + d->input->close = mxskbd_close; + d->input->dev.parent = &pdev->dev; + + set_bit(EV_KEY, d->input->evbit); + set_bit(EV_REL, d->input->evbit); + set_bit(EV_REP, d->input->evbit); + + + d->last_button = -1; + + while (keys->raw >= 0) { + set_bit(keys->kcode, d->input->keybit); + keys++; + } + + return d; +} + +static inline struct input_dev *GET_INPUT_DEV(struct mxskbd_data *d) +{ + BUG_ON(!d); + return d->input; +} + +static void mxskbd_data_free(struct mxskbd_data *d) +{ + if (!d) + return; + if (d->input) + input_free_device(d->input); + kfree(d); +} + +static unsigned mxskbd_decode_button(struct mxskbd_keypair *codes, + int raw_button) + +{ + pr_debug("Decoding %d\n", raw_button); + while (codes->raw != -1) { + if ((raw_button >= (codes->raw - LRADC_NOISE_MARGIN)) && + (raw_button < (codes->raw + LRADC_NOISE_MARGIN))) { + pr_debug("matches code 0x%x = %d\n", + codes->kcode, codes->kcode); + return codes->kcode; + } + codes++; + } + return (unsigned)-1; /* invalid key */ +} + + +static irqreturn_t mxskbd_irq_handler(int irq, void *dev_id) +{ + struct platform_device *pdev = dev_id; + struct mxskbd_data *devdata = platform_get_drvdata(pdev); + u16 raw_button, normalized_button, vddio; + unsigned btn; + + if (devdata->btn_irq == irq) { + __raw_writel(devdata->btn_irq_stat, + devdata->base + HW_LRADC_CTRL1_CLR); + __raw_writel(BM_LRADC_CTRL1_LRADC0_IRQ << devdata->chan, + devdata->base + HW_LRADC_CTRL1_CLR); + __raw_writel(BM_LRADC_CTRL1_LRADC0_IRQ_EN << devdata->chan, + devdata->base + HW_LRADC_CTRL1_SET); + return IRQ_HANDLED; + } + + raw_button = __raw_readl(devdata->base + HW_LRADC_CHn(devdata->chan)) & + BM_LRADC_CHn_VALUE; + vddio = hw_lradc_vddio(); + BUG_ON(vddio == 0); + + normalized_button = (raw_button * TARGET_VDDIO_LRADC_VALUE) / + vddio; + + if (normalized_button < BUTTON_PRESS_THRESHOLD && + devdata->last_button < 0) { + btn = mxskbd_decode_button(devdata->keycodes, + normalized_button); + if (btn < KEY_MAX) { + devdata->last_button = btn; + input_report_key(GET_INPUT_DEV(devdata), + devdata->last_button, !0); + } else + dev_err(&pdev->dev, "Invalid button: raw = %d, " + "normalized = %d, vddio = %d\n", + raw_button, normalized_button, vddio); + } else if (devdata->last_button > 0 && + normalized_button >= BUTTON_PRESS_THRESHOLD) { + input_report_key(GET_INPUT_DEV(devdata), + devdata->last_button, 0); + devdata->last_button = -1; + if (devdata->btn_irq > 0) + __raw_writel(BM_LRADC_CTRL1_LRADC0_IRQ_EN << + devdata->chan, + devdata->base + HW_LRADC_CTRL1_CLR); + } + + __raw_writel(BM_LRADC_CTRL1_LRADC0_IRQ << devdata->chan, + devdata->base + HW_LRADC_CTRL1_CLR); + return IRQ_HANDLED; +} + +static int mxskbd_open(struct input_dev *dev) +{ + /* enable clock */ + return 0; +} + +static void mxskbd_close(struct input_dev *dev) +{ + /* disable clock */ +} + +static void mxskbd_hwinit(struct platform_device *pdev) +{ + struct mxskbd_data *d = platform_get_drvdata(pdev); + + hw_lradc_init_ladder(d->chan, LRADC_DELAY_TRIGGER_BUTTON, 200); + if (d->btn_irq > 0) { + __raw_writel(d->btn_enable, d->base + HW_LRADC_CTRL0_SET); + __raw_writel(d->btn_irq_ctrl, d->base + HW_LRADC_CTRL1_SET); + } else { + __raw_writel(BM_LRADC_CTRL1_LRADC0_IRQ << d->chan, + d->base + HW_LRADC_CTRL1_CLR); + __raw_writel(BM_LRADC_CTRL1_LRADC0_IRQ_EN << d->chan, + d->base + HW_LRADC_CTRL1_SET); + } + hw_lradc_set_delay_trigger_kick(LRADC_DELAY_TRIGGER_BUTTON, !0); +} + +#ifdef CONFIG_PM +static int mxskbd_suspend(struct platform_device *pdev, pm_message_t state) +{ + struct mxskbd_data *d = platform_get_drvdata(pdev); + + hw_lradc_stop_ladder(d->chan, LRADC_DELAY_TRIGGER_BUTTON); + hw_lradc_set_delay_trigger_kick(LRADC_DELAY_TRIGGER_BUTTON, 0); + hw_lradc_unuse_channel(d->chan); + __raw_writel(BM_LRADC_CTRL1_LRADC0_IRQ_EN << d->chan, + d->base + HW_LRADC_CTRL1_CLR); + mxskbd_close(d->input); + return 0; +} + +static int mxskbd_resume(struct platform_device *pdev) +{ + struct mxskbd_data *d = platform_get_drvdata(pdev); + + __raw_writel(BM_LRADC_CTRL1_LRADC0_IRQ_EN << d->chan, + d->base + HW_LRADC_CTRL1_SET); + mxskbd_open(d->input); + hw_lradc_use_channel(d->chan); + mxskbd_hwinit(pdev); + return 0; +} +#endif + +static int __devinit mxskbd_probe(struct platform_device *pdev) +{ + int err = 0; + struct resource *res; + struct mxskbd_data *d; + struct mxs_kbd_plat_data *plat_data; + + plat_data = (struct mxs_kbd_plat_data *)pdev->dev.platform_data; + if (plat_data == NULL) + return -ENODEV; + + /* Create and register the input driver. */ + d = mxskbd_data_alloc(pdev, plat_data->keypair); + if (!d) { + dev_err(&pdev->dev, "Cannot allocate driver structures\n"); + err = -ENOMEM; + goto err_out; + } + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!res) { + err = -ENODEV; + goto err_out; + } + d->base = (unsigned int)IO_ADDRESS(res->start); + d->chan = plat_data->channel; + d->irq = platform_get_irq(pdev, 0); + d->btn_irq = platform_get_irq(pdev, 1); + d->btn_enable = plat_data->btn_enable; + d->btn_irq_stat = plat_data->btn_irq_stat; + d->btn_irq_ctrl = plat_data->btn_irq_ctrl; + + platform_set_drvdata(pdev, d); + + err = request_irq(d->irq, mxskbd_irq_handler, + IRQF_DISABLED, pdev->name, pdev); + if (err) { + dev_err(&pdev->dev, "Cannot request keypad IRQ\n"); + goto err_free_dev; + } + + if (d->btn_irq > 0) { + err = request_irq(d->btn_irq, mxskbd_irq_handler, + IRQF_DISABLED, pdev->name, pdev); + if (err) { + dev_err(&pdev->dev, + "Cannot request keybad detect IRQ\n"); + goto err_free_irq; + } + } + + /* Register the input device */ + err = input_register_device(GET_INPUT_DEV(d)); + if (err) + goto err_free_irq2; + + /* these two have to be set after registering the input device */ + d->input->rep[REP_DELAY] = delay1; + d->input->rep[REP_PERIOD] = delay2; + + hw_lradc_use_channel(d->chan); + mxskbd_hwinit(pdev); + + return 0; + +err_free_irq2: + platform_set_drvdata(pdev, NULL); + if (d->btn_irq > 0) + free_irq(d->btn_irq, pdev); +err_free_irq: + free_irq(d->irq, pdev); +err_free_dev: + mxskbd_data_free(d); +err_out: + return err; +} + +static int __devexit mxskbd_remove(struct platform_device *pdev) +{ + struct mxskbd_data *d = platform_get_drvdata(pdev); + + hw_lradc_unuse_channel(d->chan); + input_unregister_device(GET_INPUT_DEV(d)); + free_irq(d->irq, pdev); + if (d->btn_irq > 0) + free_irq(d->btn_irq, pdev); + mxskbd_data_free(d); + + platform_set_drvdata(pdev, NULL); + + return 0; +} + +static struct platform_driver mxskbd_driver = { + .probe = mxskbd_probe, + .remove = __devexit_p(mxskbd_remove), +#ifdef CONFIG_PM + .suspend = mxskbd_suspend, + .resume = mxskbd_resume, +#endif + .driver = { + .name = "mxs-kbd", + }, +}; + +static int __init mxskbd_init(void) +{ + return platform_driver_register(&mxskbd_driver); +} + +static void __exit mxskbd_exit(void) +{ + platform_driver_unregister(&mxskbd_driver); +} + +module_init(mxskbd_init); +module_exit(mxskbd_exit); +MODULE_DESCRIPTION("Freescale keyboard driver for mxs family"); +MODULE_AUTHOR("dmitry pervushin ") +MODULE_LICENSE("GPL"); diff --git a/drivers/input/touchscreen/Kconfig b/drivers/input/touchscreen/Kconfig index 3b9d5e2105d7..50d66ee066d0 100644 --- a/drivers/input/touchscreen/Kconfig +++ b/drivers/input/touchscreen/Kconfig @@ -268,6 +268,46 @@ config TOUCHSCREEN_HP7XX To compile this driver as a module, choose M here: the module will be called jornada720_ts. +config TOUCHSCREEN_MXC + tristate "MXC touchscreen input driver" + depends on MXC_MC13783_ADC || MXC_MC13892_ADC + help + Say Y here if you have an MXC based board with touchscreen + attached to it. + + If unsure, say N. + + To compile this driver as a module, choose M here: the + module will be called mxc_ts. + +config TOUCHSCREEN_IMX_ADC + tristate "Freescale i.MX ADC touchscreen input driver" + depends on IMX_ADC + help + Say Y here if you have a Freescale i.MX based board with a + touchscreen interfaced to the processor's integrated ADC. + + If unsure, say N. + + To compile this driver as a module, choose M here: the + module will be called imx_adc_ts. + +config TOUCHSCREEN_STMP3XXX + tristate "STMP3XXX LRADC-based touchscreen" + depends on ARCH_STMP3XXX + select SERIO + help + Say Y here if you want to enable TMP3XXX LRADC-based touchscreen. + module will be called stmp3xxx_ts. + +config TOUCHSCREEN_MXS + tristate "MXS LRADC-based touchscreen" + depends on ARCH_MXS + select SERIO + help + Say Y here if you want to enable MXS LRADC-based touchscreen. + module will be called mxs-ts. + config TOUCHSCREEN_HTCPEN tristate "HTC Shift X9500 touchscreen" depends on ISA diff --git a/drivers/input/touchscreen/Makefile b/drivers/input/touchscreen/Makefile index 497964a7a214..7be6e778578e 100644 --- a/drivers/input/touchscreen/Makefile +++ b/drivers/input/touchscreen/Makefile @@ -27,6 +27,10 @@ obj-$(CONFIG_TOUCHSCREEN_MK712) += mk712.o obj-$(CONFIG_TOUCHSCREEN_HP600) += hp680_ts_input.o obj-$(CONFIG_TOUCHSCREEN_HP7XX) += jornada720_ts.o obj-$(CONFIG_TOUCHSCREEN_HTCPEN) += htcpen.o +obj-$(CONFIG_TOUCHSCREEN_MXC) += mxc_ts.o +obj-$(CONFIG_TOUCHSCREEN_IMX_ADC) += imx_adc_ts.o +obj-$(CONFIG_TOUCHSCREEN_STMP3XXX) += stmp3xxx_ts.o +obj-$(CONFIG_TOUCHSCREEN_MXS) += mxs-ts.o obj-$(CONFIG_TOUCHSCREEN_USB_COMPOSITE) += usbtouchscreen.o obj-$(CONFIG_TOUCHSCREEN_PCAP) += pcap_ts.o obj-$(CONFIG_TOUCHSCREEN_PENMOUNT) += penmount.o diff --git a/drivers/input/touchscreen/imx_adc_ts.c b/drivers/input/touchscreen/imx_adc_ts.c new file mode 100644 index 000000000000..797eff5672dc --- /dev/null +++ b/drivers/input/touchscreen/imx_adc_ts.c @@ -0,0 +1,114 @@ +/* + * Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file imx_adc_ts.c + * + * @brief Driver for the Freescale Semiconductor i.MX ADC touchscreen. + * + * This touchscreen driver is designed as a standard input driver. It is a + * wrapper around the low level ADC driver. Much of the hardware configuration + * and touchscreen functionality is implemented in the low level ADC driver. + * During initialization, this driver creates a kernel thread. This thread + * then calls the ADC driver to obtain touchscreen values continously. These + * values are then passed to the input susbsystem. + * + * @ingroup touchscreen + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define IMX_ADC_TS_NAME "imx_adc_ts" + +static struct input_dev *imx_inputdev; +static u32 input_ts_installed; + +static int ts_thread(void *arg) +{ + struct t_touch_screen ts_sample; + int wait = 0; + daemonize("imx_adc_ts"); + while (input_ts_installed) { + try_to_freeze(); + + memset(&ts_sample, 0, sizeof(ts_sample)); + if (0 != imx_adc_get_touch_sample(&ts_sample, !wait)) + continue; + + input_report_abs(imx_inputdev, ABS_X, ts_sample.x_position); + input_report_abs(imx_inputdev, ABS_Y, ts_sample.y_position); + input_report_abs(imx_inputdev, ABS_PRESSURE, + ts_sample.contact_resistance); + input_sync(imx_inputdev); + wait = ts_sample.contact_resistance; + msleep(10); + } + + return 0; +} + +static int __init imx_adc_ts_init(void) +{ + int retval; + + if (!is_imx_adc_ready()) + return -ENODEV; + + imx_inputdev = input_allocate_device(); + if (!imx_inputdev) { + pr_err("imx_ts_init: not enough memory for input device\n"); + return -ENOMEM; + } + + imx_inputdev->name = IMX_ADC_TS_NAME; + imx_inputdev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS); + imx_inputdev->keybit[BIT_WORD(BTN_TOUCH)] |= BIT_MASK(BTN_TOUCH); + imx_inputdev->absbit[0] = + BIT_MASK(ABS_X) | BIT_MASK(ABS_Y) | BIT_MASK(ABS_PRESSURE); + retval = input_register_device(imx_inputdev); + if (retval < 0) { + input_free_device(imx_inputdev); + return retval; + } + + input_ts_installed = 1; + kthread_run(ts_thread, NULL, "ts_thread"); + pr_info("i.MX ADC input touchscreen loaded.\n"); + return 0; +} + +static void __exit imx_adc_ts_exit(void) +{ + input_ts_installed = 0; + input_unregister_device(imx_inputdev); + + if (imx_inputdev) { + input_free_device(imx_inputdev); + imx_inputdev = NULL; + } +} + +late_initcall(imx_adc_ts_init); +module_exit(imx_adc_ts_exit); + +MODULE_DESCRIPTION("i.MX ADC input touchscreen driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/input/touchscreen/mxc_ts.c b/drivers/input/touchscreen/mxc_ts.c new file mode 100644 index 000000000000..0783188e8376 --- /dev/null +++ b/drivers/input/touchscreen/mxc_ts.c @@ -0,0 +1,189 @@ +/* + * Freescale touchscreen driver + * + * Copyright (C) 2007-2010 Freescale Semiconductor, Inc. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +/*! + * @file mxc_ts.c + * + * @brief Driver for the Freescale Semiconductor MXC touchscreen with calibration support. + * + * The touchscreen driver is designed as a standard input driver which is a + * wrapper over low level PMIC driver. Most of the hardware configuration and + * touchscreen functionality is implemented in the low level PMIC driver. During + * initialization, this driver creates a kernel thread. This thread then calls + * PMIC driver to obtain touchscreen values continously. These values are then + * passed to the input susbsystem. + * + * @ingroup touchscreen + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MXC_TS_NAME "mxc_ts" + +static struct input_dev *mxc_inputdev; +static struct task_struct *tstask; +/** + * calibration array refers to + * (delta_x[0], delta_x[1], delta_x[2], delta_y[0], delta_y[1], delta_y[2], delta). + * Which generated by calibration service. + * In this driver when we got touch pointer (x', y') from PMIC ADC, + * we calculate the display pointer (x,y) by: + * x = (delta_x[0] * x' + delta_x[1] * y' + delta_x[2]) / delta; + * y = (delta_y[0] * x' + delta_y[1] * y' + delta_y[2]) / delta; + */ +static int calibration[7]; +module_param_array(calibration, int, NULL, S_IRUGO | S_IWUSR); + +static int ts_thread(void *arg) +{ + t_touch_screen ts_sample; + s32 wait = 0; + + do { + int x, y; + static int last_x = -1, last_y = -1, last_press = -1; + + memset(&ts_sample, 0, sizeof(t_touch_screen)); + if (0 != pmic_adc_get_touch_sample(&ts_sample, !wait)) + continue; + if (!(ts_sample.contact_resistance || wait)) + continue; + + if (ts_sample.x_position == 0 && ts_sample.y_position == 0 && + ts_sample.contact_resistance == 0) { + x = last_x; + y = last_y; + } else if (calibration[6] == 0) { + x = ts_sample.x_position; + y = ts_sample.y_position; + } else { + x = calibration[0] * (int)ts_sample.x_position + + calibration[1] * (int)ts_sample.y_position + + calibration[2]; + x /= calibration[6]; + if (x < 0) + x = 0; + y = calibration[3] * (int)ts_sample.x_position + + calibration[4] * (int)ts_sample.y_position + + calibration[5]; + y /= calibration[6]; + if (y < 0) + y = 0; + } + + if (x != last_x) { + input_report_abs(mxc_inputdev, ABS_X, x); + last_x = x; + } + if (y != last_y) { + input_report_abs(mxc_inputdev, ABS_Y, y); + last_y = y; + } + + /* report pressure */ + input_report_abs(mxc_inputdev, ABS_PRESSURE, + ts_sample.contact_resistance); +#ifdef CONFIG_MXC_PMIC_MC13892 + /* workaround for aplite ADC resistance large range value */ + if (ts_sample.contact_resistance > 22) + ts_sample.contact_resistance = 1; + else + ts_sample.contact_resistance = 0; +#endif + /* report the BTN_TOUCH */ + if (ts_sample.contact_resistance != last_press) + input_event(mxc_inputdev, EV_KEY, + BTN_TOUCH, ts_sample.contact_resistance); + + input_sync(mxc_inputdev); + last_press = ts_sample.contact_resistance; + + wait = ts_sample.contact_resistance; + msleep(20); + + } while (!kthread_should_stop()); + + return 0; +} + +static int __init mxc_ts_init(void) +{ + int retval; + + if (!is_pmic_adc_ready()) + return -ENODEV; + + mxc_inputdev = input_allocate_device(); + if (!mxc_inputdev) { + printk(KERN_ERR + "mxc_ts_init: not enough memory\n"); + return -ENOMEM; + } + + mxc_inputdev->name = MXC_TS_NAME; + mxc_inputdev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS); + mxc_inputdev->keybit[BIT_WORD(BTN_TOUCH)] |= BIT_MASK(BTN_TOUCH); + mxc_inputdev->absbit[0] = + BIT_MASK(ABS_X) | BIT_MASK(ABS_Y) | BIT_MASK(ABS_PRESSURE); + retval = input_register_device(mxc_inputdev); + if (retval < 0) { + input_free_device(mxc_inputdev); + return retval; + } + + tstask = kthread_run(ts_thread, NULL, "mxc_ts"); + if (IS_ERR(tstask)) { + printk(KERN_ERR + "mxc_ts_init: failed to create kthread"); + tstask = NULL; + return -1; + } + printk("mxc input touchscreen loaded\n"); + return 0; +} + +static void __exit mxc_ts_exit(void) +{ + if (tstask) + kthread_stop(tstask); + + input_unregister_device(mxc_inputdev); + + if (mxc_inputdev) { + input_free_device(mxc_inputdev); + mxc_inputdev = NULL; + } +} + +late_initcall(mxc_ts_init); +module_exit(mxc_ts_exit); + +MODULE_DESCRIPTION("MXC touchscreen driver with calibration"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/input/touchscreen/mxs-ts.c b/drivers/input/touchscreen/mxs-ts.c new file mode 100644 index 000000000000..1d380ac1d67a --- /dev/null +++ b/drivers/input/touchscreen/mxs-ts.c @@ -0,0 +1,463 @@ +/* + * Freesclae MXS Touchscreen driver + * + * Author: Vitaly Wool + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. + * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#define TOUCH_DEBOUNCE_TOLERANCE 100 + +struct mxs_ts_info { + int touch_irq; + int device_irq; + unsigned int base; + u8 x_plus_chan; + u8 x_minus_chan; + u8 y_plus_chan; + u8 y_minus_chan; + + unsigned int x_plus_val; + unsigned int x_minus_val; + unsigned int y_plus_val; + unsigned int y_minus_val; + unsigned int x_plus_mask; + unsigned int x_minus_mask; + unsigned int y_plus_mask; + unsigned int y_minus_mask; + + struct input_dev *idev; + enum { + TS_STATE_DISABLED, + TS_STATE_TOUCH_DETECT, + TS_STATE_TOUCH_VERIFY, + TS_STATE_X_PLANE, + TS_STATE_Y_PLANE, + } state; + u16 x; + u16 y; + int sample_count; +}; + +static inline void enter_state_touch_detect(struct mxs_ts_info *info) +{ + __raw_writel(0xFFFFFFFF, + info->base + HW_LRADC_CHn_CLR(info->x_plus_chan)); + __raw_writel(0xFFFFFFFF, + info->base + HW_LRADC_CHn_CLR(info->y_plus_chan)); + __raw_writel(0xFFFFFFFF, + info->base + HW_LRADC_CHn_CLR(info->x_minus_chan)); + __raw_writel(0xFFFFFFFF, + info->base + HW_LRADC_CHn_CLR(info->y_minus_chan)); + + __raw_writel(BM_LRADC_CTRL1_LRADC0_IRQ << info->y_minus_chan, + info->base + HW_LRADC_CTRL1_CLR); + __raw_writel(BM_LRADC_CTRL1_TOUCH_DETECT_IRQ, + info->base + HW_LRADC_CTRL1_CLR); + /* + * turn off the yplus and yminus pullup and pulldown, and turn off touch + * detect (enables yminus, and xplus through a resistor.On a press, + * xplus is pulled down) + */ + __raw_writel(info->y_plus_mask, info->base + HW_LRADC_CTRL0_CLR); + __raw_writel(info->y_minus_mask, info->base + HW_LRADC_CTRL0_CLR); + __raw_writel(info->x_plus_mask, info->base + HW_LRADC_CTRL0_CLR); + __raw_writel(info->x_minus_mask, info->base + HW_LRADC_CTRL0_CLR); + __raw_writel(BM_LRADC_CTRL0_TOUCH_DETECT_ENABLE, + info->base + HW_LRADC_CTRL0_SET); + hw_lradc_set_delay_trigger_kick(LRADC_DELAY_TRIGGER_TOUCHSCREEN, 0); + info->state = TS_STATE_TOUCH_DETECT; + info->sample_count = 0; +} + +static inline void enter_state_disabled(struct mxs_ts_info *info) +{ + __raw_writel(info->y_plus_mask, info->base + HW_LRADC_CTRL0_CLR); + __raw_writel(info->y_minus_mask, info->base + HW_LRADC_CTRL0_CLR); + __raw_writel(info->x_plus_mask, info->base + HW_LRADC_CTRL0_CLR); + __raw_writel(info->x_minus_mask, info->base + HW_LRADC_CTRL0_CLR); + __raw_writel(BM_LRADC_CTRL0_TOUCH_DETECT_ENABLE, + info->base + HW_LRADC_CTRL0_CLR); + hw_lradc_set_delay_trigger_kick(LRADC_DELAY_TRIGGER_TOUCHSCREEN, 0); + info->state = TS_STATE_DISABLED; + info->sample_count = 0; +} + + +static inline void enter_state_x_plane(struct mxs_ts_info *info) +{ + __raw_writel(info->y_plus_val, info->base + HW_LRADC_CTRL0_SET); + __raw_writel(info->y_minus_val, info->base + HW_LRADC_CTRL0_SET); + __raw_writel(info->x_plus_mask, info->base + HW_LRADC_CTRL0_CLR); + __raw_writel(info->x_minus_mask, info->base + HW_LRADC_CTRL0_CLR); + __raw_writel(BM_LRADC_CTRL0_TOUCH_DETECT_ENABLE, + info->base + HW_LRADC_CTRL0_CLR); + hw_lradc_set_delay_trigger_kick(LRADC_DELAY_TRIGGER_TOUCHSCREEN, 1); + + info->state = TS_STATE_X_PLANE; + info->sample_count = 0; +} + +static inline void enter_state_y_plane(struct mxs_ts_info *info) +{ + __raw_writel(info->y_plus_mask, info->base + HW_LRADC_CTRL0_CLR); + __raw_writel(info->y_minus_mask, info->base + HW_LRADC_CTRL0_CLR); + __raw_writel(info->x_plus_val, info->base + HW_LRADC_CTRL0_SET); + __raw_writel(info->x_minus_val, info->base + HW_LRADC_CTRL0_SET); + __raw_writel(BM_LRADC_CTRL0_TOUCH_DETECT_ENABLE, + info->base + HW_LRADC_CTRL0_CLR); + hw_lradc_set_delay_trigger_kick(LRADC_DELAY_TRIGGER_TOUCHSCREEN, 1); + info->state = TS_STATE_Y_PLANE; + info->sample_count = 0; +} + +static inline void enter_state_touch_verify(struct mxs_ts_info *info) +{ + __raw_writel(info->y_plus_mask, info->base + HW_LRADC_CTRL0_CLR); + __raw_writel(info->y_minus_mask, info->base + HW_LRADC_CTRL0_CLR); + __raw_writel(info->x_plus_mask, info->base + HW_LRADC_CTRL0_CLR); + __raw_writel(info->x_minus_mask, info->base + HW_LRADC_CTRL0_CLR); + __raw_writel(BM_LRADC_CTRL0_TOUCH_DETECT_ENABLE, + info->base + HW_LRADC_CTRL0_SET); + info->state = TS_STATE_TOUCH_VERIFY; + hw_lradc_set_delay_trigger_kick(LRADC_DELAY_TRIGGER_TOUCHSCREEN, 1); + info->sample_count = 0; +} + +static void process_lradc(struct mxs_ts_info *info, u16 x, u16 y, + int pressure) +{ + switch (info->state) { + case TS_STATE_X_PLANE: + pr_debug("%s: x plane state, sample_count %d\n", __func__, + info->sample_count); + if (info->sample_count < 2) { + info->x = x; + info->sample_count++; + } else { + if (abs(info->x - x) > TOUCH_DEBOUNCE_TOLERANCE) + info->sample_count = 1; + else { + u16 x_c = info->x * (info->sample_count - 1); + info->x = (x_c + x) / info->sample_count; + info->sample_count++; + } + } + if (info->sample_count > 4) + enter_state_y_plane(info); + else + hw_lradc_set_delay_trigger_kick( + LRADC_DELAY_TRIGGER_TOUCHSCREEN, 1); + break; + + case TS_STATE_Y_PLANE: + pr_debug("%s: y plane state, sample_count %d\n", __func__, + info->sample_count); + if (info->sample_count < 2) { + info->y = y; + info->sample_count++; + } else { + if (abs(info->y - y) > TOUCH_DEBOUNCE_TOLERANCE) + info->sample_count = 1; + else { + u16 y_c = info->y * (info->sample_count - 1); + info->y = (y_c + y) / info->sample_count; + info->sample_count++; + } + } + if (info->sample_count > 4) + enter_state_touch_verify(info); + else + hw_lradc_set_delay_trigger_kick( + LRADC_DELAY_TRIGGER_TOUCHSCREEN, 1); + break; + + case TS_STATE_TOUCH_VERIFY: + pr_debug("%s: touch verify state, sample_count %d\n", __func__, + info->sample_count); + pr_debug("%s: x %d, y %d\n", __func__, info->x, info->y); + input_report_abs(info->idev, ABS_X, info->x); + input_report_abs(info->idev, ABS_Y, info->y); + input_report_abs(info->idev, ABS_PRESSURE, pressure); + input_sync(info->idev); + /* fall through */ + case TS_STATE_TOUCH_DETECT: + pr_debug("%s: touch detect state, sample_count %d\n", __func__, + info->sample_count); + if (pressure) { + input_report_abs(info->idev, ABS_PRESSURE, pressure); + enter_state_x_plane(info); + hw_lradc_set_delay_trigger_kick( + LRADC_DELAY_TRIGGER_TOUCHSCREEN, 1); + } else + enter_state_touch_detect(info); + break; + + default: + printk(KERN_ERR "%s: unknown touchscreen state %d\n", __func__, + info->state); + } +} + +static irqreturn_t ts_handler(int irq, void *dev_id) +{ + struct mxs_ts_info *info = dev_id; + u16 x_plus, y_plus; + int pressure = 0; + + if (irq == info->touch_irq) + __raw_writel(BM_LRADC_CTRL1_TOUCH_DETECT_IRQ, + info->base + HW_LRADC_CTRL1_CLR); + else if (irq == info->device_irq) + __raw_writel(BM_LRADC_CTRL1_LRADC0_IRQ << info->y_minus_chan, + info->base + HW_LRADC_CTRL1_CLR); + + /* get x, y values */ + x_plus = __raw_readl(info->base + HW_LRADC_CHn(info->x_plus_chan)) & + BM_LRADC_CHn_VALUE; + y_plus = __raw_readl(info->base + HW_LRADC_CHn(info->y_plus_chan)) & + BM_LRADC_CHn_VALUE; + + /* pressed? */ + if (__raw_readl(info->base + HW_LRADC_STATUS) & + BM_LRADC_STATUS_TOUCH_DETECT_RAW) + pressure = 1; + + pr_debug("%s: irq %d, x_plus %d, y_plus %d, pressure %d\n", + __func__, irq, x_plus, y_plus, pressure); + + process_lradc(info, x_plus, y_plus, pressure); + + return IRQ_HANDLED; +} + +static int __devinit mxs_ts_probe(struct platform_device *pdev) +{ + struct input_dev *idev; + struct mxs_ts_info *info; + int ret = 0; + struct resource *res; + struct mxs_touchscreen_plat_data *plat_data; + + plat_data = (struct mxs_touchscreen_plat_data *)pdev->dev.platform_data; + if (plat_data == NULL) + return -ENODEV; + + idev = input_allocate_device(); + if (idev == NULL) + return -ENOMEM; + + info = kzalloc(sizeof(struct mxs_ts_info), GFP_KERNEL); + if (info == NULL) { + ret = -ENOMEM; + goto out_nomem_info; + } + + idev->name = "MXS touchscreen"; + idev->evbit[0] = BIT(EV_ABS); + input_set_abs_params(idev, ABS_X, 0, 0xFFF, 0, 0); + input_set_abs_params(idev, ABS_Y, 0, 0xFFF, 0, 0); + input_set_abs_params(idev, ABS_PRESSURE, 0, 1, 0, 0); + + ret = input_register_device(idev); + if (ret) + goto out_nomem; + + info->idev = idev; + info->x_plus_chan = plat_data->x_plus_chan; + info->x_minus_chan = plat_data->x_minus_chan; + info->y_plus_chan = plat_data->y_plus_chan; + info->y_minus_chan = plat_data->y_minus_chan; + info->x_plus_val = plat_data->x_plus_val; + info->x_minus_val = plat_data->x_minus_val; + info->y_plus_val = plat_data->y_plus_val; + info->y_minus_val = plat_data->y_minus_val; + info->x_plus_mask = plat_data->x_plus_mask; + info->x_minus_mask = plat_data->x_minus_mask; + info->y_plus_mask = plat_data->y_plus_mask; + info->y_minus_mask = plat_data->y_minus_mask; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!res) { + printk(KERN_ERR "%s: couldn't get MEM resource\n", __func__); + ret = -ENODEV; + goto out_nodev; + } + info->base = (unsigned int)IO_ADDRESS(res->start); + res = platform_get_resource(pdev, IORESOURCE_IRQ, 0); + if (!res) { + printk(KERN_ERR "%s: couldn't get IRQ resource\n", __func__); + ret = -ENODEV; + goto out_nodev; + } + info->touch_irq = res->start; + + res = platform_get_resource(pdev, IORESOURCE_IRQ, 1); + if (!res) { + printk(KERN_ERR "%s: couldn't get IRQ resource\n", __func__); + ret = -ENODEV; + goto out_nodev; + } + info->device_irq = res->start; + + ret = request_irq(info->touch_irq, ts_handler, IRQF_DISABLED, + "mxs_ts_touch", info); + if (ret) + goto out_nodev; + + ret = request_irq(info->device_irq, ts_handler, IRQF_DISABLED, + "mxs_ts_dev", info); + if (ret) { + free_irq(info->touch_irq, info); + goto out_nodev; + } + enter_state_touch_detect(info); + + hw_lradc_use_channel(info->x_plus_chan); + hw_lradc_use_channel(info->x_minus_chan); + hw_lradc_use_channel(info->y_plus_chan); + hw_lradc_use_channel(info->y_minus_chan); + hw_lradc_configure_channel(info->x_plus_chan, 0, 0, 0); + hw_lradc_configure_channel(info->x_minus_chan, 0, 0, 0); + hw_lradc_configure_channel(info->y_plus_chan, 0, 0, 0); + hw_lradc_configure_channel(info->y_minus_chan, 0, 0, 0); + + /* Clear the accumulator & NUM_SAMPLES for the channels */ + __raw_writel(0xFFFFFFFF, + info->base + HW_LRADC_CHn_CLR(info->x_plus_chan)); + __raw_writel(0xFFFFFFFF, + info->base + HW_LRADC_CHn_CLR(info->x_minus_chan)); + __raw_writel(0xFFFFFFFF, + info->base + HW_LRADC_CHn_CLR(info->y_plus_chan)); + __raw_writel(0xFFFFFFFF, + info->base + HW_LRADC_CHn_CLR(info->y_minus_chan)); + + hw_lradc_set_delay_trigger(LRADC_DELAY_TRIGGER_TOUCHSCREEN, + 0x3c, 0, 0, 8); + + __raw_writel(BM_LRADC_CTRL1_LRADC0_IRQ << info->y_minus_chan, + info->base + HW_LRADC_CTRL1_CLR); + __raw_writel(BM_LRADC_CTRL1_TOUCH_DETECT_IRQ, + info->base + HW_LRADC_CTRL1_CLR); + + __raw_writel(BM_LRADC_CTRL1_LRADC0_IRQ_EN << info->y_minus_chan, + info->base + HW_LRADC_CTRL1_SET); + __raw_writel(BM_LRADC_CTRL1_TOUCH_DETECT_IRQ_EN, + info->base + HW_LRADC_CTRL1_SET); + + platform_set_drvdata(pdev, info); + device_init_wakeup(&pdev->dev, 1); + goto out; + +out_nodev: + input_free_device(idev); +out_nomem: + kfree(info); +out_nomem_info: + kfree(idev); +out: + return ret; +} + +static int __devexit mxs_ts_remove(struct platform_device *pdev) +{ + struct mxs_ts_info *info = platform_get_drvdata(pdev); + + platform_set_drvdata(pdev, NULL); + + hw_lradc_unuse_channel(info->x_plus_chan); + hw_lradc_unuse_channel(info->x_minus_chan); + hw_lradc_unuse_channel(info->y_plus_chan); + hw_lradc_unuse_channel(info->y_minus_chan); + + __raw_writel(BM_LRADC_CTRL1_LRADC0_IRQ_EN << info->y_minus_chan, + info->base + HW_LRADC_CTRL1_CLR); + __raw_writel(BM_LRADC_CTRL1_TOUCH_DETECT_IRQ_EN, + info->base + HW_LRADC_CTRL1_CLR); + + free_irq(info->device_irq, info); + free_irq(info->touch_irq, info); + input_free_device(info->idev); + + enter_state_disabled(info); + kfree(info->idev); + kfree(info); + return 0; +} + +#ifdef CONFIG_PM +static int mxs_ts_suspend(struct platform_device *pdev, + pm_message_t state) +{ + struct mxs_ts_info *info = platform_get_drvdata(pdev); + + if (!device_may_wakeup(&pdev->dev)) { + hw_lradc_unuse_channel(info->x_plus_chan); + hw_lradc_unuse_channel(info->x_minus_chan); + hw_lradc_unuse_channel(info->y_plus_chan); + hw_lradc_unuse_channel(info->y_minus_chan); + } + return 0; +} + +static int mxs_ts_resume(struct platform_device *pdev) +{ + struct mxs_ts_info *info = platform_get_drvdata(pdev); + + if (!device_may_wakeup(&pdev->dev)) { + hw_lradc_use_channel(info->x_plus_chan); + hw_lradc_use_channel(info->x_minus_chan); + hw_lradc_use_channel(info->y_plus_chan); + hw_lradc_use_channel(info->y_minus_chan); + } + return 0; +} +#endif + +static struct platform_driver mxs_ts_driver = { + .probe = mxs_ts_probe, + .remove = __devexit_p(mxs_ts_remove), +#ifdef CONFIG_PM + .suspend = mxs_ts_suspend, + .resume = mxs_ts_resume, +#endif + .driver = { + .name = "mxs-ts", + }, +}; + +static int __init mxs_ts_init(void) +{ + return platform_driver_register(&mxs_ts_driver); +} + +static void __exit mxs_ts_exit(void) +{ + platform_driver_unregister(&mxs_ts_driver); +} + +module_init(mxs_ts_init); +module_exit(mxs_ts_exit); diff --git a/drivers/leds/Kconfig b/drivers/leds/Kconfig index 81bf25e67ce1..50590c770691 100644 --- a/drivers/leds/Kconfig +++ b/drivers/leds/Kconfig @@ -33,6 +33,17 @@ config LEDS_ATMEL_PWM This option enables support for LEDs driven using outputs of the dedicated PWM controller found on newer Atmel SOCs. +config LEDS_MXS + tristate "Support for PWM LEDs on MXS" + depends on LEDS_CLASS && ARCH_MXS + help + This option enables support for the LEDs connected to PWM + outputs on the Freescale MXS SOC. + +config LEDS_MC13892 + tristate "LED Support for mc13892 pmic" + depends on LEDS_CLASS && MXC_MC13892_LIGHT + config LEDS_LOCOMO tristate "LED Support for Locomo device" depends on SHARP_LOCOMO diff --git a/drivers/leds/Makefile b/drivers/leds/Makefile index 2493de499374..fd8042e113e2 100644 --- a/drivers/leds/Makefile +++ b/drivers/leds/Makefile @@ -8,6 +8,7 @@ obj-$(CONFIG_LEDS_TRIGGERS) += led-triggers.o obj-$(CONFIG_LEDS_88PM860X) += leds-88pm860x.o obj-$(CONFIG_LEDS_ATMEL_PWM) += leds-atmel-pwm.o obj-$(CONFIG_LEDS_BD2802) += leds-bd2802.o +obj-$(CONFIG_LEDS_MC13892) += leds-mc13892.o obj-$(CONFIG_LEDS_LOCOMO) += leds-locomo.o obj-$(CONFIG_LEDS_MIKROTIK_RB532) += leds-rb532.o obj-$(CONFIG_LEDS_S3C24XX) += leds-s3c24xx.o @@ -37,6 +38,7 @@ obj-$(CONFIG_LEDS_LT3593) += leds-lt3593.o obj-$(CONFIG_LEDS_ADP5520) += leds-adp5520.o obj-$(CONFIG_LEDS_DELL_NETBOOKS) += dell-led.o obj-$(CONFIG_LEDS_MC13783) += leds-mc13783.o +obj-$(CONFIG_LEDS_MXS) += leds-mxs-pwm.o # LED SPI Drivers obj-$(CONFIG_LEDS_DAC124S085) += leds-dac124s085.o diff --git a/drivers/leds/leds-mc13892.c b/drivers/leds/leds-mc13892.c new file mode 100644 index 000000000000..ec7ae4316b4d --- /dev/null +++ b/drivers/leds/leds-mc13892.c @@ -0,0 +1,153 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include + +static void mc13892_led_set(struct led_classdev *led_cdev, + enum led_brightness value) +{ + struct platform_device *dev = to_platform_device(led_cdev->dev->parent); + int led_ch; + + switch (dev->id) { + case 'r': + led_ch = LIT_RED; + break; + case 'g': + led_ch = LIT_GREEN; + break; + case 'b': + led_ch = LIT_BLUE; + break; + default: + return; + } + + /* set current with medium value, in case current is too large */ + mc13892_bklit_set_current(led_ch, LIT_CURR_12); + /* max duty cycle is 63, brightness needs to be divided by 4 */ + mc13892_bklit_set_dutycycle(led_ch, value / 4); + +} + +static int mc13892_led_remove(struct platform_device *dev) +{ + struct led_classdev *led_cdev = platform_get_drvdata(dev); + + led_classdev_unregister(led_cdev); + kfree(led_cdev->name); + kfree(led_cdev); + + return 0; +} + +#define LED_NAME_LEN 16 + +static int mc13892_led_probe(struct platform_device *dev) +{ + int ret; + struct led_classdev *led_cdev; + char *name; + + led_cdev = kzalloc(sizeof(struct led_classdev), GFP_KERNEL); + if (led_cdev == NULL) { + dev_err(&dev->dev, "No memory for device\n"); + return -ENOMEM; + } + name = kzalloc(LED_NAME_LEN, GFP_KERNEL); + if (name == NULL) { + dev_err(&dev->dev, "No memory for device\n"); + ret = -ENOMEM; + goto exit_err; + } + + strcpy(name, dev->name); + ret = strlen(dev->name); + if (ret > LED_NAME_LEN - 2) { + dev_err(&dev->dev, "led name is too long\n"); + goto exit_err1; + } + name[ret] = dev->id; + name[ret + 1] = '\0'; + led_cdev->name = name; + led_cdev->brightness_set = mc13892_led_set; + + ret = led_classdev_register(&dev->dev, led_cdev); + if (ret < 0) { + dev_err(&dev->dev, "led_classdev_register failed\n"); + goto exit_err1; + } + + platform_set_drvdata(dev, led_cdev); + + return 0; + exit_err1: + kfree(led_cdev->name); + exit_err: + kfree(led_cdev); + return ret; +} + +#ifdef CONFIG_PM +static int mc13892_led_suspend(struct platform_device *dev, pm_message_t state) +{ + struct led_classdev *led_cdev = platform_get_drvdata(dev); + + led_classdev_suspend(led_cdev); + return 0; +} + +static int mc13892_led_resume(struct platform_device *dev) +{ + struct led_classdev *led_cdev = platform_get_drvdata(dev); + + led_classdev_resume(led_cdev); + return 0; +} +#else +#define mc13892_led_suspend NULL +#define mc13892_led_resume NULL +#endif + +static struct platform_driver mc13892_led_driver = { + .probe = mc13892_led_probe, + .remove = mc13892_led_remove, + .suspend = mc13892_led_suspend, + .resume = mc13892_led_resume, + .driver = { + .name = "pmic_leds", + .owner = THIS_MODULE, + }, +}; + +static int __init mc13892_led_init(void) +{ + return platform_driver_register(&mc13892_led_driver); +} + +static void __exit mc13892_led_exit(void) +{ + platform_driver_unregister(&mc13892_led_driver); +} + +module_init(mc13892_led_init); +module_exit(mc13892_led_exit); + +MODULE_DESCRIPTION("Led driver for PMIC mc13892"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/leds/leds-mxs-pwm.c b/drivers/leds/leds-mxs-pwm.c new file mode 100644 index 000000000000..c76821770446 --- /dev/null +++ b/drivers/leds/leds-mxs-pwm.c @@ -0,0 +1,192 @@ +/* + * Freescale MXS PWM LED driver + * + * Author: Drew Benedetti + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. + * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + + +/* + * PWM enables are the lowest bits of HW_PWM_CTRL register + */ +#define BM_PWM_CTRL_PWM_ENABLE ((1<<(CONFIG_MXS_PWM_CHANNELS)) - 1) +#define BF_PWM_CTRL_PWM_ENABLE(n) ((1<<(n)) & BM_PWM_CTRL_PWM_ENABLE) + +#define BF_PWM_PERIODn_SETTINGS \ + (BF_PWM_PERIODn_CDIV(5) | /* divide by 64 */ \ + BF_PWM_PERIODn_INACTIVE_STATE(3) | /* low */ \ + BF_PWM_PERIODn_ACTIVE_STATE(2) | /* high */ \ + BF_PWM_PERIODn_PERIOD(LED_FULL)) /* 255 cycles */ + +struct mxs_pwm_leds { + struct clk *pwm_clk; + unsigned int base; + unsigned int led_num; + struct mxs_pwm_led *leds; +}; + +static struct mxs_pwm_leds leds; + +static void mxs_pwm_led_brightness_set(struct led_classdev *pled, + enum led_brightness value) +{ + struct mxs_pwm_led *pwm_led; + + pwm_led = container_of(pled, struct mxs_pwm_led, dev); + + if (pwm_led->pwm < CONFIG_MXS_PWM_CHANNELS) { + __raw_writel(BF_PWM_CTRL_PWM_ENABLE(pwm_led->pwm), + leds.base + HW_PWM_CTRL_CLR); + __raw_writel(BF_PWM_ACTIVEn_INACTIVE(LED_FULL) | + BF_PWM_ACTIVEn_ACTIVE(value), + leds.base + HW_PWM_ACTIVEn(pwm_led->pwm)); + __raw_writel(BF_PWM_PERIODn_SETTINGS, + leds.base + HW_PWM_PERIODn(pwm_led->pwm)); + __raw_writel(BF_PWM_CTRL_PWM_ENABLE(pwm_led->pwm), + leds.base + HW_PWM_CTRL_SET); + } +} + +static int __devinit mxs_pwm_led_probe(struct platform_device *pdev) +{ + struct mxs_pwm_leds_plat_data *plat_data; + struct resource *res; + struct led_classdev *led; + unsigned int pwmn; + int leds_in_use = 0, rc = 0; + int i; + + plat_data = (struct mxs_pwm_leds_plat_data *)pdev->dev.platform_data; + if (plat_data == NULL) + return -ENODEV; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (res == NULL) + return -ENODEV; + leds.base = (unsigned int)IO_ADDRESS(res->start); + + mxs_reset_block((void __iomem *)leds.base, 1); + + leds.led_num = plat_data->num; + if (leds.led_num <= 0 || leds.led_num > CONFIG_MXS_PWM_CHANNELS) + return -EFAULT; + leds.leds = plat_data->leds; + if (leds.leds == NULL) + return -EFAULT; + + leds.pwm_clk = clk_get(&pdev->dev, "pwm"); + if (IS_ERR(leds.pwm_clk)) { + rc = PTR_ERR(leds.pwm_clk); + return rc; + } + + clk_enable(leds.pwm_clk); + + for (i = 0; i < leds.led_num; i++) { + pwmn = leds.leds[i].pwm; + if (pwmn >= CONFIG_MXS_PWM_CHANNELS) { + dev_err(&pdev->dev, + "[led-pwm%d]:PWM %d doesn't exist\n", + i, pwmn); + continue; + } + led = &(leds.leds[i].dev); + led->name = leds.leds[i].name; + led->brightness = LED_HALF; + led->flags = 0; + led->brightness_set = mxs_pwm_led_brightness_set; + led->default_trigger = 0; + + rc = led_classdev_register(&pdev->dev, led); + if (rc < 0) { + dev_err(&pdev->dev, + "Unable to register LED device %d (err=%d)\n", + i, rc); + continue; + } + + leds_in_use++; + + /* Set default brightness */ + mxs_pwm_led_brightness_set(led, LED_HALF); + } + + if (leds_in_use == 0) { + dev_info(&pdev->dev, "No PWM LEDs available\n"); + clk_disable(leds.pwm_clk); + clk_put(leds.pwm_clk); + return -ENODEV; + } + return 0; +} + +static int __devexit mxs_pwm_led_remove(struct platform_device *pdev) +{ + int i; + unsigned int pwm; + for (i = 0; i < leds.led_num; i++) { + pwm = leds.leds[i].pwm; + __raw_writel(BF_PWM_CTRL_PWM_ENABLE(pwm), + leds.base + HW_PWM_CTRL_CLR); + __raw_writel(BF_PWM_ACTIVEn_INACTIVE(0) | + BF_PWM_ACTIVEn_ACTIVE(0), + leds.base + HW_PWM_ACTIVEn(pwm)); + __raw_writel(BF_PWM_PERIODn_SETTINGS, + leds.base + HW_PWM_PERIODn(pwm)); + led_classdev_unregister(&leds.leds[i].dev); + } + + clk_disable(leds.pwm_clk); + clk_put(leds.pwm_clk); + + return 0; +} + + +static struct platform_driver mxs_pwm_led_driver = { + .probe = mxs_pwm_led_probe, + .remove = __devexit_p(mxs_pwm_led_remove), + .driver = { + .name = "mxs-leds", + }, +}; + +static int __init mxs_pwm_led_init(void) +{ + return platform_driver_register(&mxs_pwm_led_driver); +} + +static void __exit mxs_pwm_led_exit(void) +{ + platform_driver_unregister(&mxs_pwm_led_driver); +} + +module_init(mxs_pwm_led_init); +module_exit(mxs_pwm_led_exit); + +MODULE_AUTHOR("Drew Benedetti "); +MODULE_DESCRIPTION("mxs PWM LED driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/media/video/Kconfig b/drivers/media/video/Kconfig index bdbc9d305419..e16083087e7e 100644 --- a/drivers/media/video/Kconfig +++ b/drivers/media/video/Kconfig @@ -678,6 +678,36 @@ config VIDEO_W9966 Check out for more information. +config VIDEO_MXC_CAMERA + tristate "MXC Video For Linux Camera" + depends on VIDEO_DEV && ARCH_MXC + default y + ---help--- + This is the video4linux2 capture driver based on MXC IPU/eMMA module. + +source "drivers/media/video/mxc/capture/Kconfig" + +config VIDEO_MXC_OUTPUT + tristate "MXC Video For Linux Video Output" + depends on VIDEO_DEV && ARCH_MXC + default y + ---help--- + This is the video4linux2 output driver based on MXC IPU/eMMA module. + +source "drivers/media/video/mxc/output/Kconfig" + +config VIDEO_MXS_PXP + tristate "MXS PxP" + depends on VIDEO_DEV && VIDEO_V4L2 && ARCH_MXS + select VIDEOBUF_DMA_CONTIG + ---help--- + This is a video4linux driver for the Freescale PxP + (Pixel Pipeline). This module supports output overlay of + the MXS framebuffer on a video stream. + + To compile this driver as a module, choose M here: the + module will be called pxp. + config VIDEO_CPIA tristate "CPiA Video For Linux (DEPRECATED)" depends on VIDEO_V4L1 diff --git a/drivers/media/video/Makefile b/drivers/media/video/Makefile index cc93859d3164..60a913a4baba 100644 --- a/drivers/media/video/Makefile +++ b/drivers/media/video/Makefile @@ -94,6 +94,11 @@ obj-$(CONFIG_VIDEO_W9966) += w9966.o obj-$(CONFIG_VIDEO_PMS) += pms.o obj-$(CONFIG_VIDEO_VINO) += vino.o obj-$(CONFIG_VIDEO_STRADIS) += stradis.o +obj-$(CONFIG_VIDEO_MXC_IPU_CAMERA) += mxc/capture/ +obj-$(CONFIG_VIDEO_MXC_CSI_CAMERA) += mxc/capture/ +obj-$(CONFIG_VIDEO_MXC_IPU_OUTPUT) += mxc/output/ +obj-$(CONFIG_VIDEO_MXC_IPUV1_WVGA_OUTPUT) += mxc/output/ +obj-$(CONFIG_VIDEO_MXS_PXP) += mxs_pxp.o obj-$(CONFIG_VIDEO_CPIA) += cpia.o obj-$(CONFIG_VIDEO_CPIA_PP) += cpia_pp.o obj-$(CONFIG_VIDEO_CPIA_USB) += cpia_usb.o diff --git a/drivers/media/video/mxc/capture/Kconfig b/drivers/media/video/mxc/capture/Kconfig new file mode 100644 index 000000000000..1b352afebd87 --- /dev/null +++ b/drivers/media/video/mxc/capture/Kconfig @@ -0,0 +1,123 @@ +if VIDEO_MXC_CAMERA + +menu "MXC Camera/V4L2 PRP Features support" +config VIDEO_MXC_IPU_CAMERA + bool + depends on VIDEO_MXC_CAMERA && MXC_IPU + default y + +config VIDEO_MXC_EMMA_CAMERA + tristate "MX27 eMMA support" + depends on VIDEO_MXC_CAMERA && MXC_EMMA && FB_MXC_SYNC_PANEL + select VIDEO_MXC_OPL + default y + +config VIDEO_MXC_CSI_CAMERA + tristate "MX25 CSI camera support" + depends on !VIDEO_MXC_EMMA_CAMERA + +config VIDEO_MXC_CSI_DMA + bool "CSI-DMA Still Image Capture support" + depends on VIDEO_MXC_EMMA_CAMERA + default n + ---help--- + Use CSI-DMA method instead of CSI-PrP link to capture still image. This allows + to use less physical contiguous memory to capture big resolution still image. But + with this method the CSC (Color Space Conversion) and resize are not supported. + If unsure, say N. + +choice + prompt "Select Camera/TV Decoder" + default MXC_CAMERA_OV3640 + depends on VIDEO_MXC_CAMERA + +config MXC_CAMERA_MC521DA + tristate "Magnachip mc521da camera support" + select I2C_MXC + depends on VIDEO_MXC_EMMA_CAMERA + ---help--- + If you plan to use the mc521da Camera with your MXC system, say Y here. + +config MXC_EMMA_CAMERA_MICRON111 + tristate "Micron mt9v111 camera support with eMMA" + select I2C_MXC + depends on VIDEO_MXC_EMMA_CAMERA + ---help--- + If you plan to use the mt9v111 Camera with your MXC system, say Y here. + +config MXC_CAMERA_OV2640_EMMA + tristate "OmniVision ov2640 camera support with eMMA" + depends on VIDEO_MXC_EMMA_CAMERA + ---help--- + If you plan to use the ov2640 Camera with your MXC system, say Y here. + +config MXC_CAMERA_MICRON111 + tristate "Micron mt9v111 camera support" + select I2C_MXC + depends on ! VIDEO_MXC_EMMA_CAMERA + ---help--- + If you plan to use the mt9v111 Camera with your MXC system, say Y here. + +config MXC_CAMERA_OV2640 + tristate "OmniVision ov2640 camera support" + depends on !VIDEO_MXC_EMMA_CAMERA + ---help--- + If you plan to use the ov2640 Camera with your MXC system, say Y here. + +config MXC_CAMERA_OV3640 + tristate "OmniVision ov3640 camera support" + depends on !VIDEO_MXC_EMMA_CAMERA + ---help--- + If you plan to use the ov3640 Camera with your MXC system, say Y here. + +config MXC_TVIN_ADV7180 + tristate "Analog Device adv7180 TV Decoder Input support" + depends on (MACH_MX35_3DS || MACH_MX51_3DS) + ---help--- + If you plan to use the adv7180 video decoder with your MXC system, say Y here. + +endchoice + +config MXC_IPU_PRP_VF_SDC + tristate "Pre-Processor VF SDC library" + depends on VIDEO_MXC_IPU_CAMERA && FB_MXC_SYNC_PANEL + default y + ---help--- + Use case PRP_VF_SDC: + Preprocessing image from smart sensor for viewfinder and + displaying it on synchronous display with SDC use case. + If SDC BG is selected, Rotation will not be supported. + CSI -> IC (PRP VF) -> MEM + MEM -> IC (ROT) -> MEM + MEM -> SDC (FG/BG) + +config MXC_IPU_PRP_VF_ADC + tristate "Pre-Processor VF ADC library" + depends on VIDEO_MXC_IPU_CAMERA && FB_MXC_ASYNC_PANEL + default y + ---help--- + Use case PRP_VF_ADC: + Preprocessing image from smart sensor for viewfinder and + displaying it on asynchronous display. + CSI -> IC (PRP VF) -> ADC2 + +config MXC_IPU_PRP_ENC + tristate "Pre-processor Encoder library" + depends on VIDEO_MXC_IPU_CAMERA + default y + ---help--- + Use case PRP_ENC: + Preprocessing image from smart sensor for encoder. + CSI -> IC (PRP ENC) -> MEM + +config MXC_IPU_CSI_ENC + tristate "IPU CSI Encoder library" + depends on VIDEO_MXC_IPU_CAMERA + default y + ---help--- + Use case IPU_CSI_ENC: + Get raw image with CSI from smart sensor for encoder. + CSI -> MEM +endmenu + +endif diff --git a/drivers/media/video/mxc/capture/Makefile b/drivers/media/video/mxc/capture/Makefile new file mode 100644 index 000000000000..03ff094171bf --- /dev/null +++ b/drivers/media/video/mxc/capture/Makefile @@ -0,0 +1,39 @@ +ifeq ($(CONFIG_VIDEO_MXC_IPU_CAMERA),y) + obj-$(CONFIG_VIDEO_MXC_CAMERA) += mxc_v4l2_capture.o + obj-$(CONFIG_MXC_IPU_PRP_VF_ADC) += ipu_prp_vf_adc.o + obj-$(CONFIG_MXC_IPU_PRP_VF_SDC) += ipu_prp_vf_sdc.o ipu_prp_vf_sdc_bg.o + obj-$(CONFIG_MXC_IPU_PRP_ENC) += ipu_prp_enc.o ipu_still.o + obj-$(CONFIG_MXC_IPU_CSI_ENC) += ipu_csi_enc.o ipu_still.o +endif + +obj-$(CONFIG_VIDEO_MXC_CSI_CAMERA) += fsl_csi.o csi_v4l2_capture.o + +mx27_capture-objs := mx27_prphw.o mx27_prpsw.o emma_v4l2_capture.o +obj-$(CONFIG_VIDEO_MXC_EMMA_CAMERA) += mx27_csi.o mx27_capture.o + +mc521da_camera-objs := mc521da.o sensor_clock.o +obj-$(CONFIG_MXC_CAMERA_MC521DA) += mc521da_camera.o + +emma_mt9v111_camera-objs := emma_mt9v111.o sensor_clock.o +obj-$(CONFIG_MXC_EMMA_CAMERA_MICRON111) += emma_mt9v111_camera.o + +mt9v111_camera-objs := mt9v111.o sensor_clock.o +obj-$(CONFIG_MXC_CAMERA_MICRON111) += mt9v111_camera.o + +hv7161_camera-objs := hv7161.o sensor_clock.o +obj-$(CONFIG_MXC_CAMERA_HV7161) += hv7161_camera.o + +s5k3aaex_camera-objs := s5k3aaex.o sensor_clock.o +obj-$(CONFIG_MXC_CAMERA_S5K3AAEX) += s5k3aaex_camera.o + +emma_ov2640_camera-objs := emma_ov2640.o sensor_clock.o +obj-$(CONFIG_MXC_CAMERA_OV2640_EMMA) += emma_ov2640_camera.o + +ov2640_camera-objs := ov2640.o sensor_clock.o +obj-$(CONFIG_MXC_CAMERA_OV2640) += ov2640_camera.o + +ov3640_camera-objs := ov3640.o sensor_clock.o +obj-$(CONFIG_MXC_CAMERA_OV3640) += ov3640_camera.o + +adv7180_tvin-objs := adv7180.o +obj-$(CONFIG_MXC_TVIN_ADV7180) += adv7180_tvin.o diff --git a/drivers/media/video/mxc/capture/adv7180.c b/drivers/media/video/mxc/capture/adv7180.c new file mode 100644 index 000000000000..4cbc44518725 --- /dev/null +++ b/drivers/media/video/mxc/capture/adv7180.c @@ -0,0 +1,1001 @@ +/* + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file adv7180.c + * + * @brief Analog Device ADV7180 video decoder functions + * + * @ingroup Camera + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "mxc_v4l2_capture.h" + +static struct regulator *dvddio_regulator; +static struct regulator *dvdd_regulator; +static struct regulator *avdd_regulator; +static struct regulator *pvdd_regulator; +static struct mxc_tvin_platform_data *tvin_plat; + +extern void gpio_sensor_active(void); +extern void gpio_sensor_inactive(void); + +static int adv7180_probe(struct i2c_client *adapter, + const struct i2c_device_id *id); +static int adv7180_detach(struct i2c_client *client); + +static const struct i2c_device_id adv7180_id[] = { + {"adv7180", 0}, + {}, +}; + +MODULE_DEVICE_TABLE(i2c, adv7180_id); + +static struct i2c_driver adv7180_i2c_driver = { + .driver = { + .owner = THIS_MODULE, + .name = "adv7180", + }, + .probe = adv7180_probe, + .remove = adv7180_detach, + .id_table = adv7180_id, +}; + +/*! + * Maintains the information on the current state of the sesor. + */ +struct sensor { + struct v4l2_int_device *v4l2_int_device; + struct i2c_client *i2c_client; + struct v4l2_pix_format pix; + struct v4l2_captureparm streamcap; + bool on; + + /* control settings */ + int brightness; + int hue; + int contrast; + int saturation; + int red; + int green; + int blue; + int ae_mode; + + v4l2_std_id std_id; +} adv7180_data; + +/*! List of input video formats supported. The video formats is corresponding + * with v4l2 id in video_fmt_t + */ +typedef enum { + ADV7180_NTSC = 0, /*!< Locked on (M) NTSC video signal. */ + ADV7180_PAL, /*!< (B, G, H, I, N)PAL video signal. */ + ADV7180_NOT_LOCKED, /*!< Not locked on a signal. */ +} video_fmt_idx; + +/*! Number of video standards supported (including 'not locked' signal). */ +#define ADV7180_STD_MAX (ADV7180_PAL + 1) + +/*! Video format structure. */ +typedef struct { + int v4l2_id; /*!< Video for linux ID. */ + char name[16]; /*!< Name (e.g., "NTSC", "PAL", etc.) */ + u16 raw_width; /*!< Raw width. */ + u16 raw_height; /*!< Raw height. */ + u16 active_width; /*!< Active width. */ + u16 active_height; /*!< Active height. */ +} video_fmt_t; + +/*! Description of video formats supported. + * + * PAL: raw=720x625, active=720x576. + * NTSC: raw=720x525, active=720x480. + */ +static video_fmt_t video_fmts[] = { + { /*! NTSC */ + .v4l2_id = V4L2_STD_NTSC, + .name = "NTSC", + .raw_width = 720, /* SENS_FRM_WIDTH */ + .raw_height = 525, /* SENS_FRM_HEIGHT */ + .active_width = 720, /* ACT_FRM_WIDTH plus 1 */ + .active_height = 480, /* ACT_FRM_WIDTH plus 1 */ + }, + { /*! (B, G, H, I, N) PAL */ + .v4l2_id = V4L2_STD_PAL, + .name = "PAL", + .raw_width = 720, + .raw_height = 625, + .active_width = 720, + .active_height = 576, + }, + { /*! Unlocked standard */ + .v4l2_id = V4L2_STD_ALL, + .name = "Autodetect", + .raw_width = 720, + .raw_height = 625, + .active_width = 720, + .active_height = 576, + }, +}; + +/*!* Standard index of ADV7180. */ +static video_fmt_idx video_idx = ADV7180_PAL; + +/*! @brief This mutex is used to provide mutual exclusion. + * + * Create a mutex that can be used to provide mutually exclusive + * read/write access to the globally accessible data structures + * and variables that were defined above. + */ +static DECLARE_MUTEX(mutex); + +#define IF_NAME "adv7180" +#define ADV7180_INPUT_CTL 0x00 /* Input Control */ +#define ADV7180_STATUS_1 0x10 /* Status #1 */ +#define ADV7180_BRIGHTNESS 0x0a /* Brightness */ +#define ADV7180_IDENT 0x11 /* IDENT */ +#define ADV7180_VSYNC_FIELD_CTL_1 0x31 /* VSYNC Field Control #1 */ +#define ADV7180_MANUAL_WIN_CTL 0x3d /* Manual Window Control */ +#define ADV7180_SD_SATURATION_CB 0xe3 /* SD Saturation Cb */ +#define ADV7180_SD_SATURATION_CR 0xe4 /* SD Saturation Cr */ +#define ADV7180_PWR_MNG 0x0f /* Power Management */ + +/* supported controls */ +/* This hasn't been fully implemented yet. + * This is how it should work, though. */ +static struct v4l2_queryctrl adv7180_qctrl[] = { + { + .id = V4L2_CID_BRIGHTNESS, + .type = V4L2_CTRL_TYPE_INTEGER, + .name = "Brightness", + .minimum = 0, /* check this value */ + .maximum = 255, /* check this value */ + .step = 1, /* check this value */ + .default_value = 127, /* check this value */ + .flags = 0, + }, { + .id = V4L2_CID_SATURATION, + .type = V4L2_CTRL_TYPE_INTEGER, + .name = "Saturation", + .minimum = 0, /* check this value */ + .maximum = 255, /* check this value */ + .step = 0x1, /* check this value */ + .default_value = 127, /* check this value */ + .flags = 0, + } +}; + +/*********************************************************************** + * I2C transfert. + ***********************************************************************/ + +/*! Read one register from a ADV7180 i2c slave device. + * + * @param *reg register in the device we wish to access. + * + * @return 0 if success, an error code otherwise. + */ +static inline int adv7180_read(u8 reg) +{ + int val; + val = i2c_smbus_read_byte_data(adv7180_data.i2c_client, reg); + if (val < 0) { + dev_dbg(&adv7180_data.i2c_client->dev, + "%s:read reg error: reg=%2x \n", __func__, reg); + return -1; + } + return val; +} + +/*! Write one register of a ADV7180 i2c slave device. + * + * @param *reg register in the device we wish to access. + * + * @return 0 if success, an error code otherwise. + */ +static int adv7180_write_reg(u8 reg, u8 val) +{ + if (i2c_smbus_write_byte_data(adv7180_data.i2c_client, reg, val) < 0) { + dev_dbg(&adv7180_data.i2c_client->dev, + "%s:write reg error:reg=%2x,val=%2x\n", __func__, + reg, val); + return -1; + } + return 0; +} + +/*********************************************************************** + * mxc_v4l2_capture interface. + ***********************************************************************/ + +/*! + * Return attributes of current video standard. + * Since this device autodetects the current standard, this function also + * sets the values that need to be changed if the standard changes. + * There is no set std equivalent function. + * + * @return None. + */ +static void adv7180_get_std(v4l2_std_id *std) +{ + int tmp; + int idx; + + dev_dbg(&adv7180_data.i2c_client->dev, "In adv7180_get_std\n"); + + /* Make sure power on */ + if (tvin_plat->pwdn) + tvin_plat->pwdn(0); + + /* Read the AD_RESULT to get the detect output video standard */ + tmp = adv7180_read(ADV7180_STATUS_1) & 0x70; + + down(&mutex); + if (tmp == 0x40) { + /* PAL */ + *std = V4L2_STD_PAL; + idx = ADV7180_PAL; + } else if (tmp == 0) { + /*NTSC*/ + *std = V4L2_STD_NTSC; + idx = ADV7180_NTSC; + } else { + *std = V4L2_STD_ALL; + idx = ADV7180_NOT_LOCKED; + dev_dbg(&adv7180_data.i2c_client->dev, + "Got invalid video standard! \n"); + } + up(&mutex); + + /* This assumes autodetect which this device uses. */ + if (*std != adv7180_data.std_id) { + video_idx = idx; + adv7180_data.std_id = *std; + adv7180_data.pix.width = video_fmts[video_idx].raw_width; + adv7180_data.pix.height = video_fmts[video_idx].raw_height; + } +} + +/*********************************************************************** + * IOCTL Functions from v4l2_int_ioctl_desc. + ***********************************************************************/ + +/*! + * ioctl_g_ifparm - V4L2 sensor interface handler for vidioc_int_g_ifparm_num + * s: pointer to standard V4L2 device structure + * p: pointer to standard V4L2 vidioc_int_g_ifparm_num ioctl structure + * + * Gets slave interface parameters. + * Calculates the required xclk value to support the requested + * clock parameters in p. This value is returned in the p + * parameter. + * + * vidioc_int_g_ifparm returns platform-specific information about the + * interface settings used by the sensor. + * + * Called on open. + */ +static int ioctl_g_ifparm(struct v4l2_int_device *s, struct v4l2_ifparm *p) +{ + dev_dbg(&adv7180_data.i2c_client->dev, "In adv7180:ioctl_g_ifparm\n"); + + if (s == NULL) { + pr_err(" ERROR!! no slave device set!\n"); + return -1; + } + + /* Initialize structure to 0s then set any non-0 values. */ + memset(p, 0, sizeof(*p)); + p->if_type = V4L2_IF_TYPE_BT656; /* This is the only possibility. */ + p->u.bt656.mode = V4L2_IF_TYPE_BT656_MODE_NOBT_8BIT; + p->u.bt656.nobt_hs_inv = 1; + + /* ADV7180 has a dedicated clock so no clock settings needed. */ + + return 0; +} + +/*! + * Sets the camera power. + * + * s pointer to the camera device + * on if 1, power is to be turned on. 0 means power is to be turned off + * + * ioctl_s_power - V4L2 sensor interface handler for vidioc_int_s_power_num + * @s: pointer to standard V4L2 device structure + * @on: power state to which device is to be set + * + * Sets devices power state to requrested state, if possible. + * This is called on open, close, suspend and resume. + */ +static int ioctl_s_power(struct v4l2_int_device *s, int on) +{ + struct sensor *sensor = s->priv; + + dev_dbg(&adv7180_data.i2c_client->dev, "In adv7180:ioctl_s_power\n"); + + if (on && !sensor->on) { + gpio_sensor_active(); + + /* Make sure pwoer on */ + if (tvin_plat->pwdn) + tvin_plat->pwdn(0); + + if (adv7180_write_reg(ADV7180_PWR_MNG, 0) != 0) + return -EIO; + } else if (!on && sensor->on) { + if (adv7180_write_reg(ADV7180_PWR_MNG, 0x24) != 0) + return -EIO; + gpio_sensor_inactive(); + } + + sensor->on = on; + + return 0; +} + +/*! + * ioctl_g_parm - V4L2 sensor interface handler for VIDIOC_G_PARM ioctl + * @s: pointer to standard V4L2 device structure + * @a: pointer to standard V4L2 VIDIOC_G_PARM ioctl structure + * + * Returns the sensor's video CAPTURE parameters. + */ +static int ioctl_g_parm(struct v4l2_int_device *s, struct v4l2_streamparm *a) +{ + struct sensor *sensor = s->priv; + struct v4l2_captureparm *cparm = &a->parm.capture; + + dev_dbg(&adv7180_data.i2c_client->dev, "In adv7180:ioctl_g_parm\n"); + + switch (a->type) { + /* These are all the possible cases. */ + case V4L2_BUF_TYPE_VIDEO_CAPTURE: + pr_debug(" type is V4L2_BUF_TYPE_VIDEO_CAPTURE\n"); + memset(a, 0, sizeof(*a)); + a->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + cparm->capability = sensor->streamcap.capability; + cparm->timeperframe = sensor->streamcap.timeperframe; + cparm->capturemode = sensor->streamcap.capturemode; + break; + + case V4L2_BUF_TYPE_VIDEO_OUTPUT: + case V4L2_BUF_TYPE_VIDEO_OVERLAY: + case V4L2_BUF_TYPE_VBI_CAPTURE: + case V4L2_BUF_TYPE_VBI_OUTPUT: + case V4L2_BUF_TYPE_SLICED_VBI_CAPTURE: + case V4L2_BUF_TYPE_SLICED_VBI_OUTPUT: + break; + + default: + pr_debug("ioctl_g_parm:type is unknown %d\n", a->type); + break; + } + + return 0; +} + +/*! + * ioctl_s_parm - V4L2 sensor interface handler for VIDIOC_S_PARM ioctl + * @s: pointer to standard V4L2 device structure + * @a: pointer to standard V4L2 VIDIOC_S_PARM ioctl structure + * + * Configures the sensor to use the input parameters, if possible. If + * not possible, reverts to the old parameters and returns the + * appropriate error code. + * + * This driver cannot change these settings. + */ +static int ioctl_s_parm(struct v4l2_int_device *s, struct v4l2_streamparm *a) +{ + dev_dbg(&adv7180_data.i2c_client->dev, "In adv7180:ioctl_s_parm\n"); + + switch (a->type) { + /* These are all the possible cases. */ + case V4L2_BUF_TYPE_VIDEO_CAPTURE: + case V4L2_BUF_TYPE_VIDEO_OUTPUT: + case V4L2_BUF_TYPE_VIDEO_OVERLAY: + case V4L2_BUF_TYPE_VBI_CAPTURE: + case V4L2_BUF_TYPE_VBI_OUTPUT: + case V4L2_BUF_TYPE_SLICED_VBI_CAPTURE: + case V4L2_BUF_TYPE_SLICED_VBI_OUTPUT: + break; + + default: + pr_debug(" type is unknown - %d\n", a->type); + break; + } + + return 0; +} + +/*! + * ioctl_g_fmt_cap - V4L2 sensor interface handler for ioctl_g_fmt_cap + * @s: pointer to standard V4L2 device structure + * @f: pointer to standard V4L2 v4l2_format structure + * + * Returns the sensor's current pixel format in the v4l2_format + * parameter. + */ +static int ioctl_g_fmt_cap(struct v4l2_int_device *s, struct v4l2_format *f) +{ + struct sensor *sensor = s->priv; + + dev_dbg(&adv7180_data.i2c_client->dev, "In adv7180:ioctl_g_fmt_cap\n"); + + switch (f->type) { + case V4L2_BUF_TYPE_VIDEO_CAPTURE: + pr_debug(" Returning size of %dx%d\n", + sensor->pix.width, sensor->pix.height); + f->fmt.pix = sensor->pix; + break; + + case V4L2_BUF_TYPE_PRIVATE: { + v4l2_std_id std; + adv7180_get_std(&std); + f->fmt.pix.pixelformat = (u32)std; + } + break; + + default: + f->fmt.pix = sensor->pix; + break; + } + + return 0; +} + +/*! + * ioctl_queryctrl - V4L2 sensor interface handler for VIDIOC_QUERYCTRL ioctl + * @s: pointer to standard V4L2 device structure + * @qc: standard V4L2 VIDIOC_QUERYCTRL ioctl structure + * + * If the requested control is supported, returns the control information + * from the video_control[] array. Otherwise, returns -EINVAL if the + * control is not supported. + */ +static int ioctl_queryctrl(struct v4l2_int_device *s, + struct v4l2_queryctrl *qc) +{ + int i; + + dev_dbg(&adv7180_data.i2c_client->dev, "In adv7180:ioctl_queryctrl\n"); + + for (i = 0; i < ARRAY_SIZE(adv7180_qctrl); i++) + if (qc->id && qc->id == adv7180_qctrl[i].id) { + memcpy(qc, &(adv7180_qctrl[i]), + sizeof(*qc)); + return 0; + } + + return -EINVAL; +} + +/*! + * ioctl_g_ctrl - V4L2 sensor interface handler for VIDIOC_G_CTRL ioctl + * @s: pointer to standard V4L2 device structure + * @vc: standard V4L2 VIDIOC_G_CTRL ioctl structure + * + * If the requested control is supported, returns the control's current + * value from the video_control[] array. Otherwise, returns -EINVAL + * if the control is not supported. + */ +static int ioctl_g_ctrl(struct v4l2_int_device *s, struct v4l2_control *vc) +{ + int ret = 0; + + dev_dbg(&adv7180_data.i2c_client->dev, "In adv7180:ioctl_g_ctrl\n"); + + /* Make sure power on */ + if (tvin_plat->pwdn) + tvin_plat->pwdn(0); + + switch (vc->id) { + case V4L2_CID_BRIGHTNESS: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_BRIGHTNESS\n"); + adv7180_data.brightness = adv7180_read(ADV7180_BRIGHTNESS); + vc->value = adv7180_data.brightness; + break; + case V4L2_CID_CONTRAST: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_CONTRAST\n"); + vc->value = adv7180_data.contrast; + break; + case V4L2_CID_SATURATION: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_SATURATION\n"); + adv7180_data.saturation = adv7180_read(ADV7180_SD_SATURATION_CB); + vc->value = adv7180_data.saturation; + break; + case V4L2_CID_HUE: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_HUE\n"); + vc->value = adv7180_data.hue; + break; + case V4L2_CID_AUTO_WHITE_BALANCE: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_AUTO_WHITE_BALANCE\n"); + break; + case V4L2_CID_DO_WHITE_BALANCE: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_DO_WHITE_BALANCE\n"); + break; + case V4L2_CID_RED_BALANCE: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_RED_BALANCE\n"); + vc->value = adv7180_data.red; + break; + case V4L2_CID_BLUE_BALANCE: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_BLUE_BALANCE\n"); + vc->value = adv7180_data.blue; + break; + case V4L2_CID_GAMMA: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_GAMMA\n"); + break; + case V4L2_CID_EXPOSURE: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_EXPOSURE\n"); + vc->value = adv7180_data.ae_mode; + break; + case V4L2_CID_AUTOGAIN: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_AUTOGAIN\n"); + break; + case V4L2_CID_GAIN: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_GAIN\n"); + break; + case V4L2_CID_HFLIP: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_HFLIP\n"); + break; + case V4L2_CID_VFLIP: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_VFLIP\n"); + break; + default: + dev_dbg(&adv7180_data.i2c_client->dev, + " Default case\n"); + vc->value = 0; + ret = -EPERM; + break; + } + + return ret; +} + +/*! + * ioctl_s_ctrl - V4L2 sensor interface handler for VIDIOC_S_CTRL ioctl + * @s: pointer to standard V4L2 device structure + * @vc: standard V4L2 VIDIOC_S_CTRL ioctl structure + * + * If the requested control is supported, sets the control's current + * value in HW (and updates the video_control[] array). Otherwise, + * returns -EINVAL if the control is not supported. + */ +static int ioctl_s_ctrl(struct v4l2_int_device *s, struct v4l2_control *vc) +{ + int retval = 0; + u8 tmp; + + dev_dbg(&adv7180_data.i2c_client->dev, "In adv7180:ioctl_s_ctrl\n"); + + /* Make sure power on */ + if (tvin_plat->pwdn) + tvin_plat->pwdn(0); + + switch (vc->id) { + case V4L2_CID_BRIGHTNESS: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_BRIGHTNESS\n"); + tmp = vc->value; + adv7180_write_reg(ADV7180_BRIGHTNESS, tmp); + adv7180_data.brightness = vc->value; + break; + case V4L2_CID_CONTRAST: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_CONTRAST\n"); + break; + case V4L2_CID_SATURATION: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_SATURATION\n"); + tmp = vc->value; + adv7180_write_reg(ADV7180_SD_SATURATION_CB, tmp); + adv7180_write_reg(ADV7180_SD_SATURATION_CR, tmp); + adv7180_data.saturation = vc->value; + break; + case V4L2_CID_HUE: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_HUE\n"); + break; + case V4L2_CID_AUTO_WHITE_BALANCE: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_AUTO_WHITE_BALANCE\n"); + break; + case V4L2_CID_DO_WHITE_BALANCE: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_DO_WHITE_BALANCE\n"); + break; + case V4L2_CID_RED_BALANCE: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_RED_BALANCE\n"); + break; + case V4L2_CID_BLUE_BALANCE: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_BLUE_BALANCE\n"); + break; + case V4L2_CID_GAMMA: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_GAMMA\n"); + break; + case V4L2_CID_EXPOSURE: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_EXPOSURE\n"); + break; + case V4L2_CID_AUTOGAIN: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_AUTOGAIN\n"); + break; + case V4L2_CID_GAIN: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_GAIN\n"); + break; + case V4L2_CID_HFLIP: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_HFLIP\n"); + break; + case V4L2_CID_VFLIP: + dev_dbg(&adv7180_data.i2c_client->dev, + " V4L2_CID_VFLIP\n"); + break; + default: + dev_dbg(&adv7180_data.i2c_client->dev, + " Default case\n"); + retval = -EPERM; + break; + } + + return retval; +} + +/*! + * ioctl_init - V4L2 sensor interface handler for VIDIOC_INT_INIT + * @s: pointer to standard V4L2 device structure + */ +static int ioctl_init(struct v4l2_int_device *s) +{ + dev_dbg(&adv7180_data.i2c_client->dev, "In adv7180:ioctl_init\n"); + return 0; +} + +/*! + * ioctl_dev_init - V4L2 sensor interface handler for vidioc_int_dev_init_num + * @s: pointer to standard V4L2 device structure + * + * Initialise the device when slave attaches to the master. + */ +static int ioctl_dev_init(struct v4l2_int_device *s) +{ + dev_dbg(&adv7180_data.i2c_client->dev, "In adv7180:ioctl_dev_init\n"); + return 0; +} + +/*! + * This structure defines all the ioctls for this module. + */ +static struct v4l2_int_ioctl_desc adv7180_ioctl_desc[] = { + + {vidioc_int_dev_init_num, (v4l2_int_ioctl_func*)ioctl_dev_init}, + + /*! + * Delinitialise the dev. at slave detach. + * The complement of ioctl_dev_init. + */ +/* {vidioc_int_dev_exit_num, (v4l2_int_ioctl_func *)ioctl_dev_exit}, */ + + {vidioc_int_s_power_num, (v4l2_int_ioctl_func*)ioctl_s_power}, + {vidioc_int_g_ifparm_num, (v4l2_int_ioctl_func*)ioctl_g_ifparm}, +/* {vidioc_int_g_needs_reset_num, + (v4l2_int_ioctl_func *)ioctl_g_needs_reset}, */ +/* {vidioc_int_reset_num, (v4l2_int_ioctl_func *)ioctl_reset}, */ + {vidioc_int_init_num, (v4l2_int_ioctl_func*)ioctl_init}, + + /*! + * VIDIOC_ENUM_FMT ioctl for the CAPTURE buffer type. + */ +/* {vidioc_int_enum_fmt_cap_num, + (v4l2_int_ioctl_func *)ioctl_enum_fmt_cap}, */ + + /*! + * VIDIOC_TRY_FMT ioctl for the CAPTURE buffer type. + * This ioctl is used to negotiate the image capture size and + * pixel format without actually making it take effect. + */ +/* {vidioc_int_try_fmt_cap_num, + (v4l2_int_ioctl_func *)ioctl_try_fmt_cap}, */ + + {vidioc_int_g_fmt_cap_num, (v4l2_int_ioctl_func*)ioctl_g_fmt_cap}, + + /*! + * If the requested format is supported, configures the HW to use that + * format, returns error code if format not supported or HW can't be + * correctly configured. + */ +/* {vidioc_int_s_fmt_cap_num, (v4l2_int_ioctl_func *)ioctl_s_fmt_cap}, */ + + {vidioc_int_g_parm_num, (v4l2_int_ioctl_func*)ioctl_g_parm}, + {vidioc_int_s_parm_num, (v4l2_int_ioctl_func*)ioctl_s_parm}, + {vidioc_int_queryctrl_num, (v4l2_int_ioctl_func*)ioctl_queryctrl}, + {vidioc_int_g_ctrl_num, (v4l2_int_ioctl_func*)ioctl_g_ctrl}, + {vidioc_int_s_ctrl_num, (v4l2_int_ioctl_func*)ioctl_s_ctrl}, +}; + +static struct v4l2_int_slave adv7180_slave = { + .ioctls = adv7180_ioctl_desc, + .num_ioctls = ARRAY_SIZE(adv7180_ioctl_desc), +}; + +static struct v4l2_int_device adv7180_int_device = { + .module = THIS_MODULE, + .name = "adv7180", + .type = v4l2_int_type_slave, + .u = { + .slave = &adv7180_slave, + }, +}; + + +/*********************************************************************** + * I2C client and driver. + ***********************************************************************/ + +/*! ADV7180 Reset function. + * + * @return None. + */ +static void adv7180_hard_reset(void) +{ + dev_dbg(&adv7180_data.i2c_client->dev, + "In adv7180:adv7180_hard_reset\n"); + + /*! Driver works fine without explicit register + * initialization. Furthermore, initializations takes about 2 seconds + * at startup... + */ + + /*! Set YPbPr input on AIN1,4,5 and normal + * operations(autodection of all stds). + */ + adv7180_write_reg(ADV7180_INPUT_CTL, 0x09); + + /*! Datasheet recommends: */ + adv7180_write_reg(ADV7180_VSYNC_FIELD_CTL_1, 0x02); + adv7180_write_reg(ADV7180_MANUAL_WIN_CTL, 0xa2); +} + +/*! ADV7180 I2C attach function. + * + * @param *adapter struct i2c_adapter *. + * + * @return Error code indicating success or failure. + */ + +/*! + * ADV7180 I2C probe function. + * Function set in i2c_driver struct. + * Called by insmod. + * + * @param *adapter I2C adapter descriptor. + * + * @return Error code indicating success or failure. + */ +static int adv7180_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + int rev_id; + int ret = 0; + tvin_plat = client->dev.platform_data; + + dev_dbg(&adv7180_data.i2c_client->dev, "In adv7180_probe\n"); + + if (tvin_plat->dvddio_reg) { + dvddio_regulator = + regulator_get(&client->dev, tvin_plat->dvddio_reg); + if (!IS_ERR_VALUE((unsigned long)dvddio_regulator)) { + regulator_set_voltage(dvddio_regulator, 3300000, 3300000); + if (regulator_enable(dvddio_regulator) != 0) + return -ENODEV; + } + } + + if (tvin_plat->dvdd_reg) { + dvdd_regulator = + regulator_get(&client->dev, tvin_plat->dvdd_reg); + if (!IS_ERR_VALUE((unsigned long)dvdd_regulator)) { + regulator_set_voltage(dvdd_regulator, 1800000, 1800000); + if (regulator_enable(dvdd_regulator) != 0) + return -ENODEV; + } + } + + if (tvin_plat->avdd_reg) { + avdd_regulator = + regulator_get(&client->dev, tvin_plat->avdd_reg); + if (!IS_ERR_VALUE((unsigned long)avdd_regulator)) { + regulator_set_voltage(avdd_regulator, 1800000, 1800000); + if (regulator_enable(avdd_regulator) != 0) + return -ENODEV; + } + } + + if (tvin_plat->pvdd_reg) { + pvdd_regulator = + regulator_get(&client->dev, tvin_plat->pvdd_reg); + if (!IS_ERR_VALUE((unsigned long)pvdd_regulator)) { + regulator_set_voltage(pvdd_regulator, 1800000, 1800000); + if (regulator_enable(pvdd_regulator) != 0) + return -ENODEV; + } + } + + + if (tvin_plat->reset) + tvin_plat->reset(); + + if (tvin_plat->pwdn) + tvin_plat->pwdn(0); + + msleep(1); + + /* Set initial values for the sensor struct. */ + memset(&adv7180_data, 0, sizeof(adv7180_data)); + adv7180_data.i2c_client = client; + adv7180_data.streamcap.timeperframe.denominator = 30; + adv7180_data.streamcap.timeperframe.numerator = 1; + adv7180_data.std_id = V4L2_STD_ALL; + video_idx = ADV7180_NOT_LOCKED; + adv7180_data.pix.width = video_fmts[video_idx].raw_width; + adv7180_data.pix.height = video_fmts[video_idx].raw_height; + adv7180_data.pix.pixelformat = V4L2_PIX_FMT_UYVY; /* YUV422 */ + adv7180_data.pix.priv = 1; /* 1 is used to indicate TV in */ + adv7180_data.on = true; + + gpio_sensor_active(); + + dev_dbg(&adv7180_data.i2c_client->dev, + "%s:adv7180 probe i2c address is 0x%02X \n", + __func__, adv7180_data.i2c_client->addr); + + /*! Read the revision ID of the tvin chip */ + rev_id = adv7180_read(ADV7180_IDENT); + dev_dbg(&adv7180_data.i2c_client->dev, + "%s:Analog Device adv7%2X0 detected! \n", __func__, + rev_id); + + /*! ADV7180 initialization. */ + adv7180_hard_reset(); + + pr_debug(" type is %d (expect %d)\n", + adv7180_int_device.type, v4l2_int_type_slave); + pr_debug(" num ioctls is %d\n", + adv7180_int_device.u.slave->num_ioctls); + + /* This function attaches this structure to the /dev/video0 device. + * The pointer in priv points to the mt9v111_data structure here.*/ + adv7180_int_device.priv = &adv7180_data; + ret = v4l2_int_device_register(&adv7180_int_device); + + return ret; +} + +/*! + * ADV7180 I2C detach function. + * Called on rmmod. + * + * @param *client struct i2c_client*. + * + * @return Error code indicating success or failure. + */ +static int adv7180_detach(struct i2c_client *client) +{ + struct mxc_tvin_platform_data *plat_data = client->dev.platform_data; + + dev_dbg(&adv7180_data.i2c_client->dev, + "%s:Removing %s video decoder @ 0x%02X from adapter %s \n", + __func__, IF_NAME, client->addr << 1, client->adapter->name); + + if (plat_data->pwdn) + plat_data->pwdn(1); + + if (dvddio_regulator) { + regulator_disable(dvddio_regulator); + regulator_put(dvddio_regulator); + } + + if (dvdd_regulator) { + regulator_disable(dvdd_regulator); + regulator_put(dvdd_regulator); + } + + if (avdd_regulator) { + regulator_disable(avdd_regulator); + regulator_put(avdd_regulator); + } + + if (pvdd_regulator) { + regulator_disable(pvdd_regulator); + regulator_put(pvdd_regulator); + } + + v4l2_int_device_unregister(&adv7180_int_device); + + return 0; +} + +/*! + * ADV7180 init function. + * Called on insmod. + * + * @return Error code indicating success or failure. + */ +static __init int adv7180_init(void) +{ + u8 err = 0; + + dev_dbg(&adv7180_data.i2c_client->dev, "In adv7180_init\n"); + + /* Tells the i2c driver what functions to call for this driver. */ + err = i2c_add_driver(&adv7180_i2c_driver); + if (err != 0) + pr_err("%s:driver registration failed, error=%d \n", + __func__, err); + + return err; +} + +/*! + * ADV7180 cleanup function. + * Called on rmmod. + * + * @return Error code indicating success or failure. + */ +static void __exit adv7180_clean(void) +{ + dev_dbg(&adv7180_data.i2c_client->dev, "In adv7180_clean\n"); + i2c_del_driver(&adv7180_i2c_driver); + gpio_sensor_inactive(); +} + +module_init(adv7180_init); +module_exit(adv7180_clean); + +MODULE_AUTHOR("Freescale Semiconductor"); +MODULE_DESCRIPTION("Anolog Device ADV7180 video decoder driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/media/video/mxc/capture/csi_v4l2_capture.c b/drivers/media/video/mxc/capture/csi_v4l2_capture.c new file mode 100644 index 000000000000..cf224e0673f0 --- /dev/null +++ b/drivers/media/video/mxc/capture/csi_v4l2_capture.c @@ -0,0 +1,1466 @@ +/* + * Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file drivers/media/video/mxc/capture/csi_v4l2_capture.c + * This file is derived from mxc_v4l2_capture.c + * + * @brief MX25 Video For Linux 2 driver + * + * @ingroup MXC_V4L2_CAPTURE + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "mxc_v4l2_capture.h" +#include "fsl_csi.h" + +static int video_nr = -1; +static cam_data *g_cam; + +static int csi_v4l2_master_attach(struct v4l2_int_device *slave); +static void csi_v4l2_master_detach(struct v4l2_int_device *slave); +static u8 camera_power(cam_data *cam, bool cameraOn); + +/*! Information about this driver. */ +static struct v4l2_int_master csi_v4l2_master = { + .attach = csi_v4l2_master_attach, + .detach = csi_v4l2_master_detach, +}; + +static struct v4l2_int_device csi_v4l2_int_device = { + .module = THIS_MODULE, + .name = "csi_v4l2_cap", + .type = v4l2_int_type_master, + .u = { + .master = &csi_v4l2_master, + }, +}; + +/*! + * Camera V4l2 callback function. + * + * @param mask u32 + * @param dev void device structure + * + * @return none + */ +static void camera_callback(u32 mask, void *dev) +{ + struct mxc_v4l_frame *done_frame; + struct mxc_v4l_frame *ready_frame; + cam_data *cam; + + cam = (cam_data *) dev; + if (cam == NULL) + return; + + if (list_empty(&cam->working_q)) { + pr_err("ERROR: v4l2 capture: %s: " + "working queue empty\n", __func__); + return; + } + + done_frame = + list_entry(cam->working_q.next, struct mxc_v4l_frame, queue); + if (done_frame->buffer.flags & V4L2_BUF_FLAG_QUEUED) { + done_frame->buffer.flags |= V4L2_BUF_FLAG_DONE; + done_frame->buffer.flags &= ~V4L2_BUF_FLAG_QUEUED; + if (list_empty(&cam->ready_q)) { + cam->skip_frame++; + } else { + ready_frame = list_entry(cam->ready_q.next, + struct mxc_v4l_frame, queue); + list_del(cam->ready_q.next); + list_add_tail(&ready_frame->queue, &cam->working_q); + + if (cam->ping_pong_csi == 1) { + __raw_writel(cam->frame[ready_frame->index]. + paddress, CSI_CSIDMASA_FB1); + } else { + __raw_writel(cam->frame[ready_frame->index]. + paddress, CSI_CSIDMASA_FB2); + } + } + + /* Added to the done queue */ + list_del(cam->working_q.next); + list_add_tail(&done_frame->queue, &cam->done_q); + cam->enc_counter++; + wake_up_interruptible(&cam->enc_queue); + } else { + pr_err("ERROR: v4l2 capture: %s: " + "buffer not queued\n", __func__); + } + + return; +} + +/*! + * Make csi ready for capture image. + * + * @param cam structure cam_data * + * + * @return status 0 success + */ +static int csi_cap_image(cam_data *cam) +{ + unsigned int value; + + value = __raw_readl(CSI_CSICR3); + __raw_writel(value | BIT_DMA_REFLASH_RFF | BIT_FRMCNT_RST, CSI_CSICR3); + value = __raw_readl(CSI_CSISR); + __raw_writel(value, CSI_CSISR); + + return 0; +} + +/*************************************************************************** + * Functions for handling Frame buffers. + **************************************************************************/ + +/*! + * Free frame buffers + * + * @param cam Structure cam_data * + * + * @return status 0 success. + */ +static int csi_free_frame_buf(cam_data *cam) +{ + int i; + + pr_debug("MVC: In %s\n", __func__); + + for (i = 0; i < FRAME_NUM; i++) { + if (cam->frame[i].vaddress != 0) { + dma_free_coherent(0, cam->frame[i].buffer.length, + cam->frame[i].vaddress, + cam->frame[i].paddress); + cam->frame[i].vaddress = 0; + } + } + + return 0; +} + +/*! + * Allocate frame buffers + * + * @param cam Structure cam_data * + * @param count int number of buffer need to allocated + * + * @return status -0 Successfully allocated a buffer, -ENOBUFS failed. + */ +static int csi_allocate_frame_buf(cam_data *cam, int count) +{ + int i; + + pr_debug("In MVC:%s- size=%d\n", + __func__, cam->v2f.fmt.pix.sizeimage); + for (i = 0; i < count; i++) { + cam->frame[i].vaddress = dma_alloc_coherent(0, PAGE_ALIGN + (cam->v2f.fmt. + pix.sizeimage), + &cam->frame[i]. + paddress, + GFP_DMA | + GFP_KERNEL); + if (cam->frame[i].vaddress == 0) { + pr_err("ERROR: v4l2 capture: " + "%s failed.\n", __func__); + csi_free_frame_buf(cam); + return -ENOBUFS; + } + cam->frame[i].buffer.index = i; + cam->frame[i].buffer.flags = V4L2_BUF_FLAG_MAPPED; + cam->frame[i].buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + cam->frame[i].buffer.length = PAGE_ALIGN(cam->v2f.fmt. + pix.sizeimage); + cam->frame[i].buffer.memory = V4L2_MEMORY_MMAP; + cam->frame[i].buffer.m.offset = cam->frame[i].paddress; + cam->frame[i].index = i; + } + + return 0; +} + +/*! + * Free frame buffers status + * + * @param cam Structure cam_data * + * + * @return none + */ +static void csi_free_frames(cam_data *cam) +{ + int i; + + pr_debug("In MVC: %s\n", __func__); + + for (i = 0; i < FRAME_NUM; i++) + cam->frame[i].buffer.flags = V4L2_BUF_FLAG_MAPPED; + + cam->skip_frame = 0; + INIT_LIST_HEAD(&cam->ready_q); + INIT_LIST_HEAD(&cam->working_q); + INIT_LIST_HEAD(&cam->done_q); + + return; +} + +/*! + * Return the buffer status + * + * @param cam Structure cam_data * + * @param buf Structure v4l2_buffer * + * + * @return status 0 success, EINVAL failed. + */ +static int csi_v4l2_buffer_status(cam_data *cam, struct v4l2_buffer *buf) +{ + pr_debug("In MVC: %s\n", __func__); + + if (buf->index < 0 || buf->index >= FRAME_NUM) { + pr_err("ERROR: v4l2 capture: %s buffers " + "not allocated\n", __func__); + return -EINVAL; + } + + memcpy(buf, &(cam->frame[buf->index].buffer), sizeof(*buf)); + + return 0; +} + +/*! + * Indicates whether the palette is supported. + * + * @param palette V4L2_PIX_FMT_RGB565, V4L2_PIX_FMT_UYVY or V4L2_PIX_FMT_YUV420 + * + * @return 0 if failed + */ +static inline int valid_mode(u32 palette) +{ + return (palette == V4L2_PIX_FMT_RGB565) || + (palette == V4L2_PIX_FMT_UYVY) || (palette == V4L2_PIX_FMT_YUV420); +} + +/*! + * Start stream I/O + * + * @param cam structure cam_data * + * + * @return status 0 Success + */ +static int csi_streamon(cam_data *cam) +{ + struct mxc_v4l_frame *frame; + + pr_debug("In MVC: %s\n", __func__); + + if (NULL == cam) { + pr_err("ERROR: v4l2 capture: %s cam parameter is NULL\n", + __func__); + return -1; + } + + /* move the frame from readyq to workingq */ + if (list_empty(&cam->ready_q)) { + pr_err("ERROR: v4l2 capture: %s: " + "ready_q queue empty\n", __func__); + return -1; + } + frame = list_entry(cam->ready_q.next, struct mxc_v4l_frame, queue); + list_del(cam->ready_q.next); + list_add_tail(&frame->queue, &cam->working_q); + __raw_writel(cam->frame[frame->index].paddress, CSI_CSIDMASA_FB1); + + if (list_empty(&cam->ready_q)) { + pr_err("ERROR: v4l2 capture: %s: " + "ready_q queue empty\n", __func__); + return -1; + } + frame = list_entry(cam->ready_q.next, struct mxc_v4l_frame, queue); + list_del(cam->ready_q.next); + list_add_tail(&frame->queue, &cam->working_q); + __raw_writel(cam->frame[frame->index].paddress, CSI_CSIDMASA_FB2); + + cam->capture_pid = current->pid; + cam->capture_on = true; + csi_cap_image(cam); + csi_enable_int(1); + + return 0; +} + +/*! + * Stop stream I/O + * + * @param cam structure cam_data * + * + * @return status 0 Success + */ +static int csi_streamoff(cam_data *cam) +{ + unsigned int cr3; + + pr_debug("In MVC: %s\n", __func__); + + if (cam->capture_on == false) + return 0; + + csi_disable_int(); + cam->capture_on = false; + + /* set CSI_CSIDMASA_FB1 and CSI_CSIDMASA_FB2 to default value */ + __raw_writel(0, CSI_CSIDMASA_FB1); + __raw_writel(0, CSI_CSIDMASA_FB2); + cr3 = __raw_readl(CSI_CSICR3); + __raw_writel(cr3 | BIT_DMA_REFLASH_RFF, CSI_CSICR3); + + csi_free_frames(cam); + csi_free_frame_buf(cam); + + return 0; +} + +/*! + * start the viewfinder job + * + * @param cam structure cam_data * + * + * @return status 0 Success + */ +static int start_preview(cam_data *cam) +{ + unsigned long fb_addr = (unsigned long)cam->v4l2_fb.base; + + __raw_writel(fb_addr, CSI_CSIDMASA_FB1); + __raw_writel(fb_addr, CSI_CSIDMASA_FB2); + __raw_writel(__raw_readl(CSI_CSICR3) | BIT_DMA_REFLASH_RFF, CSI_CSICR3); + + csi_enable_int(0); + + return 0; +} + +/*! + * shut down the viewfinder job + * + * @param cam structure cam_data * + * + * @return status 0 Success + */ +static int stop_preview(cam_data *cam) +{ + csi_disable_int(); + + /* set CSI_CSIDMASA_FB1 and CSI_CSIDMASA_FB2 to default value */ + __raw_writel(0, CSI_CSIDMASA_FB1); + __raw_writel(0, CSI_CSIDMASA_FB2); + __raw_writel(__raw_readl(CSI_CSICR3) | BIT_DMA_REFLASH_RFF, CSI_CSICR3); + + return 0; +} + +/*************************************************************************** + * VIDIOC Functions. + **************************************************************************/ + +/*! + * + * @param cam structure cam_data * + * + * @param f structure v4l2_format * + * + * @return status 0 success, EINVAL failed + */ +static int csi_v4l2_g_fmt(cam_data *cam, struct v4l2_format *f) +{ + int retval = 0; + + switch (f->type) { + case V4L2_BUF_TYPE_VIDEO_CAPTURE: + pr_debug(" type is V4L2_BUF_TYPE_VIDEO_CAPTURE\n"); + f->fmt.pix = cam->v2f.fmt.pix; + break; + case V4L2_BUF_TYPE_VIDEO_OVERLAY: + pr_debug(" type is V4L2_BUF_TYPE_VIDEO_OVERLAY\n"); + f->fmt.win = cam->win; + break; + default: + pr_debug(" type is invalid\n"); + retval = -EINVAL; + } + + pr_debug("End of %s: v2f pix widthxheight %d x %d\n", + __func__, cam->v2f.fmt.pix.width, cam->v2f.fmt.pix.height); + + return retval; +} + +/*! + * V4L2 - csi_v4l2_s_fmt function + * + * @param cam structure cam_data * + * + * @param f structure v4l2_format * + * + * @return status 0 success, EINVAL failed + */ +static int csi_v4l2_s_fmt(cam_data *cam, struct v4l2_format *f) +{ + int retval = 0; + int size = 0; + int bytesperline = 0; + int *width, *height; + + pr_debug("In MVC: %s\n", __func__); + + switch (f->type) { + case V4L2_BUF_TYPE_VIDEO_CAPTURE: + pr_debug(" type=V4L2_BUF_TYPE_VIDEO_CAPTURE\n"); + if (!valid_mode(f->fmt.pix.pixelformat)) { + pr_err("ERROR: v4l2 capture: %s: format " + "not supported\n", __func__); + return -EINVAL; + } + + /* Handle case where size requested is larger than cuurent + * camera setting. */ + if ((f->fmt.pix.width > cam->crop_bounds.width) + || (f->fmt.pix.height > cam->crop_bounds.height)) { + /* Need the logic here, calling vidioc_s_param if + * camera can change. */ + pr_debug("csi_v4l2_s_fmt size changed\n"); + } + if (cam->rotation >= IPU_ROTATE_90_RIGHT) { + height = &f->fmt.pix.width; + width = &f->fmt.pix.height; + } else { + width = &f->fmt.pix.width; + height = &f->fmt.pix.height; + } + + if ((cam->crop_bounds.width / *width > 8) || + ((cam->crop_bounds.width / *width == 8) && + (cam->crop_bounds.width % *width))) { + *width = cam->crop_bounds.width / 8; + if (*width % 8) + *width += 8 - *width % 8; + pr_err("ERROR: v4l2 capture: width exceeds limit " + "resize to %d.\n", *width); + } + + if ((cam->crop_bounds.height / *height > 8) || + ((cam->crop_bounds.height / *height == 8) && + (cam->crop_bounds.height % *height))) { + *height = cam->crop_bounds.height / 8; + if (*height % 8) + *height += 8 - *height % 8; + pr_err("ERROR: v4l2 capture: height exceeds limit " + "resize to %d.\n", *height); + } + + switch (f->fmt.pix.pixelformat) { + case V4L2_PIX_FMT_RGB565: + size = f->fmt.pix.width * f->fmt.pix.height * 2; + csi_set_16bit_imagpara(f->fmt.pix.width, + f->fmt.pix.height); + bytesperline = f->fmt.pix.width * 2; + break; + case V4L2_PIX_FMT_UYVY: + size = f->fmt.pix.width * f->fmt.pix.height * 2; + csi_set_16bit_imagpara(f->fmt.pix.width, + f->fmt.pix.height); + bytesperline = f->fmt.pix.width * 2; + break; + case V4L2_PIX_FMT_YUV420: + size = f->fmt.pix.width * f->fmt.pix.height * 3 / 2; + csi_set_12bit_imagpara(f->fmt.pix.width, + f->fmt.pix.height); + bytesperline = f->fmt.pix.width; + break; + case V4L2_PIX_FMT_YUV422P: + case V4L2_PIX_FMT_RGB24: + case V4L2_PIX_FMT_BGR24: + case V4L2_PIX_FMT_BGR32: + case V4L2_PIX_FMT_RGB32: + case V4L2_PIX_FMT_NV12: + default: + pr_debug(" case not supported\n"); + break; + } + + if (f->fmt.pix.bytesperline < bytesperline) + f->fmt.pix.bytesperline = bytesperline; + else + bytesperline = f->fmt.pix.bytesperline; + + if (f->fmt.pix.sizeimage < size) + f->fmt.pix.sizeimage = size; + else + size = f->fmt.pix.sizeimage; + + cam->v2f.fmt.pix = f->fmt.pix; + + if (cam->v2f.fmt.pix.priv != 0) { + if (copy_from_user(&cam->offset, + (void *)cam->v2f.fmt.pix.priv, + sizeof(cam->offset))) { + retval = -EFAULT; + break; + } + } + break; + case V4L2_BUF_TYPE_VIDEO_OVERLAY: + pr_debug(" type=V4L2_BUF_TYPE_VIDEO_OVERLAY\n"); + cam->win = f->fmt.win; + break; + default: + retval = -EINVAL; + } + + pr_debug("End of %s: v2f pix widthxheight %d x %d\n", + __func__, cam->v2f.fmt.pix.width, cam->v2f.fmt.pix.height); + + return retval; +} + +/*! + * V4L2 - csi_v4l2_s_param function + * Allows setting of capturemode and frame rate. + * + * @param cam structure cam_data * + * @param parm structure v4l2_streamparm * + * + * @return status 0 success, EINVAL failed + */ +static int csi_v4l2_s_param(cam_data *cam, struct v4l2_streamparm *parm) +{ + struct v4l2_ifparm ifparm; + struct v4l2_format cam_fmt; + struct v4l2_streamparm currentparm; + int err = 0; + + pr_debug("In %s\n", __func__); + + if (parm->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) { + pr_err(KERN_ERR "%s invalid type\n", __func__); + return -EINVAL; + } + + /* Stop the viewfinder */ + if (cam->overlay_on == true) + stop_preview(cam); + + currentparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + + /* First check that this device can support the changes requested. */ + err = vidioc_int_g_parm(cam->sensor, ¤tparm); + if (err) { + pr_err("%s: vidioc_int_g_parm returned an error %d\n", + __func__, err); + goto exit; + } + + pr_debug(" Current capabilities are %x\n", + currentparm.parm.capture.capability); + pr_debug(" Current capturemode is %d change to %d\n", + currentparm.parm.capture.capturemode, + parm->parm.capture.capturemode); + pr_debug(" Current framerate is %d change to %d\n", + currentparm.parm.capture.timeperframe.denominator, + parm->parm.capture.timeperframe.denominator); + + err = vidioc_int_s_parm(cam->sensor, parm); + if (err) { + pr_err("%s: vidioc_int_s_parm returned an error %d\n", + __func__, err); + goto exit; + } + + vidioc_int_g_ifparm(cam->sensor, &ifparm); + cam_fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + pr_debug(" g_fmt_cap returns widthxheight of input as %d x %d\n", + cam_fmt.fmt.pix.width, cam_fmt.fmt.pix.height); + +exit: + return err; +} + +/*! + * Dequeue one V4L capture buffer + * + * @param cam structure cam_data * + * @param buf structure v4l2_buffer * + * + * @return status 0 success, EINVAL invalid frame number + * ETIME timeout, ERESTARTSYS interrupted by user + */ +static int csi_v4l_dqueue(cam_data *cam, struct v4l2_buffer *buf) +{ + int retval = 0; + struct mxc_v4l_frame *frame; + unsigned long lock_flags; + + if (!wait_event_interruptible_timeout(cam->enc_queue, + cam->enc_counter != 0, 10 * HZ)) { + pr_err("ERROR: v4l2 capture: mxc_v4l_dqueue timeout " + "enc_counter %x\n", cam->enc_counter); + return -ETIME; + } else if (signal_pending(current)) { + pr_err("ERROR: v4l2 capture: mxc_v4l_dqueue() " + "interrupt received\n"); + return -ERESTARTSYS; + } + + spin_lock_irqsave(&cam->dqueue_int_lock, lock_flags); + + cam->enc_counter--; + + frame = list_entry(cam->done_q.next, struct mxc_v4l_frame, queue); + list_del(cam->done_q.next); + + if (frame->buffer.flags & V4L2_BUF_FLAG_DONE) { + frame->buffer.flags &= ~V4L2_BUF_FLAG_DONE; + } else if (frame->buffer.flags & V4L2_BUF_FLAG_QUEUED) { + pr_err("ERROR: v4l2 capture: VIDIOC_DQBUF: " + "Buffer not filled.\n"); + frame->buffer.flags &= ~V4L2_BUF_FLAG_QUEUED; + retval = -EINVAL; + } else if ((frame->buffer.flags & 0x7) == V4L2_BUF_FLAG_MAPPED) { + pr_err("ERROR: v4l2 capture: VIDIOC_DQBUF: " + "Buffer not queued.\n"); + retval = -EINVAL; + } + + spin_unlock_irqrestore(&cam->dqueue_int_lock, lock_flags); + + buf->bytesused = cam->v2f.fmt.pix.sizeimage; + buf->index = frame->index; + buf->flags = frame->buffer.flags; + buf->m = cam->frame[frame->index].buffer.m; + + return retval; +} + +/*! + * V4L interface - open function + * + * @param file structure file * + * + * @return status 0 success, ENODEV invalid device instance, + * ENODEV timeout, ERESTARTSYS interrupted by user + */ +static int csi_v4l_open(struct file *file) +{ + struct v4l2_ifparm ifparm; + struct v4l2_format cam_fmt; + struct video_device *dev = video_devdata(file); + cam_data *cam = video_get_drvdata(dev); + int err = 0; + + pr_debug(" device name is %s\n", dev->name); + + if (!cam) { + pr_err("ERROR: v4l2 capture: Internal error, " + "cam_data not found!\n"); + return -EBADF; + } + + down(&cam->busy_lock); + err = 0; + if (signal_pending(current)) + goto oops; + + if (cam->open_count++ == 0) { + wait_event_interruptible(cam->power_queue, + cam->low_power == false); + + cam->enc_counter = 0; + cam->skip_frame = 0; + INIT_LIST_HEAD(&cam->ready_q); + INIT_LIST_HEAD(&cam->working_q); + INIT_LIST_HEAD(&cam->done_q); + + vidioc_int_g_ifparm(cam->sensor, &ifparm); + + cam_fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + csi_enable_mclk(CSI_MCLK_I2C, true, true); + vidioc_int_init(cam->sensor); + } + + file->private_data = dev; + +oops: + up(&cam->busy_lock); + return err; +} + +/*! + * V4L interface - close function + * + * @param file struct file * + * + * @return 0 success + */ +static int csi_v4l_close(struct file *file) +{ + struct video_device *dev = video_devdata(file); + int err = 0; + cam_data *cam = video_get_drvdata(dev); + + pr_debug("In MVC:%s\n", __func__); + + if (!cam) { + pr_err("ERROR: v4l2 capture: Internal error, " + "cam_data not found!\n"); + return -EBADF; + } + + /* for the case somebody hit the ctrl C */ + if (cam->overlay_pid == current->pid) { + err = stop_preview(cam); + cam->overlay_on = false; + } + + if (--cam->open_count == 0) { + wait_event_interruptible(cam->power_queue, + cam->low_power == false); + file->private_data = NULL; + csi_enable_mclk(CSI_MCLK_I2C, false, false); + } + + return err; +} + +/* + * V4L interface - read function + * + * @param file struct file * + * @param read buf char * + * @param count size_t + * @param ppos structure loff_t * + * + * @return bytes read + */ +static ssize_t csi_v4l_read(struct file *file, char *buf, size_t count, + loff_t *ppos) +{ + int err = 0; + struct video_device *dev = video_devdata(file); + cam_data *cam = video_get_drvdata(dev); + + if (down_interruptible(&cam->busy_lock)) + return -EINTR; + + /* Stop the viewfinder */ + if (cam->overlay_on == true) + stop_preview(cam); + + if (cam->still_buf_vaddr == NULL) { + cam->still_buf_vaddr = dma_alloc_coherent(0, + PAGE_ALIGN + (cam->v2f.fmt. + pix.sizeimage), + &cam-> + still_buf[0], + GFP_DMA | GFP_KERNEL); + if (cam->still_buf_vaddr == NULL) { + pr_err("alloc dma memory failed\n"); + return -ENOMEM; + } + cam->still_counter = 0; + __raw_writel(cam->still_buf[0], CSI_CSIDMASA_FB2); + __raw_writel(cam->still_buf[0], CSI_CSIDMASA_FB1); + __raw_writel(__raw_readl(CSI_CSICR3) | BIT_DMA_REFLASH_RFF, + CSI_CSICR3); + __raw_writel(__raw_readl(CSI_CSISR), CSI_CSISR); + __raw_writel(__raw_readl(CSI_CSICR3) | BIT_FRMCNT_RST, + CSI_CSICR3); + csi_enable_int(1); + } + + wait_event_interruptible(cam->still_queue, cam->still_counter); + csi_disable_int(); + err = copy_to_user(buf, cam->still_buf_vaddr, + cam->v2f.fmt.pix.sizeimage); + + if (cam->still_buf_vaddr != NULL) { + dma_free_coherent(0, PAGE_ALIGN(cam->v2f.fmt.pix.sizeimage), + cam->still_buf_vaddr, cam->still_buf[0]); + cam->still_buf[0] = 0; + cam->still_buf_vaddr = NULL; + } + + if (cam->overlay_on == true) + start_preview(cam); + + up(&cam->busy_lock); + if (err < 0) + return err; + + return cam->v2f.fmt.pix.sizeimage - err; +} + +/*! + * V4L interface - ioctl function + * + * @param file struct file* + * + * @param ioctlnr unsigned int + * + * @param arg void* + * + * @return 0 success, ENODEV for invalid device instance, + * -1 for other errors. + */ +static long csi_v4l_do_ioctl(struct file *file, + unsigned int ioctlnr, void *arg) +{ + struct video_device *dev = video_devdata(file); + cam_data *cam = video_get_drvdata(dev); + int retval = 0; + unsigned long lock_flags; + + pr_debug("In MVC: %s, %x\n", __func__, ioctlnr); + wait_event_interruptible(cam->power_queue, cam->low_power == false); + /* make this _really_ smp-safe */ + if (down_interruptible(&cam->busy_lock)) + return -EBUSY; + + switch (ioctlnr) { + /*! + * V4l2 VIDIOC_G_FMT ioctl + */ + case VIDIOC_G_FMT:{ + struct v4l2_format *gf = arg; + pr_debug(" case VIDIOC_G_FMT\n"); + retval = csi_v4l2_g_fmt(cam, gf); + break; + } + + /*! + * V4l2 VIDIOC_S_FMT ioctl + */ + case VIDIOC_S_FMT:{ + struct v4l2_format *sf = arg; + pr_debug(" case VIDIOC_S_FMT\n"); + retval = csi_v4l2_s_fmt(cam, sf); + vidioc_int_s_fmt_cap(cam->sensor, sf); + break; + } + + /*! + * V4l2 VIDIOC_OVERLAY ioctl + */ + case VIDIOC_OVERLAY:{ + int *on = arg; + pr_debug(" case VIDIOC_OVERLAY\n"); + if (*on) { + cam->overlay_on = true; + cam->overlay_pid = current->pid; + start_preview(cam); + } + if (!*on) { + stop_preview(cam); + cam->overlay_on = false; + } + break; + } + + /*! + * V4l2 VIDIOC_G_FBUF ioctl + */ + case VIDIOC_G_FBUF:{ + struct v4l2_framebuffer *fb = arg; + *fb = cam->v4l2_fb; + fb->capability = V4L2_FBUF_CAP_EXTERNOVERLAY; + break; + } + + /*! + * V4l2 VIDIOC_S_FBUF ioctl + */ + case VIDIOC_S_FBUF:{ + struct v4l2_framebuffer *fb = arg; + cam->v4l2_fb = *fb; + break; + } + + case VIDIOC_G_PARM:{ + struct v4l2_streamparm *parm = arg; + pr_debug(" case VIDIOC_G_PARM\n"); + vidioc_int_g_parm(cam->sensor, parm); + break; + } + + case VIDIOC_S_PARM:{ + struct v4l2_streamparm *parm = arg; + pr_debug(" case VIDIOC_S_PARM\n"); + retval = csi_v4l2_s_param(cam, parm); + break; + } + + case VIDIOC_QUERYCAP:{ + struct v4l2_capability *cap = arg; + pr_debug(" case VIDIOC_QUERYCAP\n"); + strcpy(cap->driver, "csi_v4l2"); + cap->version = KERNEL_VERSION(0, 1, 11); + cap->capabilities = V4L2_CAP_VIDEO_OVERLAY | + V4L2_CAP_VIDEO_OUTPUT_OVERLAY | V4L2_CAP_READWRITE; + cap->card[0] = '\0'; + cap->bus_info[0] = '\0'; + break; + } + + case VIDIOC_S_CROP: + pr_debug(" case not supported\n"); + break; + + case VIDIOC_REQBUFS: { + struct v4l2_requestbuffers *req = arg; + pr_debug(" case VIDIOC_REQBUFS\n"); + + if (req->count > FRAME_NUM) { + pr_err("ERROR: v4l2 capture: VIDIOC_REQBUFS: " + "not enough buffers\n"); + req->count = FRAME_NUM; + } + + if ((req->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) || + (req->memory != V4L2_MEMORY_MMAP)) { + pr_err("ERROR: v4l2 capture: VIDIOC_REQBUFS: " + "wrong buffer type\n"); + retval = -EINVAL; + break; + } + + csi_streamoff(cam); + csi_free_frame_buf(cam); + cam->skip_frame = 0; + INIT_LIST_HEAD(&cam->ready_q); + INIT_LIST_HEAD(&cam->working_q); + INIT_LIST_HEAD(&cam->done_q); + retval = csi_allocate_frame_buf(cam, req->count); + break; + } + + case VIDIOC_QUERYBUF: { + struct v4l2_buffer *buf = arg; + int index = buf->index; + pr_debug(" case VIDIOC_QUERYBUF\n"); + + if (buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) { + retval = -EINVAL; + break; + } + + memset(buf, 0, sizeof(buf)); + buf->index = index; + retval = csi_v4l2_buffer_status(cam, buf); + break; + } + + case VIDIOC_QBUF: { + struct v4l2_buffer *buf = arg; + int index = buf->index; + pr_debug(" case VIDIOC_QBUF\n"); + + spin_lock_irqsave(&cam->queue_int_lock, lock_flags); + cam->frame[index].buffer.m.offset = buf->m.offset; + if ((cam->frame[index].buffer.flags & 0x7) == + V4L2_BUF_FLAG_MAPPED) { + cam->frame[index].buffer.flags |= V4L2_BUF_FLAG_QUEUED; + if (cam->skip_frame > 0) { + list_add_tail(&cam->frame[index].queue, + &cam->working_q); + cam->skip_frame = 0; + + if (cam->ping_pong_csi == 1) { + __raw_writel(cam->frame[index].paddress, + CSI_CSIDMASA_FB1); + } else { + __raw_writel(cam->frame[index].paddress, + CSI_CSIDMASA_FB2); + } + } else { + list_add_tail(&cam->frame[index].queue, + &cam->ready_q); + } + } else if (cam->frame[index].buffer.flags & + V4L2_BUF_FLAG_QUEUED) { + pr_err("ERROR: v4l2 capture: VIDIOC_QBUF: " + "buffer already queued\n"); + retval = -EINVAL; + } else if (cam->frame[index].buffer. + flags & V4L2_BUF_FLAG_DONE) { + pr_err("ERROR: v4l2 capture: VIDIOC_QBUF: " + "overwrite done buffer.\n"); + cam->frame[index].buffer.flags &= + ~V4L2_BUF_FLAG_DONE; + cam->frame[index].buffer.flags |= + V4L2_BUF_FLAG_QUEUED; + retval = -EINVAL; + } + buf->flags = cam->frame[index].buffer.flags; + spin_unlock_irqrestore(&cam->queue_int_lock, lock_flags); + + break; + } + + case VIDIOC_DQBUF: { + struct v4l2_buffer *buf = arg; + pr_debug(" case VIDIOC_DQBUF\n"); + + retval = csi_v4l_dqueue(cam, buf); + + break; + } + + case VIDIOC_STREAMON: { + pr_debug(" case VIDIOC_STREAMON\n"); + retval = csi_streamon(cam); + break; + } + + case VIDIOC_STREAMOFF: { + pr_debug(" case VIDIOC_STREAMOFF\n"); + retval = csi_streamoff(cam); + break; + } + + case VIDIOC_S_CTRL: + case VIDIOC_G_STD: + case VIDIOC_G_OUTPUT: + case VIDIOC_S_OUTPUT: + case VIDIOC_ENUMSTD: + case VIDIOC_G_CROP: + case VIDIOC_CROPCAP: + case VIDIOC_S_STD: + case VIDIOC_G_CTRL: + case VIDIOC_ENUM_FMT: + case VIDIOC_TRY_FMT: + case VIDIOC_QUERYCTRL: + case VIDIOC_ENUMINPUT: + case VIDIOC_G_INPUT: + case VIDIOC_S_INPUT: + case VIDIOC_G_TUNER: + case VIDIOC_S_TUNER: + case VIDIOC_G_FREQUENCY: + case VIDIOC_S_FREQUENCY: + case VIDIOC_ENUMOUTPUT: + default: + pr_debug(" case not supported\n"); + retval = -EINVAL; + break; + } + + up(&cam->busy_lock); + return retval; +} + +/* + * V4L interface - ioctl function + * + * @return None + */ +static long csi_v4l_ioctl(struct file *file, + unsigned int cmd, unsigned long arg) +{ + return video_usercopy(file, cmd, arg, csi_v4l_do_ioctl); +} + +/*! + * V4L interface - mmap function + * + * @param file structure file * + * + * @param vma structure vm_area_struct * + * + * @return status 0 Success, EINTR busy lock error, ENOBUFS remap_page error + */ +static int csi_mmap(struct file *file, struct vm_area_struct *vma) +{ + struct video_device *dev = video_devdata(file); + unsigned long size; + int res = 0; + cam_data *cam = video_get_drvdata(dev); + + pr_debug("%s\n", __func__); + pr_debug("\npgoff=0x%lx, start=0x%lx, end=0x%lx\n", + vma->vm_pgoff, vma->vm_start, vma->vm_end); + + /* make this _really_ smp-safe */ + if (down_interruptible(&cam->busy_lock)) + return -EINTR; + + size = vma->vm_end - vma->vm_start; + vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); + + if (remap_pfn_range(vma, vma->vm_start, + vma->vm_pgoff, size, vma->vm_page_prot)) { + pr_err("ERROR: v4l2 capture: %s : " + "remap_pfn_range failed\n", __func__); + res = -ENOBUFS; + goto csi_mmap_exit; + } + + vma->vm_flags &= ~VM_IO; /* using shared anonymous pages */ + +csi_mmap_exit: + up(&cam->busy_lock); + return res; +} + +/*! + * This structure defines the functions to be called in this driver. + */ +static struct v4l2_file_operations csi_v4l_fops = { + .owner = THIS_MODULE, + .open = csi_v4l_open, + .release = csi_v4l_close, + .read = csi_v4l_read, + .ioctl = csi_v4l_ioctl, + .mmap = csi_mmap, +}; + +static struct video_device csi_v4l_template = { + .name = "Mx25 Camera", + .fops = &csi_v4l_fops, + .release = video_device_release, +}; + +/*! + * This function can be used to release any platform data on closing. + */ +static void camera_platform_release(struct device *device) +{ +} + +/*! Device Definition for csi v4l2 device */ +static struct platform_device csi_v4l2_devices = { + .name = "csi_v4l2", + .dev = { + .release = camera_platform_release, + }, + .id = 0, +}; + +/*! + * initialize cam_data structure + * + * @param cam structure cam_data * + * + * @return status 0 Success + */ +static void init_camera_struct(cam_data *cam) +{ + pr_debug("In MVC: %s\n", __func__); + + /* Default everything to 0 */ + memset(cam, 0, sizeof(cam_data)); + + init_MUTEX(&cam->param_lock); + init_MUTEX(&cam->busy_lock); + + cam->video_dev = video_device_alloc(); + if (cam->video_dev == NULL) + return; + + *(cam->video_dev) = csi_v4l_template; + + video_set_drvdata(cam->video_dev, cam); + dev_set_drvdata(&csi_v4l2_devices.dev, (void *)cam); + cam->video_dev->minor = -1; + + init_waitqueue_head(&cam->enc_queue); + init_waitqueue_head(&cam->still_queue); + + cam->streamparm.parm.capture.capturemode = 0; + + cam->standard.index = 0; + cam->standard.id = V4L2_STD_UNKNOWN; + cam->standard.frameperiod.denominator = 30; + cam->standard.frameperiod.numerator = 1; + cam->standard.framelines = 480; + cam->standard_autodetect = true; + cam->streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + cam->streamparm.parm.capture.timeperframe = cam->standard.frameperiod; + cam->streamparm.parm.capture.capability = V4L2_CAP_TIMEPERFRAME; + cam->overlay_on = false; + cam->capture_on = false; + cam->skip_frame = 0; + cam->v4l2_fb.flags = V4L2_FBUF_FLAG_OVERLAY; + + cam->v2f.fmt.pix.sizeimage = 480 * 640 * 2; + cam->v2f.fmt.pix.bytesperline = 640 * 2; + cam->v2f.fmt.pix.width = 640; + cam->v2f.fmt.pix.height = 480; + cam->v2f.fmt.pix.pixelformat = V4L2_PIX_FMT_UYVY; + cam->win.w.width = 160; + cam->win.w.height = 160; + cam->win.w.left = 0; + cam->win.w.top = 0; + cam->still_counter = 0; + + cam->enc_callback = camera_callback; + csi_start_callback(cam); + init_waitqueue_head(&cam->power_queue); + spin_lock_init(&cam->queue_int_lock); + spin_lock_init(&cam->dqueue_int_lock); +} + +/*! + * camera_power function + * Turns Sensor power On/Off + * + * @param cam cam data struct + * @param cameraOn true to turn camera on, false to turn off power. + * + * @return status + */ +static u8 camera_power(cam_data *cam, bool cameraOn) +{ + pr_debug("In MVC: %s on=%d\n", __func__, cameraOn); + + if (cameraOn == true) { + csi_enable_mclk(CSI_MCLK_I2C, true, true); + vidioc_int_s_power(cam->sensor, 1); + } else { + csi_enable_mclk(CSI_MCLK_I2C, false, false); + vidioc_int_s_power(cam->sensor, 0); + } + return 0; +} + +/*! + * This function is called to put the sensor in a low power state. + * Refer to the document driver-model/driver.txt in the kernel source tree + * for more information. + * + * @param pdev the device structure used to give information on which I2C + * to suspend + * @param state the power state the device is entering + * + * @return The function returns 0 on success and -1 on failure. + */ +static int csi_v4l2_suspend(struct platform_device *pdev, pm_message_t state) +{ + cam_data *cam = platform_get_drvdata(pdev); + + pr_debug("In MVC: %s\n", __func__); + + if (cam == NULL) + return -1; + + cam->low_power = true; + + if (cam->overlay_on == true) + stop_preview(cam); + + camera_power(cam, false); + + return 0; +} + +/*! + * This function is called to bring the sensor back from a low power state. + * Refer to the document driver-model/driver.txt in the kernel source tree + * for more information. + * + * @param pdev the device structure + * + * @return The function returns 0 on success and -1 on failure + */ +static int csi_v4l2_resume(struct platform_device *pdev) +{ + cam_data *cam = platform_get_drvdata(pdev); + + pr_debug("In MVC: %s\n", __func__); + + if (cam == NULL) + return -1; + + cam->low_power = false; + wake_up_interruptible(&cam->power_queue); + camera_power(cam, true); + + if (cam->overlay_on == true) + start_preview(cam); + + return 0; +} + +/*! + * This structure contains pointers to the power management callback functions. + */ +static struct platform_driver csi_v4l2_driver = { + .driver = { + .name = "csi_v4l2", + }, + .probe = NULL, + .remove = NULL, +#ifdef CONFIG_PM + .suspend = csi_v4l2_suspend, + .resume = csi_v4l2_resume, +#endif + .shutdown = NULL, +}; + +/*! + * Initializes the camera driver. + */ +static int csi_v4l2_master_attach(struct v4l2_int_device *slave) +{ + cam_data *cam = slave->u.slave->master->priv; + struct v4l2_format cam_fmt; + + pr_debug("In MVC: %s\n", __func__); + pr_debug(" slave.name = %s\n", slave->name); + pr_debug(" master.name = %s\n", slave->u.slave->master->name); + + cam->sensor = slave; + if (slave == NULL) { + pr_err("ERROR: v4l2 capture: slave parameter not valid.\n"); + return -1; + } + + csi_enable_mclk(CSI_MCLK_I2C, true, true); + vidioc_int_dev_init(slave); + csi_enable_mclk(CSI_MCLK_I2C, false, false); + cam_fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + + /* Used to detect TV in (type 1) vs. camera (type 0) */ + cam->device_type = cam_fmt.fmt.pix.priv; + + pr_debug("End of %s: v2f pix widthxheight %d x %d\n", + __func__, cam->v2f.fmt.pix.width, cam->v2f.fmt.pix.height); + + return 0; +} + +/*! + * Disconnects the camera driver. + */ +static void csi_v4l2_master_detach(struct v4l2_int_device *slave) +{ + pr_debug("In MVC: %s\n", __func__); + + vidioc_int_dev_exit(slave); +} + +/*! + * Entry point for the V4L2 + * + * @return Error code indicating success or failure + */ +static __init int camera_init(void) +{ + u8 err = 0; + + /* Register the device driver structure. */ + err = platform_driver_register(&csi_v4l2_driver); + if (err != 0) { + pr_err("ERROR: v4l2 capture:camera_init: " + "platform_driver_register failed.\n"); + return err; + } + + /* Create g_cam and initialize it. */ + g_cam = kmalloc(sizeof(cam_data), GFP_KERNEL); + if (g_cam == NULL) { + pr_err("ERROR: v4l2 capture: failed to register camera\n"); + platform_driver_unregister(&csi_v4l2_driver); + return -1; + } + init_camera_struct(g_cam); + + /* Set up the v4l2 device and register it */ + csi_v4l2_int_device.priv = g_cam; + /* This function contains a bug that won't let this be rmmod'd. */ + v4l2_int_device_register(&csi_v4l2_int_device); + + /* Register the platform device */ + err = platform_device_register(&csi_v4l2_devices); + if (err != 0) { + pr_err("ERROR: v4l2 capture: camera_init: " + "platform_device_register failed.\n"); + platform_driver_unregister(&csi_v4l2_driver); + kfree(g_cam); + g_cam = NULL; + return err; + } + + /* register v4l video device */ + if (video_register_device(g_cam->video_dev, VFL_TYPE_GRABBER, video_nr) + == -1) { + platform_device_unregister(&csi_v4l2_devices); + platform_driver_unregister(&csi_v4l2_driver); + kfree(g_cam); + g_cam = NULL; + pr_err("ERROR: v4l2 capture: video_register_device failed\n"); + return -1; + } + pr_debug(" Video device registered: %s #%d\n", + g_cam->video_dev->name, g_cam->video_dev->minor); + + return err; +} + +/*! + * Exit and cleanup for the V4L2 + */ +static void __exit camera_exit(void) +{ + pr_debug("In MVC: %s\n", __func__); + + if (g_cam->open_count) { + pr_err("ERROR: v4l2 capture:camera open " + "-- setting ops to NULL\n"); + } else { + pr_info("V4L2 freeing image input device\n"); + v4l2_int_device_unregister(&csi_v4l2_int_device); + csi_stop_callback(g_cam); + video_unregister_device(g_cam->video_dev); + platform_driver_unregister(&csi_v4l2_driver); + platform_device_unregister(&csi_v4l2_devices); + + kfree(g_cam); + g_cam = NULL; + } +} + +module_init(camera_init); +module_exit(camera_exit); + +module_param(video_nr, int, 0444); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("V4L2 capture driver for Mx25 based cameras"); +MODULE_LICENSE("GPL"); +MODULE_SUPPORTED_DEVICE("video"); diff --git a/drivers/media/video/mxc/capture/fsl_csi.c b/drivers/media/video/mxc/capture/fsl_csi.c new file mode 100644 index 000000000000..11a8d3764e2e --- /dev/null +++ b/drivers/media/video/mxc/capture/fsl_csi.c @@ -0,0 +1,288 @@ +/* + * Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file fsl_csi.c, this file is derived from mx27_csi.c + * + * @brief mx25 CMOS Sensor interface functions + * + * @ingroup CSI + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "mxc_v4l2_capture.h" +#include "fsl_csi.h" + +static bool g_csi_mclk_on; +static csi_irq_callback_t g_callback; +static void *g_callback_data; +static struct clk csi_mclk; + +static irqreturn_t csi_irq_handler(int irq, void *data) +{ + cam_data *cam = (cam_data *) data; + unsigned long status = __raw_readl(CSI_CSISR); + unsigned long cr3 = __raw_readl(CSI_CSICR3); + unsigned int frame_count = (cr3 >> 16) & 0xFFFF; + + __raw_writel(status, CSI_CSISR); + + if (status & BIT_SOF_INT) { + /* reflash the embeded DMA controller */ + if (frame_count % 2 == 1) + __raw_writel(cr3 | BIT_DMA_REFLASH_RFF, CSI_CSICR3); + } + + if (status & BIT_DMA_TSF_DONE_FB1) { + if (cam->capture_on) { + cam->ping_pong_csi = 1; + cam->enc_callback(0, cam); + } else { + cam->still_counter++; + wake_up_interruptible(&cam->still_queue); + } + } + + if (status & BIT_DMA_TSF_DONE_FB2) { + if (cam->capture_on) { + cam->ping_pong_csi = 2; + cam->enc_callback(0, cam); + } else { + cam->still_counter++; + wake_up_interruptible(&cam->still_queue); + } + } + + if (g_callback) + g_callback(g_callback_data, status); + + pr_debug("CSI status = 0x%08lX\n", status); + + return IRQ_HANDLED; +} + +static void csihw_reset_frame_count(void) +{ + __raw_writel(__raw_readl(CSI_CSICR3) | BIT_FRMCNT_RST, CSI_CSICR3); +} + +static void csihw_reset(void) +{ + csihw_reset_frame_count(); + __raw_writel(CSICR1_RESET_VAL, CSI_CSICR1); + __raw_writel(CSICR2_RESET_VAL, CSI_CSICR2); + __raw_writel(CSICR3_RESET_VAL, CSI_CSICR3); +} + +/*! + * csi_init_interface + * Init csi interface + */ +void csi_init_interface(void) +{ + unsigned int val = 0; + unsigned int imag_para; + + val |= BIT_SOF_POL; + val |= BIT_REDGE; + val |= BIT_GCLK_MODE; + val |= BIT_HSYNC_POL; + val |= BIT_PACK_DIR; + val |= BIT_FCC; + val |= BIT_SWAP16_EN; + val |= 1 << SHIFT_MCLKDIV; + __raw_writel(val, CSI_CSICR1); + + imag_para = (640 << 16) | 960; + __raw_writel(imag_para, CSI_CSIIMAG_PARA); + + val = 0x1010; + val |= BIT_DMA_REFLASH_RFF; + __raw_writel(val, CSI_CSICR3); +} +EXPORT_SYMBOL(csi_init_interface); + +/*! + * csi_enable_mclk + * + * @param src enum define which source to control the clk + * CSI_MCLK_VF CSI_MCLK_ENC CSI_MCLK_RAW CSI_MCLK_I2C + * @param flag true to enable mclk, false to disable mclk + * @param wait true to wait 100ms make clock stable, false not wait + * + * @return 0 for success + */ +int32_t csi_enable_mclk(int src, bool flag, bool wait) +{ + if (flag == true) { + csi_mclk_enable(); + if (wait == true) + msleep(10); + pr_debug("Enable csi clock from source %d\n", src); + g_csi_mclk_on = true; + } else { + csi_mclk_disable(); + pr_debug("Disable csi clock from source %d\n", src); + g_csi_mclk_on = false; + } + + return 0; +} +EXPORT_SYMBOL(csi_enable_mclk); + +/*! + * csi_read_mclk_flag + * + * @return gcsi_mclk_source + */ +int csi_read_mclk_flag(void) +{ + return 0; +} +EXPORT_SYMBOL(csi_read_mclk_flag); + +void csi_start_callback(void *data) +{ + cam_data *cam = (cam_data *) data; + + if (request_irq(MXC_INT_CSI, csi_irq_handler, 0, "csi", cam) < 0) + pr_debug("CSI error: irq request fail\n"); + +} +EXPORT_SYMBOL(csi_start_callback); + +void csi_stop_callback(void *data) +{ + cam_data *cam = (cam_data *) data; + + free_irq(MXC_INT_CSI, cam); +} +EXPORT_SYMBOL(csi_stop_callback); + +void csi_enable_int(int arg) +{ + unsigned long cr1 = __raw_readl(CSI_CSICR1); + + cr1 |= BIT_SOF_INTEN; + if (arg == 1) { + /* still capture needs DMA intterrupt */ + cr1 |= BIT_FB1_DMA_DONE_INTEN; + cr1 |= BIT_FB2_DMA_DONE_INTEN; + } + __raw_writel(cr1, CSI_CSICR1); +} +EXPORT_SYMBOL(csi_enable_int); + +void csi_disable_int(void) +{ + unsigned long cr1 = __raw_readl(CSI_CSICR1); + + cr1 &= ~BIT_SOF_INTEN; + cr1 &= ~BIT_FB1_DMA_DONE_INTEN; + cr1 &= ~BIT_FB2_DMA_DONE_INTEN; + __raw_writel(cr1, CSI_CSICR1); +} +EXPORT_SYMBOL(csi_disable_int); + +void csi_set_16bit_imagpara(int width, int height) +{ + int imag_para = 0; + unsigned long cr3 = __raw_readl(CSI_CSICR3); + + imag_para = (width << 16) | (height * 2); + __raw_writel(imag_para, CSI_CSIIMAG_PARA); + + /* reflash the embeded DMA controller */ + __raw_writel(cr3 | BIT_DMA_REFLASH_RFF, CSI_CSICR3); +} +EXPORT_SYMBOL(csi_set_16bit_imagpara); + +void csi_set_12bit_imagpara(int width, int height) +{ + int imag_para = 0; + unsigned long cr3 = __raw_readl(CSI_CSICR3); + + imag_para = (width << 16) | (height * 3 / 2); + __raw_writel(imag_para, CSI_CSIIMAG_PARA); + + /* reflash the embeded DMA controller */ + __raw_writel(cr3 | BIT_DMA_REFLASH_RFF, CSI_CSICR3); +} +EXPORT_SYMBOL(csi_set_12bit_imagpara); + +static void csi_mclk_recalc(struct clk *clk) +{ + u32 div; + + div = (__raw_readl(CSI_CSICR1) & BIT_MCLKDIV) >> SHIFT_MCLKDIV; + if (div == 0) + div = 1; + else + div = div * 2; + + clk->rate = clk->parent->rate / div; +} + +void csi_mclk_enable(void) +{ + __raw_writel(__raw_readl(CSI_CSICR1) | BIT_MCLKEN, CSI_CSICR1); +} + +void csi_mclk_disable(void) +{ + __raw_writel(__raw_readl(CSI_CSICR1) & ~BIT_MCLKEN, CSI_CSICR1); +} + +int32_t __init csi_init_module(void) +{ + int ret = 0; + struct clk *per_clk; + + csihw_reset(); + csi_init_interface(); + + per_clk = clk_get(NULL, "csi_clk"); + if (IS_ERR(per_clk)) + return PTR_ERR(per_clk); + + clk_put(per_clk); + csi_mclk.name = "csi_mclk"; + csi_mclk.parent = per_clk; + clk_register(&csi_mclk); + clk_enable(per_clk); + csi_mclk_recalc(&csi_mclk); + + return ret; +} + +void __exit csi_cleanup_module(void) +{ + clk_disable(&csi_mclk); + clk_unregister(&csi_mclk); +} + +module_init(csi_init_module); +module_exit(csi_cleanup_module); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("fsl CSI driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/media/video/mxc/capture/fsl_csi.h b/drivers/media/video/mxc/capture/fsl_csi.h new file mode 100644 index 000000000000..4d6babd3691d --- /dev/null +++ b/drivers/media/video/mxc/capture/fsl_csi.h @@ -0,0 +1,198 @@ +/* + * Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file fsl_csi.h + * + * @brief mx25 CMOS Sensor interface functions + * + * @ingroup CSI + */ + +#ifndef MX25_CSI_H +#define MX25_CSI_H + +#include +#include + +/* reset values */ +#define CSICR1_RESET_VAL 0x40000800 +#define CSICR2_RESET_VAL 0x0 +#define CSICR3_RESET_VAL 0x0 + +/* csi control reg 1 */ +#define BIT_SWAP16_EN (0x1 << 31) +#define BIT_EXT_VSYNC (0x1 << 30) +#define BIT_EOF_INT_EN (0x1 << 29) +#define BIT_PRP_IF_EN (0x1 << 28) +#define BIT_CCIR_MODE (0x1 << 27) +#define BIT_COF_INT_EN (0x1 << 26) +#define BIT_SF_OR_INTEN (0x1 << 25) +#define BIT_RF_OR_INTEN (0x1 << 24) +#define BIT_SFF_DMA_DONE_INTEN (0x1 << 22) +#define BIT_STATFF_INTEN (0x1 << 21) +#define BIT_FB2_DMA_DONE_INTEN (0x1 << 20) +#define BIT_FB1_DMA_DONE_INTEN (0x1 << 19) +#define BIT_RXFF_INTEN (0x1 << 18) +#define BIT_SOF_POL (0x1 << 17) +#define BIT_SOF_INTEN (0x1 << 16) +#define BIT_MCLKDIV (0xF << 12) +#define BIT_HSYNC_POL (0x1 << 11) +#define BIT_CCIR_EN (0x1 << 10) +#define BIT_MCLKEN (0x1 << 9) +#define BIT_FCC (0x1 << 8) +#define BIT_PACK_DIR (0x1 << 7) +#define BIT_CLR_STATFIFO (0x1 << 6) +#define BIT_CLR_RXFIFO (0x1 << 5) +#define BIT_GCLK_MODE (0x1 << 4) +#define BIT_INV_DATA (0x1 << 3) +#define BIT_INV_PCLK (0x1 << 2) +#define BIT_REDGE (0x1 << 1) +#define BIT_PIXEL_BIT (0x1 << 0) + +#define SHIFT_MCLKDIV 12 + +/* control reg 3 */ +#define BIT_FRMCNT (0xFFFF << 16) +#define BIT_FRMCNT_RST (0x1 << 15) +#define BIT_DMA_REFLASH_RFF (0x1 << 14) +#define BIT_DMA_REFLASH_SFF (0x1 << 13) +#define BIT_DMA_REQ_EN_RFF (0x1 << 12) +#define BIT_DMA_REQ_EN_SFF (0x1 << 11) +#define BIT_STATFF_LEVEL (0x7 << 8) +#define BIT_HRESP_ERR_EN (0x1 << 7) +#define BIT_RXFF_LEVEL (0x7 << 4) +#define BIT_TWO_8BIT_SENSOR (0x1 << 3) +#define BIT_ZERO_PACK_EN (0x1 << 2) +#define BIT_ECC_INT_EN (0x1 << 1) +#define BIT_ECC_AUTO_EN (0x1 << 0) + +#define SHIFT_FRMCNT 16 + +/* csi status reg */ +#define BIT_SFF_OR_INT (0x1 << 25) +#define BIT_RFF_OR_INT (0x1 << 24) +#define BIT_DMA_TSF_DONE_SFF (0x1 << 22) +#define BIT_STATFF_INT (0x1 << 21) +#define BIT_DMA_TSF_DONE_FB2 (0x1 << 20) +#define BIT_DMA_TSF_DONE_FB1 (0x1 << 19) +#define BIT_RXFF_INT (0x1 << 18) +#define BIT_EOF_INT (0x1 << 17) +#define BIT_SOF_INT (0x1 << 16) +#define BIT_F2_INT (0x1 << 15) +#define BIT_F1_INT (0x1 << 14) +#define BIT_COF_INT (0x1 << 13) +#define BIT_HRESP_ERR_INT (0x1 << 7) +#define BIT_ECC_INT (0x1 << 1) +#define BIT_DRDY (0x1 << 0) + +#define CSI_MCLK_VF 1 +#define CSI_MCLK_ENC 2 +#define CSI_MCLK_RAW 4 +#define CSI_MCLK_I2C 8 +#endif + +#define CSI_CSICR1 (IO_ADDRESS(CSI_BASE_ADDR)) +#define CSI_CSICR2 (IO_ADDRESS(CSI_BASE_ADDR + 0x4)) +#define CSI_CSICR3 (IO_ADDRESS(CSI_BASE_ADDR + 0x8)) +#define CSI_STATFIFO (IO_ADDRESS(CSI_BASE_ADDR + 0xC)) +#define CSI_CSIRXFIFO (IO_ADDRESS(CSI_BASE_ADDR + 0x10)) +#define CSI_CSIRXCNT (IO_ADDRESS(CSI_BASE_ADDR + 0x14)) +#define CSI_CSISR (IO_ADDRESS(CSI_BASE_ADDR + 0x18)) + +#define CSI_CSIDBG (IO_ADDRESS(CSI_BASE_ADDR + 0x1C)) +#define CSI_CSIDMASA_STATFIFO (IO_ADDRESS(CSI_BASE_ADDR + 0x20)) +#define CSI_CSIDMATS_STATFIFO (IO_ADDRESS(CSI_BASE_ADDR + 0x24)) +#define CSI_CSIDMASA_FB1 (IO_ADDRESS(CSI_BASE_ADDR + 0x28)) +#define CSI_CSIDMASA_FB2 (IO_ADDRESS(CSI_BASE_ADDR + 0x2C)) +#define CSI_CSIFBUF_PARA (IO_ADDRESS(CSI_BASE_ADDR + 0x30)) +#define CSI_CSIIMAG_PARA (IO_ADDRESS(CSI_BASE_ADDR + 0x34)) + +#define CSI_CSIRXFIFO_PHYADDR (CSI_BASE_ADDR + 0x10) + +static inline void csi_clear_status(unsigned long status) +{ + __raw_writel(status, CSI_CSISR); +} + +struct csi_signal_cfg_t { + unsigned data_width:3; + unsigned clk_mode:2; + unsigned ext_vsync:1; + unsigned Vsync_pol:1; + unsigned Hsync_pol:1; + unsigned pixclk_pol:1; + unsigned data_pol:1; + unsigned sens_clksrc:1; +}; + +struct csi_config_t { + /* control reg 1 */ + unsigned int swap16_en:1; + unsigned int ext_vsync:1; + unsigned int eof_int_en:1; + unsigned int prp_if_en:1; + unsigned int ccir_mode:1; + unsigned int cof_int_en:1; + unsigned int sf_or_inten:1; + unsigned int rf_or_inten:1; + unsigned int sff_dma_done_inten:1; + unsigned int statff_inten:1; + unsigned int fb2_dma_done_inten:1; + unsigned int fb1_dma_done_inten:1; + unsigned int rxff_inten:1; + unsigned int sof_pol:1; + unsigned int sof_inten:1; + unsigned int mclkdiv:4; + unsigned int hsync_pol:1; + unsigned int ccir_en:1; + unsigned int mclken:1; + unsigned int fcc:1; + unsigned int pack_dir:1; + unsigned int gclk_mode:1; + unsigned int inv_data:1; + unsigned int inv_pclk:1; + unsigned int redge:1; + unsigned int pixel_bit:1; + + /* control reg 3 */ + unsigned int frmcnt:16; + unsigned int frame_reset:1; + unsigned int dma_reflash_rff:1; + unsigned int dma_reflash_sff:1; + unsigned int dma_req_en_rff:1; + unsigned int dma_req_en_sff:1; + unsigned int statff_level:3; + unsigned int hresp_err_en:1; + unsigned int rxff_level:3; + unsigned int two_8bit_sensor:1; + unsigned int zero_pack_en:1; + unsigned int ecc_int_en:1; + unsigned int ecc_auto_en:1; + /* fifo counter */ + unsigned int rxcnt; +}; + +typedef void (*csi_irq_callback_t) (void *data, unsigned long status); + +int32_t csi_enable_mclk(int src, bool flag, bool wait); +void csi_init_interface(void); +void csi_set_16bit_imagpara(int width, int height); +void csi_set_12bit_imagpara(int width, int height); +int csi_read_mclk_flag(void); +void csi_start_callback(void *data); +void csi_stop_callback(void *data); +void csi_enable_int(int arg); +void csi_disable_int(void); +void csi_mclk_enable(void); +void csi_mclk_disable(void); diff --git a/drivers/media/video/mxc/capture/ipu_csi_enc.c b/drivers/media/video/mxc/capture/ipu_csi_enc.c new file mode 100644 index 000000000000..c0842f81ee27 --- /dev/null +++ b/drivers/media/video/mxc/capture/ipu_csi_enc.c @@ -0,0 +1,332 @@ +/* + * Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file ipu_csi_enc.c + * + * @brief CSI Use case for video capture + * + * @ingroup IPU + */ + +#include +#include +#include "mxc_v4l2_capture.h" +#include "ipu_prp_sw.h" + +#ifdef CAMERA_DBG + #define CAMERA_TRACE(x) (printk)x +#else + #define CAMERA_TRACE(x) +#endif + +/* + * Function definitions + */ + +/*! + * csi ENC callback function. + * + * @param irq int irq line + * @param dev_id void * device id + * + * @return status IRQ_HANDLED for handled + */ +static irqreturn_t csi_enc_callback(int irq, void *dev_id) +{ + cam_data *cam = (cam_data *) dev_id; + + if (cam->enc_callback == NULL) + return IRQ_HANDLED; + + cam->enc_callback(irq, dev_id); + return IRQ_HANDLED; +} + +/*! + * CSI ENC enable channel setup function + * + * @param cam struct cam_data * mxc capture instance + * + * @return status + */ +static int csi_enc_setup(cam_data *cam) +{ + ipu_channel_params_t params; + u32 pixel_fmt; + int err = 0; + dma_addr_t dummy = cam->dummy_frame.buffer.m.offset; + + CAMERA_TRACE("In csi_enc_setup\n"); + if (!cam) { + printk(KERN_ERR "cam private is NULL\n"); + return -ENXIO; + } + + memset(¶ms, 0, sizeof(ipu_channel_params_t)); + params.csi_mem.csi = cam->csi; + + if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_YUV420) + pixel_fmt = IPU_PIX_FMT_YUV420P; + else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_YUV422P) + pixel_fmt = IPU_PIX_FMT_YUV422P; + else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_UYVY) + pixel_fmt = IPU_PIX_FMT_UYVY; + else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_YUYV) + pixel_fmt = IPU_PIX_FMT_YUYV; + else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_NV12) + pixel_fmt = IPU_PIX_FMT_NV12; + else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_BGR24) + pixel_fmt = IPU_PIX_FMT_BGR24; + else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_RGB24) + pixel_fmt = IPU_PIX_FMT_RGB24; + else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_RGB565) + pixel_fmt = IPU_PIX_FMT_RGB565; + else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_BGR32) + pixel_fmt = IPU_PIX_FMT_BGR32; + else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_RGB32) + pixel_fmt = IPU_PIX_FMT_RGB32; + else { + printk(KERN_ERR "format not supported\n"); + return -EINVAL; + } + + ipu_csi_enable_mclk_if(CSI_MCLK_ENC, cam->csi, true, true); + + err = ipu_init_channel(CSI_MEM, ¶ms); + if (err != 0) { + printk(KERN_ERR "ipu_init_channel %d\n", err); + return err; + } + + err = ipu_init_channel_buffer(CSI_MEM, IPU_OUTPUT_BUFFER, + pixel_fmt, cam->v2f.fmt.pix.width, + cam->v2f.fmt.pix.height, + cam->v2f.fmt.pix.width, IPU_ROTATE_NONE, + dummy, dummy, + cam->offset.u_offset, + cam->offset.v_offset); + if (err != 0) { + printk(KERN_ERR "CSI_MEM output buffer\n"); + return err; + } + err = ipu_enable_channel(CSI_MEM); + if (err < 0) { + printk(KERN_ERR "ipu_enable_channel CSI_MEM\n"); + return err; + } + + return err; +} + +/*! + * function to update physical buffer address for encorder IDMA channel + * + * @param eba physical buffer address for encorder IDMA channel + * @param buffer_num int buffer 0 or buffer 1 + * + * @return status + */ +static int csi_enc_eba_update(dma_addr_t eba, int *buffer_num) +{ + int err = 0; + + pr_debug("eba %x\n", eba); + err = ipu_update_channel_buffer(CSI_MEM, IPU_OUTPUT_BUFFER, + *buffer_num, eba); + if (err != 0) { + ipu_clear_buffer_ready(CSI_MEM, IPU_OUTPUT_BUFFER, + *buffer_num); + printk(KERN_ERR "err %d buffer_num %d\n", err, *buffer_num); + return err; + } + + ipu_select_buffer(CSI_MEM, IPU_OUTPUT_BUFFER, *buffer_num); + + *buffer_num = (*buffer_num == 0) ? 1 : 0; + + return 0; +} + +/*! + * Enable encoder task + * @param private struct cam_data * mxc capture instance + * + * @return status + */ +static int csi_enc_enabling_tasks(void *private) +{ + cam_data *cam = (cam_data *) private; + int err = 0; + CAMERA_TRACE("IPU:In csi_enc_enabling_tasks\n"); + + cam->dummy_frame.vaddress = dma_alloc_coherent(0, + PAGE_ALIGN(cam->v2f.fmt.pix.sizeimage), + &cam->dummy_frame.paddress, + GFP_DMA | GFP_KERNEL); + if (cam->dummy_frame.vaddress == 0) { + pr_err("ERROR: v4l2 capture: Allocate dummy frame " + "failed.\n"); + return -ENOBUFS; + } + cam->dummy_frame.buffer.type = V4L2_BUF_TYPE_PRIVATE; + cam->dummy_frame.buffer.length = + PAGE_ALIGN(cam->v2f.fmt.pix.sizeimage); + cam->dummy_frame.buffer.m.offset = cam->dummy_frame.paddress; + + ipu_clear_irq(IPU_IRQ_CSI0_OUT_EOF); + err = ipu_request_irq(IPU_IRQ_CSI0_OUT_EOF, + csi_enc_callback, 0, "Mxc Camera", cam); + if (err != 0) { + printk(KERN_ERR "Error registering rot irq\n"); + return err; + } + + err = csi_enc_setup(cam); + if (err != 0) { + printk(KERN_ERR "csi_enc_setup %d\n", err); + return err; + } + + return err; +} + +/*! + * Disable encoder task + * @param private struct cam_data * mxc capture instance + * + * @return int + */ +static int csi_enc_disabling_tasks(void *private) +{ + cam_data *cam = (cam_data *) private; + int err = 0; + + ipu_free_irq(IPU_IRQ_CSI0_OUT_EOF, cam); + + err = ipu_disable_channel(CSI_MEM, true); + + ipu_uninit_channel(CSI_MEM); + + if (cam->dummy_frame.vaddress != 0) { + dma_free_coherent(0, cam->dummy_frame.buffer.length, + cam->dummy_frame.vaddress, + cam->dummy_frame.paddress); + cam->dummy_frame.vaddress = 0; + } + ipu_csi_enable_mclk_if(CSI_MCLK_ENC, cam->csi, false, false); + + return err; +} + +/*! + * Enable csi + * @param private struct cam_data * mxc capture instance + * + * @return status + */ +static int csi_enc_enable_csi(void *private) +{ + cam_data *cam = (cam_data *) private; + + return ipu_enable_csi(cam->csi); +} + +/*! + * Disable csi + * @param private struct cam_data * mxc capture instance + * + * @return status + */ +static int csi_enc_disable_csi(void *private) +{ + cam_data *cam = (cam_data *) private; + + return ipu_disable_csi(cam->csi); +} + +/*! + * function to select CSI ENC as the working path + * + * @param private struct cam_data * mxc capture instance + * + * @return int + */ +int csi_enc_select(void *private) +{ + cam_data *cam = (cam_data *) private; + int err = 0; + + if (cam) { + cam->enc_update_eba = csi_enc_eba_update; + cam->enc_enable = csi_enc_enabling_tasks; + cam->enc_disable = csi_enc_disabling_tasks; + cam->enc_enable_csi = csi_enc_enable_csi; + cam->enc_disable_csi = csi_enc_disable_csi; + } else { + err = -EIO; + } + + return err; +} + +/*! + * function to de-select CSI ENC as the working path + * + * @param private struct cam_data * mxc capture instance + * + * @return int + */ +int csi_enc_deselect(void *private) +{ + cam_data *cam = (cam_data *) private; + int err = 0; + + if (cam) { + cam->enc_update_eba = NULL; + cam->enc_enable = NULL; + cam->enc_disable = NULL; + cam->enc_enable_csi = NULL; + cam->enc_disable_csi = NULL; + } + + return err; +} + +/*! + * Init the Encorder channels + * + * @return Error code indicating success or failure + */ +__init int csi_enc_init(void) +{ + return 0; +} + +/*! + * Deinit the Encorder channels + * + */ +void __exit csi_enc_exit(void) +{ +} + +module_init(csi_enc_init); +module_exit(csi_enc_exit); + +EXPORT_SYMBOL(csi_enc_select); +EXPORT_SYMBOL(csi_enc_deselect); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("CSI ENC Driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/media/video/mxc/capture/ipu_prp_enc.c b/drivers/media/video/mxc/capture/ipu_prp_enc.c new file mode 100644 index 000000000000..5bdbe81cb626 --- /dev/null +++ b/drivers/media/video/mxc/capture/ipu_prp_enc.c @@ -0,0 +1,489 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file ipu_prp_enc.c + * + * @brief IPU Use case for PRP-ENC + * + * @ingroup IPU + */ + +#include +#include +#include "mxc_v4l2_capture.h" +#include "ipu_prp_sw.h" + +#ifdef CAMERA_DBG + #define CAMERA_TRACE(x) (printk)x +#else + #define CAMERA_TRACE(x) +#endif + +static ipu_rotate_mode_t grotation = IPU_ROTATE_NONE; + +/* + * Function definitions + */ + +/*! + * IPU ENC callback function. + * + * @param irq int irq line + * @param dev_id void * device id + * + * @return status IRQ_HANDLED for handled + */ +static irqreturn_t prp_enc_callback(int irq, void *dev_id) +{ + cam_data *cam = (cam_data *) dev_id; + + if (cam->enc_callback == NULL) + return IRQ_HANDLED; + + cam->enc_callback(irq, dev_id); + + return IRQ_HANDLED; +} + +/*! + * PrpENC enable channel setup function + * + * @param cam struct cam_data * mxc capture instance + * + * @return status + */ +static int prp_enc_setup(cam_data *cam) +{ + ipu_channel_params_t enc; + int err = 0; + dma_addr_t dummy = 0xdeadbeaf; + + CAMERA_TRACE("In prp_enc_setup\n"); + if (!cam) { + printk(KERN_ERR "cam private is NULL\n"); + return -ENXIO; + } + memset(&enc, 0, sizeof(ipu_channel_params_t)); + + ipu_csi_get_window_size(&enc.csi_prp_enc_mem.in_width, + &enc.csi_prp_enc_mem.in_height, cam->csi); + + enc.csi_prp_enc_mem.in_pixel_fmt = IPU_PIX_FMT_UYVY; + enc.csi_prp_enc_mem.out_width = cam->v2f.fmt.pix.width; + enc.csi_prp_enc_mem.out_height = cam->v2f.fmt.pix.height; + enc.csi_prp_enc_mem.csi = cam->csi; + if (cam->rotation >= IPU_ROTATE_90_RIGHT) { + enc.csi_prp_enc_mem.out_width = cam->v2f.fmt.pix.height; + enc.csi_prp_enc_mem.out_height = cam->v2f.fmt.pix.width; + } + + if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_YUV420) { + enc.csi_prp_enc_mem.out_pixel_fmt = IPU_PIX_FMT_YUV420P; + pr_info("YUV420\n"); + } else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_YUV422P) { + enc.csi_prp_enc_mem.out_pixel_fmt = IPU_PIX_FMT_YUV422P; + pr_info("YUV422P\n"); + } else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_YUYV) { + enc.csi_prp_enc_mem.out_pixel_fmt = IPU_PIX_FMT_YUYV; + pr_info("YUYV\n"); + } else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_UYVY) { + enc.csi_prp_enc_mem.out_pixel_fmt = IPU_PIX_FMT_UYVY; + pr_info("UYVY\n"); + } else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_NV12) { + enc.csi_prp_enc_mem.out_pixel_fmt = IPU_PIX_FMT_NV12; + pr_info("NV12\n"); + } else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_BGR24) { + enc.csi_prp_enc_mem.out_pixel_fmt = IPU_PIX_FMT_BGR24; + pr_info("BGR24\n"); + } else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_RGB24) { + enc.csi_prp_enc_mem.out_pixel_fmt = IPU_PIX_FMT_RGB24; + pr_info("RGB24\n"); + } else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_RGB565) { + enc.csi_prp_enc_mem.out_pixel_fmt = IPU_PIX_FMT_RGB565; + pr_info("RGB565\n"); + } else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_BGR32) { + enc.csi_prp_enc_mem.out_pixel_fmt = IPU_PIX_FMT_BGR32; + pr_info("BGR32\n"); + } else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_RGB32) { + enc.csi_prp_enc_mem.out_pixel_fmt = IPU_PIX_FMT_RGB32; + pr_info("RGB32\n"); + } else { + printk(KERN_ERR "format not supported\n"); + return -EINVAL; + } + + err = ipu_init_channel(CSI_PRP_ENC_MEM, &enc); + if (err != 0) { + printk(KERN_ERR "ipu_init_channel %d\n", err); + return err; + } + + ipu_csi_enable_mclk_if(CSI_MCLK_ENC, cam->csi, true, true); + + grotation = cam->rotation; + if (cam->rotation >= IPU_ROTATE_90_RIGHT) { + if (cam->rot_enc_bufs_vaddr[0]) { + dma_free_coherent(0, cam->rot_enc_buf_size[0], + cam->rot_enc_bufs_vaddr[0], + cam->rot_enc_bufs[0]); + } + if (cam->rot_enc_bufs_vaddr[1]) { + dma_free_coherent(0, cam->rot_enc_buf_size[1], + cam->rot_enc_bufs_vaddr[1], + cam->rot_enc_bufs[1]); + } + cam->rot_enc_buf_size[0] = + PAGE_ALIGN(cam->v2f.fmt.pix.sizeimage); + cam->rot_enc_bufs_vaddr[0] = + (void *)dma_alloc_coherent(0, cam->rot_enc_buf_size[0], + &cam->rot_enc_bufs[0], + GFP_DMA | GFP_KERNEL); + if (!cam->rot_enc_bufs_vaddr[0]) { + printk(KERN_ERR "alloc enc_bufs0\n"); + return -ENOMEM; + } + cam->rot_enc_buf_size[1] = + PAGE_ALIGN(cam->v2f.fmt.pix.sizeimage); + cam->rot_enc_bufs_vaddr[1] = + (void *)dma_alloc_coherent(0, cam->rot_enc_buf_size[1], + &cam->rot_enc_bufs[1], + GFP_DMA | GFP_KERNEL); + if (!cam->rot_enc_bufs_vaddr[1]) { + dma_free_coherent(0, cam->rot_enc_buf_size[0], + cam->rot_enc_bufs_vaddr[0], + cam->rot_enc_bufs[0]); + cam->rot_enc_bufs_vaddr[0] = NULL; + cam->rot_enc_bufs[0] = 0; + printk(KERN_ERR "alloc enc_bufs1\n"); + return -ENOMEM; + } + + err = ipu_init_channel_buffer(CSI_PRP_ENC_MEM, + IPU_OUTPUT_BUFFER, + enc.csi_prp_enc_mem.out_pixel_fmt, + enc.csi_prp_enc_mem.out_width, + enc.csi_prp_enc_mem.out_height, + enc.csi_prp_enc_mem.out_width, + IPU_ROTATE_NONE, + cam->rot_enc_bufs[0], + cam->rot_enc_bufs[1], 0, 0); + if (err != 0) { + printk(KERN_ERR "CSI_PRP_ENC_MEM err\n"); + return err; + } + + err = ipu_init_channel(MEM_ROT_ENC_MEM, NULL); + if (err != 0) { + printk(KERN_ERR "MEM_ROT_ENC_MEM channel err\n"); + return err; + } + + err = ipu_init_channel_buffer(MEM_ROT_ENC_MEM, IPU_INPUT_BUFFER, + enc.csi_prp_enc_mem.out_pixel_fmt, + enc.csi_prp_enc_mem.out_width, + enc.csi_prp_enc_mem.out_height, + enc.csi_prp_enc_mem.out_width, + cam->rotation, + cam->rot_enc_bufs[0], + cam->rot_enc_bufs[1], 0, 0); + if (err != 0) { + printk(KERN_ERR "MEM_ROT_ENC_MEM input buffer\n"); + return err; + } + + err = + ipu_init_channel_buffer(MEM_ROT_ENC_MEM, IPU_OUTPUT_BUFFER, + enc.csi_prp_enc_mem.out_pixel_fmt, + enc.csi_prp_enc_mem.out_height, + enc.csi_prp_enc_mem.out_width, + cam->v2f.fmt.pix.bytesperline / + bytes_per_pixel(enc.csi_prp_enc_mem. + out_pixel_fmt), + IPU_ROTATE_NONE, dummy, dummy, + cam->offset.u_offset, + cam->offset.v_offset); + if (err != 0) { + printk(KERN_ERR "MEM_ROT_ENC_MEM output buffer\n"); + return err; + } + + err = ipu_link_channels(CSI_PRP_ENC_MEM, MEM_ROT_ENC_MEM); + if (err < 0) { + printk(KERN_ERR + "link CSI_PRP_ENC_MEM-MEM_ROT_ENC_MEM\n"); + return err; + } + + err = ipu_enable_channel(CSI_PRP_ENC_MEM); + if (err < 0) { + printk(KERN_ERR "ipu_enable_channel CSI_PRP_ENC_MEM\n"); + return err; + } + err = ipu_enable_channel(MEM_ROT_ENC_MEM); + if (err < 0) { + printk(KERN_ERR "ipu_enable_channel MEM_ROT_ENC_MEM\n"); + return err; + } + + ipu_select_buffer(CSI_PRP_ENC_MEM, IPU_OUTPUT_BUFFER, 0); + ipu_select_buffer(CSI_PRP_ENC_MEM, IPU_OUTPUT_BUFFER, 1); + } else { + err = + ipu_init_channel_buffer(CSI_PRP_ENC_MEM, IPU_OUTPUT_BUFFER, + enc.csi_prp_enc_mem.out_pixel_fmt, + enc.csi_prp_enc_mem.out_width, + enc.csi_prp_enc_mem.out_height, + cam->v2f.fmt.pix.bytesperline / + bytes_per_pixel(enc.csi_prp_enc_mem. + out_pixel_fmt), + cam->rotation, dummy, dummy, + cam->offset.u_offset, + cam->offset.v_offset); + if (err != 0) { + printk(KERN_ERR "CSI_PRP_ENC_MEM output buffer\n"); + return err; + } + err = ipu_enable_channel(CSI_PRP_ENC_MEM); + if (err < 0) { + printk(KERN_ERR "ipu_enable_channel CSI_PRP_ENC_MEM\n"); + return err; + } + } + + return err; +} + +/*! + * function to update physical buffer address for encorder IDMA channel + * + * @param eba physical buffer address for encorder IDMA channel + * @param buffer_num int buffer 0 or buffer 1 + * + * @return status + */ +static int prp_enc_eba_update(dma_addr_t eba, int *buffer_num) +{ + int err = 0; + + pr_debug("eba %x\n", eba); + if (grotation >= IPU_ROTATE_90_RIGHT) { + err = ipu_update_channel_buffer(MEM_ROT_ENC_MEM, + IPU_OUTPUT_BUFFER, *buffer_num, + eba); + } else { + err = ipu_update_channel_buffer(CSI_PRP_ENC_MEM, + IPU_OUTPUT_BUFFER, *buffer_num, + eba); + } + if (err != 0) { + printk(KERN_ERR "err %d buffer_num %d\n", err, *buffer_num); + return err; + } + + if (grotation >= IPU_ROTATE_90_RIGHT) { + ipu_select_buffer(MEM_ROT_ENC_MEM, IPU_OUTPUT_BUFFER, + *buffer_num); + } else { + ipu_select_buffer(CSI_PRP_ENC_MEM, IPU_OUTPUT_BUFFER, + *buffer_num); + } + + *buffer_num = (*buffer_num == 0) ? 1 : 0; + return 0; +} + +/*! + * Enable encoder task + * @param private struct cam_data * mxc capture instance + * + * @return status + */ +static int prp_enc_enabling_tasks(void *private) +{ + cam_data *cam = (cam_data *) private; + int err = 0; + CAMERA_TRACE("IPU:In prp_enc_enabling_tasks\n"); + + if (cam->rotation >= IPU_ROTATE_90_RIGHT) { + err = ipu_request_irq(IPU_IRQ_PRP_ENC_ROT_OUT_EOF, + prp_enc_callback, 0, "Mxc Camera", cam); + } else { + err = ipu_request_irq(IPU_IRQ_PRP_ENC_OUT_EOF, + prp_enc_callback, 0, "Mxc Camera", cam); + } + if (err != 0) { + printk(KERN_ERR "Error registering rot irq\n"); + return err; + } + + err = prp_enc_setup(cam); + if (err != 0) { + printk(KERN_ERR "prp_enc_setup %d\n", err); + return err; + } + + return err; +} + +/*! + * Disable encoder task + * @param private struct cam_data * mxc capture instance + * + * @return int + */ +static int prp_enc_disabling_tasks(void *private) +{ + cam_data *cam = (cam_data *) private; + int err = 0; + + if (cam->rotation >= IPU_ROTATE_90_RIGHT) { + ipu_free_irq(IPU_IRQ_PRP_ENC_ROT_OUT_EOF, cam); + } else { + ipu_free_irq(IPU_IRQ_PRP_ENC_OUT_EOF, cam); + } + + if (cam->rotation >= IPU_ROTATE_90_RIGHT) { + ipu_unlink_channels(CSI_PRP_ENC_MEM, MEM_ROT_ENC_MEM); + } + + err = ipu_disable_channel(CSI_PRP_ENC_MEM, true); + if (cam->rotation >= IPU_ROTATE_90_RIGHT) { + err |= ipu_disable_channel(MEM_ROT_ENC_MEM, true); + } + + ipu_uninit_channel(CSI_PRP_ENC_MEM); + if (cam->rotation >= IPU_ROTATE_90_RIGHT) { + ipu_uninit_channel(MEM_ROT_ENC_MEM); + } + + ipu_csi_enable_mclk_if(CSI_MCLK_ENC, cam->csi, false, false); + + return err; +} + +/*! + * Enable csi + * @param private struct cam_data * mxc capture instance + * + * @return status + */ +static int prp_enc_enable_csi(void *private) +{ + cam_data *cam = (cam_data *) private; + + return ipu_enable_csi(cam->csi); +} + +/*! + * Disable csi + * @param private struct cam_data * mxc capture instance + * + * @return status + */ +static int prp_enc_disable_csi(void *private) +{ + cam_data *cam = (cam_data *) private; + + return ipu_disable_csi(cam->csi); +} + +/*! + * function to select PRP-ENC as the working path + * + * @param private struct cam_data * mxc capture instance + * + * @return int + */ +int prp_enc_select(void *private) +{ + cam_data *cam = (cam_data *) private; + int err = 0; + + if (cam) { + cam->enc_update_eba = prp_enc_eba_update; + cam->enc_enable = prp_enc_enabling_tasks; + cam->enc_disable = prp_enc_disabling_tasks; + cam->enc_enable_csi = prp_enc_enable_csi; + cam->enc_disable_csi = prp_enc_disable_csi; + } else { + err = -EIO; + } + + return err; +} + +/*! + * function to de-select PRP-ENC as the working path + * + * @param private struct cam_data * mxc capture instance + * + * @return int + */ +int prp_enc_deselect(void *private) +{ + cam_data *cam = (cam_data *) private; + int err = 0; + + if (cam) { + cam->enc_update_eba = NULL; + cam->enc_enable = NULL; + cam->enc_disable = NULL; + cam->enc_enable_csi = NULL; + cam->enc_disable_csi = NULL; + if (cam->rot_enc_bufs_vaddr[0]) { + dma_free_coherent(0, cam->rot_enc_buf_size[0], + cam->rot_enc_bufs_vaddr[0], + cam->rot_enc_bufs[0]); + cam->rot_enc_bufs_vaddr[0] = NULL; + cam->rot_enc_bufs[0] = 0; + } + if (cam->rot_enc_bufs_vaddr[1]) { + dma_free_coherent(0, cam->rot_enc_buf_size[1], + cam->rot_enc_bufs_vaddr[1], + cam->rot_enc_bufs[1]); + cam->rot_enc_bufs_vaddr[1] = NULL; + cam->rot_enc_bufs[1] = 0; + } + } + + return err; +} + +/*! + * Init the Encorder channels + * + * @return Error code indicating success or failure + */ +__init int prp_enc_init(void) +{ + return 0; +} + +/*! + * Deinit the Encorder channels + * + */ +void __exit prp_enc_exit(void) +{ +} + +module_init(prp_enc_init); +module_exit(prp_enc_exit); + +EXPORT_SYMBOL(prp_enc_select); +EXPORT_SYMBOL(prp_enc_deselect); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("IPU PRP ENC Driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/media/video/mxc/capture/ipu_prp_sw.h b/drivers/media/video/mxc/capture/ipu_prp_sw.h new file mode 100644 index 000000000000..c9462045261d --- /dev/null +++ b/drivers/media/video/mxc/capture/ipu_prp_sw.h @@ -0,0 +1,38 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file ipu_prp_sw.h + * + * @brief This file contains the IPU PRP use case driver header. + * + * @ingroup IPU + */ + +#ifndef _INCLUDE_IPU__PRP_SW_H_ +#define _INCLUDE_IPU__PRP_SW_H_ + +int csi_enc_select(void *private); +int csi_enc_deselect(void *private); +int prp_enc_select(void *private); +int prp_enc_deselect(void *private); +int prp_vf_adc_select(void *private); +int prp_vf_sdc_select(void *private); +int prp_vf_sdc_select_bg(void *private); +int prp_vf_adc_deselect(void *private); +int prp_vf_sdc_deselect(void *private); +int prp_vf_sdc_deselect_bg(void *private); +int prp_still_select(void *private); +int prp_still_deselect(void *private); + +#endif diff --git a/drivers/media/video/mxc/capture/ipu_prp_vf_adc.c b/drivers/media/video/mxc/capture/ipu_prp_vf_adc.c new file mode 100644 index 000000000000..b6550fa52dc6 --- /dev/null +++ b/drivers/media/video/mxc/capture/ipu_prp_vf_adc.c @@ -0,0 +1,601 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file ipu_prp_vf_adc.c + * + * @brief IPU Use case for PRP-VF + * + * @ingroup IPU + */ + +#include "mxc_v4l2_capture.h" +#include "ipu_prp_sw.h" +#include +#include +#include + +/* + * Function definitions + */ + +/*! + * prpvf_start - start the vf task + * + * @param private cam_data * mxc v4l2 main structure + * + */ +static int prpvf_start(void *private) +{ + cam_data *cam = (cam_data *) private; + ipu_channel_params_t vf; + ipu_channel_params_t params; + u32 format = IPU_PIX_FMT_RGB565; + u32 size = 2; + int err = 0; + + if (!cam) { + printk(KERN_ERR "prpvf_start private is NULL\n"); + return -ENXIO; + } + + if (cam->overlay_active == true) { + printk(KERN_ERR "prpvf_start already start.\n"); + return 0; + } + + mxcfb_set_refresh_mode(cam->overlay_fb, MXCFB_REFRESH_OFF, 0); + + memset(&vf, 0, sizeof(ipu_channel_params_t)); + ipu_csi_get_window_size(&vf.csi_prp_vf_adc.in_width, + &vf.csi_prp_vf_adc.in_height); + vf.csi_prp_vf_adc.in_pixel_fmt = IPU_PIX_FMT_UYVY; + vf.csi_prp_vf_adc.out_width = cam->win.w.width; + vf.csi_prp_vf_adc.out_height = cam->win.w.height; + vf.csi_prp_vf_adc.graphics_combine_en = 0; + vf.csi_prp_vf_adc.out_left = cam->win.w.left; + + /* hope to be removed when those offset taken cared by adc driver. */ +#ifdef CONFIG_FB_MXC_EPSON_QVGA_PANEL + vf.csi_prp_vf_adc.out_left += 12; +#endif +#ifdef CONFIG_FB_MXC_EPSON_PANEL + vf.csi_prp_vf_adc.out_left += 2; +#endif + + vf.csi_prp_vf_adc.out_top = cam->win.w.top; + + if (cam->vf_rotation >= IPU_ROTATE_90_RIGHT) { + vf.csi_prp_vf_adc.out_width = cam->win.w.height; + vf.csi_prp_vf_adc.out_height = cam->win.w.width; + + size = cam->win.w.width * cam->win.w.height * size; + vf.csi_prp_vf_adc.out_pixel_fmt = format; + err = ipu_init_channel(CSI_PRP_VF_MEM, &vf); + if (err != 0) + return err; + + ipu_csi_enable_mclk_if(CSI_MCLK_VF, cam->csi, true, true); + + if (cam->vf_bufs_vaddr[0]) { + dma_free_coherent(0, cam->vf_bufs_size[0], + cam->vf_bufs_vaddr[0], + cam->vf_bufs[0]); + } + if (cam->vf_bufs_vaddr[1]) { + dma_free_coherent(0, cam->vf_bufs_size[1], + cam->vf_bufs_vaddr[1], + cam->vf_bufs[1]); + } + cam->vf_bufs_size[0] = size; + cam->vf_bufs_vaddr[0] = (void *)dma_alloc_coherent(0, + cam-> + vf_bufs_size + [0], + &cam-> + vf_bufs[0], + GFP_DMA | + GFP_KERNEL); + if (cam->vf_bufs_vaddr[0] == NULL) { + printk(KERN_ERR + "prpvf_start: Error to allocate vf buffer\n"); + err = -ENOMEM; + goto out_3; + } + cam->vf_bufs_size[1] = size; + cam->vf_bufs_vaddr[1] = (void *)dma_alloc_coherent(0, + cam-> + vf_bufs_size + [1], + &cam-> + vf_bufs[1], + GFP_DMA | + GFP_KERNEL); + if (cam->vf_bufs_vaddr[1] == NULL) { + printk(KERN_ERR + "prpvf_start: Error to allocate vf buffer\n"); + err = -ENOMEM; + goto out_3; + } + + err = ipu_init_channel_buffer(CSI_PRP_VF_MEM, IPU_OUTPUT_BUFFER, + format, + vf.csi_prp_vf_mem.out_width, + vf.csi_prp_vf_mem.out_height, + vf.csi_prp_vf_mem.out_width, + IPU_ROTATE_NONE, + cam->vf_bufs[0], cam->vf_bufs[1], + 0, 0); + if (err != 0) + goto out_3; + + if (cam->rot_vf_bufs[0]) { + dma_free_coherent(0, cam->rot_vf_buf_size[0], + cam->rot_vf_bufs_vaddr[0], + cam->rot_vf_bufs[0]); + } + if (cam->rot_vf_bufs[1]) { + dma_free_coherent(0, cam->rot_vf_buf_size[1], + cam->rot_vf_bufs_vaddr[1], + cam->rot_vf_bufs[1]); + } + cam->rot_vf_buf_size[0] = PAGE_ALIGN(size); + cam->rot_vf_bufs_vaddr[0] = (void *)dma_alloc_coherent(0, + cam-> + rot_vf_buf_size + [0], + &cam-> + rot_vf_bufs + [0], + GFP_DMA | + GFP_KERNEL); + if (cam->rot_vf_bufs_vaddr[0] == NULL) { + printk(KERN_ERR + "prpvf_start: Error to allocate rot_vf_bufs\n"); + err = -ENOMEM; + goto out_3; + } + cam->rot_vf_buf_size[1] = PAGE_ALIGN(size); + cam->rot_vf_bufs_vaddr[1] = (void *)dma_alloc_coherent(0, + cam-> + rot_vf_buf_size + [1], + &cam-> + rot_vf_bufs + [1], + GFP_DMA | + GFP_KERNEL); + if (cam->rot_vf_bufs_vaddr[1] == NULL) { + printk(KERN_ERR + "prpvf_start: Error to allocate rot_vf_bufs\n"); + err = -ENOMEM; + goto out_3; + } + err = ipu_init_channel(MEM_ROT_VF_MEM, NULL); + if (err != 0) { + printk(KERN_ERR "prpvf_start :Error " + "MEM_ROT_VF_MEM channel\n"); + goto out_3; + } + + err = ipu_init_channel_buffer(MEM_ROT_VF_MEM, IPU_INPUT_BUFFER, + format, + vf.csi_prp_vf_mem.out_width, + vf.csi_prp_vf_mem.out_height, + vf.csi_prp_vf_mem.out_width, + cam->vf_rotation, cam->vf_bufs[0], + cam->vf_bufs[1], 0, 0); + if (err != 0) { + printk(KERN_ERR "prpvf_start: Error " + "MEM_ROT_VF_MEM input buffer\n"); + goto out_2; + } + + err = ipu_init_channel_buffer(MEM_ROT_VF_MEM, IPU_OUTPUT_BUFFER, + format, + vf.csi_prp_vf_mem.out_height, + vf.csi_prp_vf_mem.out_width, + vf.csi_prp_vf_mem.out_height, + IPU_ROTATE_NONE, + cam->rot_vf_bufs[0], + cam->rot_vf_bufs[1], 0, 0); + if (err != 0) { + printk(KERN_ERR "prpvf_start: Error " + "MEM_ROT_VF_MEM output buffer\n"); + goto out_2; + } + + err = ipu_link_channels(CSI_PRP_VF_MEM, MEM_ROT_VF_MEM); + if (err < 0) { + printk(KERN_ERR "prpvf_start: Error " + "linking CSI_PRP_VF_MEM-MEM_ROT_VF_MEM\n"); + goto out_2; + } + + ipu_disable_channel(ADC_SYS2, false); + ipu_uninit_channel(ADC_SYS2); + + params.adc_sys2.disp = DISP0; + params.adc_sys2.ch_mode = WriteTemplateNonSeq; + params.adc_sys2.out_left = cam->win.w.left; + /* going to be removed when those offset taken cared by adc driver. */ +#ifdef CONFIG_FB_MXC_EPSON_QVGA_PANEL + params.adc_sys2.out_left += 12; +#endif +#ifdef CONFIG_FB_MXC_EPSON_PANEL + params.adc_sys2.out_left += 2; +#endif + params.adc_sys2.out_top = cam->win.w.top; + err = ipu_init_channel(ADC_SYS2, ¶ms); + if (err != 0) { + printk(KERN_ERR + "prpvf_start: Error initializing ADC SYS1\n"); + goto out_2; + } + + err = ipu_init_channel_buffer(ADC_SYS2, IPU_INPUT_BUFFER, + format, + vf.csi_prp_vf_mem.out_height, + vf.csi_prp_vf_mem.out_width, + vf.csi_prp_vf_mem.out_height, + IPU_ROTATE_NONE, + cam->rot_vf_bufs[0], + cam->rot_vf_bufs[1], 0, 0); + if (err != 0) { + printk(KERN_ERR "Error initializing ADC SYS1 buffer\n"); + goto out_1; + } + + err = ipu_link_channels(MEM_ROT_VF_MEM, ADC_SYS2); + if (err < 0) { + printk(KERN_ERR + "Error linking MEM_ROT_VF_MEM-ADC_SYS2\n"); + goto out_1; + } + + ipu_enable_channel(CSI_PRP_VF_MEM); + ipu_enable_channel(MEM_ROT_VF_MEM); + ipu_enable_channel(ADC_SYS2); + + ipu_select_buffer(CSI_PRP_VF_MEM, IPU_OUTPUT_BUFFER, 0); + ipu_select_buffer(CSI_PRP_VF_MEM, IPU_OUTPUT_BUFFER, 1); + ipu_select_buffer(MEM_ROT_VF_MEM, IPU_OUTPUT_BUFFER, 0); + ipu_select_buffer(MEM_ROT_VF_MEM, IPU_OUTPUT_BUFFER, 1); + } +#ifndef CONFIG_MXC_IPU_PRP_VF_SDC + else if (cam->vf_rotation == IPU_ROTATE_NONE) { + vf.csi_prp_vf_adc.out_pixel_fmt = IPU_PIX_FMT_BGR32; + err = ipu_init_channel(CSI_PRP_VF_ADC, &vf); + if (err != 0) { + printk(KERN_ERR "prpvf_start: Error " + "initializing CSI_PRP_VF_ADC\n"); + return err; + } + ipu_csi_enable_mclk_if(CSI_MCLK_VF, cam->csi, true, true); + err = ipu_init_channel_buffer(CSI_PRP_VF_ADC, IPU_OUTPUT_BUFFER, + format, cam->win.w.width, + cam->win.w.height, + cam->win.w.width, IPU_ROTATE_NONE, + 0, 0, 0, 0); + if (err != 0) { + printk(KERN_ERR "prpvf_start: Error " + "initializing CSI_PRP_VF_MEM\n"); + return err; + } + ipu_enable_channel(CSI_PRP_VF_ADC); + } +#endif + else { + size = cam->win.w.width * cam->win.w.height * size; + vf.csi_prp_vf_adc.out_pixel_fmt = format; + err = ipu_init_channel(CSI_PRP_VF_MEM, &vf); + if (err != 0) { + printk(KERN_ERR "prpvf_start: Error " + "initializing CSI_PRP_VF_MEM\n"); + return err; + } + + ipu_csi_enable_mclk_if(CSI_MCLK_VF, cam->csi, true, true); + + if (cam->vf_bufs[0]) { + dma_free_coherent(0, cam->vf_bufs_size[0], + cam->vf_bufs_vaddr[0], + cam->vf_bufs[0]); + } + if (cam->vf_bufs[1]) { + dma_free_coherent(0, cam->vf_bufs_size[1], + cam->vf_bufs_vaddr[1], + cam->vf_bufs[1]); + } + cam->vf_bufs_size[0] = PAGE_ALIGN(size); + cam->vf_bufs_vaddr[0] = (void *)dma_alloc_coherent(0, + cam-> + vf_bufs_size + [0], + &cam-> + vf_bufs[0], + GFP_DMA | + GFP_KERNEL); + if (cam->vf_bufs_vaddr[0] == NULL) { + printk(KERN_ERR + "prpvf_start: Error to allocate vf_bufs\n"); + err = -ENOMEM; + goto out_3; + } + cam->vf_bufs_size[1] = PAGE_ALIGN(size); + cam->vf_bufs_vaddr[1] = (void *)dma_alloc_coherent(0, + cam-> + vf_bufs_size + [1], + &cam-> + vf_bufs[1], + GFP_DMA | + GFP_KERNEL); + if (cam->vf_bufs_vaddr[1] == NULL) { + printk(KERN_ERR + "prpvf_start: Error to allocate vf_bufs\n"); + err = -ENOMEM; + goto out_3; + } + err = ipu_init_channel_buffer(CSI_PRP_VF_MEM, IPU_OUTPUT_BUFFER, + format, + vf.csi_prp_vf_mem.out_width, + vf.csi_prp_vf_mem.out_height, + vf.csi_prp_vf_mem.out_width, + cam->vf_rotation, + cam->vf_bufs[0], cam->vf_bufs[1], + 0, 0); + if (err != 0) { + printk(KERN_ERR "prpvf_start: Error " + "initializing CSI_PRP_VF_MEM\n"); + goto out_3; + } + + ipu_disable_channel(ADC_SYS2, false); + ipu_uninit_channel(ADC_SYS2); + + params.adc_sys2.disp = DISP0; + params.adc_sys2.ch_mode = WriteTemplateNonSeq; + params.adc_sys2.out_left = cam->win.w.left; + /* going to be removed when those offset taken cared by adc driver.*/ +#ifdef CONFIG_FB_MXC_EPSON_QVGA_PANEL + params.adc_sys2.out_left += 12; +#endif +#ifdef CONFIG_FB_MXC_EPSON_PANEL + params.adc_sys2.out_left += 2; +#endif + params.adc_sys2.out_top = cam->win.w.top; + err = ipu_init_channel(ADC_SYS2, ¶ms); + if (err != 0) { + printk(KERN_ERR "prpvf_start: Error " + "initializing ADC_SYS2\n"); + goto out_3; + } + + err = ipu_init_channel_buffer(ADC_SYS2, IPU_INPUT_BUFFER, + format, + vf.csi_prp_vf_mem.out_width, + vf.csi_prp_vf_mem.out_height, + vf.csi_prp_vf_mem.out_width, + IPU_ROTATE_NONE, cam->vf_bufs[0], + cam->vf_bufs[1], 0, 0); + if (err != 0) { + printk(KERN_ERR "prpvf_start: Error " + "initializing ADC SYS1 buffer\n"); + goto out_1; + } + + err = ipu_link_channels(CSI_PRP_VF_MEM, ADC_SYS2); + if (err < 0) { + printk(KERN_ERR "prpvf_start: Error " + "linking MEM_ROT_VF_MEM-ADC_SYS2\n"); + goto out_1; + } + + ipu_enable_channel(CSI_PRP_VF_MEM); + ipu_enable_channel(ADC_SYS2); + + ipu_select_buffer(CSI_PRP_VF_MEM, IPU_OUTPUT_BUFFER, 0); + ipu_select_buffer(CSI_PRP_VF_MEM, IPU_OUTPUT_BUFFER, 1); + } + + cam->overlay_active = true; + return err; + + out_1: + ipu_uninit_channel(ADC_SYS2); + out_2: + if (cam->vf_rotation >= IPU_ROTATE_90_RIGHT) { + ipu_uninit_channel(MEM_ROT_VF_MEM); + } + out_3: + ipu_uninit_channel(CSI_PRP_VF_MEM); + if (cam->rot_vf_bufs_vaddr[0]) { + dma_free_coherent(0, cam->rot_vf_buf_size[0], + cam->rot_vf_bufs_vaddr[0], + cam->rot_vf_bufs[0]); + cam->rot_vf_bufs_vaddr[0] = NULL; + cam->rot_vf_bufs[0] = 0; + } + if (cam->rot_vf_bufs_vaddr[1]) { + dma_free_coherent(0, cam->rot_vf_buf_size[1], + cam->rot_vf_bufs_vaddr[1], + cam->rot_vf_bufs[1]); + cam->rot_vf_bufs_vaddr[1] = NULL; + cam->rot_vf_bufs[1] = 0; + } + if (cam->vf_bufs_vaddr[0]) { + dma_free_coherent(0, cam->vf_bufs_size[0], + cam->vf_bufs_vaddr[0], cam->vf_bufs[0]); + cam->vf_bufs_vaddr[0] = NULL; + cam->vf_bufs[0] = 0; + } + if (cam->vf_bufs_vaddr[1]) { + dma_free_coherent(0, cam->vf_bufs_size[1], + cam->vf_bufs_vaddr[1], cam->vf_bufs[1]); + cam->vf_bufs_vaddr[1] = NULL; + cam->vf_bufs[1] = 0; + } + return err; +} + +/*! + * prpvf_stop - stop the vf task + * + * @param private cam_data * mxc v4l2 main structure + * + */ +static int prpvf_stop(void *private) +{ + cam_data *cam = (cam_data *) private; + int err = 0; + + if (cam->overlay_active == false) + return 0; + + if (cam->vf_rotation >= IPU_ROTATE_90_RIGHT) { + ipu_unlink_channels(CSI_PRP_VF_MEM, MEM_ROT_VF_MEM); + ipu_unlink_channels(MEM_ROT_VF_MEM, ADC_SYS2); + + ipu_disable_channel(CSI_PRP_VF_MEM, true); + ipu_disable_channel(MEM_ROT_VF_MEM, true); + ipu_disable_channel(ADC_SYS2, true); + + ipu_uninit_channel(CSI_PRP_VF_MEM); + ipu_uninit_channel(MEM_ROT_VF_MEM); + ipu_uninit_channel(ADC_SYS2); + + ipu_csi_enable_mclk_if(CSI_MCLK_VF, cam->csi, false, false); + } +#ifndef CONFIG_MXC_IPU_PRP_VF_SDC + else if (cam->vf_rotation == IPU_ROTATE_NONE) { + ipu_disable_channel(CSI_PRP_VF_ADC, false); + ipu_uninit_channel(CSI_PRP_VF_ADC); + ipu_csi_enable_mclk_if(CSI_MCLK_VF, cam->csi, false, false); + } +#endif + else { + ipu_unlink_channels(CSI_PRP_VF_MEM, ADC_SYS2); + + ipu_disable_channel(CSI_PRP_VF_MEM, true); + ipu_disable_channel(ADC_SYS2, true); + + ipu_uninit_channel(CSI_PRP_VF_MEM); + ipu_uninit_channel(ADC_SYS2); + + ipu_csi_enable_mclk_if(CSI_MCLK_VF, cam->csi, false, false); + } + + if (cam->vf_bufs_vaddr[0]) { + dma_free_coherent(0, cam->vf_bufs_size[0], + cam->vf_bufs_vaddr[0], cam->vf_bufs[0]); + cam->vf_bufs_vaddr[0] = NULL; + cam->vf_bufs[0] = 0; + } + if (cam->vf_bufs_vaddr[1]) { + dma_free_coherent(0, cam->vf_bufs_size[1], + cam->vf_bufs_vaddr[1], cam->vf_bufs[1]); + cam->vf_bufs_vaddr[1] = NULL; + cam->vf_bufs[1] = 0; + } + if (cam->rot_vf_bufs_vaddr[0]) { + dma_free_coherent(0, cam->rot_vf_buf_size[0], + cam->rot_vf_bufs_vaddr[0], + cam->rot_vf_bufs[0]); + cam->rot_vf_bufs_vaddr[0] = NULL; + cam->rot_vf_bufs[0] = 0; + } + if (cam->rot_vf_bufs_vaddr[1]) { + dma_free_coherent(0, cam->rot_vf_buf_size[1], + cam->rot_vf_bufs_vaddr[1], + cam->rot_vf_bufs[1]); + cam->rot_vf_bufs_vaddr[1] = NULL; + cam->rot_vf_bufs[1] = 0; + } + + cam->overlay_active = false; + + mxcfb_set_refresh_mode(cam->overlay_fb, MXCFB_REFRESH_PARTIAL, 0); + return err; +} + +/*! + * function to select PRP-VF as the working path + * + * @param private cam_data * mxc v4l2 main structure + * + * @return status + */ +int prp_vf_adc_select(void *private) +{ + cam_data *cam; + if (private) { + cam = (cam_data *) private; + cam->vf_start_adc = prpvf_start; + cam->vf_stop_adc = prpvf_stop; + cam->overlay_active = false; + } else { + return -EIO; + } + return 0; +} + +/*! + * function to de-select PRP-VF as the working path + * + * @param private cam_data * mxc v4l2 main structure + * + * @return status + */ +int prp_vf_adc_deselect(void *private) +{ + cam_data *cam; + int err = 0; + err = prpvf_stop(private); + + if (private) { + cam = (cam_data *) private; + cam->vf_start_adc = NULL; + cam->vf_stop_adc = NULL; + } + return err; +} + +/*! + * Init viewfinder task. + * + * @return Error code indicating success or failure + */ +__init int prp_vf_adc_init(void) +{ + return 0; +} + +/*! + * Deinit viewfinder task. + * + * @return Error code indicating success or failure + */ +void __exit prp_vf_adc_exit(void) +{ +} + +module_init(prp_vf_adc_init); +module_exit(prp_vf_adc_exit); + +EXPORT_SYMBOL(prp_vf_adc_select); +EXPORT_SYMBOL(prp_vf_adc_deselect); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("IPU PRP VF ADC Driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/media/video/mxc/capture/ipu_prp_vf_sdc.c b/drivers/media/video/mxc/capture/ipu_prp_vf_sdc.c new file mode 100644 index 000000000000..490dcd2d2f30 --- /dev/null +++ b/drivers/media/video/mxc/capture/ipu_prp_vf_sdc.c @@ -0,0 +1,467 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file ipu_prp_vf_sdc.c + * + * @brief IPU Use case for PRP-VF + * + * @ingroup IPU + */ + +#include +#include +#include +#include +#include +#include "mxc_v4l2_capture.h" +#include "ipu_prp_sw.h" + +#define OVERLAY_FB_SUPPORT_NONSTD (cpu_is_mx5()) + +/* + * Function definitions + */ + +/*! + * prpvf_start - start the vf task + * + * @param private cam_data * mxc v4l2 main structure + * + */ +static int prpvf_start(void *private) +{ + struct fb_var_screeninfo fbvar; + struct fb_info *fbi = NULL; + cam_data *cam = (cam_data *) private; + ipu_channel_params_t vf; + u32 vf_out_format = 0; + u32 size = 2, temp = 0; + int err = 0, i = 0; + + if (!cam) { + printk(KERN_ERR "private is NULL\n"); + return -EIO; + } + + if (cam->overlay_active == true) { + pr_debug("already started.\n"); + return 0; + } + + for (i = 0; i < num_registered_fb; i++) { + char *idstr = registered_fb[i]->fix.id; + if (strcmp(idstr, "DISP3 FG") == 0) { + fbi = registered_fb[i]; + break; + } + } + + if (fbi == NULL) { + printk(KERN_ERR "DISP3 FG fb not found\n"); + return -EPERM; + } + + fbvar = fbi->var; + + /* Store the overlay frame buffer's original std */ + cam->fb_origin_std = fbvar.nonstd; + + if (OVERLAY_FB_SUPPORT_NONSTD) { + /* Use DP to do CSC so that we can get better performance */ + vf_out_format = IPU_PIX_FMT_UYVY; + fbvar.nonstd = vf_out_format; + } else { + vf_out_format = IPU_PIX_FMT_RGB565; + fbvar.nonstd = 0; + } + + fbvar.bits_per_pixel = 16; + fbvar.xres = fbvar.xres_virtual = cam->win.w.width; + fbvar.yres = cam->win.w.height; + fbvar.yres_virtual = cam->win.w.height * 2; + fbvar.activate |= FB_ACTIVATE_FORCE; + fb_set_var(fbi, &fbvar); + + ipu_disp_set_window_pos(MEM_FG_SYNC, cam->win.w.left, + cam->win.w.top); + + acquire_console_sem(); + fb_blank(fbi, FB_BLANK_UNBLANK); + release_console_sem(); + + memset(&vf, 0, sizeof(ipu_channel_params_t)); + ipu_csi_get_window_size(&vf.csi_prp_vf_mem.in_width, + &vf.csi_prp_vf_mem.in_height, cam->csi); + vf.csi_prp_vf_mem.in_pixel_fmt = IPU_PIX_FMT_UYVY; + vf.csi_prp_vf_mem.out_width = cam->win.w.width; + vf.csi_prp_vf_mem.out_height = cam->win.w.height; + vf.csi_prp_vf_mem.csi = cam->csi; + if (cam->vf_rotation >= IPU_ROTATE_90_RIGHT) { + vf.csi_prp_vf_mem.out_width = cam->win.w.height; + vf.csi_prp_vf_mem.out_height = cam->win.w.width; + } + vf.csi_prp_vf_mem.out_pixel_fmt = vf_out_format; + size = cam->win.w.width * cam->win.w.height * size; + + err = ipu_init_channel(CSI_PRP_VF_MEM, &vf); + if (err != 0) + goto out_5; + + ipu_csi_enable_mclk_if(CSI_MCLK_VF, cam->csi, true, true); + + if (cam->vf_bufs_vaddr[0]) { + dma_free_coherent(0, cam->vf_bufs_size[0], + cam->vf_bufs_vaddr[0], + (dma_addr_t) cam->vf_bufs[0]); + } + if (cam->vf_bufs_vaddr[1]) { + dma_free_coherent(0, cam->vf_bufs_size[1], + cam->vf_bufs_vaddr[1], + (dma_addr_t) cam->vf_bufs[1]); + } + cam->vf_bufs_size[0] = PAGE_ALIGN(size); + cam->vf_bufs_vaddr[0] = (void *)dma_alloc_coherent(0, + cam->vf_bufs_size[0], + (dma_addr_t *) & + cam->vf_bufs[0], + GFP_DMA | + GFP_KERNEL); + if (cam->vf_bufs_vaddr[0] == NULL) { + printk(KERN_ERR "Error to allocate vf buffer\n"); + err = -ENOMEM; + goto out_4; + } + cam->vf_bufs_size[1] = PAGE_ALIGN(size); + cam->vf_bufs_vaddr[1] = (void *)dma_alloc_coherent(0, + cam->vf_bufs_size[1], + (dma_addr_t *) & + cam->vf_bufs[1], + GFP_DMA | + GFP_KERNEL); + if (cam->vf_bufs_vaddr[1] == NULL) { + printk(KERN_ERR "Error to allocate vf buffer\n"); + err = -ENOMEM; + goto out_3; + } + pr_debug("vf_bufs %x %x\n", cam->vf_bufs[0], cam->vf_bufs[1]); + + if (cam->vf_rotation >= IPU_ROTATE_VERT_FLIP) { + err = ipu_init_channel_buffer(CSI_PRP_VF_MEM, IPU_OUTPUT_BUFFER, + vf_out_format, + vf.csi_prp_vf_mem.out_width, + vf.csi_prp_vf_mem.out_height, + vf.csi_prp_vf_mem.out_width, + IPU_ROTATE_NONE, cam->vf_bufs[0], + cam->vf_bufs[1], 0, 0); + if (err != 0) { + goto out_3; + } + + err = ipu_init_channel(MEM_ROT_VF_MEM, NULL); + if (err != 0) { + printk(KERN_ERR "Error MEM_ROT_VF_MEM channel\n"); + goto out_3; + } + + err = ipu_init_channel_buffer(MEM_ROT_VF_MEM, IPU_INPUT_BUFFER, + vf_out_format, + vf.csi_prp_vf_mem.out_width, + vf.csi_prp_vf_mem.out_height, + vf.csi_prp_vf_mem.out_width, + cam->vf_rotation, cam->vf_bufs[0], + cam->vf_bufs[1], 0, 0); + if (err != 0) { + printk(KERN_ERR "Error MEM_ROT_VF_MEM input buffer\n"); + goto out_2; + } + + if (cam->vf_rotation < IPU_ROTATE_90_RIGHT) { + temp = vf.csi_prp_vf_mem.out_width; + vf.csi_prp_vf_mem.out_width = + vf.csi_prp_vf_mem.out_height; + vf.csi_prp_vf_mem.out_height = temp; + } + + err = ipu_init_channel_buffer(MEM_ROT_VF_MEM, IPU_OUTPUT_BUFFER, + vf_out_format, + vf.csi_prp_vf_mem.out_height, + vf.csi_prp_vf_mem.out_width, + vf.csi_prp_vf_mem.out_height, + IPU_ROTATE_NONE, + fbi->fix.smem_start + + (fbi->fix.line_length * + fbi->var.yres), + fbi->fix.smem_start, 0, 0); + + if (err != 0) { + printk(KERN_ERR "Error MEM_ROT_VF_MEM output buffer\n"); + goto out_2; + } + + err = ipu_link_channels(CSI_PRP_VF_MEM, MEM_ROT_VF_MEM); + if (err < 0) { + printk(KERN_ERR + "Error link CSI_PRP_VF_MEM-MEM_ROT_VF_MEM\n"); + goto out_2; + } + + err = ipu_link_channels(MEM_ROT_VF_MEM, MEM_FG_SYNC); + if (err < 0) { + printk(KERN_ERR + "Error link MEM_ROT_VF_MEM-MEM_FG_SYNC\n"); + goto out_1; + } + + ipu_enable_channel(CSI_PRP_VF_MEM); + ipu_enable_channel(MEM_ROT_VF_MEM); + + ipu_select_buffer(CSI_PRP_VF_MEM, IPU_OUTPUT_BUFFER, 0); + ipu_select_buffer(CSI_PRP_VF_MEM, IPU_OUTPUT_BUFFER, 1); + ipu_select_buffer(MEM_ROT_VF_MEM, IPU_OUTPUT_BUFFER, 0); + ipu_select_buffer(MEM_ROT_VF_MEM, IPU_OUTPUT_BUFFER, 1); + } else { + err = ipu_init_channel_buffer(CSI_PRP_VF_MEM, IPU_OUTPUT_BUFFER, + vf_out_format, cam->win.w.width, + cam->win.w.height, + cam->win.w.width, + cam->vf_rotation, + fbi->fix.smem_start + + (fbi->fix.line_length * + fbi->var.yres), + fbi->fix.smem_start, 0, 0); + if (err != 0) { + printk(KERN_ERR "Error initializing CSI_PRP_VF_MEM\n"); + goto out_4; + } + + err = ipu_link_channels(CSI_PRP_VF_MEM, MEM_FG_SYNC); + if (err < 0) { + printk(KERN_ERR "Error linking ipu channels\n"); + goto out_4; + } + + ipu_enable_channel(CSI_PRP_VF_MEM); + + ipu_select_buffer(CSI_PRP_VF_MEM, IPU_OUTPUT_BUFFER, 0); + ipu_select_buffer(CSI_PRP_VF_MEM, IPU_OUTPUT_BUFFER, 1); + } + + cam->overlay_active = true; + return err; + +out_1: + ipu_unlink_channels(CSI_PRP_VF_MEM, MEM_ROT_VF_MEM); +out_2: + if (cam->vf_rotation >= IPU_ROTATE_VERT_FLIP) { + ipu_uninit_channel(MEM_ROT_VF_MEM); + } +out_3: + if (cam->vf_bufs_vaddr[0]) { + dma_free_coherent(0, cam->vf_bufs_size[0], + cam->vf_bufs_vaddr[0], + (dma_addr_t) cam->vf_bufs[0]); + cam->vf_bufs_vaddr[0] = NULL; + cam->vf_bufs[0] = 0; + } + if (cam->vf_bufs_vaddr[1]) { + dma_free_coherent(0, cam->vf_bufs_size[1], + cam->vf_bufs_vaddr[1], + (dma_addr_t) cam->vf_bufs[1]); + cam->vf_bufs_vaddr[1] = NULL; + cam->vf_bufs[1] = 0; + } +out_4: + ipu_uninit_channel(CSI_PRP_VF_MEM); +out_5: + return err; +} + +/*! + * prpvf_stop - stop the vf task + * + * @param private cam_data * mxc v4l2 main structure + * + */ +static int prpvf_stop(void *private) +{ + cam_data *cam = (cam_data *) private; + int err = 0, i = 0; + struct fb_info *fbi = NULL; + struct fb_var_screeninfo fbvar; + + if (cam->overlay_active == false) + return 0; + + for (i = 0; i < num_registered_fb; i++) { + char *idstr = registered_fb[i]->fix.id; + if (strcmp(idstr, "DISP3 FG") == 0) { + fbi = registered_fb[i]; + break; + } + } + + if (fbi == NULL) { + printk(KERN_ERR "DISP3 FG fb not found\n"); + return -EPERM; + } + + ipu_disp_set_window_pos(MEM_FG_SYNC, 0, 0); + + if (cam->vf_rotation >= IPU_ROTATE_VERT_FLIP) { + ipu_unlink_channels(CSI_PRP_VF_MEM, MEM_ROT_VF_MEM); + ipu_unlink_channels(MEM_ROT_VF_MEM, MEM_FG_SYNC); + } else { + ipu_unlink_channels(CSI_PRP_VF_MEM, MEM_FG_SYNC); + } + + ipu_disable_channel(CSI_PRP_VF_MEM, true); + + if (cam->vf_rotation >= IPU_ROTATE_VERT_FLIP) { + ipu_disable_channel(MEM_ROT_VF_MEM, true); + ipu_uninit_channel(MEM_ROT_VF_MEM); + } + ipu_uninit_channel(CSI_PRP_VF_MEM); + + acquire_console_sem(); + fb_blank(fbi, FB_BLANK_POWERDOWN); + release_console_sem(); + + /* Set the overlay frame buffer std to what it is used to be */ + fbvar = fbi->var; + fbvar.nonstd = cam->fb_origin_std; + fbvar.activate |= FB_ACTIVATE_FORCE; + fb_set_var(fbi, &fbvar); + + ipu_csi_enable_mclk_if(CSI_MCLK_VF, cam->csi, false, false); + + if (cam->vf_bufs_vaddr[0]) { + dma_free_coherent(0, cam->vf_bufs_size[0], + cam->vf_bufs_vaddr[0], + (dma_addr_t) cam->vf_bufs[0]); + cam->vf_bufs_vaddr[0] = NULL; + cam->vf_bufs[0] = 0; + } + if (cam->vf_bufs_vaddr[1]) { + dma_free_coherent(0, cam->vf_bufs_size[1], + cam->vf_bufs_vaddr[1], + (dma_addr_t) cam->vf_bufs[1]); + cam->vf_bufs_vaddr[1] = NULL; + cam->vf_bufs[1] = 0; + } + + cam->overlay_active = false; + return err; +} + +/*! + * Enable csi + * @param private struct cam_data * mxc capture instance + * + * @return status + */ +static int prp_vf_enable_csi(void *private) +{ + cam_data *cam = (cam_data *) private; + + return ipu_enable_csi(cam->csi); +} + +/*! + * Disable csi + * @param private struct cam_data * mxc capture instance + * + * @return status + */ +static int prp_vf_disable_csi(void *private) +{ + cam_data *cam = (cam_data *) private; + + return ipu_disable_csi(cam->csi); +} + +/*! + * function to select PRP-VF as the working path + * + * @param private cam_data * mxc v4l2 main structure + * + * @return status + */ +int prp_vf_sdc_select(void *private) +{ + cam_data *cam; + int err = 0; + if (private) { + cam = (cam_data *) private; + cam->vf_start_sdc = prpvf_start; + cam->vf_stop_sdc = prpvf_stop; + cam->vf_enable_csi = prp_vf_enable_csi; + cam->vf_disable_csi = prp_vf_disable_csi; + cam->overlay_active = false; + } else + err = -EIO; + + return err; +} + +/*! + * function to de-select PRP-VF as the working path + * + * @param private cam_data * mxc v4l2 main structure + * + * @return int + */ +int prp_vf_sdc_deselect(void *private) +{ + cam_data *cam; + int err = 0; + err = prpvf_stop(private); + + if (private) { + cam = (cam_data *) private; + cam->vf_start_sdc = NULL; + cam->vf_stop_sdc = NULL; + cam->vf_enable_csi = NULL; + cam->vf_disable_csi = NULL; + } + return err; +} + +/*! + * Init viewfinder task. + * + * @return Error code indicating success or failure + */ +__init int prp_vf_sdc_init(void) +{ + return 0; +} + +/*! + * Deinit viewfinder task. + * + * @return Error code indicating success or failure + */ +void __exit prp_vf_sdc_exit(void) +{ +} + +module_init(prp_vf_sdc_init); +module_exit(prp_vf_sdc_exit); + +EXPORT_SYMBOL(prp_vf_sdc_select); +EXPORT_SYMBOL(prp_vf_sdc_deselect); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("IPU PRP VF SDC Driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/media/video/mxc/capture/ipu_prp_vf_sdc_bg.c b/drivers/media/video/mxc/capture/ipu_prp_vf_sdc_bg.c new file mode 100644 index 000000000000..4e21f0c93b32 --- /dev/null +++ b/drivers/media/video/mxc/capture/ipu_prp_vf_sdc_bg.c @@ -0,0 +1,443 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file ipu_prp_vf_sdc_bg.c + * + * @brief IPU Use case for PRP-VF back-ground + * + * @ingroup IPU + */ +#include +#include +#include +#include "mxc_v4l2_capture.h" +#include "ipu_prp_sw.h" + +static int buffer_num; +static int buffer_ready; + +/* + * Function definitions + */ + +/*! + * SDC V-Sync callback function. + * + * @param irq int irq line + * @param dev_id void * device id + * + * @return status IRQ_HANDLED for handled + */ +static irqreturn_t prpvf_sdc_vsync_callback(int irq, void *dev_id) +{ + pr_debug("buffer_ready %d buffer_num %d\n", buffer_ready, buffer_num); + if (buffer_ready > 0) { + ipu_select_buffer(MEM_ROT_VF_MEM, IPU_OUTPUT_BUFFER, 0); + buffer_ready--; + } + + return IRQ_HANDLED; +} + +/*! + * VF EOF callback function. + * + * @param irq int irq line + * @param dev_id void * device id + * + * @return status IRQ_HANDLED for handled + */ +static irqreturn_t prpvf_vf_eof_callback(int irq, void *dev_id) +{ + pr_debug("buffer_ready %d buffer_num %d\n", buffer_ready, buffer_num); + + ipu_select_buffer(MEM_ROT_VF_MEM, IPU_INPUT_BUFFER, buffer_num); + + buffer_num = (buffer_num == 0) ? 1 : 0; + + ipu_select_buffer(CSI_PRP_VF_MEM, IPU_OUTPUT_BUFFER, buffer_num); + buffer_ready++; + return IRQ_HANDLED; +} + +/*! + * prpvf_start - start the vf task + * + * @param private cam_data * mxc v4l2 main structure + * + */ +static int prpvf_start(void *private) +{ + cam_data *cam = (cam_data *) private; + ipu_channel_params_t vf; + u32 format; + u32 offset; + u32 bpp, size = 3; + int err = 0; + + if (!cam) { + printk(KERN_ERR "private is NULL\n"); + return -EIO; + } + + if (cam->overlay_active == true) { + pr_debug("already start.\n"); + return 0; + } + + format = cam->v4l2_fb.fmt.pixelformat; + if (cam->v4l2_fb.fmt.pixelformat == IPU_PIX_FMT_BGR24) { + bpp = 3, size = 3; + pr_info("BGR24\n"); + } else if (cam->v4l2_fb.fmt.pixelformat == IPU_PIX_FMT_RGB565) { + bpp = 2, size = 2; + pr_info("RGB565\n"); + } else if (cam->v4l2_fb.fmt.pixelformat == IPU_PIX_FMT_BGR32) { + bpp = 4, size = 4; + pr_info("BGR32\n"); + } else { + printk(KERN_ERR + "unsupported fix format from the framebuffer.\n"); + return -EINVAL; + } + + offset = cam->v4l2_fb.fmt.bytesperline * cam->win.w.top + + size * cam->win.w.left; + + if (cam->v4l2_fb.base == 0) { + printk(KERN_ERR "invalid frame buffer address.\n"); + } else { + offset += (u32) cam->v4l2_fb.base; + } + + memset(&vf, 0, sizeof(ipu_channel_params_t)); + ipu_csi_get_window_size(&vf.csi_prp_vf_mem.in_width, + &vf.csi_prp_vf_mem.in_height, cam->csi); + vf.csi_prp_vf_mem.in_pixel_fmt = IPU_PIX_FMT_UYVY; + vf.csi_prp_vf_mem.out_width = cam->win.w.width; + vf.csi_prp_vf_mem.out_height = cam->win.w.height; + vf.csi_prp_vf_mem.csi = cam->csi; + if (cam->vf_rotation >= IPU_ROTATE_90_RIGHT) { + vf.csi_prp_vf_mem.out_width = cam->win.w.height; + vf.csi_prp_vf_mem.out_height = cam->win.w.width; + } + vf.csi_prp_vf_mem.out_pixel_fmt = format; + size = cam->win.w.width * cam->win.w.height * size; + + err = ipu_init_channel(CSI_PRP_VF_MEM, &vf); + if (err != 0) + goto out_4; + + ipu_csi_enable_mclk_if(CSI_MCLK_VF, cam->csi, true, true); + + if (cam->vf_bufs_vaddr[0]) { + dma_free_coherent(0, cam->vf_bufs_size[0], + cam->vf_bufs_vaddr[0], cam->vf_bufs[0]); + } + if (cam->vf_bufs_vaddr[1]) { + dma_free_coherent(0, cam->vf_bufs_size[1], + cam->vf_bufs_vaddr[1], cam->vf_bufs[1]); + } + cam->vf_bufs_size[0] = PAGE_ALIGN(size); + cam->vf_bufs_vaddr[0] = (void *)dma_alloc_coherent(0, + cam->vf_bufs_size[0], + &cam->vf_bufs[0], + GFP_DMA | + GFP_KERNEL); + if (cam->vf_bufs_vaddr[0] == NULL) { + printk(KERN_ERR "Error to allocate vf buffer\n"); + err = -ENOMEM; + goto out_3; + } + cam->vf_bufs_size[1] = PAGE_ALIGN(size); + cam->vf_bufs_vaddr[1] = (void *)dma_alloc_coherent(0, + cam->vf_bufs_size[1], + &cam->vf_bufs[1], + GFP_DMA | + GFP_KERNEL); + if (cam->vf_bufs_vaddr[1] == NULL) { + printk(KERN_ERR "Error to allocate vf buffer\n"); + err = -ENOMEM; + goto out_3; + } + + err = ipu_init_channel_buffer(CSI_PRP_VF_MEM, IPU_OUTPUT_BUFFER, + format, vf.csi_prp_vf_mem.out_width, + vf.csi_prp_vf_mem.out_height, + vf.csi_prp_vf_mem.out_width, + IPU_ROTATE_NONE, cam->vf_bufs[0], + cam->vf_bufs[1], 0, 0); + if (err != 0) { + printk(KERN_ERR "Error initializing CSI_PRP_VF_MEM\n"); + goto out_3; + } + err = ipu_init_channel(MEM_ROT_VF_MEM, NULL); + if (err != 0) { + printk(KERN_ERR "Error MEM_ROT_VF_MEM channel\n"); + goto out_3; + } + + err = ipu_init_channel_buffer(MEM_ROT_VF_MEM, IPU_INPUT_BUFFER, + format, vf.csi_prp_vf_mem.out_width, + vf.csi_prp_vf_mem.out_height, + vf.csi_prp_vf_mem.out_width, + cam->vf_rotation, cam->vf_bufs[0], + cam->vf_bufs[1], 0, 0); + if (err != 0) { + printk(KERN_ERR "Error MEM_ROT_VF_MEM input buffer\n"); + goto out_2; + } + + if (cam->vf_rotation >= IPU_ROTATE_90_RIGHT) { + err = ipu_init_channel_buffer(MEM_ROT_VF_MEM, IPU_OUTPUT_BUFFER, + format, + vf.csi_prp_vf_mem.out_height, + vf.csi_prp_vf_mem.out_width, + cam->overlay_fb->var.xres * bpp, + IPU_ROTATE_NONE, offset, 0, 0, 0); + + if (err != 0) { + printk(KERN_ERR "Error MEM_ROT_VF_MEM output buffer\n"); + goto out_2; + } + } else { + err = ipu_init_channel_buffer(MEM_ROT_VF_MEM, IPU_OUTPUT_BUFFER, + format, + vf.csi_prp_vf_mem.out_width, + vf.csi_prp_vf_mem.out_height, + cam->overlay_fb->var.xres * bpp, + IPU_ROTATE_NONE, offset, 0, 0, 0); + if (err != 0) { + printk(KERN_ERR "Error MEM_ROT_VF_MEM output buffer\n"); + goto out_2; + } + } + + ipu_clear_irq(IPU_IRQ_PRP_VF_OUT_EOF); + err = ipu_request_irq(IPU_IRQ_PRP_VF_OUT_EOF, prpvf_vf_eof_callback, + 0, "Mxc Camera", cam); + if (err != 0) { + printk(KERN_ERR + "Error registering IPU_IRQ_PRP_VF_OUT_EOF irq.\n"); + goto out_2; + } + + ipu_clear_irq(IPU_IRQ_BG_SF_END); + err = ipu_request_irq(IPU_IRQ_BG_SF_END, prpvf_sdc_vsync_callback, + 0, "Mxc Camera", NULL); + if (err != 0) { + printk(KERN_ERR "Error registering IPU_IRQ_BG_SF_END irq.\n"); + goto out_1; + } + + ipu_enable_channel(CSI_PRP_VF_MEM); + ipu_enable_channel(MEM_ROT_VF_MEM); + + buffer_num = 0; + buffer_ready = 0; + ipu_select_buffer(CSI_PRP_VF_MEM, IPU_OUTPUT_BUFFER, 0); + + cam->overlay_active = true; + return err; + + out_1: + ipu_free_irq(IPU_IRQ_PRP_VF_OUT_EOF, NULL); + out_2: + ipu_uninit_channel(MEM_ROT_VF_MEM); + out_3: + ipu_uninit_channel(CSI_PRP_VF_MEM); + out_4: + if (cam->vf_bufs_vaddr[0]) { + dma_free_coherent(0, cam->vf_bufs_size[0], + cam->vf_bufs_vaddr[0], cam->vf_bufs[0]); + cam->vf_bufs_vaddr[0] = NULL; + cam->vf_bufs[0] = 0; + } + if (cam->vf_bufs_vaddr[1]) { + dma_free_coherent(0, cam->vf_bufs_size[1], + cam->vf_bufs_vaddr[1], cam->vf_bufs[1]); + cam->vf_bufs_vaddr[1] = NULL; + cam->vf_bufs[1] = 0; + } + if (cam->rot_vf_bufs_vaddr[0]) { + dma_free_coherent(0, cam->rot_vf_buf_size[0], + cam->rot_vf_bufs_vaddr[0], + cam->rot_vf_bufs[0]); + cam->rot_vf_bufs_vaddr[0] = NULL; + cam->rot_vf_bufs[0] = 0; + } + if (cam->rot_vf_bufs_vaddr[1]) { + dma_free_coherent(0, cam->rot_vf_buf_size[1], + cam->rot_vf_bufs_vaddr[1], + cam->rot_vf_bufs[1]); + cam->rot_vf_bufs_vaddr[1] = NULL; + cam->rot_vf_bufs[1] = 0; + } + return err; +} + +/*! + * prpvf_stop - stop the vf task + * + * @param private cam_data * mxc v4l2 main structure + * + */ +static int prpvf_stop(void *private) +{ + cam_data *cam = (cam_data *) private; + + if (cam->overlay_active == false) + return 0; + + ipu_free_irq(IPU_IRQ_BG_SF_END, NULL); + + ipu_free_irq(IPU_IRQ_PRP_VF_OUT_EOF, cam); + + ipu_disable_channel(CSI_PRP_VF_MEM, true); + ipu_disable_channel(MEM_ROT_VF_MEM, true); + ipu_uninit_channel(CSI_PRP_VF_MEM); + ipu_uninit_channel(MEM_ROT_VF_MEM); + ipu_csi_enable_mclk_if(CSI_MCLK_VF, cam->csi, false, false); + + if (cam->vf_bufs_vaddr[0]) { + dma_free_coherent(0, cam->vf_bufs_size[0], + cam->vf_bufs_vaddr[0], cam->vf_bufs[0]); + cam->vf_bufs_vaddr[0] = NULL; + cam->vf_bufs[0] = 0; + } + if (cam->vf_bufs_vaddr[1]) { + dma_free_coherent(0, cam->vf_bufs_size[1], + cam->vf_bufs_vaddr[1], cam->vf_bufs[1]); + cam->vf_bufs_vaddr[1] = NULL; + cam->vf_bufs[1] = 0; + } + if (cam->rot_vf_bufs_vaddr[0]) { + dma_free_coherent(0, cam->rot_vf_buf_size[0], + cam->rot_vf_bufs_vaddr[0], + cam->rot_vf_bufs[0]); + cam->rot_vf_bufs_vaddr[0] = NULL; + cam->rot_vf_bufs[0] = 0; + } + if (cam->rot_vf_bufs_vaddr[1]) { + dma_free_coherent(0, cam->rot_vf_buf_size[1], + cam->rot_vf_bufs_vaddr[1], + cam->rot_vf_bufs[1]); + cam->rot_vf_bufs_vaddr[1] = NULL; + cam->rot_vf_bufs[1] = 0; + } + + buffer_num = 0; + buffer_ready = 0; + cam->overlay_active = false; + return 0; +} + +/*! + * Enable csi + * @param private struct cam_data * mxc capture instance + * + * @return status + */ +static int prp_vf_enable_csi(void *private) +{ + cam_data *cam = (cam_data *) private; + + return ipu_enable_csi(cam->csi); +} + +/*! + * Disable csi + * @param private struct cam_data * mxc capture instance + * + * @return status + */ +static int prp_vf_disable_csi(void *private) +{ + cam_data *cam = (cam_data *) private; + + return ipu_disable_csi(cam->csi); +} + +/*! + * function to select PRP-VF as the working path + * + * @param private cam_data * mxc v4l2 main structure + * + * @return status + */ +int prp_vf_sdc_select_bg(void *private) +{ + cam_data *cam = (cam_data *) private; + + if (cam) { + cam->vf_start_sdc = prpvf_start; + cam->vf_stop_sdc = prpvf_stop; + cam->vf_enable_csi = prp_vf_enable_csi; + cam->vf_disable_csi = prp_vf_disable_csi; + cam->overlay_active = false; + } + + return 0; +} + +/*! + * function to de-select PRP-VF as the working path + * + * @param private cam_data * mxc v4l2 main structure + * + * @return status + */ +int prp_vf_sdc_deselect_bg(void *private) +{ + cam_data *cam = (cam_data *) private; + int err = 0; + err = prpvf_stop(private); + + if (cam) { + cam->vf_start_sdc = NULL; + cam->vf_stop_sdc = NULL; + cam->vf_enable_csi = NULL; + cam->vf_disable_csi = NULL; + } + return err; +} + +/*! + * Init viewfinder task. + * + * @return Error code indicating success or failure + */ +__init int prp_vf_sdc_init_bg(void) +{ + return 0; +} + +/*! + * Deinit viewfinder task. + * + * @return Error code indicating success or failure + */ +void __exit prp_vf_sdc_exit_bg(void) +{ +} + +module_init(prp_vf_sdc_init_bg); +module_exit(prp_vf_sdc_exit_bg); + +EXPORT_SYMBOL(prp_vf_sdc_select_bg); +EXPORT_SYMBOL(prp_vf_sdc_deselect_bg); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("IPU PRP VF SDC Backgroud Driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/media/video/mxc/capture/ipu_still.c b/drivers/media/video/mxc/capture/ipu_still.c new file mode 100644 index 000000000000..ded24623ce2a --- /dev/null +++ b/drivers/media/video/mxc/capture/ipu_still.c @@ -0,0 +1,268 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file ipu_still.c + * + * @brief IPU Use case for still image capture + * + * @ingroup IPU + */ + +#include +#include +#include +#include "mxc_v4l2_capture.h" +#include "ipu_prp_sw.h" + +static int callback_eof_flag; +#ifndef CONFIG_MXC_IPU_V1 +static int buffer_num; +#endif + +#ifdef CONFIG_MXC_IPU_V1 +static int callback_flag; +/* + * Function definitions + */ +/*! + * CSI EOF callback function. + * + * @param irq int irq line + * @param dev_id void * device id + * + * @return status IRQ_HANDLED for handled + */ +static irqreturn_t prp_csi_eof_callback(int irq, void *dev_id) +{ + ipu_select_buffer(CSI_MEM, IPU_OUTPUT_BUFFER, + callback_flag%2 ? 1 : 0); + if (callback_flag == 0) + ipu_enable_channel(CSI_MEM); + + callback_flag++; + return IRQ_HANDLED; +} +#endif + +/*! + * CSI callback function. + * + * @param irq int irq line + * @param dev_id void * device id + * + * @return status IRQ_HANDLED for handled + */ +static irqreturn_t prp_still_callback(int irq, void *dev_id) +{ + cam_data *cam = (cam_data *) dev_id; + + callback_eof_flag++; + if (callback_eof_flag < 5) { +#ifndef CONFIG_MXC_IPU_V1 + buffer_num = (buffer_num == 0) ? 1 : 0; + ipu_select_buffer(CSI_MEM, IPU_OUTPUT_BUFFER, buffer_num); +#endif + } else { + cam->still_counter++; + wake_up_interruptible(&cam->still_queue); + } + + return IRQ_HANDLED; +} + +/*! + * start csi->mem task + * @param private struct cam_data * mxc capture instance + * + * @return status + */ +static int prp_still_start(void *private) +{ + cam_data *cam = (cam_data *) private; + u32 pixel_fmt; + int err; + ipu_channel_params_t params; + + if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_YUV420) + pixel_fmt = IPU_PIX_FMT_YUV420P; + else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_NV12) + pixel_fmt = IPU_PIX_FMT_NV12; + else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_YUV422P) + pixel_fmt = IPU_PIX_FMT_YUV422P; + else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_UYVY) + pixel_fmt = IPU_PIX_FMT_UYVY; + else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_YUYV) + pixel_fmt = IPU_PIX_FMT_YUYV; + else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_BGR24) + pixel_fmt = IPU_PIX_FMT_BGR24; + else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_RGB24) + pixel_fmt = IPU_PIX_FMT_RGB24; + else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_RGB565) + pixel_fmt = IPU_PIX_FMT_RGB565; + else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_BGR32) + pixel_fmt = IPU_PIX_FMT_BGR32; + else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_RGB32) + pixel_fmt = IPU_PIX_FMT_RGB32; + else { + printk(KERN_ERR "format not supported\n"); + return -EINVAL; + } + + ipu_csi_enable_mclk_if(CSI_MCLK_RAW, cam->csi, true, true); + + memset(¶ms, 0, sizeof(params)); + err = ipu_init_channel(CSI_MEM, ¶ms); + if (err != 0) + return err; + + err = ipu_init_channel_buffer(CSI_MEM, IPU_OUTPUT_BUFFER, + pixel_fmt, cam->v2f.fmt.pix.width, + cam->v2f.fmt.pix.height, + cam->v2f.fmt.pix.width, IPU_ROTATE_NONE, + cam->still_buf[0], cam->still_buf[1], + 0, 0); + if (err != 0) + return err; + +#ifdef CONFIG_MXC_IPU_V1 + ipu_clear_irq(IPU_IRQ_SENSOR_OUT_EOF); + err = ipu_request_irq(IPU_IRQ_SENSOR_OUT_EOF, prp_still_callback, + 0, "Mxc Camera", cam); + if (err != 0) { + printk(KERN_ERR "Error registering irq.\n"); + return err; + } + callback_flag = 0; + callback_eof_flag = 0; + ipu_clear_irq(IPU_IRQ_SENSOR_EOF); + err = ipu_request_irq(IPU_IRQ_SENSOR_EOF, prp_csi_eof_callback, + 0, "Mxc Camera", NULL); + if (err != 0) { + printk(KERN_ERR "Error IPU_IRQ_SENSOR_EOF \n"); + return err; + } +#else + callback_eof_flag = 0; + buffer_num = 0; + + ipu_clear_irq(IPU_IRQ_CSI0_OUT_EOF); + err = ipu_request_irq(IPU_IRQ_CSI0_OUT_EOF, prp_still_callback, + 0, "Mxc Camera", cam); + if (err != 0) { + printk(KERN_ERR "Error registering irq.\n"); + return err; + } + + ipu_select_buffer(CSI_MEM, IPU_OUTPUT_BUFFER, 0); + ipu_enable_channel(CSI_MEM); + ipu_enable_csi(cam->csi); +#endif + + return err; +} + +/*! + * stop csi->mem encoder task + * @param private struct cam_data * mxc capture instance + * + * @return status + */ +static int prp_still_stop(void *private) +{ + cam_data *cam = (cam_data *) private; + int err = 0; + +#ifdef CONFIG_MXC_IPU_V1 + ipu_free_irq(IPU_IRQ_SENSOR_EOF, NULL); + ipu_free_irq(IPU_IRQ_SENSOR_OUT_EOF, cam); +#else + ipu_free_irq(IPU_IRQ_CSI0_OUT_EOF, cam); +#endif + + ipu_disable_csi(cam->csi); + ipu_disable_channel(CSI_MEM, true); + ipu_uninit_channel(CSI_MEM); + ipu_csi_enable_mclk_if(CSI_MCLK_RAW, cam->csi, false, false); + + return err; +} + +/*! + * function to select CSI_MEM as the working path + * + * @param private struct cam_data * mxc capture instance + * + * @return status + */ +int prp_still_select(void *private) +{ + cam_data *cam = (cam_data *) private; + + if (cam) { + cam->csi_start = prp_still_start; + cam->csi_stop = prp_still_stop; + } + + return 0; +} + +/*! + * function to de-select CSI_MEM as the working path + * + * @param private struct cam_data * mxc capture instance + * + * @return status + */ +int prp_still_deselect(void *private) +{ + cam_data *cam = (cam_data *) private; + int err = 0; + + err = prp_still_stop(cam); + + if (cam) { + cam->csi_start = NULL; + cam->csi_stop = NULL; + } + + return err; +} + +/*! + * Init the Encorder channels + * + * @return Error code indicating success or failure + */ +__init int prp_still_init(void) +{ + return 0; +} + +/*! + * Deinit the Encorder channels + * + */ +void __exit prp_still_exit(void) +{ +} + +module_init(prp_still_init); +module_exit(prp_still_exit); + +EXPORT_SYMBOL(prp_still_select); +EXPORT_SYMBOL(prp_still_deselect); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("IPU PRP STILL IMAGE Driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/media/video/mxc/capture/mt9v111.c b/drivers/media/video/mxc/capture/mt9v111.c new file mode 100644 index 000000000000..ccf3ea24024e --- /dev/null +++ b/drivers/media/video/mxc/capture/mt9v111.c @@ -0,0 +1,1076 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mt9v111.c + * + * @brief mt9v111 camera driver functions + * + * @ingroup Camera + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "mxc_v4l2_capture.h" +#include "mt9v111.h" + +#ifdef MT9V111_DEBUG +static u16 testpattern; +#endif + +static mt9v111_conf mt9v111_device; + +/*! + * Holds the current frame rate. + */ +static int reset_frame_rate = MT9V111_FRAME_RATE; + +struct sensor { + const struct mt9v111_platform_data *platform_data; + struct v4l2_int_device *v4l2_int_device; + struct i2c_client *i2c_client; + struct v4l2_pix_format pix; + struct v4l2_captureparm streamcap; + bool on; + + /* control settings */ + int brightness; + int hue; + int contrast; + int saturation; + int red; + int green; + int blue; + int ae_mode; + +} mt9v111_data; + +extern void gpio_sensor_active(void); +extern void gpio_sensor_inactive(void); + +static int mt9v111_probe(struct i2c_client *client, + const struct i2c_device_id *id); +static int mt9v111_remove(struct i2c_client *client); + +static const struct i2c_device_id mt9v111_id[] = { + {"mt9v111", 0}, + {}, +}; + +MODULE_DEVICE_TABLE(i2c, mt9v111_id); + +static struct i2c_driver mt9v111_i2c_driver = { + .driver = { + .owner = THIS_MODULE, + .name = "mt9v111", + }, + .probe = mt9v111_probe, + .remove = mt9v111_remove, + .id_table = mt9v111_id, +/* To add power management add .suspend and .resume functions */ +}; + +/* + * Function definitions + */ + +#ifdef MT9V111_DEBUG +static inline int mt9v111_read_reg(u8 reg) +{ + int val = i2c_smbus_read_word_data(mt9v111_data.i2c_client, reg); + if (val != -1) + val = cpu_to_be16(val); + return val; +} +#endif + +/*! + * Writes to the register via I2C. + */ +static inline int mt9v111_write_reg(u8 reg, u16 val) +{ + pr_debug("In mt9v111_write_reg (0x%x, 0x%x)\n", reg, val); + pr_debug(" write reg %x val %x.\n", reg, val); + + return i2c_smbus_write_word_data(mt9v111_data.i2c_client, + reg, cpu_to_be16(val)); +} + +/*! + * Initialize mt9v111_sensor_lib + * Libarary for Sensor configuration through I2C + * + * @param coreReg Core Registers + * @param ifpReg IFP Register + * + * @return status + */ +static u8 mt9v111_sensor_lib(mt9v111_coreReg *coreReg, mt9v111_IFPReg *ifpReg) +{ + u8 reg; + u16 data; + u8 error = 0; + + pr_debug("In mt9v111_sensor_lib\n"); + + /* + * setup to IFP registers + */ + reg = MT9V111I_ADDR_SPACE_SEL; + data = ifpReg->addrSpaceSel; + mt9v111_write_reg(reg, data); + + /* Operation Mode Control */ + reg = MT9V111I_MODE_CONTROL; + data = ifpReg->modeControl; + mt9v111_write_reg(reg, data); + + /* Output format */ + reg = MT9V111I_FORMAT_CONTROL; + data = ifpReg->formatControl; /* Set bit 12 */ + mt9v111_write_reg(reg, data); + + /* AE limit 4 */ + reg = MT9V111I_SHUTTER_WIDTH_LIMIT_AE; + data = ifpReg->gainLimitAE; + mt9v111_write_reg(reg, data); + + reg = MT9V111I_OUTPUT_FORMAT_CTRL2; + data = ifpReg->outputFormatCtrl2; + mt9v111_write_reg(reg, data); + + reg = MT9V111I_AE_SPEED; + data = ifpReg->AESpeed; + mt9v111_write_reg(reg, data); + + /* output image size */ + reg = MT9V111i_H_PAN; + data = 0x8000 | ifpReg->HPan; + mt9v111_write_reg(reg, data); + + reg = MT9V111i_H_ZOOM; + data = 0x8000 | ifpReg->HZoom; + mt9v111_write_reg(reg, data); + + reg = MT9V111i_H_SIZE; + data = 0x8000 | ifpReg->HSize; + mt9v111_write_reg(reg, data); + + reg = MT9V111i_V_PAN; + data = 0x8000 | ifpReg->VPan; + mt9v111_write_reg(reg, data); + + reg = MT9V111i_V_ZOOM; + data = 0x8000 | ifpReg->VZoom; + mt9v111_write_reg(reg, data); + + reg = MT9V111i_V_SIZE; + data = 0x8000 | ifpReg->VSize; + mt9v111_write_reg(reg, data); + + reg = MT9V111i_H_PAN; + data = ~0x8000 & ifpReg->HPan; + mt9v111_write_reg(reg, data); +#if 0 + reg = MT9V111I_UPPER_SHUTTER_DELAY_LIM; + data = ifpReg->upperShutterDelayLi; + mt9v111_write_reg(reg, data); + + reg = MT9V111I_SHUTTER_60; + data = ifpReg->shutter_width_60; + mt9v111_write_reg(reg, data); + + reg = MT9V111I_SEARCH_FLICK_60; + data = ifpReg->search_flicker_60; + mt9v111_write_reg(reg, data); +#endif + + /* + * setup to sensor core registers + */ + reg = MT9V111I_ADDR_SPACE_SEL; + data = coreReg->addressSelect; + mt9v111_write_reg(reg, data); + + /* enable changes and put the Sync bit on */ + reg = MT9V111S_OUTPUT_CTRL; + data = MT9V111S_OUTCTRL_SYNC | MT9V111S_OUTCTRL_CHIP_ENABLE | 0x3000; + mt9v111_write_reg(reg, data); + + /* min PIXCLK - Default */ + reg = MT9V111S_PIXEL_CLOCK_SPEED; + data = coreReg->pixelClockSpeed; + mt9v111_write_reg(reg, data); + + /* Setup image flipping / Dark rows / row/column skip */ + reg = MT9V111S_READ_MODE; + data = coreReg->readMode; + mt9v111_write_reg(reg, data); + + /* zoom 0 */ + reg = MT9V111S_DIGITAL_ZOOM; + data = coreReg->digitalZoom; + mt9v111_write_reg(reg, data); + + /* min H-blank */ + reg = MT9V111S_HOR_BLANKING; + data = coreReg->horizontalBlanking; + mt9v111_write_reg(reg, data); + + /* min V-blank */ + reg = MT9V111S_VER_BLANKING; + data = coreReg->verticalBlanking; + mt9v111_write_reg(reg, data); + + reg = MT9V111S_SHUTTER_WIDTH; + data = coreReg->shutterWidth; + mt9v111_write_reg(reg, data); + + reg = MT9V111S_SHUTTER_DELAY; + data = ifpReg->upperShutterDelayLi; + mt9v111_write_reg(reg, data); + + /* changes become effective */ + reg = MT9V111S_OUTPUT_CTRL; + data = MT9V111S_OUTCTRL_CHIP_ENABLE | 0x3000; + mt9v111_write_reg(reg, data); + + return error; +} + +/*! + * MT9V111 frame rate calculate + * + * @param frame_rate int * + * @param mclk int + * @return None + */ +static void mt9v111_rate_cal(int *frame_rate, int mclk) +{ + int num_clock_per_row; + int max_rate = 0; + + pr_debug("In mt9v111_rate_cal\n"); + + num_clock_per_row = (MT9V111_MAX_WIDTH + 114 + MT9V111_HORZBLANK_MIN) + * 2; + max_rate = mclk / (num_clock_per_row * + (MT9V111_MAX_HEIGHT + MT9V111_VERTBLANK_DEFAULT)); + + if ((*frame_rate > max_rate) || (*frame_rate == 0)) { + *frame_rate = max_rate; + } + + mt9v111_device.coreReg->verticalBlanking + = mclk / (*frame_rate * num_clock_per_row) - MT9V111_MAX_HEIGHT; + + reset_frame_rate = *frame_rate; +} + +/*! + * MT9V111 sensor configuration + */ +void mt9v111_config(void) +{ + pr_debug("In mt9v111_config\n"); + + mt9v111_device.coreReg->addressSelect = MT9V111I_SEL_SCA; + mt9v111_device.ifpReg->addrSpaceSel = MT9V111I_SEL_IFP; + + mt9v111_device.coreReg->windowHeight = MT9V111_WINHEIGHT; + mt9v111_device.coreReg->windowWidth = MT9V111_WINWIDTH; + mt9v111_device.coreReg->zoomColStart = 0; + mt9v111_device.coreReg->zomRowStart = 0; + mt9v111_device.coreReg->digitalZoom = 0x0; + + mt9v111_device.coreReg->verticalBlanking = MT9V111_VERTBLANK_DEFAULT; + mt9v111_device.coreReg->horizontalBlanking = MT9V111_HORZBLANK_MIN; + mt9v111_device.coreReg->pixelClockSpeed = 0; + mt9v111_device.coreReg->readMode = 0xd0a1; + + mt9v111_device.ifpReg->outputFormatCtrl2 = 0; + mt9v111_device.ifpReg->gainLimitAE = 0x300; + mt9v111_device.ifpReg->AESpeed = 0x80; + + /* here is the default value */ + mt9v111_device.ifpReg->formatControl = 0xc800; + mt9v111_device.ifpReg->modeControl = 0x708e; + mt9v111_device.ifpReg->awbSpeed = 0x4514; + mt9v111_device.coreReg->shutterWidth = 0xf8; + + /* output size */ + mt9v111_device.ifpReg->HPan = 0; + mt9v111_device.ifpReg->HZoom = MT9V111_MAX_WIDTH; + mt9v111_device.ifpReg->HSize = MT9V111_MAX_WIDTH; + mt9v111_device.ifpReg->VPan = 0; + mt9v111_device.ifpReg->VZoom = MT9V111_MAX_HEIGHT; + mt9v111_device.ifpReg->VSize = MT9V111_MAX_HEIGHT; +} + +/*! + * mt9v111 sensor set saturtionn + * + * @param saturation int + + * @return Error code of 0. + */ +static int mt9v111_set_saturation(int saturation) +{ + u8 reg; + u16 data; + pr_debug("In mt9v111_set_saturation(%d)\n", + saturation); + + switch (saturation) { + case 150: + mt9v111_device.ifpReg->awbSpeed = 0x6D14; + break; + case 100: + mt9v111_device.ifpReg->awbSpeed = 0x4514; + break; + case 75: + mt9v111_device.ifpReg->awbSpeed = 0x4D14; + break; + case 50: + mt9v111_device.ifpReg->awbSpeed = 0x5514; + break; + case 37: + mt9v111_device.ifpReg->awbSpeed = 0x5D14; + break; + case 25: + mt9v111_device.ifpReg->awbSpeed = 0x6514; + break; + default: + mt9v111_device.ifpReg->awbSpeed = 0x4514; + break; + } + + reg = MT9V111I_ADDR_SPACE_SEL; + data = mt9v111_device.ifpReg->addrSpaceSel; + mt9v111_write_reg(reg, data); + + /* Operation Mode Control */ + reg = MT9V111I_AWB_SPEED; + data = mt9v111_device.ifpReg->awbSpeed; + mt9v111_write_reg(reg, data); + + return 0; +} + +/*! + * mt9v111 sensor set Auto Exposure measurement window mode configuration + * + * @param ae_mode int + * @return Error code of 0 (no Error) + */ +static int mt9v111_set_ae_mode(int ae_mode) +{ + u8 reg; + u16 data; + + pr_debug("In mt9v111_set_ae_mode(%d)\n", + ae_mode); + + /* Currently this driver only supports auto and manual exposure + * modes. */ + if ((ae_mode > 1) || (ae_mode << 0)) + return -EPERM; + + /* + * The auto exposure is set in bit 14. + * Other values are set for: + * -on the fly defect correction is on (bit 13). + * -aperature correction knee enabled (bit 12). + * -ITU_R BT656 synchronization codes are embedded in the image (bit 7) + * -AE measurement window is weighted sum of large and center windows + * (bits 2-3). + * -auto white balance is on (bit 1). + * -normal color processing (bit 4 = 0). + */ + /* V4L2_EXPOSURE_AUTO = 0; needs register setting of 0x708E */ + /* V4L2_EXPOSURE_MANUAL = 1 needs register setting of 0x308E */ + mt9v111_device.ifpReg->modeControl &= 0x3fff; + mt9v111_device.ifpReg->modeControl |= (ae_mode & 0x03) << 14; + mt9v111_data.ae_mode = ae_mode; + + reg = MT9V111I_ADDR_SPACE_SEL; + data = mt9v111_device.ifpReg->addrSpaceSel; + mt9v111_write_reg(reg, data); + + reg = MT9V111I_MODE_CONTROL; + data = mt9v111_device.ifpReg->modeControl; + mt9v111_write_reg(reg, data); + + return 0; +} + +/*! + * mt9v111 sensor get AE measurement window mode configuration + * + * @param ae_mode int * + * @return None + */ +static void mt9v111_get_ae_mode(int *ae_mode) +{ + pr_debug("In mt9v111_get_ae_mode(%d)\n", *ae_mode); + + if (ae_mode != NULL) { + *ae_mode = (mt9v111_device.ifpReg->modeControl & 0xc) >> 2; + } +} + +#ifdef MT9V111_DEBUG +/*! + * Set sensor to test mode, which will generate test pattern. + * + * @return none + */ +static void mt9v111_test_pattern(bool flag) +{ + u16 data; + + /* switch to sensor registers */ + mt9v111_write_reg(MT9V111I_ADDR_SPACE_SEL, MT9V111I_SEL_SCA); + + if (flag == true) { + testpattern = MT9V111S_OUTCTRL_TEST_MODE; + + data = mt9v111_read_reg(MT9V111S_ROW_NOISE_CTRL) & 0xBF; + mt9v111_write_reg(MT9V111S_ROW_NOISE_CTRL, data); + + mt9v111_write_reg(MT9V111S_TEST_DATA, 0); + + /* changes take effect */ + data = MT9V111S_OUTCTRL_CHIP_ENABLE | testpattern | 0x3000; + mt9v111_write_reg(MT9V111S_OUTPUT_CTRL, data); + } else { + testpattern = 0; + + data = mt9v111_read_reg(MT9V111S_ROW_NOISE_CTRL) | 0x40; + mt9v111_write_reg(MT9V111S_ROW_NOISE_CTRL, data); + + /* changes take effect */ + data = MT9V111S_OUTCTRL_CHIP_ENABLE | testpattern | 0x3000; + mt9v111_write_reg(MT9V111S_OUTPUT_CTRL, data); + } +} +#endif + + +/* --------------- IOCTL functions from v4l2_int_ioctl_desc --------------- */ + +/*! + * ioctl_g_ifparm - V4L2 sensor interface handler for vidioc_int_g_ifparm_num + * s: pointer to standard V4L2 device structure + * p: pointer to standard V4L2 vidioc_int_g_ifparm_num ioctl structure + * + * Gets slave interface parameters. + * Calculates the required xclk value to support the requested + * clock parameters in p. This value is returned in the p + * parameter. + * + * vidioc_int_g_ifparm returns platform-specific information about the + * interface settings used by the sensor. + * + * Given the image capture format in pix, the nominal frame period in + * timeperframe, calculate the required xclk frequency. + * + * Called on open. + */ +static int ioctl_g_ifparm(struct v4l2_int_device *s, struct v4l2_ifparm *p) +{ + pr_debug("In mt9v111:ioctl_g_ifparm\n"); + + if (s == NULL) { + pr_err(" ERROR!! no slave device set!\n"); + return -1; + } + + memset(p, 0, sizeof(*p)); + p->u.bt656.clock_curr = MT9V111_MCLK; + p->if_type = V4L2_IF_TYPE_BT656; + p->u.bt656.mode = V4L2_IF_TYPE_BT656_MODE_NOBT_8BIT; + p->u.bt656.clock_min = MT9V111_CLK_MIN; + p->u.bt656.clock_max = MT9V111_CLK_MAX; + + return 0; +} + +/*! + * Sets the camera power. + * + * s pointer to the camera device + * on if 1, power is to be turned on. 0 means power is to be turned off + * + * ioctl_s_power - V4L2 sensor interface handler for vidioc_int_s_power_num + * @s: pointer to standard V4L2 device structure + * @on: power state to which device is to be set + * + * Sets devices power state to requrested state, if possible. + * This is called on suspend and resume. + */ +static int ioctl_s_power(struct v4l2_int_device *s, int on) +{ + struct sensor *sensor = s->priv; + + pr_debug("In mt9v111:ioctl_s_power\n"); + + sensor->on = on; + + if (on) + gpio_sensor_active(); + else + gpio_sensor_inactive(); + + return 0; +} + +/*! + * ioctl_g_parm - V4L2 sensor interface handler for VIDIOC_G_PARM ioctl + * @s: pointer to standard V4L2 device structure + * @a: pointer to standard V4L2 VIDIOC_G_PARM ioctl structure + * + * Returns the sensor's video CAPTURE parameters. + */ +static int ioctl_g_parm(struct v4l2_int_device *s, struct v4l2_streamparm *a) +{ + int ret = 0; + struct v4l2_captureparm *cparm = &a->parm.capture; + /* s->priv points to mt9v111_data */ + + pr_debug("In mt9v111:ioctl_g_parm\n"); + + switch (a->type) { + /* This is the only case currently handled. */ + case V4L2_BUF_TYPE_VIDEO_CAPTURE: + pr_debug(" type is V4L2_BUF_TYPE_VIDEO_CAPTURE\n"); + memset(a, 0, sizeof(*a)); + a->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + cparm->capability = mt9v111_data.streamcap.capability; + cparm->timeperframe = + mt9v111_data.streamcap.timeperframe; + cparm->capturemode = mt9v111_data.streamcap.capturemode; + ret = 0; + break; + + /* These are all the possible cases. */ + case V4L2_BUF_TYPE_VIDEO_OUTPUT: + case V4L2_BUF_TYPE_VIDEO_OVERLAY: + case V4L2_BUF_TYPE_VBI_CAPTURE: + case V4L2_BUF_TYPE_VBI_OUTPUT: + case V4L2_BUF_TYPE_SLICED_VBI_CAPTURE: + case V4L2_BUF_TYPE_SLICED_VBI_OUTPUT: + pr_err(" type is not V4L2_BUF_TYPE_VIDEO_CAPTURE " \ + "but %d\n", a->type); + ret = -EINVAL; + break; + + default: + pr_err(" type is unknown - %d\n", a->type); + ret = -EINVAL; + break; + } + + return ret; +} + +/*! + * ioctl_s_parm - V4L2 sensor interface handler for VIDIOC_S_PARM ioctl + * @s: pointer to standard V4L2 device structure + * @a: pointer to standard V4L2 VIDIOC_S_PARM ioctl structure + * + * Configures the sensor to use the input parameters, if possible. If + * not possible, reverts to the old parameters and returns the + * appropriate error code. + */ +static int ioctl_s_parm(struct v4l2_int_device *s, struct v4l2_streamparm *a) +{ + int ret = 0; + struct v4l2_captureparm *cparm = &a->parm.capture; + /* s->priv points to mt9v111_data */ + + pr_debug("In mt9v111:ioctl_s_parm\n"); + + switch (a->type) { + /* This is the only case currently handled. */ + case V4L2_BUF_TYPE_VIDEO_CAPTURE: + pr_debug(" type is V4L2_BUF_TYPE_VIDEO_CAPTURE\n"); + + /* Check that the new frame rate is allowed. + * Changing the frame rate is not allowed on this + *camera. */ + if (cparm->timeperframe.denominator != + mt9v111_data.streamcap.timeperframe.denominator) { + pr_err("ERROR: mt9v111: ioctl_s_parm: " \ + "This camera does not allow frame rate " + "changes.\n"); + ret = -EINVAL; + } else { + mt9v111_data.streamcap.timeperframe = + cparm->timeperframe; + /* Call any camera functions to match settings. */ + } + + /* Check that new capture mode is supported. */ + if ((cparm->capturemode != 0) && + !(cparm->capturemode & V4L2_MODE_HIGHQUALITY)) { + pr_err("ERROR: mt9v111: ioctl_s_parm: " \ + "unsupported capture mode\n"); + ret = -EINVAL; + } else { + mt9v111_data.streamcap.capturemode = + cparm->capturemode; + /* Call any camera functions to match settings. */ + /* Right now this camera only supports 1 mode. */ + } + break; + + /* These are all the possible cases. */ + case V4L2_BUF_TYPE_VIDEO_OUTPUT: + case V4L2_BUF_TYPE_VIDEO_OVERLAY: + case V4L2_BUF_TYPE_VBI_CAPTURE: + case V4L2_BUF_TYPE_VBI_OUTPUT: + case V4L2_BUF_TYPE_SLICED_VBI_CAPTURE: + case V4L2_BUF_TYPE_SLICED_VBI_OUTPUT: + pr_err(" type is not V4L2_BUF_TYPE_VIDEO_CAPTURE " \ + "but %d\n", a->type); + ret = -EINVAL; + break; + + default: + pr_err(" type is unknown - %d\n", a->type); + ret = -EINVAL; + break; + } + + return 0; +} + +/*! + * ioctl_g_fmt_cap - V4L2 sensor interface handler for ioctl_g_fmt_cap + * @s: pointer to standard V4L2 device structure + * @f: pointer to standard V4L2 v4l2_format structure + * + * Returns the sensor's current pixel format in the v4l2_format + * parameter. + */ +static int ioctl_g_fmt_cap(struct v4l2_int_device *s, struct v4l2_format *f) +{ + struct sensor *sensor = s->priv; + /* s->priv points to mt9v111_data */ + + pr_debug("In mt9v111:ioctl_g_fmt_cap.\n"); + pr_debug(" Returning size of %dx%d\n", + sensor->pix.width, sensor->pix.height); + + f->fmt.pix = sensor->pix; + + return 0; +} + +/*! + * ioctl_queryctrl - V4L2 sensor interface handler for VIDIOC_QUERYCTRL ioctl + * @s: pointer to standard V4L2 device structure + * @qc: standard V4L2 VIDIOC_QUERYCTRL ioctl structure + * + * If the requested control is supported, returns the control information + * from the video_control[] array. Otherwise, returns -EINVAL if the + * control is not supported. + */ +static int ioctl_queryctrl(struct v4l2_int_device *s, struct v4l2_queryctrl *qc) +{ + pr_debug("In mt9v111:ioctl_queryctrl\n"); + + return 0; +} + +/*! + * ioctl_g_ctrl - V4L2 sensor interface handler for VIDIOC_G_CTRL ioctl + * @s: pointer to standard V4L2 device structure + * @vc: standard V4L2 VIDIOC_G_CTRL ioctl structure + * + * If the requested control is supported, returns the control's current + * value from the video_control[] array. Otherwise, returns -EINVAL + * if the control is not supported. + */ +static int ioctl_g_ctrl(struct v4l2_int_device *s, struct v4l2_control *vc) +{ + pr_debug("In mt9v111:ioctl_g_ctrl\n"); + + switch (vc->id) { + case V4L2_CID_BRIGHTNESS: + pr_debug(" V4L2_CID_BRIGHTNESS\n"); + vc->value = mt9v111_data.brightness; + break; + case V4L2_CID_CONTRAST: + pr_debug(" V4L2_CID_CONTRAST\n"); + vc->value = mt9v111_data.contrast; + break; + case V4L2_CID_SATURATION: + pr_debug(" V4L2_CID_SATURATION\n"); + vc->value = mt9v111_data.saturation; + break; + case V4L2_CID_HUE: + pr_debug(" V4L2_CID_HUE\n"); + vc->value = mt9v111_data.hue; + break; + case V4L2_CID_AUTO_WHITE_BALANCE: + pr_debug( + " V4L2_CID_AUTO_WHITE_BALANCE\n"); + vc->value = 0; + break; + case V4L2_CID_DO_WHITE_BALANCE: + pr_debug( + " V4L2_CID_DO_WHITE_BALANCE\n"); + vc->value = 0; + break; + case V4L2_CID_RED_BALANCE: + pr_debug(" V4L2_CID_RED_BALANCE\n"); + vc->value = mt9v111_data.red; + break; + case V4L2_CID_BLUE_BALANCE: + pr_debug(" V4L2_CID_BLUE_BALANCE\n"); + vc->value = mt9v111_data.blue; + break; + case V4L2_CID_GAMMA: + pr_debug(" V4L2_CID_GAMMA\n"); + vc->value = 0; + break; + case V4L2_CID_EXPOSURE: + pr_debug(" V4L2_CID_EXPOSURE\n"); + vc->value = mt9v111_data.ae_mode; + break; + case V4L2_CID_AUTOGAIN: + pr_debug(" V4L2_CID_AUTOGAIN\n"); + vc->value = 0; + break; + case V4L2_CID_GAIN: + pr_debug(" V4L2_CID_GAIN\n"); + vc->value = 0; + break; + case V4L2_CID_HFLIP: + pr_debug(" V4L2_CID_HFLIP\n"); + vc->value = 0; + break; + case V4L2_CID_VFLIP: + pr_debug(" V4L2_CID_VFLIP\n"); + vc->value = 0; + break; + default: + pr_debug(" Default case\n"); + return -EPERM; + break; + } + + return 0; +} + +/*! + * ioctl_s_ctrl - V4L2 sensor interface handler for VIDIOC_S_CTRL ioctl + * @s: pointer to standard V4L2 device structure + * @vc: standard V4L2 VIDIOC_S_CTRL ioctl structure + * + * If the requested control is supported, sets the control's current + * value in HW (and updates the video_control[] array). Otherwise, + * returns -EINVAL if the control is not supported. + */ +static int ioctl_s_ctrl(struct v4l2_int_device *s, struct v4l2_control *vc) +{ + int retval = 0; + + pr_debug("In mt9v111:ioctl_s_ctrl %d\n", + vc->id); + + switch (vc->id) { + case V4L2_CID_BRIGHTNESS: + pr_debug(" V4L2_CID_BRIGHTNESS\n"); + break; + case V4L2_CID_CONTRAST: + pr_debug(" V4L2_CID_CONTRAST\n"); + break; + case V4L2_CID_SATURATION: + pr_debug(" V4L2_CID_SATURATION\n"); + retval = mt9v111_set_saturation(vc->value); + break; + case V4L2_CID_HUE: + pr_debug(" V4L2_CID_HUE\n"); + break; + case V4L2_CID_AUTO_WHITE_BALANCE: + pr_debug( + " V4L2_CID_AUTO_WHITE_BALANCE\n"); + break; + case V4L2_CID_DO_WHITE_BALANCE: + pr_debug( + " V4L2_CID_DO_WHITE_BALANCE\n"); + break; + case V4L2_CID_RED_BALANCE: + pr_debug(" V4L2_CID_RED_BALANCE\n"); + break; + case V4L2_CID_BLUE_BALANCE: + pr_debug(" V4L2_CID_BLUE_BALANCE\n"); + break; + case V4L2_CID_GAMMA: + pr_debug(" V4L2_CID_GAMMA\n"); + break; + case V4L2_CID_EXPOSURE: + pr_debug(" V4L2_CID_EXPOSURE\n"); + retval = mt9v111_set_ae_mode(vc->value); + break; + case V4L2_CID_AUTOGAIN: + pr_debug(" V4L2_CID_AUTOGAIN\n"); + break; + case V4L2_CID_GAIN: + pr_debug(" V4L2_CID_GAIN\n"); + break; + case V4L2_CID_HFLIP: + pr_debug(" V4L2_CID_HFLIP\n"); + break; + case V4L2_CID_VFLIP: + pr_debug(" V4L2_CID_VFLIP\n"); + break; + default: + pr_debug(" Default case\n"); + retval = -EPERM; + break; + } + + return retval; +} + +/*! + * ioctl_init - V4L2 sensor interface handler for VIDIOC_INT_INIT + * @s: pointer to standard V4L2 device structure + */ +static int ioctl_init(struct v4l2_int_device *s) +{ + pr_debug("In mt9v111:ioctl_init\n"); + + return 0; +} + +/*! + * ioctl_dev_init - V4L2 sensor interface handler for vidioc_int_dev_init_num + * @s: pointer to standard V4L2 device structure + * + * Initialise the device when slave attaches to the master. + */ +static int ioctl_dev_init(struct v4l2_int_device *s) +{ + uint32_t clock_rate = MT9V111_MCLK; + + pr_debug("In mt9v111:ioctl_dev_init\n"); + + gpio_sensor_active(); + + set_mclk_rate(&clock_rate); + mt9v111_rate_cal(&reset_frame_rate, clock_rate); + mt9v111_sensor_lib(mt9v111_device.coreReg, mt9v111_device.ifpReg); + + return 0; +} + +/*! + * This structure defines all the ioctls for this module and links them to the + * enumeration. + */ +static struct v4l2_int_ioctl_desc mt9v111_ioctl_desc[] = { + + {vidioc_int_dev_init_num, (v4l2_int_ioctl_func*)ioctl_dev_init}, + + /*! + * Delinitialise the dev. at slave detach. + * The complement of ioctl_dev_init. + */ +/* {vidioc_int_dev_exit_num, (v4l2_int_ioctl_func *) ioctl_dev_exit}, */ + + {vidioc_int_s_power_num, (v4l2_int_ioctl_func*) ioctl_s_power}, + {vidioc_int_g_ifparm_num, (v4l2_int_ioctl_func*) ioctl_g_ifparm}, +/* {vidioc_int_g_needs_reset_num, + (v4l2_int_ioctl_func *) ioctl_g_needs_reset}, */ +/* {vidioc_int_reset_num, (v4l2_int_ioctl_func *) ioctl_reset}, */ + {vidioc_int_init_num, (v4l2_int_ioctl_func*) ioctl_init}, + + /*! + * VIDIOC_ENUM_FMT ioctl for the CAPTURE buffer type. + */ +/* {vidioc_int_enum_fmt_cap_num, + (v4l2_int_ioctl_func *) ioctl_enum_fmt_cap}, */ + + /*! + * VIDIOC_TRY_FMT ioctl for the CAPTURE buffer type. + * This ioctl is used to negotiate the image capture size and + * pixel format without actually making it take effect. + */ +/* {vidioc_int_try_fmt_cap_num, + (v4l2_int_ioctl_func *) ioctl_try_fmt_cap}, */ + + {vidioc_int_g_fmt_cap_num, (v4l2_int_ioctl_func*) ioctl_g_fmt_cap}, + + /*! + * If the requested format is supported, configures the HW to use that + * format, returns error code if format not supported or HW can't be + * correctly configured. + */ +/* {vidioc_int_s_fmt_cap_num, (v4l2_int_ioctl_func *)ioctl_s_fmt_cap}, */ + + {vidioc_int_g_parm_num, (v4l2_int_ioctl_func*) ioctl_g_parm}, + {vidioc_int_s_parm_num, (v4l2_int_ioctl_func*) ioctl_s_parm}, +/* {vidioc_int_queryctrl_num, (v4l2_int_ioctl_func *) ioctl_queryctrl}, */ + {vidioc_int_g_ctrl_num, (v4l2_int_ioctl_func*) ioctl_g_ctrl}, + {vidioc_int_s_ctrl_num, (v4l2_int_ioctl_func*) ioctl_s_ctrl}, +}; + +static struct v4l2_int_slave mt9v111_slave = { + .ioctls = mt9v111_ioctl_desc, + .num_ioctls = ARRAY_SIZE(mt9v111_ioctl_desc), +}; + +static struct v4l2_int_device mt9v111_int_device = { + .module = THIS_MODULE, + .name = "mt9v111", + .type = v4l2_int_type_slave, + .u = { + .slave = &mt9v111_slave, + }, +}; + +/*! + * mt9v111 I2C probe function + * Function set in i2c_driver struct. + * Called by insmod mt9v111_camera.ko. + * + * @return Error code indicating success or failure + */ +static int mt9v111_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + int retval; + + pr_debug("In mt9v111_probe device id is %s\n", id->name); + + /* Set initial values for the sensor struct. */ + memset(&mt9v111_data, 0, sizeof(mt9v111_data)); + mt9v111_data.i2c_client = client; + pr_debug(" client name is %s\n", client->name); + mt9v111_data.pix.pixelformat = V4L2_PIX_FMT_UYVY; + mt9v111_data.pix.width = MT9V111_MAX_WIDTH; + mt9v111_data.pix.height = MT9V111_MAX_HEIGHT; + mt9v111_data.streamcap.capability = 0; /* No higher resolution or frame + * frame rate changes supported. + */ + mt9v111_data.streamcap.timeperframe.denominator = MT9V111_FRAME_RATE; + mt9v111_data.streamcap.timeperframe.numerator = 1; + + mt9v111_int_device.priv = &mt9v111_data; + + pr_debug(" type is %d (expect %d)\n", + mt9v111_int_device.type, v4l2_int_type_slave); + pr_debug(" num ioctls is %d\n", + mt9v111_int_device.u.slave->num_ioctls); + + /* This function attaches this structure to the /dev/video0 device. + * The pointer in priv points to the mt9v111_data structure here.*/ + retval = v4l2_int_device_register(&mt9v111_int_device); + + return retval; +} + +/*! + * Function set in i2c_driver struct. + * Called on rmmod mt9v111_camera.ko + */ +static int mt9v111_remove(struct i2c_client *client) +{ + pr_debug("In mt9v111_remove\n"); + + v4l2_int_device_unregister(&mt9v111_int_device); + return 0; +} + +/*! + * MT9V111 init function. + * Called by insmod mt9v111_camera.ko. + * + * @return Error code indicating success or failure + */ +static __init int mt9v111_init(void) +{ + u8 err; + + pr_debug("In mt9v111_init\n"); + + /* Allocate memory for state structures. */ + mt9v111_device.coreReg = (mt9v111_coreReg *) + kmalloc(sizeof(mt9v111_coreReg), GFP_KERNEL); + if (!mt9v111_device.coreReg) + return -1; + memset(mt9v111_device.coreReg, 0, sizeof(mt9v111_coreReg)); + + mt9v111_device.ifpReg = (mt9v111_IFPReg *) + kmalloc(sizeof(mt9v111_IFPReg), GFP_KERNEL); + if (!mt9v111_device.ifpReg) { + kfree(mt9v111_device.coreReg); + mt9v111_device.coreReg = NULL; + return -1; + } + memset(mt9v111_device.ifpReg, 0, sizeof(mt9v111_IFPReg)); + + /* Set contents of the just created structures. */ + mt9v111_config(); + + /* Tells the i2c driver what functions to call for this driver. */ + err = i2c_add_driver(&mt9v111_i2c_driver); + if (err != 0) + pr_err("%s:driver registration failed, error=%d \n", + __func__, err); + + return err; +} + +/*! + * MT9V111 cleanup function. + * Called on rmmod mt9v111_camera.ko + * + * @return Error code indicating success or failure + */ +static void __exit mt9v111_clean(void) +{ + pr_debug("In mt9v111_clean()\n"); + + i2c_del_driver(&mt9v111_i2c_driver); + gpio_sensor_inactive(); + + if (mt9v111_device.coreReg) { + kfree(mt9v111_device.coreReg); + mt9v111_device.coreReg = NULL; + } + + if (mt9v111_device.ifpReg) { + kfree(mt9v111_device.ifpReg); + mt9v111_device.ifpReg = NULL; + } +} + +module_init(mt9v111_init); +module_exit(mt9v111_clean); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("Mt9v111 Camera Driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/media/video/mxc/capture/mt9v111.h b/drivers/media/video/mxc/capture/mt9v111.h new file mode 100644 index 000000000000..6b9d37b5decd --- /dev/null +++ b/drivers/media/video/mxc/capture/mt9v111.h @@ -0,0 +1,431 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @defgroup Camera Sensor Drivers + */ + +/*! + * @file mt9v111.h + * + * @brief MT9V111 Camera Header file + * + * This header file contains defines and structures for the iMagic mi8012 + * aka the Micron mt9v111 camera. + * + * @ingroup Camera + */ + +#ifndef MT9V111_H_ +#define MT9V111_H_ + +/*! + * Basic camera values + */ +#define MT9V111_FRAME_RATE 30 +#define MT9V111_MCLK 27000000 /* Desired clock rate */ +#define MT9V111_CLK_MIN 12000000 /* This clock rate yields 15 fps */ +#define MT9V111_CLK_MAX 27000000 +#define MT9V111_MAX_WIDTH 640 /* Max width for this camera */ +#define MT9V111_MAX_HEIGHT 480 /* Max height for this camera */ + +/*! + * mt9v111 IFP REGISTER BANK MAP + */ +#define MT9V111I_ADDR_SPACE_SEL 0x1 +#define MT9V111I_BASE_MAXTRIX_SIGN 0x2 +#define MT9V111I_BASE_MAXTRIX_SCALE15 0x3 +#define MT9V111I_BASE_MAXTRIX_SCALE69 0x4 +#define MT9V111I_APERTURE_GAIN 0x5 +#define MT9V111I_MODE_CONTROL 0x6 +#define MT9V111I_SOFT_RESET 0x7 +#define MT9V111I_FORMAT_CONTROL 0x8 +#define MT9V111I_BASE_MATRIX_CFK1 0x9 +#define MT9V111I_BASE_MATRIX_CFK2 0xa +#define MT9V111I_BASE_MATRIX_CFK3 0xb +#define MT9V111I_BASE_MATRIX_CFK4 0xc +#define MT9V111I_BASE_MATRIX_CFK5 0xd +#define MT9V111I_BASE_MATRIX_CFK6 0xe +#define MT9V111I_BASE_MATRIX_CFK7 0xf +#define MT9V111I_BASE_MATRIX_CFK8 0x10 +#define MT9V111I_BASE_MATRIX_CFK9 0x11 +#define MT9V111I_AWB_POSITION 0x12 +#define MT9V111I_AWB_RED_GAIN 0x13 +#define MT9V111I_AWB_BLUE_GAIN 0x14 +#define MT9V111I_DELTA_MATRIX_CF_SIGN 0x15 +#define MT9V111I_DELTA_MATRIX_CF_D1 0x16 +#define MT9V111I_DELTA_MATRIX_CF_D2 0x17 +#define MT9V111I_DELTA_MATRIX_CF_D3 0x18 +#define MT9V111I_DELTA_MATRIX_CF_D4 0x19 +#define MT9V111I_DELTA_MATRIX_CF_D5 0x1a +#define MT9V111I_DELTA_MATRIX_CF_D6 0x1b +#define MT9V111I_DELTA_MATRIX_CF_D7 0x1c +#define MT9V111I_DELTA_MATRIX_CF_D8 0x1d +#define MT9V111I_DELTA_MATRIX_CF_D9 0x1e +#define MT9V111I_LUMINANCE_LIMIT_WB 0x20 +#define MT9V111I_RBG_MANUUAL_WB 0x21 +#define MT9V111I_AWB_RED_LIMIT 0x22 +#define MT9V111I_AWB_BLUE_LIMIT 0x23 +#define MT9V111I_MATRIX_ADJUST_LIMIT 0x24 +#define MT9V111I_AWB_SPEED 0x25 +#define MT9V111I_H_BOUND_AE 0x26 +#define MT9V111I_V_BOUND_AE 0x27 +#define MT9V111I_H_BOUND_AE_CEN_WIN 0x2b +#define MT9V111I_V_BOUND_AE_CEN_WIN 0x2c +#define MT9V111I_BOUND_AWB_WIN 0x2d +#define MT9V111I_AE_PRECISION_TARGET 0x2e +#define MT9V111I_AE_SPEED 0x2f +#define MT9V111I_RED_AWB_MEASURE 0x30 +#define MT9V111I_LUMA_AWB_MEASURE 0x31 +#define MT9V111I_BLUE_AWB_MEASURE 0x32 +#define MT9V111I_LIMIT_SHARP_SATU_CTRL 0x33 +#define MT9V111I_LUMA_OFFSET 0x34 +#define MT9V111I_CLIP_LIMIT_OUTPUT_LUMI 0x35 +#define MT9V111I_GAIN_LIMIT_AE 0x36 +#define MT9V111I_SHUTTER_WIDTH_LIMIT_AE 0x37 +#define MT9V111I_UPPER_SHUTTER_DELAY_LIM 0x39 +#define MT9V111I_OUTPUT_FORMAT_CTRL2 0x3a +#define MT9V111I_IPF_BLACK_LEVEL_SUB 0x3b +#define MT9V111I_IPF_BLACK_LEVEL_ADD 0x3c +#define MT9V111I_ADC_LIMIT_AE_ADJ 0x3d +#define MT9V111I_GAIN_THRE_CCAM_ADJ 0x3e +#define MT9V111I_LINEAR_AE 0x3f +#define MT9V111I_THRESHOLD_EDGE_DEFECT 0x47 +#define MT9V111I_LUMA_SUM_MEASURE 0x4c +#define MT9V111I_TIME_ADV_SUM_LUMA 0x4d +#define MT9V111I_MOTION 0x52 +#define MT9V111I_GAMMA_KNEE_Y12 0x53 +#define MT9V111I_GAMMA_KNEE_Y34 0x54 +#define MT9V111I_GAMMA_KNEE_Y56 0x55 +#define MT9V111I_GAMMA_KNEE_Y78 0x56 +#define MT9V111I_GAMMA_KNEE_Y90 0x57 +#define MT9V111I_GAMMA_VALUE_Y0 0x58 +#define MT9V111I_SHUTTER_60 0x59 +#define MT9V111I_SEARCH_FLICK_60 0x5c +#define MT9V111I_RATIO_IMAGE_GAIN_BASE 0x5e +#define MT9V111I_RATIO_IMAGE_GAIN_DELTA 0x5f +#define MT9V111I_SIGN_VALUE_REG5F 0x60 +#define MT9V111I_AE_GAIN 0x62 +#define MT9V111I_MAX_GAIN_AE 0x67 +#define MT9V111I_LENS_CORRECT_CTRL 0x80 +#define MT9V111I_SHADING_PARAMETER1 0x81 +#define MT9V111I_SHADING_PARAMETER2 0x82 +#define MT9V111I_SHADING_PARAMETER3 0x83 +#define MT9V111I_SHADING_PARAMETER4 0x84 +#define MT9V111I_SHADING_PARAMETER5 0x85 +#define MT9V111I_SHADING_PARAMETER6 0x86 +#define MT9V111I_SHADING_PARAMETER7 0x87 +#define MT9V111I_SHADING_PARAMETER8 0x88 +#define MT9V111I_SHADING_PARAMETER9 0x89 +#define MT9V111I_SHADING_PARAMETER10 0x8A +#define MT9V111I_SHADING_PARAMETER11 0x8B +#define MT9V111I_SHADING_PARAMETER12 0x8C +#define MT9V111I_SHADING_PARAMETER13 0x8D +#define MT9V111I_SHADING_PARAMETER14 0x8E +#define MT9V111I_SHADING_PARAMETER15 0x8F +#define MT9V111I_SHADING_PARAMETER16 0x90 +#define MT9V111I_SHADING_PARAMETER17 0x91 +#define MT9V111I_SHADING_PARAMETER18 0x92 +#define MT9V111I_SHADING_PARAMETER19 0x93 +#define MT9V111I_SHADING_PARAMETER20 0x94 +#define MT9V111I_SHADING_PARAMETER21 0x95 +#define MT9V111i_FLASH_CTRL 0x98 +#define MT9V111i_LINE_COUNTER 0x99 +#define MT9V111i_FRAME_COUNTER 0x9A +#define MT9V111i_H_PAN 0xA5 +#define MT9V111i_H_ZOOM 0xA6 +#define MT9V111i_H_SIZE 0xA7 +#define MT9V111i_V_PAN 0xA8 +#define MT9V111i_V_ZOOM 0xA9 +#define MT9V111i_V_SIZE 0xAA + +#define MT9V111I_SEL_IFP 0x1 +#define MT9V111I_SEL_SCA 0x4 +#define MT9V111I_FC_RGB_OR_YUV 0x1000 + +/*! + * Mt9v111 SENSOR CORE REGISTER BANK MAP + */ +#define MT9V111S_ADDR_SPACE_SEL 0x1 +#define MT9V111S_COLUMN_START 0x2 +#define MT9V111S_WIN_HEIGHT 0x3 +#define MT9V111S_WIN_WIDTH 0x4 +#define MT9V111S_HOR_BLANKING 0x5 +#define MT9V111S_VER_BLANKING 0x6 +#define MT9V111S_OUTPUT_CTRL 0x7 +#define MT9V111S_ROW_START 0x8 +#define MT9V111S_SHUTTER_WIDTH 0x9 +#define MT9V111S_PIXEL_CLOCK_SPEED 0xa +#define MT9V111S_RESTART 0xb +#define MT9V111S_SHUTTER_DELAY 0xc +#define MT9V111S_RESET 0xd +#define MT9V111S_COLUMN_START_IN_ZOOM 0x12 +#define MT9V111S_ROW_START_IN_ZOOM 0x13 +#define MT9V111S_DIGITAL_ZOOM 0x1e +#define MT9V111S_READ_MODE 0x20 +#define MT9V111S_DAC_CTRL 0x27 +#define MT9V111S_GREEN1_GAIN 0x2b +#define MT9V111S_BLUE_GAIN 0x2c +#define MT9V111S_READ_GAIN 0x2d +#define MT9V111S_GREEN2_GAIN 0x2e +#define MT9V111S_ROW_NOISE_CTRL 0x30 +#define MT9V111S_DARK_TARGET_W 0x31 +#define MT9V111S_TEST_DATA 0x32 +#define MT9V111S_GLOBAL_GAIN 0x35 +#define MT9V111S_SENSOR_CORE_VERSION 0x36 +#define MT9V111S_DARK_TARGET_WO 0x37 +#define MT9V111S_VERF_DAC 0x41 +#define MT9V111S_VCM_VCL 0x42 +#define MT9V111S_DISABLE_BYPASS 0x58 +#define MT9V111S_CALIB_MEAN_TEST 0x59 +#define MT9V111S_DARK_G1_AVE 0x5B +#define MT9V111S_DARK_G2_AVE 0x5C +#define MT9V111S_DARK_R_AVE 0x5D +#define MT9V111S_DARK_B_AVE 0x5E +#define MT9V111S_CAL_THRESHOLD 0x5f +#define MT9V111S_CAL_G1 0x60 +#define MT9V111S_CAL_G2 0x61 +#define MT9V111S_CAL_CTRL 0x62 +#define MT9V111S_CAL_R 0x63 +#define MT9V111S_CAL_B 0x64 +#define MT9V111S_CHIP_ENABLE 0xF1 +#define MT9V111S_CHIP_VERSION 0xFF + +/* OUTPUT_CTRL */ +#define MT9V111S_OUTCTRL_SYNC 0x1 +#define MT9V111S_OUTCTRL_CHIP_ENABLE 0x2 +#define MT9V111S_OUTCTRL_TEST_MODE 0x40 + +/* READ_MODE */ +#define MT9V111S_RM_NOBADFRAME 0x1 +#define MT9V111S_RM_NODESTRUCT 0x2 +#define MT9V111S_RM_COLUMNSKIP 0x4 +#define MT9V111S_RM_ROWSKIP 0x8 +#define MT9V111S_RM_BOOSTEDRESET 0x1000 +#define MT9V111S_RM_COLUMN_LATE 0x10 +#define MT9V111S_RM_ROW_LATE 0x80 +#define MT9V111S_RM_RIGTH_TO_LEFT 0x4000 +#define MT9V111S_RM_BOTTOM_TO_TOP 0x8000 + +/*! I2C Slave Address */ +#define MT9V111_I2C_ADDRESS 0x48 + +/*! + * The image resolution enum for the mt9v111 sensor + */ +typedef enum { + MT9V111_OutputResolution_VGA = 0, /*!< VGA size */ + MT9V111_OutputResolution_QVGA, /*!< QVGA size */ + MT9V111_OutputResolution_CIF, /*!< CIF size */ + MT9V111_OutputResolution_QCIF, /*!< QCIF size */ + MT9V111_OutputResolution_QQVGA, /*!< QQVGA size */ + MT9V111_OutputResolution_SXGA /*!< SXGA size */ +} MT9V111_OutputResolution; + +enum { + MT9V111_WINWIDTH = 0x287, + MT9V111_WINWIDTH_DEFAULT = 0x287, + MT9V111_WINWIDTH_MIN = 0x9, + + MT9V111_WINHEIGHT = 0x1E7, + MT9V111_WINHEIGHT_DEFAULT = 0x1E7, + + MT9V111_HORZBLANK_DEFAULT = 0x26, + MT9V111_HORZBLANK_MIN = 0x9, + MT9V111_HORZBLANK_MAX = 0x3FF, + + MT9V111_VERTBLANK_DEFAULT = 0x4, + MT9V111_VERTBLANK_MIN = 0x3, + MT9V111_VERTBLANK_MAX = 0xFFF, +}; + +/*! + * Mt9v111 Core Register structure. + */ +typedef struct { + u32 addressSelect; /*!< select address bank for Core Register 0x4 */ + u32 columnStart; /*!< Starting Column */ + u32 windowHeight; /*!< Window Height */ + u32 windowWidth; /*!< Window Width */ + u32 horizontalBlanking; /*!< Horizontal Blank time, in pixels */ + u32 verticalBlanking; /*!< Vertical Blank time, in pixels */ + u32 outputControl; /*!< Register to control sensor output */ + u32 rowStart; /*!< Starting Row */ + u32 shutterWidth; + u32 pixelClockSpeed; /*!< pixel date rate */ + u32 restart; /*!< Abandon the readout of current frame */ + u32 shutterDelay; + u32 reset; /*!< reset the sensor to the default mode */ + u32 zoomColStart; /*!< Column start in the Zoom mode */ + u32 zomRowStart; /*!< Row start in the Zoom mode */ + u32 digitalZoom; /*!< 1 means zoom by 2 */ + u32 readMode; /*!< Readmode: aspects of the readout of the sensor */ + u32 dACStandbyControl; + u32 green1Gain; /*!< Gain Settings */ + u32 blueGain; + u32 redGain; + u32 green2Gain; + u32 rowNoiseControl; + u32 darkTargetwNC; + u32 testData; /*!< test mode */ + u32 globalGain; + u32 chipVersion; + u32 darkTargetwoNC; + u32 vREFDACs; + u32 vCMandVCL; + u32 disableBypass; + u32 calibMeanTest; + u32 darkG1average; + u32 darkG2average; + u32 darkRaverage; + u32 darkBaverage; + u32 calibThreshold; + u32 calibGreen1; + u32 calibGreen2; + u32 calibControl; + u32 calibRed; + u32 calibBlue; + u32 chipEnable; /*!< Image core Registers written by image flow processor */ +} mt9v111_coreReg; + +/*! + * Mt9v111 IFP Register structure. + */ +typedef struct { + u32 addrSpaceSel; /*!< select address bank for Core Register 0x1 */ + u32 baseMaxtrixSign; /*!< sign of coefficient for base color correction matrix */ + u32 baseMaxtrixScale15; /*!< scaling of color correction coefficient K1-5 */ + u32 baseMaxtrixScale69; /*!< scaling of color correction coefficient K6-9 */ + u32 apertureGain; /*!< sharpening */ + u32 modeControl; /*!< bit 7 CCIR656 sync codes are embedded in the image */ + u32 softReset; /*!< Image processing mode: 1 reset mode, 0 operational mode */ + u32 formatControl; /*!< bit12 1 for RGB565, 0 for YcrCb */ + u32 baseMatrixCfk1; /*!< K1 Color correction coefficient */ + u32 baseMatrixCfk2; /*!< K2 Color correction coefficient */ + u32 baseMatrixCfk3; /*!< K3 Color correction coefficient */ + u32 baseMatrixCfk4; /*!< K4 Color correction coefficient */ + u32 baseMatrixCfk5; /*!< K5 Color correction coefficient */ + u32 baseMatrixCfk6; /*!< K6 Color correction coefficient */ + u32 baseMatrixCfk7; /*!< K7 Color correction coefficient */ + u32 baseMatrixCfk8; /*!< K8 Color correction coefficient */ + u32 baseMatrixCfk9; /*!< K9 Color correction coefficient */ + u32 awbPosition; /*!< Current position of AWB color correction matrix */ + u32 awbRedGain; /*!< Current value of AWB red channel gain */ + u32 awbBlueGain; /*!< Current value of AWB blue channel gain */ + u32 deltaMatrixCFSign; /*!< Sign of coefficients of delta color correction matrix register */ + u32 deltaMatrixCFD1; /*!< D1 Delta coefficient */ + u32 deltaMatrixCFD2; /*!< D2 Delta coefficient */ + u32 deltaMatrixCFD3; /*!< D3 Delta coefficient */ + u32 deltaMatrixCFD4; /*!< D4 Delta coefficient */ + u32 deltaMatrixCFD5; /*!< D5 Delta coefficient */ + u32 deltaMatrixCFD6; /*!< D6 Delta coefficient */ + u32 deltaMatrixCFD7; /*!< D7 Delta coefficient */ + u32 deltaMatrixCFD8; /*!< D8 Delta coefficient */ + u32 deltaMatrixCFD9; /*!< D9 Delta coefficient */ + u32 lumLimitWB; /*!< Luminance range of pixels considered in WB statistics */ + u32 RBGManualWB; /*!< Red and Blue color channel gains for manual white balance */ + u32 awbRedLimit; /*!< Limits on Red channel gain adjustment through AWB */ + u32 awbBlueLimit; /*!< Limits on Blue channel gain adjustment through AWB */ + u32 matrixAdjLimit; /*!< Limits on color correction matrix adjustment through AWB */ + u32 awbSpeed; /*!< AWB speed and color saturation control */ + u32 HBoundAE; /*!< Horizontal boundaries of AWB measurement window */ + u32 VBoundAE; /*!< Vertical boundaries of AWB measurement window */ + u32 HBoundAECenWin; /*!< Horizontal boundaries of AE measurement window for backlight compensation */ + u32 VBoundAECenWin; /*!< Vertical boundaries of AE measurement window for backlight compensation */ + u32 boundAwbWin; /*!< Boundaries of AWB measurement window */ + u32 AEPrecisionTarget; /*!< Auto exposure target and precision control */ + u32 AESpeed; /*!< AE speed and sensitivity control register */ + u32 redAWBMeasure; /*!< Measure of the red channel value used by AWB */ + u32 lumaAWBMeasure; /*!< Measure of the luminance channel value used by AWB */ + u32 blueAWBMeasure; /*!< Measure of the blue channel value used by AWB */ + u32 limitSharpSatuCtrl; /*!< Automatic control of sharpness and color saturation */ + u32 lumaOffset; /*!< Luminance offset control (brightness control) */ + u32 clipLimitOutputLumi; /*!< Clipping limits for output luminance */ + u32 gainLimitAE; /*!< Imager gain limits for AE adjustment */ + u32 shutterWidthLimitAE; /*!< Shutter width (exposure time) limits for AE adjustment */ + u32 upperShutterDelayLi; /*!< Upper Shutter Delay Limit */ + u32 outputFormatCtrl2; /*!< Output Format Control 2 + 00 = 16-bit RGB565. + 01 = 15-bit RGB555. + 10 = 12-bit RGB444x. + 11 = 12-bit RGBx444. */ + u32 ipfBlackLevelSub; /*!< IFP black level subtraction */ + u32 ipfBlackLevelAdd; /*!< IFP black level addition */ + u32 adcLimitAEAdj; /*!< ADC limits for AE adjustment */ + u32 agimnThreCamAdj; /*!< Gain threshold for CCM adjustment */ + u32 linearAE; + u32 thresholdEdgeDefect; /*!< Edge threshold for interpolation and defect correction */ + u32 lumaSumMeasure; /*!< Luma measured by AE engine */ + u32 timeAdvSumLuma; /*!< Time-averaged luminance value tracked by auto exposure */ + u32 motion; /*!< 1 when motion is detected */ + u32 gammaKneeY12; /*!< Gamma knee points Y1 and Y2 */ + u32 gammaKneeY34; /*!< Gamma knee points Y3 and Y4 */ + u32 gammaKneeY56; /*!< Gamma knee points Y5 and Y6 */ + u32 gammaKneeY78; /*!< Gamma knee points Y7 and Y8 */ + u32 gammaKneeY90; /*!< Gamma knee points Y9 and Y10 */ + u32 gammaKneeY0; /*!< Gamma knee point Y0 */ + u32 shutter_width_60; + u32 search_flicker_60; + u32 ratioImageGainBase; + u32 ratioImageGainDelta; + u32 signValueReg5F; + u32 aeGain; + u32 maxGainAE; + u32 lensCorrectCtrl; + u32 shadingParameter1; /*!< Shade Parameters */ + u32 shadingParameter2; + u32 shadingParameter3; + u32 shadingParameter4; + u32 shadingParameter5; + u32 shadingParameter6; + u32 shadingParameter7; + u32 shadingParameter8; + u32 shadingParameter9; + u32 shadingParameter10; + u32 shadingParameter11; + u32 shadingParameter12; + u32 shadingParameter13; + u32 shadingParameter14; + u32 shadingParameter15; + u32 shadingParameter16; + u32 shadingParameter17; + u32 shadingParameter18; + u32 shadingParameter19; + u32 shadingParameter20; + u32 shadingParameter21; + u32 flashCtrl; /*!< Flash control */ + u32 lineCounter; /*!< Line counter */ + u32 frameCounter; /*!< Frame counter */ + u32 HPan; /*!< Horizontal pan in decimation */ + u32 HZoom; /*!< Horizontal zoom in decimation */ + u32 HSize; /*!< Horizontal output size iIn decimation */ + u32 VPan; /*!< Vertical pan in decimation */ + u32 VZoom; /*!< Vertical zoom in decimation */ + u32 VSize; /*!< Vertical output size in decimation */ +} mt9v111_IFPReg; + +/*! + * mt9v111 Config structure + */ +typedef struct { + mt9v111_coreReg *coreReg; /*!< Sensor Core Register Bank */ + mt9v111_IFPReg *ifpReg; /*!< IFP Register Bank */ +} mt9v111_conf; + +typedef struct { + u8 index; + u16 width; + u16 height; +} mt9v111_image_format; + +#endif /* MT9V111_H_ */ diff --git a/drivers/media/video/mxc/capture/mxc_v4l2_capture.c b/drivers/media/video/mxc/capture/mxc_v4l2_capture.c new file mode 100644 index 000000000000..56cc875d2da8 --- /dev/null +++ b/drivers/media/video/mxc/capture/mxc_v4l2_capture.c @@ -0,0 +1,2728 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file drivers/media/video/mxc/capture/mxc_v4l2_capture.c + * + * @brief Mxc Video For Linux 2 driver + * + * @ingroup MXC_V4L2_CAPTURE + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "mxc_v4l2_capture.h" +#include "ipu_prp_sw.h" + +static int video_nr = -1; +static cam_data *g_cam; + +/*! This data is used for the output to the display. */ +#define MXC_V4L2_CAPTURE_NUM_OUTPUTS 3 +#define MXC_V4L2_CAPTURE_NUM_INPUTS 2 +static struct v4l2_output mxc_capture_outputs[MXC_V4L2_CAPTURE_NUM_OUTPUTS] = { + { + .index = 0, + .name = "DISP3 BG", + .type = V4L2_OUTPUT_TYPE_ANALOG, + .audioset = 0, + .modulator = 0, + .std = V4L2_STD_UNKNOWN, + }, + { + .index = 1, + .name = "DISP0", + .type = V4L2_OUTPUT_TYPE_ANALOG, + .audioset = 0, + .modulator = 0, + .std = V4L2_STD_UNKNOWN, + }, + { + .index = 2, + .name = "DISP3 FG", + .type = V4L2_OUTPUT_TYPE_ANALOG, + .audioset = 0, + .modulator = 0, + .std = V4L2_STD_UNKNOWN, + }, +}; + +static struct v4l2_input mxc_capture_inputs[MXC_V4L2_CAPTURE_NUM_INPUTS] = { + { + .index = 0, + .name = "CSI IC MEM", + .type = V4L2_INPUT_TYPE_CAMERA, + .audioset = 0, + .tuner = 0, + .std = V4L2_STD_UNKNOWN, + .status = 0, + }, + { + .index = 1, + .name = "CSI MEM", + .type = V4L2_INPUT_TYPE_CAMERA, + .audioset = 0, + .tuner = 0, + .std = V4L2_STD_UNKNOWN, + .status = V4L2_IN_ST_NO_POWER, + }, +}; + +/*! List of TV input video formats supported. The video formats is corresponding + * to the v4l2_id in video_fmt_t. + * Currently, only PAL and NTSC is supported. Needs to be expanded in the + * future. + */ +typedef enum { + TV_NTSC = 0, /*!< Locked on (M) NTSC video signal. */ + TV_PAL, /*!< (B, G, H, I, N)PAL video signal. */ + TV_NOT_LOCKED, /*!< Not locked on a signal. */ +} video_fmt_idx; + +/*! Number of video standards supported (including 'not locked' signal). */ +#define TV_STD_MAX (TV_NOT_LOCKED + 1) + +/*! Video format structure. */ +typedef struct { + int v4l2_id; /*!< Video for linux ID. */ + char name[16]; /*!< Name (e.g., "NTSC", "PAL", etc.) */ + u16 raw_width; /*!< Raw width. */ + u16 raw_height; /*!< Raw height. */ + u16 active_width; /*!< Active width. */ + u16 active_height; /*!< Active height. */ + u16 active_top; /*!< Active top. */ + u16 active_left; /*!< Active left. */ +} video_fmt_t; + +/*! + * Description of video formats supported. + * + * PAL: raw=720x625, active=720x576. + * NTSC: raw=720x525, active=720x480. + */ +static video_fmt_t video_fmts[] = { + { /*! NTSC */ + .v4l2_id = V4L2_STD_NTSC, + .name = "NTSC", + .raw_width = 720, /* SENS_FRM_WIDTH */ + .raw_height = 525, /* SENS_FRM_HEIGHT */ + .active_width = 720, /* ACT_FRM_WIDTH */ + .active_height = 240, /* ACT_FRM_HEIGHT */ + .active_top = 0, + .active_left = 0, + }, + { /*! (B, G, H, I, N) PAL */ + .v4l2_id = V4L2_STD_PAL, + .name = "PAL", + .raw_width = 720, + .raw_height = 625, + .active_width = 720, + .active_height = 288, + .active_top = 0, + .active_left = 0, + }, + { /*! Unlocked standard */ + .v4l2_id = V4L2_STD_ALL, + .name = "Autodetect", + .raw_width = 720, + .raw_height = 625, + .active_width = 720, + .active_height = 288, + .active_top = 0, + .active_left = 0, + }, +}; + +/*!* Standard index of TV. */ +static video_fmt_idx video_index = TV_NOT_LOCKED; + +static int mxc_v4l2_master_attach(struct v4l2_int_device *slave); +static void mxc_v4l2_master_detach(struct v4l2_int_device *slave); +static u8 camera_power(cam_data *cam, bool cameraOn); +static int start_preview(cam_data *cam); +static int stop_preview(cam_data *cam); + +/*! Information about this driver. */ +static struct v4l2_int_master mxc_v4l2_master = { + .attach = mxc_v4l2_master_attach, + .detach = mxc_v4l2_master_detach, +}; + +static struct v4l2_int_device mxc_v4l2_int_device = { + .module = THIS_MODULE, + .name = "mxc_v4l2_cap", + .type = v4l2_int_type_master, + .u = { + .master = &mxc_v4l2_master, + }, +}; + +/*************************************************************************** + * Functions for handling Frame buffers. + **************************************************************************/ + +/*! + * Free frame buffers + * + * @param cam Structure cam_data * + * + * @return status 0 success. + */ +static int mxc_free_frame_buf(cam_data *cam) +{ + int i; + + pr_debug("MVC: In mxc_free_frame_buf\n"); + + for (i = 0; i < FRAME_NUM; i++) { + if (cam->frame[i].vaddress != 0) { + dma_free_coherent(0, cam->frame[i].buffer.length, + cam->frame[i].vaddress, + cam->frame[i].paddress); + cam->frame[i].vaddress = 0; + } + } + + return 0; +} + +/*! + * Allocate frame buffers + * + * @param cam Structure cam_data* + * @param count int number of buffer need to allocated + * + * @return status -0 Successfully allocated a buffer, -ENOBUFS failed. + */ +static int mxc_allocate_frame_buf(cam_data *cam, int count) +{ + int i; + + pr_debug("In MVC:mxc_allocate_frame_buf - size=%d\n", + cam->v2f.fmt.pix.sizeimage); + + for (i = 0; i < count; i++) { + cam->frame[i].vaddress = + dma_alloc_coherent(0, + PAGE_ALIGN(cam->v2f.fmt.pix.sizeimage), + &cam->frame[i].paddress, + GFP_DMA | GFP_KERNEL); + if (cam->frame[i].vaddress == 0) { + pr_err("ERROR: v4l2 capture: " + "mxc_allocate_frame_buf failed.\n"); + mxc_free_frame_buf(cam); + return -ENOBUFS; + } + cam->frame[i].buffer.index = i; + cam->frame[i].buffer.flags = V4L2_BUF_FLAG_MAPPED; + cam->frame[i].buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + cam->frame[i].buffer.length = + PAGE_ALIGN(cam->v2f.fmt.pix.sizeimage); + cam->frame[i].buffer.memory = V4L2_MEMORY_MMAP; + cam->frame[i].buffer.m.offset = cam->frame[i].paddress; + cam->frame[i].index = i; + } + + return 0; +} + +/*! + * Free frame buffers status + * + * @param cam Structure cam_data * + * + * @return none + */ +static void mxc_free_frames(cam_data *cam) +{ + int i; + + pr_debug("In MVC:mxc_free_frames\n"); + + for (i = 0; i < FRAME_NUM; i++) { + cam->frame[i].buffer.flags = V4L2_BUF_FLAG_MAPPED; + } + + cam->enc_counter = 0; + cam->skip_frame = 0; + INIT_LIST_HEAD(&cam->ready_q); + INIT_LIST_HEAD(&cam->working_q); + INIT_LIST_HEAD(&cam->done_q); +} + +/*! + * Return the buffer status + * + * @param cam Structure cam_data * + * @param buf Structure v4l2_buffer * + * + * @return status 0 success, EINVAL failed. + */ +static int mxc_v4l2_buffer_status(cam_data *cam, struct v4l2_buffer *buf) +{ + pr_debug("In MVC:mxc_v4l2_buffer_status\n"); + + if (buf->index < 0 || buf->index >= FRAME_NUM) { + pr_err("ERROR: v4l2 capture: mxc_v4l2_buffer_status buffers " + "not allocated\n"); + return -EINVAL; + } + + memcpy(buf, &(cam->frame[buf->index].buffer), sizeof(*buf)); + return 0; +} + +/*************************************************************************** + * Functions for handling the video stream. + **************************************************************************/ + +/*! + * Indicates whether the palette is supported. + * + * @param palette V4L2_PIX_FMT_RGB565, V4L2_PIX_FMT_BGR24 or V4L2_PIX_FMT_BGR32 + * + * @return 0 if failed + */ +static inline int valid_mode(u32 palette) +{ + return ((palette == V4L2_PIX_FMT_RGB565) || + (palette == V4L2_PIX_FMT_BGR24) || + (palette == V4L2_PIX_FMT_RGB24) || + (palette == V4L2_PIX_FMT_BGR32) || + (palette == V4L2_PIX_FMT_RGB32) || + (palette == V4L2_PIX_FMT_YUV422P) || + (palette == V4L2_PIX_FMT_UYVY) || + (palette == V4L2_PIX_FMT_YUYV) || + (palette == V4L2_PIX_FMT_YUV420) || + (palette == V4L2_PIX_FMT_NV12)); +} + +/*! + * Start the encoder job + * + * @param cam structure cam_data * + * + * @return status 0 Success + */ +static int mxc_streamon(cam_data *cam) +{ + struct mxc_v4l_frame *frame; + int err = 0; + + pr_debug("In MVC:mxc_streamon\n"); + + if (NULL == cam) { + pr_err("ERROR! cam parameter is NULL\n"); + return -1; + } + + if (cam->capture_on) { + pr_err("ERROR: v4l2 capture: Capture stream has been turned " + " on\n"); + return -1; + } + + if (list_empty(&cam->ready_q)) { + pr_err("ERROR: v4l2 capture: mxc_streamon buffer has not been " + "queued yet\n"); + return -EINVAL; + } + + cam->capture_pid = current->pid; + + if (cam->overlay_on == true) + stop_preview(cam); + + if (cam->enc_enable) { + err = cam->enc_enable(cam); + if (err != 0) { + return err; + } + } + + cam->ping_pong_csi = 0; + if (cam->enc_update_eba) { + frame = + list_entry(cam->ready_q.next, struct mxc_v4l_frame, queue); + list_del(cam->ready_q.next); + list_add_tail(&frame->queue, &cam->working_q); + err = cam->enc_update_eba(frame->buffer.m.offset, + &cam->ping_pong_csi); + + frame = + list_entry(cam->ready_q.next, struct mxc_v4l_frame, queue); + list_del(cam->ready_q.next); + list_add_tail(&frame->queue, &cam->working_q); + err |= cam->enc_update_eba(frame->buffer.m.offset, + &cam->ping_pong_csi); + } else { + return -EINVAL; + } + + if (cam->overlay_on == true) + start_preview(cam); + + if (cam->enc_enable_csi) { + err = cam->enc_enable_csi(cam); + if (err != 0) + return err; + } + + cam->capture_on = true; + + return err; +} + +/*! + * Shut down the encoder job + * + * @param cam structure cam_data * + * + * @return status 0 Success + */ +static int mxc_streamoff(cam_data *cam) +{ + int err = 0; + + pr_debug("In MVC:mxc_streamoff\n"); + + if (cam->capture_on == false) + return 0; + + if (cam->enc_disable_csi) { + err = cam->enc_disable_csi(cam); + if (err != 0) + return err; + } + if (cam->enc_disable) + err = cam->enc_disable(cam); + + mxc_free_frames(cam); + mxc_capture_inputs[cam->current_input].status |= V4L2_IN_ST_NO_POWER; + cam->capture_on = false; + return err; +} + +/*! + * Valid and adjust the overlay window size, position + * + * @param cam structure cam_data * + * @param win struct v4l2_window * + * + * @return 0 + */ +static int verify_preview(cam_data *cam, struct v4l2_window *win) +{ + int i = 0, width_bound = 0, height_bound = 0; + int *width, *height; + struct fb_info *bg_fbi = NULL; + bool foregound_fb; + + pr_debug("In MVC: verify_preview\n"); + + do { + cam->overlay_fb = (struct fb_info *)registered_fb[i]; + if (cam->overlay_fb == NULL) { + pr_err("ERROR: verify_preview frame buffer NULL.\n"); + return -1; + } + if (strcmp(cam->overlay_fb->fix.id, "DISP3 BG") == 0) + bg_fbi = cam->overlay_fb; + if (strcmp(cam->overlay_fb->fix.id, + mxc_capture_outputs[cam->output].name) == 0) { + if (strcmp(cam->overlay_fb->fix.id, "DISP3 FG") == 0) + foregound_fb = true; + break; + } + } while (++i < FB_MAX); + + if (foregound_fb) { + width_bound = bg_fbi->var.xres; + height_bound = bg_fbi->var.yres; + + if (win->w.width + win->w.left > bg_fbi->var.xres || + win->w.height + win->w.top > bg_fbi->var.yres) { + pr_err("ERROR: FG window position exceeds.\n"); + return -1; + } + } else { + /* 4 bytes alignment for BG */ + width_bound = cam->overlay_fb->var.xres; + height_bound = cam->overlay_fb->var.yres; + + if (cam->overlay_fb->var.bits_per_pixel == 24) { + win->w.left -= win->w.left % 4; + } else if (cam->overlay_fb->var.bits_per_pixel == 16) { + win->w.left -= win->w.left % 2; + } + + if (win->w.width + win->w.left > cam->overlay_fb->var.xres) + win->w.width = cam->overlay_fb->var.xres - win->w.left; + if (win->w.height + win->w.top > cam->overlay_fb->var.yres) + win->w.height = cam->overlay_fb->var.yres - win->w.top; + } + + /* stride line limitation */ + win->w.height -= win->w.height % 8; + win->w.width -= win->w.width % 8; + + if (cam->rotation >= IPU_ROTATE_90_RIGHT) { + height = &win->w.width; + width = &win->w.height; + } else { + width = &win->w.width; + height = &win->w.height; + } + + if ((cam->crop_bounds.width / *width > 8) || + ((cam->crop_bounds.width / *width == 8) && + (cam->crop_bounds.width % *width))) { + *width = cam->crop_bounds.width / 8; + if (*width % 8) + *width += 8 - *width % 8; + if (*width + win->w.left > width_bound) { + pr_err("ERROR: v4l2 capture: width exceeds " + "resize limit.\n"); + return -1; + } + pr_err("ERROR: v4l2 capture: width exceeds limit. " + "Resize to %d.\n", + *width); + } + + if ((cam->crop_bounds.height / *height > 8) || + ((cam->crop_bounds.height / *height == 8) && + (cam->crop_bounds.height % *height))) { + *height = cam->crop_bounds.height / 8; + if (*height % 8) + *height += 8 - *height % 8; + if (*height + win->w.top > height_bound) { + pr_err("ERROR: v4l2 capture: height exceeds " + "resize limit.\n"); + return -1; + } + pr_err("ERROR: v4l2 capture: height exceeds limit " + "resize to %d.\n", + *height); + } + + return 0; +} + +/*! + * start the viewfinder job + * + * @param cam structure cam_data * + * + * @return status 0 Success + */ +static int start_preview(cam_data *cam) +{ + int err = 0; + + pr_debug("MVC: start_preview\n"); + +#if defined(CONFIG_MXC_IPU_PRP_VF_SDC) || defined(CONFIG_MXC_IPU_PRP_VF_SDC_MODULE) + pr_debug(" This is an SDC display\n"); + if (cam->output == 0 || cam->output == 2) { + if (cam->v4l2_fb.flags == V4L2_FBUF_FLAG_OVERLAY) + err = prp_vf_sdc_select(cam); + else if (cam->v4l2_fb.flags == V4L2_FBUF_FLAG_PRIMARY) + err = prp_vf_sdc_select_bg(cam); + if (err != 0) + return err; + + err = cam->vf_start_sdc(cam); + if (err != 0) + return err; + + if (cam->vf_enable_csi) + err = cam->vf_enable_csi(cam); + } +#endif + +#if defined(CONFIG_MXC_IPU_PRP_VF_ADC) || defined(CONFIG_MXC_IPU_PRP_VF_ADC_MODULE) + pr_debug(" This is an ADC display\n"); + if (cam->output == 1) { + err = prp_vf_adc_select(cam); + if (err != 0) + return err; + + err = cam->vf_start_adc(cam); + } +#endif + + pr_debug("End of %s: v2f pix widthxheight %d x %d\n", + __func__, + cam->v2f.fmt.pix.width, cam->v2f.fmt.pix.height); + pr_debug("End of %s: crop_bounds widthxheight %d x %d\n", + __func__, + cam->crop_bounds.width, cam->crop_bounds.height); + pr_debug("End of %s: crop_defrect widthxheight %d x %d\n", + __func__, + cam->crop_defrect.width, cam->crop_defrect.height); + pr_debug("End of %s: crop_current widthxheight %d x %d\n", + __func__, + cam->crop_current.width, cam->crop_current.height); + + return err; +} + +/*! + * shut down the viewfinder job + * + * @param cam structure cam_data * + * + * @return status 0 Success + */ +static int stop_preview(cam_data *cam) +{ + int err = 0; + + pr_debug("MVC: stop preview\n"); + +#if defined(CONFIG_MXC_IPU_PRP_VF_ADC) || defined(CONFIG_MXC_IPU_PRP_VF_ADC_MODULE) + if (cam->output == 1) { + err = prp_vf_adc_deselect(cam); + } +#endif + +#if defined(CONFIG_MXC_IPU_PRP_VF_SDC) || defined(CONFIG_MXC_IPU_PRP_VF_SDC_MODULE) + if (cam->vf_disable_csi) { + err = cam->vf_disable_csi(cam); + if (err != 0) + return err; + } + + if (cam->output == 0 || cam->output == 2) { + if (cam->v4l2_fb.flags == V4L2_FBUF_FLAG_OVERLAY) + err = prp_vf_sdc_deselect(cam); + else if (cam->v4l2_fb.flags == V4L2_FBUF_FLAG_PRIMARY) + err = prp_vf_sdc_deselect_bg(cam); + } +#endif + + return err; +} + +/*************************************************************************** + * VIDIOC Functions. + **************************************************************************/ + +/*! + * V4L2 - mxc_v4l2_g_fmt function + * + * @param cam structure cam_data * + * + * @param f structure v4l2_format * + * + * @return status 0 success, EINVAL failed + */ +static int mxc_v4l2_g_fmt(cam_data *cam, struct v4l2_format *f) +{ + int retval = 0; + + pr_debug("In MVC: mxc_v4l2_g_fmt type=%d\n", f->type); + + switch (f->type) { + case V4L2_BUF_TYPE_VIDEO_CAPTURE: + pr_debug(" type is V4L2_BUF_TYPE_VIDEO_CAPTURE\n"); + f->fmt.pix = cam->v2f.fmt.pix; + break; + case V4L2_BUF_TYPE_VIDEO_OVERLAY: + pr_debug(" type is V4L2_BUF_TYPE_VIDEO_OVERLAY\n"); + f->fmt.win = cam->win; + break; + default: + pr_debug(" type is invalid\n"); + retval = -EINVAL; + } + + pr_debug("End of %s: v2f pix widthxheight %d x %d\n", + __func__, + cam->v2f.fmt.pix.width, cam->v2f.fmt.pix.height); + pr_debug("End of %s: crop_bounds widthxheight %d x %d\n", + __func__, + cam->crop_bounds.width, cam->crop_bounds.height); + pr_debug("End of %s: crop_defrect widthxheight %d x %d\n", + __func__, + cam->crop_defrect.width, cam->crop_defrect.height); + pr_debug("End of %s: crop_current widthxheight %d x %d\n", + __func__, + cam->crop_current.width, cam->crop_current.height); + + return retval; +} + +/*! + * V4L2 - mxc_v4l2_s_fmt function + * + * @param cam structure cam_data * + * + * @param f structure v4l2_format * + * + * @return status 0 success, EINVAL failed + */ +static int mxc_v4l2_s_fmt(cam_data *cam, struct v4l2_format *f) +{ + int retval = 0; + int size = 0; + int bytesperline = 0; + int *width, *height; + + pr_debug("In MVC: mxc_v4l2_s_fmt\n"); + + switch (f->type) { + case V4L2_BUF_TYPE_VIDEO_CAPTURE: + pr_debug(" type=V4L2_BUF_TYPE_VIDEO_CAPTURE\n"); + if (!valid_mode(f->fmt.pix.pixelformat)) { + pr_err("ERROR: v4l2 capture: mxc_v4l2_s_fmt: format " + "not supported\n"); + return -EINVAL; + } + + /* + * Force the capture window resolution to be crop bounds + * for CSI MEM input mode. + */ + if (strcmp(mxc_capture_inputs[cam->current_input].name, + "CSI MEM") == 0) { + f->fmt.pix.width = cam->crop_current.width; + f->fmt.pix.height = cam->crop_current.height; + } + + if (cam->rotation >= IPU_ROTATE_90_RIGHT) { + height = &f->fmt.pix.width; + width = &f->fmt.pix.height; + } else { + width = &f->fmt.pix.width; + height = &f->fmt.pix.height; + } + + /* stride line limitation */ + *width -= *width % 8; + *height -= *height % 8; + + if ((cam->crop_current.width / *width > 8) || + ((cam->crop_current.width / *width == 8) && + (cam->crop_current.width % *width))) { + *width = cam->crop_current.width / 8; + if (*width % 8) + *width += 8 - *width % 8; + pr_err("ERROR: v4l2 capture: width exceeds limit " + "resize to %d.\n", + *width); + } + + if ((cam->crop_current.height / *height > 8) || + ((cam->crop_current.height / *height == 8) && + (cam->crop_current.height % *height))) { + *height = cam->crop_current.height / 8; + if (*height % 8) + *height += 8 - *height % 8; + pr_err("ERROR: v4l2 capture: height exceeds limit " + "resize to %d.\n", + *height); + } + + switch (f->fmt.pix.pixelformat) { + case V4L2_PIX_FMT_RGB565: + size = f->fmt.pix.width * f->fmt.pix.height * 2; + bytesperline = f->fmt.pix.width * 2; + break; + case V4L2_PIX_FMT_BGR24: + size = f->fmt.pix.width * f->fmt.pix.height * 3; + bytesperline = f->fmt.pix.width * 3; + break; + case V4L2_PIX_FMT_RGB24: + size = f->fmt.pix.width * f->fmt.pix.height * 3; + bytesperline = f->fmt.pix.width * 3; + break; + case V4L2_PIX_FMT_BGR32: + size = f->fmt.pix.width * f->fmt.pix.height * 4; + bytesperline = f->fmt.pix.width * 4; + break; + case V4L2_PIX_FMT_RGB32: + size = f->fmt.pix.width * f->fmt.pix.height * 4; + bytesperline = f->fmt.pix.width * 4; + break; + case V4L2_PIX_FMT_YUV422P: + size = f->fmt.pix.width * f->fmt.pix.height * 2; + bytesperline = f->fmt.pix.width; + break; + case V4L2_PIX_FMT_UYVY: + case V4L2_PIX_FMT_YUYV: + size = f->fmt.pix.width * f->fmt.pix.height * 2; + bytesperline = f->fmt.pix.width * 2; + break; + case V4L2_PIX_FMT_YUV420: + size = f->fmt.pix.width * f->fmt.pix.height * 3 / 2; + bytesperline = f->fmt.pix.width; + break; + case V4L2_PIX_FMT_NV12: + size = f->fmt.pix.width * f->fmt.pix.height * 3 / 2; + bytesperline = f->fmt.pix.width; + break; + default: + break; + } + + if (f->fmt.pix.bytesperline < bytesperline) { + f->fmt.pix.bytesperline = bytesperline; + } else { + bytesperline = f->fmt.pix.bytesperline; + } + + if (f->fmt.pix.sizeimage < size) { + f->fmt.pix.sizeimage = size; + } else { + size = f->fmt.pix.sizeimage; + } + + cam->v2f.fmt.pix = f->fmt.pix; + + if (cam->v2f.fmt.pix.priv != 0) { + if (copy_from_user(&cam->offset, + (void *)cam->v2f.fmt.pix.priv, + sizeof(cam->offset))) { + retval = -EFAULT; + break; + } + } + break; + case V4L2_BUF_TYPE_VIDEO_OVERLAY: + pr_debug(" type=V4L2_BUF_TYPE_VIDEO_OVERLAY\n"); + retval = verify_preview(cam, &f->fmt.win); + cam->win = f->fmt.win; + break; + default: + retval = -EINVAL; + } + + pr_debug("End of %s: v2f pix widthxheight %d x %d\n", + __func__, + cam->v2f.fmt.pix.width, cam->v2f.fmt.pix.height); + pr_debug("End of %s: crop_bounds widthxheight %d x %d\n", + __func__, + cam->crop_bounds.width, cam->crop_bounds.height); + pr_debug("End of %s: crop_defrect widthxheight %d x %d\n", + __func__, + cam->crop_defrect.width, cam->crop_defrect.height); + pr_debug("End of %s: crop_current widthxheight %d x %d\n", + __func__, + cam->crop_current.width, cam->crop_current.height); + + return retval; +} + +/*! + * get control param + * + * @param cam structure cam_data * + * + * @param c structure v4l2_control * + * + * @return status 0 success, EINVAL failed + */ +static int mxc_v4l2_g_ctrl(cam_data *cam, struct v4l2_control *c) +{ + int status = 0; + + pr_debug("In MVC:mxc_v4l2_g_ctrl\n"); + + /* probably don't need to store the values that can be retrieved, + * locally, but they are for now. */ + switch (c->id) { + case V4L2_CID_HFLIP: + /* This is handled in the ipu. */ + if (cam->rotation == IPU_ROTATE_HORIZ_FLIP) + c->value = 1; + break; + case V4L2_CID_VFLIP: + /* This is handled in the ipu. */ + if (cam->rotation == IPU_ROTATE_VERT_FLIP) + c->value = 1; + break; + case V4L2_CID_MXC_ROT: + /* This is handled in the ipu. */ + c->value = cam->rotation; + break; + case V4L2_CID_BRIGHTNESS: + c->value = cam->bright; + status = vidioc_int_g_ctrl(cam->sensor, c); + cam->bright = c->value; + break; + case V4L2_CID_HUE: + c->value = cam->hue; + status = vidioc_int_g_ctrl(cam->sensor, c); + cam->hue = c->value; + break; + case V4L2_CID_CONTRAST: + c->value = cam->contrast; + status = vidioc_int_g_ctrl(cam->sensor, c); + cam->contrast = c->value; + break; + case V4L2_CID_SATURATION: + c->value = cam->saturation; + status = vidioc_int_g_ctrl(cam->sensor, c); + cam->saturation = c->value; + break; + case V4L2_CID_RED_BALANCE: + c->value = cam->red; + status = vidioc_int_g_ctrl(cam->sensor, c); + cam->red = c->value; + break; + case V4L2_CID_BLUE_BALANCE: + c->value = cam->blue; + status = vidioc_int_g_ctrl(cam->sensor, c); + cam->blue = c->value; + break; + case V4L2_CID_BLACK_LEVEL: + c->value = cam->ae_mode; + status = vidioc_int_g_ctrl(cam->sensor, c); + cam->ae_mode = c->value; + break; + default: + status = vidioc_int_g_ctrl(cam->sensor, c); + } + + return status; +} + +/*! + * V4L2 - set_control function + * V4L2_CID_PRIVATE_BASE is the extention for IPU preprocessing. + * 0 for normal operation + * 1 for vertical flip + * 2 for horizontal flip + * 3 for horizontal and vertical flip + * 4 for 90 degree rotation + * @param cam structure cam_data * + * + * @param c structure v4l2_control * + * + * @return status 0 success, EINVAL failed + */ +static int mxc_v4l2_s_ctrl(cam_data *cam, struct v4l2_control *c) +{ + int ret = 0; + int tmp_rotation = IPU_ROTATE_NONE; + + pr_debug("In MVC:mxc_v4l2_s_ctrl\n"); + + switch (c->id) { + case V4L2_CID_HFLIP: + /* This is done by the IPU */ + if (c->value == 1) { + if ((cam->rotation != IPU_ROTATE_VERT_FLIP) && + (cam->rotation != IPU_ROTATE_180)) + cam->rotation = IPU_ROTATE_HORIZ_FLIP; + else + cam->rotation = IPU_ROTATE_180; + } else { + if (cam->rotation == IPU_ROTATE_HORIZ_FLIP) + cam->rotation = IPU_ROTATE_NONE; + if (cam->rotation == IPU_ROTATE_180) + cam->rotation = IPU_ROTATE_VERT_FLIP; + } + break; + case V4L2_CID_VFLIP: + /* This is done by the IPU */ + if (c->value == 1) { + if ((cam->rotation != IPU_ROTATE_HORIZ_FLIP) && + (cam->rotation != IPU_ROTATE_180)) + cam->rotation = IPU_ROTATE_VERT_FLIP; + else + cam->rotation = IPU_ROTATE_180; + } else { + if (cam->rotation == IPU_ROTATE_VERT_FLIP) + cam->rotation = IPU_ROTATE_NONE; + if (cam->rotation == IPU_ROTATE_180) + cam->rotation = IPU_ROTATE_HORIZ_FLIP; + } + break; + case V4L2_CID_MXC_ROT: + case V4L2_CID_MXC_VF_ROT: + /* This is done by the IPU */ + switch (c->value) { + case V4L2_MXC_ROTATE_NONE: + tmp_rotation = IPU_ROTATE_NONE; + break; + case V4L2_MXC_ROTATE_VERT_FLIP: + tmp_rotation = IPU_ROTATE_VERT_FLIP; + break; + case V4L2_MXC_ROTATE_HORIZ_FLIP: + tmp_rotation = IPU_ROTATE_HORIZ_FLIP; + break; + case V4L2_MXC_ROTATE_180: + tmp_rotation = IPU_ROTATE_180; + break; + case V4L2_MXC_ROTATE_90_RIGHT: + tmp_rotation = IPU_ROTATE_90_RIGHT; + break; + case V4L2_MXC_ROTATE_90_RIGHT_VFLIP: + tmp_rotation = IPU_ROTATE_90_RIGHT_VFLIP; + break; + case V4L2_MXC_ROTATE_90_RIGHT_HFLIP: + tmp_rotation = IPU_ROTATE_90_RIGHT_HFLIP; + break; + case V4L2_MXC_ROTATE_90_LEFT: + tmp_rotation = IPU_ROTATE_90_LEFT; + break; + default: + ret = -EINVAL; + } + + if (c->id == V4L2_CID_MXC_VF_ROT) + cam->vf_rotation = tmp_rotation; + else + cam->rotation = tmp_rotation; + + break; + case V4L2_CID_HUE: + cam->hue = c->value; + ipu_csi_enable_mclk_if(CSI_MCLK_I2C, cam->csi, true, true); + ret = vidioc_int_s_ctrl(cam->sensor, c); + ipu_csi_enable_mclk_if(CSI_MCLK_I2C, cam->csi, false, false); + break; + case V4L2_CID_CONTRAST: + cam->contrast = c->value; + ipu_csi_enable_mclk_if(CSI_MCLK_I2C, cam->csi, true, true); + ret = vidioc_int_s_ctrl(cam->sensor, c); + ipu_csi_enable_mclk_if(CSI_MCLK_I2C, cam->csi, false, false); + break; + case V4L2_CID_BRIGHTNESS: + cam->bright = c->value; + ipu_csi_enable_mclk_if(CSI_MCLK_I2C, cam->csi, true, true); + ret = vidioc_int_s_ctrl(cam->sensor, c); + ipu_csi_enable_mclk_if(CSI_MCLK_I2C, cam->csi, false, false); + break; + case V4L2_CID_SATURATION: + cam->saturation = c->value; + ipu_csi_enable_mclk_if(CSI_MCLK_I2C, cam->csi, true, true); + ret = vidioc_int_s_ctrl(cam->sensor, c); + ipu_csi_enable_mclk_if(CSI_MCLK_I2C, cam->csi, false, false); + break; + case V4L2_CID_RED_BALANCE: + cam->red = c->value; + ipu_csi_enable_mclk_if(CSI_MCLK_I2C, cam->csi, true, true); + ret = vidioc_int_s_ctrl(cam->sensor, c); + ipu_csi_enable_mclk_if(CSI_MCLK_I2C, cam->csi, false, false); + break; + case V4L2_CID_BLUE_BALANCE: + cam->blue = c->value; + ipu_csi_enable_mclk_if(CSI_MCLK_I2C, cam->csi, true, true); + ret = vidioc_int_s_ctrl(cam->sensor, c); + ipu_csi_enable_mclk_if(CSI_MCLK_I2C, cam->csi, false, false); + break; + case V4L2_CID_EXPOSURE: + cam->ae_mode = c->value; + ipu_csi_enable_mclk_if(CSI_MCLK_I2C, cam->csi, true, true); + ret = vidioc_int_s_ctrl(cam->sensor, c); + ipu_csi_enable_mclk_if(CSI_MCLK_I2C, cam->csi, false, false); + break; + case V4L2_CID_MXC_FLASH: +#ifdef CONFIG_MXC_IPU_V1 + ipu_csi_flash_strobe(true); +#endif + break; + default: + pr_debug(" default case\n"); + ret = -EINVAL; + break; + } + + return ret; +} + +/*! + * V4L2 - mxc_v4l2_s_param function + * Allows setting of capturemode and frame rate. + * + * @param cam structure cam_data * + * @param parm structure v4l2_streamparm * + * + * @return status 0 success, EINVAL failed + */ +static int mxc_v4l2_s_param(cam_data *cam, struct v4l2_streamparm *parm) +{ + struct v4l2_ifparm ifparm; + struct v4l2_format cam_fmt; + struct v4l2_streamparm currentparm; + ipu_csi_signal_cfg_t csi_param; + int err = 0; + + pr_debug("In mxc_v4l2_s_param\n"); + + if (parm->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) { + pr_err(KERN_ERR "mxc_v4l2_s_param invalid type\n"); + return -EINVAL; + } + + /* Stop the viewfinder */ + if (cam->overlay_on == true) { + stop_preview(cam); + } + + currentparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + + /* First check that this device can support the changes requested. */ + err = vidioc_int_g_parm(cam->sensor, ¤tparm); + if (err) { + pr_err("%s: vidioc_int_g_parm returned an error %d\n", + __func__, err); + goto exit; + } + + pr_debug(" Current capabilities are %x\n", + currentparm.parm.capture.capability); + pr_debug(" Current capturemode is %d change to %d\n", + currentparm.parm.capture.capturemode, + parm->parm.capture.capturemode); + pr_debug(" Current framerate is %d change to %d\n", + currentparm.parm.capture.timeperframe.denominator, + parm->parm.capture.timeperframe.denominator); + + /* This will change any camera settings needed. */ + ipu_csi_enable_mclk_if(CSI_MCLK_I2C, cam->csi, true, true); + err = vidioc_int_s_parm(cam->sensor, parm); + ipu_csi_enable_mclk_if(CSI_MCLK_I2C, cam->csi, false, false); + if (err) { + pr_err("%s: vidioc_int_s_parm returned an error %d\n", + __func__, err); + goto exit; + } + + /* If resolution changed, need to re-program the CSI */ + /* Get new values. */ + vidioc_int_g_ifparm(cam->sensor, &ifparm); + + csi_param.data_width = 0; + csi_param.clk_mode = 0; + csi_param.ext_vsync = 0; + csi_param.Vsync_pol = 0; + csi_param.Hsync_pol = 0; + csi_param.pixclk_pol = 0; + csi_param.data_pol = 0; + csi_param.sens_clksrc = 0; + csi_param.pack_tight = 0; + csi_param.force_eof = 0; + csi_param.data_en_pol = 0; + csi_param.data_fmt = 0; + csi_param.csi = 0; + csi_param.mclk = 0; + + /* This may not work on other platforms. Check when adding a new one.*/ + pr_debug(" clock_curr=mclk=%d\n", ifparm.u.bt656.clock_curr); + if (ifparm.u.bt656.clock_curr == 0) { + csi_param.clk_mode = IPU_CSI_CLK_MODE_CCIR656_INTERLACED; + } else { + csi_param.clk_mode = IPU_CSI_CLK_MODE_GATED_CLK; + } + + csi_param.pixclk_pol = ifparm.u.bt656.latch_clk_inv; + + if (ifparm.u.bt656.mode == V4L2_IF_TYPE_BT656_MODE_NOBT_8BIT) { + csi_param.data_width = IPU_CSI_DATA_WIDTH_8; + } else if (ifparm.u.bt656.mode + == V4L2_IF_TYPE_BT656_MODE_NOBT_10BIT) { + csi_param.data_width = IPU_CSI_DATA_WIDTH_10; + } else { + csi_param.data_width = IPU_CSI_DATA_WIDTH_8; + } + + csi_param.Vsync_pol = ifparm.u.bt656.nobt_vs_inv; + csi_param.Hsync_pol = ifparm.u.bt656.nobt_hs_inv; + csi_param.ext_vsync = ifparm.u.bt656.bt_sync_correct; + + /* if the capturemode changed, the size bounds will have changed. */ + cam_fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + vidioc_int_g_fmt_cap(cam->sensor, &cam_fmt); + pr_debug(" g_fmt_cap returns widthxheight of input as %d x %d\n", + cam_fmt.fmt.pix.width, cam_fmt.fmt.pix.height); + + csi_param.data_fmt = cam_fmt.fmt.pix.pixelformat; + + cam->crop_bounds.top = cam->crop_bounds.left = 0; + cam->crop_bounds.width = cam_fmt.fmt.pix.width; + cam->crop_bounds.height = cam_fmt.fmt.pix.height; + + /* + * Set the default current cropped resolution to be the same with + * the cropping boundary(except for tvin module). + */ + if (cam->device_type != 1) { + cam->crop_current.width = cam->crop_bounds.width; + cam->crop_current.height = cam->crop_bounds.height; + } + + /* This essentially loses the data at the left and bottom of the image + * giving a digital zoom image, if crop_current is less than the full + * size of the image. */ + ipu_csi_set_window_size(cam->crop_current.width, + cam->crop_current.height, cam->csi); + ipu_csi_set_window_pos(cam->crop_current.left, + cam->crop_current.top, + cam->csi); + ipu_csi_init_interface(cam->crop_bounds.width, + cam->crop_bounds.height, + cam_fmt.fmt.pix.pixelformat, csi_param); + + +exit: + if (cam->overlay_on == true) + start_preview(cam); + + return err; +} + +/*! + * V4L2 - mxc_v4l2_s_std function + * + * Sets the TV standard to be used. + * + * @param cam structure cam_data * + * @param parm structure v4l2_streamparm * + * + * @return status 0 success, EINVAL failed + */ +static int mxc_v4l2_s_std(cam_data *cam, v4l2_std_id e) +{ + bool change = false; + + if (e != cam->standard.id) { + change = true; + } + + pr_debug("In mxc_v4l2_s_std %Lx\n", e); + if (e == V4L2_STD_PAL) { + pr_debug(" Setting standard to PAL %Lx\n", V4L2_STD_PAL); + cam->standard.id = V4L2_STD_PAL; + video_index = TV_PAL; + cam->crop_current.top = 0; + } else if (e == V4L2_STD_NTSC) { + pr_debug(" Setting standard to NTSC %Lx\n", + V4L2_STD_NTSC); + /* Get rid of the white dot line in NTSC signal input */ + cam->standard.id = V4L2_STD_NTSC; + video_index = TV_NTSC; + cam->crop_current.top = 12; + } else { + cam->standard.id = V4L2_STD_ALL; + video_index = TV_NOT_LOCKED; + cam->crop_current.top = 0; + pr_err("ERROR: unrecognized std! %Lx (PAL=%Lx, NTSC=%Lx\n", + e, V4L2_STD_PAL, V4L2_STD_NTSC); + } + + cam->standard.index = video_index; + strcpy(cam->standard.name, video_fmts[video_index].name); + cam->crop_bounds.width = video_fmts[video_index].raw_width; + cam->crop_bounds.height = video_fmts[video_index].raw_height; + cam->crop_current.width = video_fmts[video_index].active_width; + cam->crop_current.height = video_fmts[video_index].active_height; + cam->crop_current.left = 0; + + return 0; +} + +/*! + * V4L2 - mxc_v4l2_g_std function + * + * Gets the TV standard from the TV input device. + * + * @param cam structure cam_data * + * + * @param e structure v4l2_streamparm * + * + * @return status 0 success, EINVAL failed + */ +static int mxc_v4l2_g_std(cam_data *cam, v4l2_std_id *e) +{ + struct v4l2_format tv_fmt; + + pr_debug("In mxc_v4l2_g_std\n"); + + if (cam->device_type == 1) { + /* Use this function to get what the TV-In device detects the + * format to be. pixelformat is used to return the std value + * since the interface has no vidioc_g_std.*/ + tv_fmt.type = V4L2_BUF_TYPE_PRIVATE; + vidioc_int_g_fmt_cap(cam->sensor, &tv_fmt); + + /* If the TV-in automatically detects the standard, then if it + * changes, the settings need to change. */ + if (cam->standard_autodetect) { + if (cam->standard.id != tv_fmt.fmt.pix.pixelformat) { + pr_debug("MVC: mxc_v4l2_g_std: " + "Changing standard\n"); + mxc_v4l2_s_std(cam, tv_fmt.fmt.pix.pixelformat); + } + } + + *e = tv_fmt.fmt.pix.pixelformat; + } + + return 0; +} + +/*! + * Dequeue one V4L capture buffer + * + * @param cam structure cam_data * + * @param buf structure v4l2_buffer * + * + * @return status 0 success, EINVAL invalid frame number, + * ETIME timeout, ERESTARTSYS interrupted by user + */ +static int mxc_v4l_dqueue(cam_data *cam, struct v4l2_buffer *buf) +{ + int retval = 0; + struct mxc_v4l_frame *frame; + unsigned long lock_flags; + + pr_debug("In MVC:mxc_v4l_dqueue\n"); + + if (!wait_event_interruptible_timeout(cam->enc_queue, + cam->enc_counter != 0, 10 * HZ)) { + pr_err("ERROR: v4l2 capture: mxc_v4l_dqueue timeout " + "enc_counter %x\n", + cam->enc_counter); + return -ETIME; + } else if (signal_pending(current)) { + pr_err("ERROR: v4l2 capture: mxc_v4l_dqueue() " + "interrupt received\n"); + return -ERESTARTSYS; + } + + spin_lock_irqsave(&cam->dqueue_int_lock, lock_flags); + + cam->enc_counter--; + + frame = list_entry(cam->done_q.next, struct mxc_v4l_frame, queue); + list_del(cam->done_q.next); + if (frame->buffer.flags & V4L2_BUF_FLAG_DONE) { + frame->buffer.flags &= ~V4L2_BUF_FLAG_DONE; + } else if (frame->buffer.flags & V4L2_BUF_FLAG_QUEUED) { + pr_err("ERROR: v4l2 capture: VIDIOC_DQBUF: " + "Buffer not filled.\n"); + frame->buffer.flags &= ~V4L2_BUF_FLAG_QUEUED; + retval = -EINVAL; + } else if ((frame->buffer.flags & 0x7) == V4L2_BUF_FLAG_MAPPED) { + pr_err("ERROR: v4l2 capture: VIDIOC_DQBUF: " + "Buffer not queued.\n"); + retval = -EINVAL; + } + + buf->bytesused = cam->v2f.fmt.pix.sizeimage; + buf->index = frame->index; + buf->flags = frame->buffer.flags; + buf->m = cam->frame[frame->index].buffer.m; + buf->timestamp = cam->frame[frame->index].buffer.timestamp; + + spin_unlock_irqrestore(&cam->dqueue_int_lock, lock_flags); + return retval; +} + +/*! + * V4L interface - open function + * + * @param file structure file * + * + * @return status 0 success, ENODEV invalid device instance, + * ENODEV timeout, ERESTARTSYS interrupted by user + */ +static int mxc_v4l_open(struct file *file) +{ + struct v4l2_ifparm ifparm; + struct v4l2_format cam_fmt; + ipu_csi_signal_cfg_t csi_param; + struct video_device *dev = video_devdata(file); + cam_data *cam = video_get_drvdata(dev); + int err = 0; + + pr_debug("\nIn MVC: mxc_v4l_open\n"); + pr_debug(" device name is %s\n", dev->name); + + if (!cam) { + pr_err("ERROR: v4l2 capture: Internal error, " + "cam_data not found!\n"); + return -EBADF; + } + + down(&cam->busy_lock); + err = 0; + if (signal_pending(current)) + goto oops; + + if (cam->open_count++ == 0) { + wait_event_interruptible(cam->power_queue, + cam->low_power == false); + + if (strcmp(mxc_capture_inputs[cam->current_input].name, + "CSI MEM") == 0) { +#if defined(CONFIG_MXC_IPU_CSI_ENC) || defined(CONFIG_MXC_IPU_CSI_ENC_MODULE) + err = csi_enc_select(cam); +#endif + } else if (strcmp(mxc_capture_inputs[cam->current_input].name, + "CSI IC MEM") == 0) { +#if defined(CONFIG_MXC_IPU_PRP_ENC) || defined(CONFIG_MXC_IPU_PRP_ENC_MODULE) + err = prp_enc_select(cam); +#endif + } + + cam->enc_counter = 0; + cam->skip_frame = 0; + INIT_LIST_HEAD(&cam->ready_q); + INIT_LIST_HEAD(&cam->working_q); + INIT_LIST_HEAD(&cam->done_q); + + vidioc_int_g_ifparm(cam->sensor, &ifparm); + + csi_param.sens_clksrc = 0; + + csi_param.clk_mode = 0; + csi_param.data_pol = 0; + csi_param.ext_vsync = 0; + + csi_param.pack_tight = 0; + csi_param.force_eof = 0; + csi_param.data_en_pol = 0; + csi_param.mclk = ifparm.u.bt656.clock_curr; + + csi_param.pixclk_pol = ifparm.u.bt656.latch_clk_inv; + + /* Once we handle multiple inputs this will need to change. */ + csi_param.csi = 0; + + if (ifparm.u.bt656.mode + == V4L2_IF_TYPE_BT656_MODE_NOBT_8BIT) + csi_param.data_width = IPU_CSI_DATA_WIDTH_8; + else if (ifparm.u.bt656.mode + == V4L2_IF_TYPE_BT656_MODE_NOBT_10BIT) + csi_param.data_width = IPU_CSI_DATA_WIDTH_10; + else + csi_param.data_width = IPU_CSI_DATA_WIDTH_8; + + + csi_param.Vsync_pol = ifparm.u.bt656.nobt_vs_inv; + csi_param.Hsync_pol = ifparm.u.bt656.nobt_hs_inv; + + csi_param.csi = cam->csi; + + cam_fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + vidioc_int_g_fmt_cap(cam->sensor, &cam_fmt); + + /* Reset the sizes. Needed to prevent carryover of last + * operation.*/ + cam->crop_bounds.top = cam->crop_bounds.left = 0; + cam->crop_bounds.width = cam_fmt.fmt.pix.width; + cam->crop_bounds.height = cam_fmt.fmt.pix.height; + + /* This also is the max crop size for this device. */ + cam->crop_defrect.top = cam->crop_defrect.left = 0; + cam->crop_defrect.width = cam_fmt.fmt.pix.width; + cam->crop_defrect.height = cam_fmt.fmt.pix.height; + + /* At this point, this is also the current image size. */ + cam->crop_current.top = cam->crop_current.left = 0; + cam->crop_current.width = cam_fmt.fmt.pix.width; + cam->crop_current.height = cam_fmt.fmt.pix.height; + + pr_debug("End of %s: v2f pix widthxheight %d x %d\n", + __func__, + cam->v2f.fmt.pix.width, cam->v2f.fmt.pix.height); + pr_debug("End of %s: crop_bounds widthxheight %d x %d\n", + __func__, + cam->crop_bounds.width, cam->crop_bounds.height); + pr_debug("End of %s: crop_defrect widthxheight %d x %d\n", + __func__, + cam->crop_defrect.width, cam->crop_defrect.height); + pr_debug("End of %s: crop_current widthxheight %d x %d\n", + __func__, + cam->crop_current.width, cam->crop_current.height); + + csi_param.data_fmt = cam_fmt.fmt.pix.pixelformat; + pr_debug("On Open: Input to ipu size is %d x %d\n", + cam_fmt.fmt.pix.width, cam_fmt.fmt.pix.height); + ipu_csi_set_window_size(cam->crop_current.width, + cam->crop_current.width, + cam->csi); + ipu_csi_set_window_pos(cam->crop_current.left, + cam->crop_current.top, + cam->csi); + ipu_csi_init_interface(cam->crop_bounds.width, + cam->crop_bounds.height, + cam_fmt.fmt.pix.pixelformat, + csi_param); + + ipu_csi_enable_mclk_if(CSI_MCLK_I2C, cam->csi, + true, true); + vidioc_int_init(cam->sensor); + + ipu_csi_enable_mclk_if(CSI_MCLK_I2C, cam->csi, + false, false); +} + + file->private_data = dev; + + oops: + up(&cam->busy_lock); + return err; +} + +/*! + * V4L interface - close function + * + * @param file struct file * + * + * @return 0 success + */ +static int mxc_v4l_close(struct file *file) +{ + struct video_device *dev = video_devdata(file); + int err = 0; + cam_data *cam = video_get_drvdata(dev); + + pr_debug("In MVC:mxc_v4l_close\n"); + + if (!cam) { + pr_err("ERROR: v4l2 capture: Internal error, " + "cam_data not found!\n"); + return -EBADF; + } + + /* for the case somebody hit the ctrl C */ + if (cam->overlay_pid == current->pid) { + err = stop_preview(cam); + cam->overlay_on = false; + } + if (cam->capture_pid == current->pid) { + err |= mxc_streamoff(cam); + wake_up_interruptible(&cam->enc_queue); + } + + if (--cam->open_count == 0) { + wait_event_interruptible(cam->power_queue, + cam->low_power == false); + pr_info("mxc_v4l_close: release resource\n"); + + if (strcmp(mxc_capture_inputs[cam->current_input].name, + "CSI MEM") == 0) { +#if defined(CONFIG_MXC_IPU_CSI_ENC) || defined(CONFIG_MXC_IPU_CSI_ENC_MODULE) + err |= csi_enc_deselect(cam); +#endif + } else if (strcmp(mxc_capture_inputs[cam->current_input].name, + "CSI IC MEM") == 0) { +#if defined(CONFIG_MXC_IPU_PRP_ENC) || defined(CONFIG_MXC_IPU_PRP_ENC_MODULE) + err |= prp_enc_deselect(cam); +#endif + } + + mxc_free_frame_buf(cam); + file->private_data = NULL; + + /* capture off */ + wake_up_interruptible(&cam->enc_queue); + mxc_free_frames(cam); + cam->enc_counter++; + } + + return err; +} + +#if defined(CONFIG_MXC_IPU_PRP_ENC) || defined(CONFIG_MXC_IPU_CSI_ENC) || \ + defined(CONFIG_MXC_IPU_PRP_ENC_MODULE) || \ + defined(CONFIG_MXC_IPU_CSI_ENC_MODULE) +/* + * V4L interface - read function + * + * @param file struct file * + * @param read buf char * + * @param count size_t + * @param ppos structure loff_t * + * + * @return bytes read + */ +static ssize_t mxc_v4l_read(struct file *file, char *buf, size_t count, + loff_t *ppos) +{ + int err = 0; + u8 *v_address[2]; + struct video_device *dev = video_devdata(file); + cam_data *cam = video_get_drvdata(dev); + + if (down_interruptible(&cam->busy_lock)) + return -EINTR; + + /* Stop the viewfinder */ + if (cam->overlay_on == true) + stop_preview(cam); + + v_address[0] = dma_alloc_coherent(0, + PAGE_ALIGN(cam->v2f.fmt.pix.sizeimage), + &cam->still_buf[0], + GFP_DMA | GFP_KERNEL); + + v_address[1] = dma_alloc_coherent(0, + PAGE_ALIGN(cam->v2f.fmt.pix.sizeimage), + &cam->still_buf[1], + GFP_DMA | GFP_KERNEL); + + if (!v_address[0] || !v_address[1]) { + err = -ENOBUFS; + goto exit0; + } + + err = prp_still_select(cam); + if (err != 0) { + err = -EIO; + goto exit0; + } + + cam->still_counter = 0; + err = cam->csi_start(cam); + if (err != 0) { + err = -EIO; + goto exit1; + } + + if (!wait_event_interruptible_timeout(cam->still_queue, + cam->still_counter != 0, + 10 * HZ)) { + pr_err("ERROR: v4l2 capture: mxc_v4l_read timeout counter %x\n", + cam->still_counter); + err = -ETIME; + goto exit1; + } + err = copy_to_user(buf, v_address[1], cam->v2f.fmt.pix.sizeimage); + + exit1: + prp_still_deselect(cam); + + exit0: + if (v_address[0] != 0) + dma_free_coherent(0, cam->v2f.fmt.pix.sizeimage, v_address[0], + cam->still_buf[0]); + if (v_address[1] != 0) + dma_free_coherent(0, cam->v2f.fmt.pix.sizeimage, v_address[1], + cam->still_buf[1]); + + cam->still_buf[0] = cam->still_buf[1] = 0; + + if (cam->overlay_on == true) { + start_preview(cam); + } + + up(&cam->busy_lock); + if (err < 0) + return err; + + return cam->v2f.fmt.pix.sizeimage - err; +} +#endif + +/*! + * V4L interface - ioctl function + * + * @param file struct file* + * + * @param ioctlnr unsigned int + * + * @param arg void* + * + * @return 0 success, ENODEV for invalid device instance, + * -1 for other errors. + */ +static long mxc_v4l_do_ioctl(struct file *file, + unsigned int ioctlnr, void *arg) +{ + struct video_device *dev = video_devdata(file); + cam_data *cam = video_get_drvdata(dev); + int retval = 0; + unsigned long lock_flags; + + pr_debug("In MVC: mxc_v4l_do_ioctl %x\n", ioctlnr); + wait_event_interruptible(cam->power_queue, cam->low_power == false); + /* make this _really_ smp-safe */ + if (down_interruptible(&cam->busy_lock)) + return -EBUSY; + + switch (ioctlnr) { + /*! + * V4l2 VIDIOC_QUERYCAP ioctl + */ + case VIDIOC_QUERYCAP: { + struct v4l2_capability *cap = arg; + pr_debug(" case VIDIOC_QUERYCAP\n"); + strcpy(cap->driver, "mxc_v4l2"); + cap->version = KERNEL_VERSION(0, 1, 11); + cap->capabilities = V4L2_CAP_VIDEO_CAPTURE | + V4L2_CAP_VIDEO_OVERLAY | + V4L2_CAP_STREAMING | + V4L2_CAP_READWRITE; + cap->card[0] = '\0'; + cap->bus_info[0] = '\0'; + break; + } + + /*! + * V4l2 VIDIOC_G_FMT ioctl + */ + case VIDIOC_G_FMT: { + struct v4l2_format *gf = arg; + pr_debug(" case VIDIOC_G_FMT\n"); + retval = mxc_v4l2_g_fmt(cam, gf); + break; + } + + /*! + * V4l2 VIDIOC_S_FMT ioctl + */ + case VIDIOC_S_FMT: { + struct v4l2_format *sf = arg; + pr_debug(" case VIDIOC_S_FMT\n"); + retval = mxc_v4l2_s_fmt(cam, sf); + break; + } + + /*! + * V4l2 VIDIOC_REQBUFS ioctl + */ + case VIDIOC_REQBUFS: { + struct v4l2_requestbuffers *req = arg; + pr_debug(" case VIDIOC_REQBUFS\n"); + + if (req->count > FRAME_NUM) { + pr_err("ERROR: v4l2 capture: VIDIOC_REQBUFS: " + "not enough buffers\n"); + req->count = FRAME_NUM; + } + + if ((req->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) || + (req->memory != V4L2_MEMORY_MMAP)) { + pr_err("ERROR: v4l2 capture: VIDIOC_REQBUFS: " + "wrong buffer type\n"); + retval = -EINVAL; + break; + } + + mxc_streamoff(cam); + mxc_free_frame_buf(cam); + cam->enc_counter = 0; + cam->skip_frame = 0; + INIT_LIST_HEAD(&cam->ready_q); + INIT_LIST_HEAD(&cam->working_q); + INIT_LIST_HEAD(&cam->done_q); + + retval = mxc_allocate_frame_buf(cam, req->count); + break; + } + + /*! + * V4l2 VIDIOC_QUERYBUF ioctl + */ + case VIDIOC_QUERYBUF: { + struct v4l2_buffer *buf = arg; + int index = buf->index; + pr_debug(" case VIDIOC_QUERYBUF\n"); + + if (buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) { + pr_err("ERROR: v4l2 capture: " + "VIDIOC_QUERYBUFS: " + "wrong buffer type\n"); + retval = -EINVAL; + break; + } + + memset(buf, 0, sizeof(buf)); + buf->index = index; + + down(&cam->param_lock); + retval = mxc_v4l2_buffer_status(cam, buf); + up(&cam->param_lock); + break; + } + + /*! + * V4l2 VIDIOC_QBUF ioctl + */ + case VIDIOC_QBUF: { + struct v4l2_buffer *buf = arg; + int index = buf->index; + pr_debug(" case VIDIOC_QBUF\n"); + + spin_lock_irqsave(&cam->queue_int_lock, lock_flags); + cam->frame[index].buffer.m.offset = buf->m.offset; + if ((cam->frame[index].buffer.flags & 0x7) == + V4L2_BUF_FLAG_MAPPED) { + cam->frame[index].buffer.flags |= + V4L2_BUF_FLAG_QUEUED; + if (strcmp(mxc_capture_inputs[cam->current_input].name, + "CSI IC MEM") == 0) { + if (cam->skip_frame > 0) { + list_add_tail(&cam->frame[index].queue, + &cam->working_q); + + retval = + cam->enc_update_eba(cam-> + frame[index]. + buffer.m.offset, + &cam-> + ping_pong_csi); + + cam->skip_frame = 0; + } else + list_add_tail(&cam->frame[index].queue, + &cam->ready_q); + } else if (strcmp( + mxc_capture_inputs[cam->current_input]. + name, "CSI MEM") == 0) { + list_add_tail(&cam->frame[index].queue, + &cam->ready_q); + } + } else if (cam->frame[index].buffer. + flags & V4L2_BUF_FLAG_QUEUED) { + pr_err("ERROR: v4l2 capture: VIDIOC_QBUF: " + "buffer already queued\n"); + retval = -EINVAL; + } else if (cam->frame[index].buffer. + flags & V4L2_BUF_FLAG_DONE) { + pr_err("ERROR: v4l2 capture: VIDIOC_QBUF: " + "overwrite done buffer.\n"); + cam->frame[index].buffer.flags &= + ~V4L2_BUF_FLAG_DONE; + cam->frame[index].buffer.flags |= + V4L2_BUF_FLAG_QUEUED; + retval = -EINVAL; + } + + buf->flags = cam->frame[index].buffer.flags; + spin_unlock_irqrestore(&cam->queue_int_lock, lock_flags); + break; + } + + /*! + * V4l2 VIDIOC_DQBUF ioctl + */ + case VIDIOC_DQBUF: { + struct v4l2_buffer *buf = arg; + pr_debug(" case VIDIOC_DQBUF\n"); + + if ((cam->enc_counter == 0) && + (file->f_flags & O_NONBLOCK)) { + retval = -EAGAIN; + break; + } + + retval = mxc_v4l_dqueue(cam, buf); + + break; + } + + /*! + * V4l2 VIDIOC_STREAMON ioctl + */ + case VIDIOC_STREAMON: { + pr_debug(" case VIDIOC_STREAMON\n"); + retval = mxc_streamon(cam); + break; + } + + /*! + * V4l2 VIDIOC_STREAMOFF ioctl + */ + case VIDIOC_STREAMOFF: { + pr_debug(" case VIDIOC_STREAMOFF\n"); + retval = mxc_streamoff(cam); + break; + } + + /*! + * V4l2 VIDIOC_G_CTRL ioctl + */ + case VIDIOC_G_CTRL: { + pr_debug(" case VIDIOC_G_CTRL\n"); + retval = mxc_v4l2_g_ctrl(cam, arg); + break; + } + + /*! + * V4l2 VIDIOC_S_CTRL ioctl + */ + case VIDIOC_S_CTRL: { + pr_debug(" case VIDIOC_S_CTRL\n"); + retval = mxc_v4l2_s_ctrl(cam, arg); + break; + } + + /*! + * V4l2 VIDIOC_CROPCAP ioctl + */ + case VIDIOC_CROPCAP: { + struct v4l2_cropcap *cap = arg; + pr_debug(" case VIDIOC_CROPCAP\n"); + if (cap->type != V4L2_BUF_TYPE_VIDEO_CAPTURE && + cap->type != V4L2_BUF_TYPE_VIDEO_OVERLAY) { + retval = -EINVAL; + break; + } + cap->bounds = cam->crop_bounds; + cap->defrect = cam->crop_defrect; + break; + } + + /*! + * V4l2 VIDIOC_G_CROP ioctl + */ + case VIDIOC_G_CROP: { + struct v4l2_crop *crop = arg; + pr_debug(" case VIDIOC_G_CROP\n"); + + if (crop->type != V4L2_BUF_TYPE_VIDEO_CAPTURE && + crop->type != V4L2_BUF_TYPE_VIDEO_OVERLAY) { + retval = -EINVAL; + break; + } + crop->c = cam->crop_current; + break; + } + + /*! + * V4l2 VIDIOC_S_CROP ioctl + */ + case VIDIOC_S_CROP: { + struct v4l2_crop *crop = arg; + struct v4l2_rect *b = &cam->crop_bounds; + pr_debug(" case VIDIOC_S_CROP\n"); + + if (crop->type != V4L2_BUF_TYPE_VIDEO_CAPTURE && + crop->type != V4L2_BUF_TYPE_VIDEO_OVERLAY) { + retval = -EINVAL; + break; + } + + crop->c.top = (crop->c.top < b->top) ? b->top + : crop->c.top; + if (crop->c.top > b->top + b->height) + crop->c.top = b->top + b->height - 1; + if (crop->c.height > b->top + b->height - crop->c.top) + crop->c.height = + b->top + b->height - crop->c.top; + + crop->c.left = (crop->c.left < b->left) ? b->left + : crop->c.left; + if (crop->c.left > b->left + b->width) + crop->c.left = b->left + b->width - 1; + if (crop->c.width > b->left - crop->c.left + b->width) + crop->c.width = + b->left - crop->c.left + b->width; + + crop->c.width -= crop->c.width % 8; + crop->c.left -= crop->c.left % 4; + cam->crop_current = crop->c; + + pr_debug(" Cropping Input to ipu size %d x %d\n", + cam->crop_current.width, + cam->crop_current.height); + ipu_csi_set_window_size(cam->crop_current.width, + cam->crop_current.height, + cam->csi); + ipu_csi_set_window_pos(cam->crop_current.left, + cam->crop_current.top, + cam->csi); + break; + } + + /*! + * V4l2 VIDIOC_OVERLAY ioctl + */ + case VIDIOC_OVERLAY: { + int *on = arg; + pr_debug(" VIDIOC_OVERLAY on=%d\n", *on); + if (*on) { + cam->overlay_on = true; + cam->overlay_pid = current->pid; + retval = start_preview(cam); + } + if (!*on) { + retval = stop_preview(cam); + cam->overlay_on = false; + } + break; + } + + /*! + * V4l2 VIDIOC_G_FBUF ioctl + */ + case VIDIOC_G_FBUF: { + struct v4l2_framebuffer *fb = arg; + pr_debug(" case VIDIOC_G_FBUF\n"); + *fb = cam->v4l2_fb; + fb->capability = V4L2_FBUF_CAP_EXTERNOVERLAY; + break; + } + + /*! + * V4l2 VIDIOC_S_FBUF ioctl + */ + case VIDIOC_S_FBUF: { + struct v4l2_framebuffer *fb = arg; + pr_debug(" case VIDIOC_S_FBUF\n"); + cam->v4l2_fb = *fb; + break; + } + + case VIDIOC_G_PARM: { + struct v4l2_streamparm *parm = arg; + pr_debug(" case VIDIOC_G_PARM\n"); + vidioc_int_g_parm(cam->sensor, parm); + break; + } + + case VIDIOC_S_PARM: { + struct v4l2_streamparm *parm = arg; + pr_debug(" case VIDIOC_S_PARM\n"); + retval = mxc_v4l2_s_param(cam, parm); + break; + } + + /* linux v4l2 bug, kernel c0485619 user c0405619 */ + case VIDIOC_ENUMSTD: { + struct v4l2_standard *e = arg; + pr_debug(" case VIDIOC_ENUMSTD\n"); + *e = cam->standard; + break; + } + + case VIDIOC_G_STD: { + v4l2_std_id *e = arg; + pr_debug(" case VIDIOC_G_STD\n"); + retval = mxc_v4l2_g_std(cam, e); + break; + } + + case VIDIOC_S_STD: { + v4l2_std_id *e = arg; + pr_debug(" case VIDIOC_S_STD\n"); + retval = mxc_v4l2_s_std(cam, *e); + + break; + } + + case VIDIOC_ENUMOUTPUT: { + struct v4l2_output *output = arg; + pr_debug(" case VIDIOC_ENUMOUTPUT\n"); + if (output->index >= MXC_V4L2_CAPTURE_NUM_OUTPUTS) { + retval = -EINVAL; + break; + } + *output = mxc_capture_outputs[output->index]; + + break; + } + case VIDIOC_G_OUTPUT: { + int *p_output_num = arg; + pr_debug(" case VIDIOC_G_OUTPUT\n"); + *p_output_num = cam->output; + break; + } + + case VIDIOC_S_OUTPUT: { + int *p_output_num = arg; + pr_debug(" case VIDIOC_S_OUTPUT\n"); + if (*p_output_num >= MXC_V4L2_CAPTURE_NUM_OUTPUTS) { + retval = -EINVAL; + break; + } + cam->output = *p_output_num; + break; + } + + case VIDIOC_ENUMINPUT: { + struct v4l2_input *input = arg; + pr_debug(" case VIDIOC_ENUMINPUT\n"); + if (input->index >= MXC_V4L2_CAPTURE_NUM_INPUTS) { + retval = -EINVAL; + break; + } + *input = mxc_capture_inputs[input->index]; + break; + } + + case VIDIOC_G_INPUT: { + int *index = arg; + pr_debug(" case VIDIOC_G_INPUT\n"); + *index = cam->current_input; + break; + } + + case VIDIOC_S_INPUT: { + int *index = arg; + pr_debug(" case VIDIOC_S_INPUT\n"); + if (*index >= MXC_V4L2_CAPTURE_NUM_INPUTS) { + retval = -EINVAL; + break; + } + + if (*index == cam->current_input) + break; + + if ((mxc_capture_inputs[cam->current_input].status & + V4L2_IN_ST_NO_POWER) == 0) { + retval = mxc_streamoff(cam); + if (retval) + break; + mxc_capture_inputs[cam->current_input].status |= + V4L2_IN_ST_NO_POWER; + } + + if (strcmp(mxc_capture_inputs[*index].name, "CSI MEM") == 0) { +#if defined(CONFIG_MXC_IPU_CSI_ENC) || defined(CONFIG_MXC_IPU_CSI_ENC_MODULE) + retval = csi_enc_select(cam); + if (retval) + break; +#endif + } else if (strcmp(mxc_capture_inputs[*index].name, + "CSI IC MEM") == 0) { +#if defined(CONFIG_MXC_IPU_PRP_ENC) || defined(CONFIG_MXC_IPU_PRP_ENC_MODULE) + retval = prp_enc_select(cam); + if (retval) + break; +#endif + } + + mxc_capture_inputs[*index].status &= ~V4L2_IN_ST_NO_POWER; + cam->current_input = *index; + break; + } + + case VIDIOC_ENUM_FMT: + case VIDIOC_TRY_FMT: + case VIDIOC_QUERYCTRL: + case VIDIOC_G_TUNER: + case VIDIOC_S_TUNER: + case VIDIOC_G_FREQUENCY: + case VIDIOC_S_FREQUENCY: + default: + pr_debug(" case default or not supported\n"); + retval = -EINVAL; + break; + } + + up(&cam->busy_lock); + return retval; +} + +/* + * V4L interface - ioctl function + * + * @return None + */ +static long mxc_v4l_ioctl(struct file *file, unsigned int cmd, + unsigned long arg) +{ + pr_debug("In MVC:mxc_v4l_ioctl\n"); + return video_usercopy(file, cmd, arg, mxc_v4l_do_ioctl); +} + +/*! + * V4L interface - mmap function + * + * @param file structure file * + * + * @param vma structure vm_area_struct * + * + * @return status 0 Success, EINTR busy lock error, ENOBUFS remap_page error + */ +static int mxc_mmap(struct file *file, struct vm_area_struct *vma) +{ + struct video_device *dev = video_devdata(file); + unsigned long size; + int res = 0; + cam_data *cam = video_get_drvdata(dev); + + pr_debug("In MVC:mxc_mmap\n"); + pr_debug(" pgoff=0x%lx, start=0x%lx, end=0x%lx\n", + vma->vm_pgoff, vma->vm_start, vma->vm_end); + + /* make this _really_ smp-safe */ + if (down_interruptible(&cam->busy_lock)) + return -EINTR; + + size = vma->vm_end - vma->vm_start; + vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); + + if (remap_pfn_range(vma, vma->vm_start, + vma->vm_pgoff, size, vma->vm_page_prot)) { + pr_err("ERROR: v4l2 capture: mxc_mmap: " + "remap_pfn_range failed\n"); + res = -ENOBUFS; + goto mxc_mmap_exit; + } + + vma->vm_flags &= ~VM_IO; /* using shared anonymous pages */ + + mxc_mmap_exit: + up(&cam->busy_lock); + return res; +} + +/*! + * V4L interface - poll function + * + * @param file structure file * + * + * @param wait structure poll_table_struct * + * + * @return status POLLIN | POLLRDNORM + */ +static unsigned int mxc_poll(struct file *file, struct poll_table_struct *wait) +{ + struct video_device *dev = video_devdata(file); + cam_data *cam = video_get_drvdata(dev); + wait_queue_head_t *queue = NULL; + int res = POLLIN | POLLRDNORM; + + pr_debug("In MVC:mxc_poll\n"); + + if (down_interruptible(&cam->busy_lock)) + return -EINTR; + + queue = &cam->enc_queue; + poll_wait(file, queue, wait); + + up(&cam->busy_lock); + + return res; +} + +/*! + * This structure defines the functions to be called in this driver. + */ +static struct v4l2_file_operations mxc_v4l_fops = { + .owner = THIS_MODULE, + .open = mxc_v4l_open, + .release = mxc_v4l_close, + .read = mxc_v4l_read, + .ioctl = mxc_v4l_ioctl, + .mmap = mxc_mmap, + .poll = mxc_poll, +}; + +static struct video_device mxc_v4l_template = { + .name = "Mxc Camera", + .fops = &mxc_v4l_fops, + .release = video_device_release, +}; + +/*! + * This function can be used to release any platform data on closing. + */ +static void camera_platform_release(struct device *device) +{ +} + +/*! + * Camera V4l2 callback function. + * + * @param mask u32 + * + * @param dev void device structure + * + * @return status + */ +static void camera_callback(u32 mask, void *dev) +{ + struct mxc_v4l_frame *done_frame; + struct mxc_v4l_frame *ready_frame; + struct timeval cur_time; + + cam_data *cam = (cam_data *) dev; + if (cam == NULL) + return; + + pr_debug("In MVC:camera_callback\n"); + + if (strcmp(mxc_capture_inputs[cam->current_input].name, "CSI IC MEM") + == 0) { + if (list_empty(&cam->working_q)) { + pr_err("ERROR: v4l2 capture: camera_callback: " + "working queue empty\n"); + return; + } + do_gettimeofday(&cur_time); + + done_frame = list_entry(cam->working_q.next, + struct mxc_v4l_frame, + queue); + + /* + * Set the current time to done frame buffer's timestamp. + * Users can use this information to judge the frame's usage. + */ + done_frame->buffer.timestamp = cur_time; + if (done_frame->buffer.flags & V4L2_BUF_FLAG_QUEUED) { + done_frame->buffer.flags |= V4L2_BUF_FLAG_DONE; + done_frame->buffer.flags &= ~V4L2_BUF_FLAG_QUEUED; + + /* Added to the done queue */ + list_del(cam->working_q.next); + list_add_tail(&done_frame->queue, &cam->done_q); + + /* Wake up the queue */ + cam->enc_counter++; + wake_up_interruptible(&cam->enc_queue); + + if (list_empty(&cam->ready_q)) { + cam->skip_frame++; + } else { + ready_frame = list_entry(cam->ready_q.next, + struct mxc_v4l_frame, + queue); + + if (cam->enc_update_eba( + ready_frame->buffer.m.offset, + &cam->ping_pong_csi) == 0) { + list_del(cam->ready_q.next); + list_add_tail(&ready_frame->queue, + &cam->working_q); + } else + return; + } + } else { + pr_err("ERROR: v4l2 capture: camera_callback: " + "buffer not queued\n"); + } + } else if (strcmp(mxc_capture_inputs[cam->current_input].name, + "CSI MEM") == 0) { + if (!list_empty(&cam->working_q)) { + do_gettimeofday(&cur_time); + + done_frame = list_entry(cam->working_q.next, + struct mxc_v4l_frame, + queue); + + /* + * Set the current time to done frame buffer's + * timestamp. Users can use this information to judge + * the frame's usage. + */ + done_frame->buffer.timestamp = cur_time; + + if (done_frame->buffer.flags & V4L2_BUF_FLAG_QUEUED) { + done_frame->buffer.flags |= + V4L2_BUF_FLAG_DONE; + done_frame->buffer.flags &= + ~V4L2_BUF_FLAG_QUEUED; + + /* Added to the done queue */ + list_del(cam->working_q.next); + list_add_tail(&done_frame->queue, &cam->done_q); + + /* Wake up the queue */ + cam->enc_counter++; + wake_up_interruptible(&cam->enc_queue); + } else { + pr_err("ERROR: v4l2 capture: camera_callback: " + "buffer not queued\n"); + } + } + + if (!list_empty(&cam->ready_q)) { + ready_frame = list_entry(cam->ready_q.next, + struct mxc_v4l_frame, + queue); + if (cam->enc_update_eba(ready_frame->buffer.m.offset, + &cam->ping_pong_csi) == 0) { + list_del(cam->ready_q.next); + list_add_tail(&ready_frame->queue, + &cam->working_q); + } else + return; + } else { + if (cam->enc_update_eba( + cam->dummy_frame.buffer.m.offset, + &cam->ping_pong_csi) == -EACCES) + return; + } + } + + return; +} + +/*! + * initialize cam_data structure + * + * @param cam structure cam_data * + * + * @return status 0 Success + */ +static void init_camera_struct(cam_data *cam, struct platform_device *pdev) +{ + pr_debug("In MVC: init_camera_struct\n"); + + /* Default everything to 0 */ + memset(cam, 0, sizeof(cam_data)); + + init_MUTEX(&cam->param_lock); + init_MUTEX(&cam->busy_lock); + + cam->video_dev = video_device_alloc(); + if (cam->video_dev == NULL) + return; + + *(cam->video_dev) = mxc_v4l_template; + + video_set_drvdata(cam->video_dev, cam); + dev_set_drvdata(&pdev->dev, (void *)cam); + cam->video_dev->minor = -1; + + init_waitqueue_head(&cam->enc_queue); + init_waitqueue_head(&cam->still_queue); + + /* setup cropping */ + cam->crop_bounds.left = 0; + cam->crop_bounds.width = 640; + cam->crop_bounds.top = 0; + cam->crop_bounds.height = 480; + cam->crop_current = cam->crop_defrect = cam->crop_bounds; + ipu_csi_set_window_size(cam->crop_current.width, + cam->crop_current.height, cam->csi); + ipu_csi_set_window_pos(cam->crop_current.left, + cam->crop_current.top, cam->csi); + cam->streamparm.parm.capture.capturemode = 0; + + cam->standard.index = 0; + cam->standard.id = V4L2_STD_UNKNOWN; + cam->standard.frameperiod.denominator = 30; + cam->standard.frameperiod.numerator = 1; + cam->standard.framelines = 480; + cam->standard_autodetect = true; + cam->streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + cam->streamparm.parm.capture.timeperframe = cam->standard.frameperiod; + cam->streamparm.parm.capture.capability = V4L2_CAP_TIMEPERFRAME; + cam->overlay_on = false; + cam->capture_on = false; + cam->skip_frame = 0; + cam->v4l2_fb.flags = V4L2_FBUF_FLAG_OVERLAY; + + cam->v2f.fmt.pix.sizeimage = 352 * 288 * 3 / 2; + cam->v2f.fmt.pix.bytesperline = 288 * 3 / 2; + cam->v2f.fmt.pix.width = 288; + cam->v2f.fmt.pix.height = 352; + cam->v2f.fmt.pix.pixelformat = V4L2_PIX_FMT_YUV420; + cam->win.w.width = 160; + cam->win.w.height = 160; + cam->win.w.left = 0; + cam->win.w.top = 0; + + cam->csi = 0; /* Need to determine how to set this correctly with + * multiple video input devices. */ + + cam->enc_callback = camera_callback; + init_waitqueue_head(&cam->power_queue); + spin_lock_init(&cam->queue_int_lock); + spin_lock_init(&cam->dqueue_int_lock); +} + +/*! + * camera_power function + * Turns Sensor power On/Off + * + * @param cam cam data struct + * @param cameraOn true to turn camera on, false to turn off power. + * + * @return status + */ +static u8 camera_power(cam_data *cam, bool cameraOn) +{ + pr_debug("In MVC:camera_power on=%d\n", cameraOn); + + if (cameraOn == true) { + ipu_csi_enable_mclk_if(CSI_MCLK_I2C, cam->csi, true, true); + vidioc_int_s_power(cam->sensor, 1); + } else { + ipu_csi_enable_mclk_if(CSI_MCLK_I2C, cam->csi, false, false); + vidioc_int_s_power(cam->sensor, 0); + } + return 0; +} + +/*! + * This function is called to probe the devices if registered. + * + * @param pdev the device structure used to give information on which device + * to probe + * + * @return The function returns 0 on success and -1 on failure. + */ +static int mxc_v4l2_probe(struct platform_device *pdev) +{ + /* Create g_cam and initialize it. */ + g_cam = kmalloc(sizeof(cam_data), GFP_KERNEL); + if (g_cam == NULL) { + pr_err("ERROR: v4l2 capture: failed to register camera\n"); + return -1; + } + init_camera_struct(g_cam, pdev); + pdev->dev.release = camera_platform_release; + + /* Set up the v4l2 device and register it*/ + mxc_v4l2_int_device.priv = g_cam; + /* This function contains a bug that won't let this be rmmod'd. */ + v4l2_int_device_register(&mxc_v4l2_int_device); + + /* register v4l video device */ + if (video_register_device(g_cam->video_dev, VFL_TYPE_GRABBER, video_nr) + == -1) { + kfree(g_cam); + g_cam = NULL; + pr_err("ERROR: v4l2 capture: video_register_device failed\n"); + return -1; + } + pr_debug(" Video device registered: %s #%d\n", + g_cam->video_dev->name, g_cam->video_dev->minor); + + return 0; +} + +/*! + * This function is called to remove the devices when device unregistered. + * + * @param pdev the device structure used to give information on which device + * to remove + * + * @return The function returns 0 on success and -1 on failure. + */ +static int mxc_v4l2_remove(struct platform_device *pdev) +{ + + if (g_cam->open_count) { + pr_err("ERROR: v4l2 capture:camera open " + "-- setting ops to NULL\n"); + return -EBUSY; + } else { + pr_info("V4L2 freeing image input device\n"); + v4l2_int_device_unregister(&mxc_v4l2_int_device); + video_unregister_device(g_cam->video_dev); + + mxc_free_frame_buf(g_cam); + kfree(g_cam); + g_cam = NULL; + } + + pr_info("V4L2 unregistering video\n"); + return 0; +} + +/*! + * This function is called to put the sensor in a low power state. + * Refer to the document driver-model/driver.txt in the kernel source tree + * for more information. + * + * @param pdev the device structure used to give information on which I2C + * to suspend + * @param state the power state the device is entering + * + * @return The function returns 0 on success and -1 on failure. + */ +static int mxc_v4l2_suspend(struct platform_device *pdev, pm_message_t state) +{ + cam_data *cam = platform_get_drvdata(pdev); + + pr_debug("In MVC:mxc_v4l2_suspend\n"); + + if (cam == NULL) { + return -1; + } + + cam->low_power = true; + + if (cam->overlay_on == true) + stop_preview(cam); + if ((cam->capture_on == true) && cam->enc_disable) { + cam->enc_disable(cam); + } + camera_power(cam, false); + + return 0; +} + +/*! + * This function is called to bring the sensor back from a low power state. + * Refer to the document driver-model/driver.txt in the kernel source tree + * for more information. + * + * @param pdev the device structure + * + * @return The function returns 0 on success and -1 on failure + */ +static int mxc_v4l2_resume(struct platform_device *pdev) +{ + cam_data *cam = platform_get_drvdata(pdev); + + pr_debug("In MVC:mxc_v4l2_resume\n"); + + if (cam == NULL) { + return -1; + } + + cam->low_power = false; + wake_up_interruptible(&cam->power_queue); + camera_power(cam, true); + + if (cam->overlay_on == true) + start_preview(cam); + if (cam->capture_on == true) + mxc_streamon(cam); + + return 0; +} + +/*! + * This structure contains pointers to the power management callback functions. + */ +static struct platform_driver mxc_v4l2_driver = { + .driver = { + .name = "mxc_v4l2_capture", + }, + .probe = mxc_v4l2_probe, + .remove = mxc_v4l2_remove, + .suspend = mxc_v4l2_suspend, + .resume = mxc_v4l2_resume, + .shutdown = NULL, +}; + +/*! + * Initializes the camera driver. + */ +static int mxc_v4l2_master_attach(struct v4l2_int_device *slave) +{ + cam_data *cam = slave->u.slave->master->priv; + struct v4l2_format cam_fmt; + + pr_debug("In MVC: mxc_v4l2_master_attach\n"); + pr_debug(" slave.name = %s\n", slave->name); + pr_debug(" master.name = %s\n", slave->u.slave->master->name); + + cam->sensor = slave; + if (slave == NULL) { + pr_err("ERROR: v4l2 capture: slave parameter not valid.\n"); + return -1; + } + + ipu_csi_enable_mclk_if(CSI_MCLK_I2C, cam->csi, true, true); + vidioc_int_s_power(cam->sensor, 1); + vidioc_int_dev_init(slave); + ipu_csi_enable_mclk_if(CSI_MCLK_I2C, cam->csi, false, false); + cam_fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + vidioc_int_g_fmt_cap(cam->sensor, &cam_fmt); + + /* Used to detect TV in (type 1) vs. camera (type 0)*/ + cam->device_type = cam_fmt.fmt.pix.priv; + + /* Set the input size to the ipu for this device */ + cam->crop_bounds.top = cam->crop_bounds.left = 0; + cam->crop_bounds.width = cam_fmt.fmt.pix.width; + cam->crop_bounds.height = cam_fmt.fmt.pix.height; + + /* This also is the max crop size for this device. */ + cam->crop_defrect.top = cam->crop_defrect.left = 0; + cam->crop_defrect.width = cam_fmt.fmt.pix.width; + cam->crop_defrect.height = cam_fmt.fmt.pix.height; + + /* At this point, this is also the current image size. */ + cam->crop_current.top = cam->crop_current.left = 0; + cam->crop_current.width = cam_fmt.fmt.pix.width; + cam->crop_current.height = cam_fmt.fmt.pix.height; + + pr_debug("End of %s: v2f pix widthxheight %d x %d\n", + __func__, + cam->v2f.fmt.pix.width, cam->v2f.fmt.pix.height); + pr_debug("End of %s: crop_bounds widthxheight %d x %d\n", + __func__, + cam->crop_bounds.width, cam->crop_bounds.height); + pr_debug("End of %s: crop_defrect widthxheight %d x %d\n", + __func__, + cam->crop_defrect.width, cam->crop_defrect.height); + pr_debug("End of %s: crop_current widthxheight %d x %d\n", + __func__, + cam->crop_current.width, cam->crop_current.height); + + return 0; +} + +/*! + * Disconnects the camera driver. + */ +static void mxc_v4l2_master_detach(struct v4l2_int_device *slave) +{ + pr_debug("In MVC:mxc_v4l2_master_detach\n"); + vidioc_int_dev_exit(slave); +} + +/*! + * Entry point for the V4L2 + * + * @return Error code indicating success or failure + */ +static __init int camera_init(void) +{ + u8 err = 0; + + pr_debug("In MVC:camera_init\n"); + + /* Register the device driver structure. */ + err = platform_driver_register(&mxc_v4l2_driver); + if (err != 0) { + pr_err("ERROR: v4l2 capture:camera_init: " + "platform_driver_register failed.\n"); + return err; + } + + return err; +} + +/*! + * Exit and cleanup for the V4L2 + */ +static void __exit camera_exit(void) +{ + pr_debug("In MVC: camera_exit\n"); + + platform_driver_unregister(&mxc_v4l2_driver); +} + +module_init(camera_init); +module_exit(camera_exit); + +module_param(video_nr, int, 0444); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("V4L2 capture driver for Mxc based cameras"); +MODULE_LICENSE("GPL"); +MODULE_SUPPORTED_DEVICE("video"); diff --git a/drivers/media/video/mxc/capture/mxc_v4l2_capture.h b/drivers/media/video/mxc/capture/mxc_v4l2_capture.h new file mode 100644 index 000000000000..50f695102095 --- /dev/null +++ b/drivers/media/video/mxc/capture/mxc_v4l2_capture.h @@ -0,0 +1,206 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @defgroup MXC_V4L2_CAPTURE MXC V4L2 Video Capture Driver + */ +/*! + * @file mxc_v4l2_capture.h + * + * @brief mxc V4L2 capture device API Header file + * + * It include all the defines for frame operations, also three structure defines + * use case ops structure, common v4l2 driver structure and frame structure. + * + * @ingroup MXC_V4L2_CAPTURE + */ +#ifndef __MXC_V4L2_CAPTURE_H__ +#define __MXC_V4L2_CAPTURE_H__ + +#include +#include +#include +#include +#include + +#include + +#define FRAME_NUM 3 + +/*! + * v4l2 frame structure. + */ +struct mxc_v4l_frame { + u32 paddress; + void *vaddress; + int count; + int width; + int height; + + struct v4l2_buffer buffer; + struct list_head queue; + int index; +}; + +/* Only for old version. Will go away soon. */ +typedef struct { + u8 clk_mode; + u8 ext_vsync; + u8 Vsync_pol; + u8 Hsync_pol; + u8 pixclk_pol; + u8 data_pol; + u8 data_width; + u8 pack_tight; + u8 force_eof; + u8 data_en_pol; + u16 width; + u16 height; + u32 pixel_fmt; + u32 mclk; + u16 active_width; + u16 active_height; +} sensor_interface; + +/* Sensor control function */ +/* Only for old version. Will go away soon. */ +struct camera_sensor { + void (*set_color) (int bright, int saturation, int red, int green, + int blue); + void (*get_color) (int *bright, int *saturation, int *red, int *green, + int *blue); + void (*set_ae_mode) (int ae_mode); + void (*get_ae_mode) (int *ae_mode); + sensor_interface *(*config) (int *frame_rate, int high_quality); + sensor_interface *(*reset) (void); + void (*get_std) (v4l2_std_id *std); + void (*set_std) (v4l2_std_id std); + unsigned int csi; +}; + +/*! + * common v4l2 driver structure. + */ +typedef struct _cam_data { + struct video_device *video_dev; + int device_type; + + /* semaphore guard against SMP multithreading */ + struct semaphore busy_lock; + + int open_count; + + /* params lock for this camera */ + struct semaphore param_lock; + + /* Encoder */ + struct list_head ready_q; + struct list_head done_q; + struct list_head working_q; + int ping_pong_csi; + spinlock_t queue_int_lock; + spinlock_t dqueue_int_lock; + struct mxc_v4l_frame frame[FRAME_NUM]; + struct mxc_v4l_frame dummy_frame; + int skip_frame; + wait_queue_head_t enc_queue; + int enc_counter; + dma_addr_t rot_enc_bufs[2]; + void *rot_enc_bufs_vaddr[2]; + int rot_enc_buf_size[2]; + enum v4l2_buf_type type; + + /* still image capture */ + wait_queue_head_t still_queue; + int still_counter; + dma_addr_t still_buf[2]; + void *still_buf_vaddr; + + /* overlay */ + struct v4l2_window win; + struct v4l2_framebuffer v4l2_fb; + dma_addr_t vf_bufs[2]; + void *vf_bufs_vaddr[2]; + int vf_bufs_size[2]; + dma_addr_t rot_vf_bufs[2]; + void *rot_vf_bufs_vaddr[2]; + int rot_vf_buf_size[2]; + bool overlay_active; + int output; + struct fb_info *overlay_fb; + int fb_origin_std; + + /* v4l2 format */ + struct v4l2_format v2f; + int rotation; /* for IPUv1 and IPUv3, this means encoder rotation */ + int vf_rotation; /* viewfinder rotation only for IPUv1 and IPUv3 */ + struct v4l2_mxc_offset offset; + + /* V4l2 control bit */ + int bright; + int hue; + int contrast; + int saturation; + int red; + int green; + int blue; + int ae_mode; + + /* standard */ + struct v4l2_streamparm streamparm; + struct v4l2_standard standard; + bool standard_autodetect; + + /* crop */ + struct v4l2_rect crop_bounds; + struct v4l2_rect crop_defrect; + struct v4l2_rect crop_current; + + int (*enc_update_eba) (dma_addr_t eba, int *bufferNum); + int (*enc_enable) (void *private); + int (*enc_disable) (void *private); + int (*enc_enable_csi) (void *private); + int (*enc_disable_csi) (void *private); + void (*enc_callback) (u32 mask, void *dev); + int (*vf_start_adc) (void *private); + int (*vf_stop_adc) (void *private); + int (*vf_start_sdc) (void *private); + int (*vf_stop_sdc) (void *private); + int (*vf_enable_csi) (void *private); + int (*vf_disable_csi) (void *private); + int (*csi_start) (void *private); + int (*csi_stop) (void *private); + + /* misc status flag */ + bool overlay_on; + bool capture_on; + int overlay_pid; + int capture_pid; + bool low_power; + wait_queue_head_t power_queue; + unsigned int csi; + int current_input; + + /* camera sensor interface */ + struct camera_sensor *cam_sensor; /* old version */ + struct v4l2_int_device *sensor; +} cam_data; + +#if defined(CONFIG_MXC_IPU_V1) || defined(CONFIG_VIDEO_MXC_EMMA_CAMERA) \ + || defined(CONFIG_VIDEO_MXC_CSI_CAMERA_MODULE) \ + || defined(CONFIG_VIDEO_MXC_CSI_CAMERA) +void set_mclk_rate(uint32_t *p_mclk_freq); +#else +void set_mclk_rate(uint32_t *p_mclk_freq, uint32_t csi); +#endif +#endif /* __MXC_V4L2_CAPTURE_H__ */ diff --git a/drivers/media/video/mxc/capture/ov2640.c b/drivers/media/video/mxc/capture/ov2640.c new file mode 100644 index 000000000000..eef2340096ae --- /dev/null +++ b/drivers/media/video/mxc/capture/ov2640.c @@ -0,0 +1,1080 @@ +/* + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file ov2640.c + * + * @brief ov2640 camera driver functions + * + * @ingroup Camera + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include "mxc_v4l2_capture.h" + +#define MIN_FPS 5 +#define MAX_FPS 30 +#define DEFAULT_FPS 30 + +#define OV2640_XCLK_MIN 6000000 +#define OV2640_XCLK_MAX 27000000 + +/* +enum ov2640_mode { + ov2640_mode_1600_1120, + ov2640_mode_800_600 +}; +*/ + +struct reg_value { + u8 reg; + u8 value; + int delay_ms; +}; + +static struct reg_value ov2640_setting_1600_1120[] = { +#ifdef CONFIG_MACH_MX25_3DS + {0xff, 0x01, 0}, {0x12, 0x80, 5}, {0xff, 0x00, 0}, {0x2c, 0xff, 0}, + {0x2e, 0xdf, 0}, {0xff, 0x01, 0}, {0x3c, 0x32, 0}, {0x11, 0x00, 0}, + {0x09, 0x02, 0}, {0x04, 0x28, 0}, {0x13, 0xe5, 0}, {0x14, 0x48, 0}, + {0x2c, 0x0c, 0}, {0x33, 0x78, 0}, {0x3a, 0x33, 0}, {0x3b, 0xfb, 0}, + {0x3e, 0x00, 0}, {0x43, 0x11, 0}, {0x16, 0x10, 0}, {0x39, 0x02, 0}, + {0x35, 0x58, 0}, {0x22, 0x0a, 0}, {0x37, 0x40, 0}, {0x23, 0x00, 0}, + {0x34, 0xa0, 0}, {0x36, 0x1a, 0}, {0x06, 0x02, 0}, {0x07, 0xc0, 0}, + {0x0d, 0xb7, 0}, {0x0e, 0x01, 0}, {0x4c, 0x00, 0}, {0x4a, 0x81, 0}, + {0x21, 0x99, 0}, {0x24, 0x40, 0}, {0x25, 0x38, 0}, {0x26, 0x82, 0}, + {0x5c, 0x00, 0}, {0x63, 0x00, 0}, {0x46, 0x3f, 0}, {0x61, 0x70, 0}, + {0x62, 0x80, 0}, {0x7c, 0x05, 0}, {0x20, 0x80, 0}, {0x28, 0x30, 0}, + {0x6c, 0x00, 0}, {0x6d, 0x80, 0}, {0x6e, 0x00, 0}, {0x70, 0x02, 0}, + {0x71, 0x94, 0}, {0x73, 0xc1, 0}, {0x3d, 0x34, 0}, {0x5a, 0x57, 0}, + {0x4f, 0xbb, 0}, {0x50, 0x9c, 0}, {0xff, 0x00, 0}, {0xe5, 0x7f, 0}, + {0xf9, 0xc0, 0}, {0x41, 0x24, 0}, {0xe0, 0x14, 0}, {0x76, 0xff, 0}, + {0x33, 0xa0, 0}, {0x42, 0x20, 0}, {0x43, 0x18, 0}, {0x4c, 0x00, 0}, + {0x87, 0xd0, 0}, {0x88, 0x3f, 0}, {0xd7, 0x01, 0}, {0xd9, 0x10, 0}, + {0xd3, 0x82, 0}, {0xc8, 0x08, 0}, {0xc9, 0x80, 0}, {0x7c, 0x00, 0}, + {0x7d, 0x00, 0}, {0x7c, 0x03, 0}, {0x7d, 0x48, 0}, {0x7d, 0x48, 0}, + {0x7c, 0x08, 0}, {0x7d, 0x20, 0}, {0x7d, 0x10, 0}, {0x7d, 0x0e, 0}, + {0x90, 0x00, 0}, {0x91, 0x0e, 0}, {0x91, 0x1a, 0}, {0x91, 0x31, 0}, + {0x91, 0x5a, 0}, {0x91, 0x69, 0}, {0x91, 0x75, 0}, {0x91, 0x7e, 0}, + {0x91, 0x88, 0}, {0x91, 0x8f, 0}, {0x91, 0x96, 0}, {0x91, 0xa3, 0}, + {0x91, 0xaf, 0}, {0x91, 0xc4, 0}, {0x91, 0xd7, 0}, {0x91, 0xe8, 0}, + {0x91, 0x20, 0}, {0x92, 0x00, 0}, {0x93, 0x06, 0}, {0x93, 0xe3, 0}, + {0x93, 0x05, 0}, {0x93, 0x05, 0}, {0x93, 0x00, 0}, {0x93, 0x04, 0}, + {0x93, 0x00, 0}, {0x93, 0x00, 0}, {0x93, 0x00, 0}, {0x93, 0x00, 0}, + {0x93, 0x00, 0}, {0x93, 0x00, 0}, {0x93, 0x00, 0}, {0x96, 0x00, 0}, + {0x97, 0x08, 0}, {0x97, 0x19, 0}, {0x97, 0x02, 0}, {0x97, 0x0c, 0}, + {0x97, 0x24, 0}, {0x97, 0x30, 0}, {0x97, 0x28, 0}, {0x97, 0x26, 0}, + {0x97, 0x02, 0}, {0x97, 0x98, 0}, {0x97, 0x80, 0}, {0x97, 0x00, 0}, + {0x97, 0x00, 0}, {0xc3, 0xed, 0}, {0xa4, 0x00, 0}, {0xa8, 0x00, 0}, + {0xc5, 0x11, 0}, {0xc6, 0x51, 0}, {0xbf, 0x80, 0}, {0xc7, 0x10, 0}, + {0xb6, 0x66, 0}, {0xb8, 0xa5, 0}, {0xb7, 0x64, 0}, {0xb9, 0x7c, 0}, + {0xb3, 0xaf, 0}, {0xb4, 0x97, 0}, {0xb5, 0xff, 0}, {0xb0, 0xc5, 0}, + {0xb1, 0x94, 0}, {0xb2, 0x0f, 0}, {0xc4, 0x5c, 0}, {0xc0, 0xc8, 0}, + {0xc1, 0x96, 0}, {0x86, 0x1d, 0}, {0x50, 0x00, 0}, {0x51, 0x90, 0}, + {0x52, 0x2c, 0}, {0x53, 0x00, 0}, {0x54, 0x00, 0}, {0x55, 0x88, 0}, + {0x57, 0x00, 0}, {0x5a, 0x90, 0}, {0x5b, 0x2c, 0}, {0x5c, 0x05, 0}, + {0xc3, 0xed, 0}, {0x7f, 0x00, 0}, {0xda, 0x00, 0}, {0xe5, 0x1f, 0}, + {0xe1, 0x77, 0}, {0xe0, 0x00, 0}, {0xdd, 0x7f, 0}, {0x05, 0x00, 0}, + {0xff, 0x00, 0}, {0xe0, 0x04, 0}, {0xc0, 0xc8, 0}, {0xc1, 0x96, 0}, + {0x86, 0x3d, 0}, {0x50, 0x00, 0}, {0x51, 0x90, 0}, {0x52, 0x2c, 0}, + {0x53, 0x00, 0}, {0x54, 0x00, 0}, {0x55, 0x88, 0}, {0x57, 0x00, 0}, + {0x5a, 0x40, 0}, {0x5b, 0xf0, 0}, {0x5c, 0x01, 0}, {0xd3, 0x82, 0}, + {0xe0, 0x00, 1000} +#else + {0xff, 0x1, 0}, {0x12, 0x80, 1}, {0xff, 0, 0}, {0x2c, 0xff, 0}, + {0x2e, 0xdf, 0}, {0xff, 0x1, 0}, {0x3c, 0x32, 0}, {0x11, 0x01, 0}, + {0x09, 0x00, 0}, {0x04, 0x28, 0}, {0x13, 0xe5, 0}, {0x14, 0x48, 0}, + {0x2c, 0x0c, 0}, {0x33, 0x78, 0}, {0x3a, 0x33, 0}, {0x3b, 0xfb, 0}, + {0x3e, 0x00, 0}, {0x43, 0x11, 0}, {0x16, 0x10, 0}, {0x39, 0x82, 0}, + {0x35, 0x88, 0}, {0x22, 0x0a, 0}, {0x37, 0x40, 0}, {0x23, 0x00, 0}, + {0x34, 0xa0, 0}, {0x36, 0x1a, 0}, {0x06, 0x02, 0}, {0x07, 0xc0, 0}, + {0x0d, 0xb7, 0}, {0x0e, 0x01, 0}, {0x4c, 0x00, 0}, {0x4a, 0x81, 0}, + {0x21, 0x99, 0}, {0x24, 0x40, 0}, {0x25, 0x38, 0}, {0x26, 0x82, 0}, + {0x5c, 0x00, 0}, {0x63, 0x00, 0}, {0x46, 0x3f, 0}, {0x0c, 0x3c, 0}, + {0x5d, 0x55, 0}, {0x5e, 0x7d, 0}, {0x5f, 0x7d, 0}, {0x60, 0x55, 0}, + {0x61, 0x70, 0}, {0x62, 0x80, 0}, {0x7c, 0x05, 0}, {0x20, 0x80, 0}, + {0x28, 0x30, 0}, {0x6c, 0x00, 0}, {0x6d, 0x80, 0}, {0x6e, 00, 0}, + {0x70, 0x02, 0}, {0x71, 0x94, 0}, {0x73, 0xc1, 0}, {0x3d, 0x34, 0}, + {0x5a, 0x57, 0}, {0x4f, 0xbb, 0}, {0x50, 0x9c, 0}, {0xff, 0x00, 0}, + {0xe5, 0x7f, 0}, {0xf9, 0xc0, 0}, {0x41, 0x24, 0}, {0x44, 0x06, 0}, + {0xe0, 0x14, 0}, {0x76, 0xff, 0}, {0x33, 0xa0, 0}, {0x42, 0x20, 0}, + {0x43, 0x18, 0}, {0x4c, 0x00, 0}, {0x87, 0xd0, 0}, {0xd7, 0x03, 0}, + {0xd9, 0x10, 0}, {0xd3, 0x82, 0}, {0xc8, 0x08, 0}, {0xc9, 0x80, 0}, + {0x7c, 0x00, 0}, {0x7d, 0x00, 0}, {0x7c, 0x03, 0}, {0x7d, 0x48, 0}, + {0x7d, 0x48, 0}, {0x7c, 0x08, 0}, {0x7d, 0x20, 0}, {0x7d, 0x10, 0}, + {0x7d, 0x0e, 0}, {0x90, 0x00, 0}, {0x91, 0x0e, 0}, {0x91, 0x1a, 0}, + {0x91, 0x31, 0}, {0x91, 0x5a, 0}, {0x91, 0x69, 0}, {0x91, 0x75, 0}, + {0x91, 0x7e, 0}, {0x91, 0x88, 0}, {0x91, 0x8f, 0}, {0x91, 0x96, 0}, + {0x91, 0xa3, 0}, {0x91, 0xaf, 0}, {0x91, 0xc4, 0}, {0x91, 0xd7, 0}, + {0x91, 0xe8, 0}, {0x91, 0x20, 0}, {0x92, 0x00, 0}, {0x93, 0x06, 0}, + {0x93, 0xe3, 0}, {0x93, 0x03, 0}, {0x93, 0x03, 0}, {0x93, 0x00, 0}, + {0x93, 0x02, 0}, {0x93, 0x00, 0}, {0x93, 0x00, 0}, {0x93, 0x00, 0}, + {0x93, 0x00, 0}, {0x93, 0x00, 0}, {0x93, 0x00, 0}, {0x93, 0x00, 0}, + {0x96, 0x00, 0}, {0x97, 0x08, 0}, {0x97, 0x19, 0}, {0x97, 0x02, 0}, + {0x97, 0x0c, 0}, {0x97, 0x24, 0}, {0x97, 0x30, 0}, {0x97, 0x28, 0}, + {0x97, 0x26, 0}, {0x97, 0x02, 0}, {0x97, 0x98, 0}, {0x97, 0x80, 0}, + {0x97, 0x00, 0}, {0x97, 0x00, 0}, {0xa4, 0x00, 0}, {0xa8, 0x00, 0}, + {0xc5, 0x11, 0}, {0xc6, 0x51, 0}, {0xbf, 0x80, 0}, {0xc7, 0x10, 0}, + {0xb6, 0x66, 0}, {0xb8, 0xa5, 0}, {0xb7, 0x64, 0}, {0xb9, 0x7c, 0}, + {0xb3, 0xaf, 0}, {0xb4, 0x97, 0}, {0xb5, 0xff, 0}, {0xb0, 0xc5, 0}, + {0xb1, 0x94, 0}, {0xb2, 0x0f, 0}, {0xc4, 0x5c, 0}, {0xa6, 0x00, 0}, + {0xa7, 0x20, 0}, {0xa7, 0xd8, 0}, {0xa7, 0x1b, 0}, {0xa7, 0x31, 0}, + {0xa7, 0x00, 0}, {0xa7, 0x18, 0}, {0xa7, 0x20, 0}, {0xa7, 0xd8, 0}, + {0xa7, 0x19, 0}, {0xa7, 0x31, 0}, {0xa7, 0x00, 0}, {0xa7, 0x18, 0}, + {0xa7, 0x20, 0}, {0xa7, 0xd8, 0}, {0xa7, 0x19, 0}, {0xa7, 0x31, 0}, + {0xa7, 0x00, 0}, {0xa7, 0x18, 0}, {0xc0, 0xc8, 0}, {0xc1, 0x96, 0}, + {0x86, 0x3d, 0}, {0x50, 0x00, 0}, {0x51, 0x90, 0}, {0x52, 0x18, 0}, + {0x53, 0x00, 0}, {0x54, 0x00, 0}, {0x55, 0x88, 0}, {0x57, 0x00, 0}, + {0x5a, 0x90, 0}, {0x5b, 0x18, 0}, {0x5c, 0x05, 0}, {0xc3, 0xef, 0}, + {0x7f, 0x00, 0}, {0xda, 0x01, 0}, {0xe5, 0x1f, 0}, {0xe1, 0x67, 0}, + {0xe0, 0x00, 0}, {0xdd, 0x7f, 0}, {0x05, 0x00, 0} +#endif +}; + +static struct reg_value ov2640_setting_800_600[] = { +#ifdef CONFIG_MACH_MX25_3DS + {0xff, 0x01, 0}, {0x12, 0x80, 5}, {0xff, 0x00, 0}, {0x2c, 0xff, 0}, + {0x2e, 0xdf, 0}, {0xff, 0x01, 0}, {0x3c, 0x32, 0}, {0x11, 0x00, 0}, + {0x09, 0x02, 0}, {0x04, 0x28, 0}, {0x13, 0xe5, 0}, {0x14, 0x48, 0}, + {0x2c, 0x0c, 0}, {0x33, 0x78, 0}, {0x3a, 0x33, 0}, {0x3b, 0xfb, 0}, + {0x3e, 0x00, 0}, {0x43, 0x11, 0}, {0x16, 0x10, 0}, {0x39, 0x92, 0}, + {0x35, 0xda, 0}, {0x22, 0x1a, 0}, {0x37, 0xc3, 0}, {0x23, 0x00, 0}, + {0x34, 0xc0, 0}, {0x36, 0x1a, 0}, {0x06, 0x88, 0}, {0x07, 0xc0, 0}, + {0x0d, 0x87, 0}, {0x0e, 0x41, 0}, {0x4c, 0x00, 0}, + {0x48, 0x00, 0}, {0x5b, 0x00, 0}, {0x42, 0x03, 0}, {0x4a, 0x81, 0}, + {0x21, 0x99, 0}, {0x24, 0x40, 0}, {0x25, 0x38, 0}, {0x26, 0x82, 0}, + {0x5c, 0x00, 0}, {0x63, 0x00, 0}, {0x46, 0x22, 0}, {0x0c, 0x3c, 0}, + {0x61, 0x70, 0}, {0x62, 0x80, 0}, {0x7c, 0x05, 0}, {0x20, 0x80, 0}, + {0x28, 0x30, 0}, {0x6c, 0x00, 0}, {0x6d, 0x80, 0}, {0x6e, 0x00, 0}, + {0x70, 0x02, 0}, {0x71, 0x94, 0}, {0x73, 0xc1, 0}, {0x12, 0x40, 0}, + {0x17, 0x11, 0}, {0x18, 0x43, 0}, {0x19, 0x00, 0}, {0x1a, 0x4b, 0}, + {0x32, 0x09, 0}, {0x37, 0xc0, 0}, {0x4f, 0xca, 0}, {0x50, 0xa8, 0}, + {0x5a, 0x23, 0}, {0x6d, 0x00, 0}, {0x3d, 0x38, 0}, {0xff, 0x00, 0}, + {0xe5, 0x7f, 0}, {0xf9, 0xc0, 0}, {0x41, 0x24, 0}, {0xe0, 0x14, 0}, + {0x76, 0xff, 0}, {0x33, 0xa0, 0}, {0x42, 0x20, 0}, {0x43, 0x18, 0}, + {0x4c, 0x00, 0}, {0x87, 0xd5, 0}, {0x88, 0x3f, 0}, {0xd7, 0x01, 0}, + {0xd9, 0x10, 0}, {0xd3, 0x82, 0}, {0xc8, 0x08, 0}, {0xc9, 0x80, 0}, + {0x7c, 0x00, 0}, {0x7d, 0x00, 0}, {0x7c, 0x03, 0}, {0x7d, 0x48, 0}, + {0x7d, 0x48, 0}, {0x7c, 0x08, 0}, {0x7d, 0x20, 0}, {0x7d, 0x10, 0}, + {0x7d, 0x0e, 0}, {0x90, 0x00, 0}, {0x91, 0x0e, 0}, {0x91, 0x1a, 0}, + {0x91, 0x31, 0}, {0x91, 0x5a, 0}, {0x91, 0x69, 0}, {0x91, 0x75, 0}, + {0x91, 0x7e, 0}, {0x91, 0x88, 0}, {0x91, 0x8f, 0}, {0x91, 0x96, 0}, + {0x91, 0xa3, 0}, {0x91, 0xaf, 0}, {0x91, 0xc4, 0}, {0x91, 0xd7, 0}, + {0x91, 0xe8, 0}, {0x91, 0x20, 0}, {0x92, 0x00, 0}, {0x93, 0x06, 0}, + {0x93, 0xe3, 0}, {0x93, 0x05, 0}, {0x93, 0x05, 0}, {0x93, 0x00, 0}, + {0x93, 0x04, 0}, {0x93, 0x00, 0}, {0x93, 0x00, 0}, {0x93, 0x00, 0}, + {0x93, 0x00, 0}, {0x93, 0x00, 0}, {0x93, 0x00, 0}, {0x93, 0x00, 0}, + {0x96, 0x00, 0}, {0x97, 0x08, 0}, {0x97, 0x19, 0}, {0x97, 0x02, 0}, + {0x97, 0x0c, 0}, {0x97, 0x24, 0}, {0x97, 0x30, 0}, {0x97, 0x28, 0}, + {0x97, 0x26, 0}, {0x97, 0x02, 0}, {0x97, 0x98, 0}, {0x97, 0x80, 0}, + {0x97, 0x00, 0}, {0x97, 0x00, 0}, {0xc3, 0xed, 0}, {0xa4, 0x00, 0}, + {0xa8, 0x00, 0}, {0xc5, 0x11, 0}, {0xc6, 0x51, 0}, {0xbf, 0x80, 0}, + {0xc7, 0x10, 0}, {0xb6, 0x66, 0}, {0xb8, 0xa5, 0}, {0xb7, 0x64, 0}, + {0xb9, 0x7c, 0}, {0xb3, 0xaf, 0}, {0xb4, 0x97, 0}, {0xb5, 0xff, 0}, + {0xb0, 0xc5, 0}, {0xb1, 0x94, 0}, {0xb2, 0x0f, 0}, {0xc4, 0x5c, 0}, + {0xc0, 0x64, 0}, {0xc1, 0x4b, 0}, {0x8c, 0x00, 0}, {0x86, 0x3d, 0}, + {0x50, 0x00, 0}, {0x51, 0xc8, 0}, {0x52, 0x96, 0}, {0x53, 0x00, 0}, + {0x54, 0x00, 0}, {0x55, 0x00, 0}, {0x5a, 0xc8, 0}, {0x5b, 0x96, 0}, + {0x5c, 0x00, 0}, {0xd3, 0x82, 0}, {0xc3, 0xed, 0}, {0x7f, 0x00, 0}, + {0xda, 0x00, 0}, {0xe5, 0x1f, 0}, {0xe1, 0x67, 0}, {0xe0, 0x00, 0}, + {0xdd, 0x7f, 0}, {0x05, 0x00, 0}, {0xff, 0x00, 0}, {0xe0, 0x04, 0}, + {0xc0, 0x64, 0}, {0xc1, 0x4b, 0}, {0x8c, 0x00, 0}, {0x86, 0x3d, 0}, + {0x50, 0x00, 0}, {0x51, 0xc8, 0}, {0x52, 0x96, 0}, {0x53, 0x00, 0}, + {0x54, 0x00, 0}, {0x55, 0x00, 0}, {0x5a, 0xa0, 0}, {0x5b, 0x78, 0}, + {0x5c, 0x00, 0}, {0xd3, 0x82, 0}, {0xe0, 0x00, 1000} +#else + {0xff, 0, 0}, {0xff, 1, 0}, {0x12, 0x80, 1}, {0xff, 00, 0}, + {0x2c, 0xff, 0}, {0x2e, 0xdf, 0}, {0xff, 0x1, 0}, {0x3c, 0x32, 0}, + {0x11, 0x01, 0}, {0x09, 0x00, 0}, {0x04, 0x28, 0}, {0x13, 0xe5, 0}, + {0x14, 0x48, 0}, {0x2c, 0x0c, 0}, {0x33, 0x78, 0}, {0x3a, 0x33, 0}, + {0x3b, 0xfb, 0}, {0x3e, 0x00, 0}, {0x43, 0x11, 0}, {0x16, 0x10, 0}, + {0x39, 0x92, 0}, {0x35, 0xda, 0}, {0x22, 0x1a, 0}, {0x37, 0xc3, 0}, + {0x23, 0x00, 0}, {0x34, 0xc0, 0}, {0x36, 0x1a, 0}, {0x06, 0x88, 0}, + {0x07, 0xc0, 0}, {0x0d, 0x87, 0}, {0x0e, 0x41, 0}, {0x4c, 0x00, 0}, + {0x4a, 0x81, 0}, {0x21, 0x99, 0}, {0x24, 0x40, 0}, {0x25, 0x38, 0}, + {0x26, 0x82, 0}, {0x5c, 0x00, 0}, {0x63, 0x00, 0}, {0x46, 0x22, 0}, + {0x0c, 0x3c, 0}, {0x5d, 0x55, 0}, {0x5e, 0x7d, 0}, {0x5f, 0x7d, 0}, + {0x60, 0x55, 0}, {0x61, 0x70, 0}, {0x62, 0x80, 0}, {0x7c, 0x05, 0}, + {0x20, 0x80, 0}, {0x28, 0x30, 0}, {0x6c, 0x00, 0}, {0x6d, 0x80, 0}, + {0x6e, 00, 0}, {0x70, 0x02, 0}, {0x71, 0x94, 0}, {0x73, 0xc1, 0}, + {0x12, 0x40, 0}, {0x17, 0x11, 0}, {0x18, 0x43, 0}, {0x19, 0x00, 0}, + {0x1a, 0x4b, 0}, {0x32, 0x09, 0}, {0x37, 0xc0, 0}, {0x4f, 0xca, 0}, + {0x50, 0xa8, 0}, {0x6d, 0x00, 0}, {0x3d, 0x38, 0}, {0xff, 0x00, 0}, + {0xe5, 0x7f, 0}, {0xf9, 0xc0, 0}, {0x41, 0x24, 0}, {0x44, 0x06, 0}, + {0xe0, 0x14, 0}, {0x76, 0xff, 0}, {0x33, 0xa0, 0}, {0x42, 0x20, 0}, + {0x43, 0x18, 0}, {0x4c, 0x00, 0}, {0x87, 0xd0, 0}, {0x88, 0x3f, 0}, + {0xd7, 0x03, 0}, {0xd9, 0x10, 0}, {0xd3, 0x82, 0}, {0xc8, 0x08, 0}, + {0xc9, 0x80, 0}, {0x7c, 0x00, 0}, {0x7d, 0x00, 0}, {0x7c, 0x03, 0}, + {0x7d, 0x48, 0}, {0x7d, 0x48, 0}, {0x7c, 0x08, 0}, {0x7d, 0x20, 0}, + {0x7d, 0x10, 0}, {0x7d, 0x0e, 0}, {0x90, 0x00, 0}, {0x91, 0x0e, 0}, + {0x91, 0x1a, 0}, {0x91, 0x31, 0}, {0x91, 0x5a, 0}, {0x91, 0x69, 0}, + {0x91, 0x75, 0}, {0x91, 0x7e, 0}, {0x91, 0x88, 0}, {0x91, 0x8f, 0}, + {0x91, 0x96, 0}, {0x91, 0xa3, 0}, {0x91, 0xaf, 0}, {0x91, 0xc4, 0}, + {0x91, 0xd7, 0}, {0x91, 0xe8, 0}, {0x91, 0x20, 0}, {0x92, 0x00, 0}, + {0x93, 0x06, 0}, {0x93, 0xe3, 0}, {0x93, 0x03, 0}, {0x93, 0x03, 0}, + {0x93, 0x00, 0}, {0x93, 0x02, 0}, {0x93, 0x00, 0}, {0x93, 0x00, 0}, + {0x93, 0x00, 0}, {0x93, 0x00, 0}, {0x93, 0x00, 0}, {0x93, 0x00, 0}, + {0x93, 0x00, 0}, {0x96, 0x00, 0}, {0x97, 0x08, 0}, {0x97, 0x19, 0}, + {0x97, 0x02, 0}, {0x97, 0x0c, 0}, {0x97, 0x24, 0}, {0x97, 0x30, 0}, + {0x97, 0x28, 0}, {0x97, 0x26, 0}, {0x97, 0x02, 0}, {0x97, 0x98, 0}, + {0x97, 0x80, 0}, {0x97, 0x00, 0}, {0x97, 0x00, 0}, {0xa4, 0x00, 0}, + {0xa8, 0x00, 0}, {0xc5, 0x11, 0}, {0xc6, 0x51, 0}, {0xbf, 0x80, 0}, + {0xc7, 0x10, 0}, {0xb6, 0x66, 0}, {0xb8, 0xa5, 0}, {0xb7, 0x64, 0}, + {0xb9, 0x7c, 0}, {0xb3, 0xaf, 0}, {0xb4, 0x97, 0}, {0xb5, 0xff, 0}, + {0xb0, 0xc5, 0}, {0xb1, 0x94, 0}, {0xb2, 0x0f, 0}, {0xc4, 0x5c, 0}, + {0xa6, 0x00, 0}, {0xa7, 0x20, 0}, {0xa7, 0xd8, 0}, {0xa7, 0x1b, 0}, + {0xa7, 0x31, 0}, {0xa7, 0x00, 0}, {0xa7, 0x18, 0}, {0xa7, 0x20, 0}, + {0xa7, 0xd8, 0}, {0xa7, 0x19, 0}, {0xa7, 0x31, 0}, {0xa7, 0x00, 0}, + {0xa7, 0x18, 0}, {0xa7, 0x20, 0}, {0xa7, 0xd8, 0}, {0xa7, 0x19, 0}, + {0xa7, 0x31, 0}, {0xa7, 0x00, 0}, {0xa7, 0x18, 0}, {0xc0, 0x64, 0}, + {0xc1, 0x4b, 0}, {0x86, 0x1d, 0}, {0x50, 0x00, 0}, {0x51, 0xc8, 0}, + {0x52, 0x96, 0}, {0x53, 0x00, 0}, {0x54, 0x00, 0}, {0x55, 0x00, 0}, + {0x57, 0x00, 0}, {0x5a, 0xc8, 0}, {0x5b, 0x96, 0}, {0x5c, 0x00, 0}, + {0xc3, 0xef, 0}, {0x7f, 0x00, 0}, {0xda, 0x01, 0}, {0xe5, 0x1f, 0}, + {0xe1, 0x67, 0}, {0xe0, 0x00, 0}, {0xdd, 0x7f, 0}, {0x05, 0x00, 0} +#endif +}; + +/*! + * Maintains the information on the current state of the sesor. + */ +struct sensor { + const struct ov2640_platform_data *platform_data; + struct v4l2_int_device *v4l2_int_device; + struct i2c_client *i2c_client; + struct v4l2_pix_format pix; + struct v4l2_captureparm streamcap; + bool on; + + /* control settings */ + int brightness; + int hue; + int contrast; + int saturation; + int red; + int green; + int blue; + int ae_mode; + + u32 csi; + u32 mclk; + +} ov2640_data; + +static struct regulator *io_regulator; +static struct regulator *core_regulator; +static struct regulator *analog_regulator; +static struct regulator *gpo_regulator; + +extern void gpio_sensor_active(void); +extern void gpio_sensor_inactive(void); + +/* list of image formats supported by this sensor */ +/* +const static struct v4l2_fmtdesc ov2640_formats[] = { + { + .description = "YUYV (YUV 4:2:2), packed", + .pixelformat = V4L2_PIX_FMT_UYVY, + }, +}; + */ + +static int ov2640_init_mode(struct sensor *s) +{ + int ret = -1; + struct reg_value *setting; + int i, num; + + pr_debug("In ov2640:ov2640_init_mode capturemode is %d\n", + s->streamcap.capturemode); + + if (s->streamcap.capturemode & V4L2_MODE_HIGHQUALITY) { + s->pix.width = 1600; + s->pix.height = 1120; + setting = ov2640_setting_1600_1120; + num = ARRAY_SIZE(ov2640_setting_1600_1120); + } else { + s->pix.width = 800; + s->pix.height = 600; + setting = ov2640_setting_800_600; + num = ARRAY_SIZE(ov2640_setting_800_600); + } + + for (i = 0; i < num; i++) { + ret = i2c_smbus_write_byte_data(s->i2c_client, + setting[i].reg, + setting[i].value); + if (ret < 0) { + pr_err("write reg error: reg=%x, val=%x\n", + setting[i].reg, setting[i].value); + return ret; + } + if (setting[i].delay_ms > 0) + msleep(setting[i].delay_ms); + } + + return ret; +} + +/* At present only support change to 15fps(only for SVGA mode) */ +static int ov2640_set_fps(struct sensor *s, int fps) +{ + int ret = 0; + + if (i2c_smbus_write_byte_data(s->i2c_client, 0xff, 0x01) < 0) { + pr_err("in %s,change to sensor addr failed\n", __func__); + ret = -EPERM; + } + + /* change the camera framerate to 15fps(only for SVGA mode) */ + if (i2c_smbus_write_byte_data(s->i2c_client, 0x11, 0x01) < 0) { + pr_err("change camera to 15fps failed\n"); + ret = -EPERM; + } + + return ret; +} + +static int ov2640_set_format(struct sensor *s, int format) +{ + int ret = 0; + + if (i2c_smbus_write_byte_data(s->i2c_client, 0xff, 0x00) < 0) + ret = -EPERM; + + if (format == V4L2_PIX_FMT_RGB565) { + /* set RGB565 format */ + if (i2c_smbus_write_byte_data(s->i2c_client, 0xda, 0x08) < 0) + ret = -EPERM; + + if (i2c_smbus_write_byte_data(s->i2c_client, 0xd7, 0x03) < 0) + ret = -EPERM; + } else if (format == V4L2_PIX_FMT_YUV420) { + /* set YUV420 format */ + if (i2c_smbus_write_byte_data(s->i2c_client, 0xda, 0x00) < 0) + ret = -EPERM; + + if (i2c_smbus_write_byte_data(s->i2c_client, 0xd7, 0x1b) < 0) + ret = -EPERM; + } else { + pr_debug("format not supported\n"); + } + + return ret; +} + +/* --------------- IOCTL functions from v4l2_int_ioctl_desc --------------- */ + +/*! + * ioctl_g_ifparm - V4L2 sensor interface handler for vidioc_int_g_ifparm_num + * s: pointer to standard V4L2 device structure + * p: pointer to standard V4L2 vidioc_int_g_ifparm_num ioctl structure + * + * Gets slave interface parameters. + * Calculates the required xclk value to support the requested + * clock parameters in p. This value is returned in the p + * parameter. + * + * vidioc_int_g_ifparm returns platform-specific information about the + * interface settings used by the sensor. + * + * Given the image capture format in pix, the nominal frame period in + * timeperframe, calculate the required xclk frequency. + * + * Called on open. + */ +static int ioctl_g_ifparm(struct v4l2_int_device *s, struct v4l2_ifparm *p) +{ + pr_debug("In ov2640:ioctl_g_ifparm\n"); + + if (s == NULL) { + pr_err(" ERROR!! no slave device set!\n"); + return -1; + } + + memset(p, 0, sizeof(*p)); + p->u.bt656.clock_curr = ov2640_data.mclk; + p->if_type = V4L2_IF_TYPE_BT656; + p->u.bt656.mode = V4L2_IF_TYPE_BT656_MODE_NOBT_8BIT; + p->u.bt656.clock_min = OV2640_XCLK_MIN; + p->u.bt656.clock_max = OV2640_XCLK_MAX; + + return 0; +} + +/*! + * Sets the camera power. + * + * s pointer to the camera device + * on if 1, power is to be turned on. 0 means power is to be turned off + * + * ioctl_s_power - V4L2 sensor interface handler for vidioc_int_s_power_num + * @s: pointer to standard V4L2 device structure + * @on: power state to which device is to be set + * + * Sets devices power state to requrested state, if possible. + * This is called on open, close, suspend and resume. + */ +static int ioctl_s_power(struct v4l2_int_device *s, int on) +{ + struct sensor *sensor = s->priv; + + pr_debug("In ov2640:ioctl_s_power\n"); + + if (on && !sensor->on) { + gpio_sensor_active(); + if (io_regulator) + if (regulator_enable(io_regulator) != 0) + return -EIO; + if (core_regulator) + if (regulator_enable(core_regulator) != 0) + return -EIO; + if (gpo_regulator) + if (regulator_enable(gpo_regulator) != 0) + return -EIO; + if (analog_regulator) + if (regulator_enable(analog_regulator) != 0) + return -EIO; + } else if (!on && sensor->on) { + if (analog_regulator) + regulator_disable(analog_regulator); + if (core_regulator) + regulator_disable(core_regulator); + if (io_regulator) + regulator_disable(io_regulator); + if (gpo_regulator) + regulator_disable(gpo_regulator); + gpio_sensor_inactive(); + } + + sensor->on = on; + + return 0; +} + +/*! + * ioctl_g_parm - V4L2 sensor interface handler for VIDIOC_G_PARM ioctl + * @s: pointer to standard V4L2 device structure + * @a: pointer to standard V4L2 VIDIOC_G_PARM ioctl structure + * + * Returns the sensor's video CAPTURE parameters. + */ +static int ioctl_g_parm(struct v4l2_int_device *s, struct v4l2_streamparm *a) +{ + struct sensor *sensor = s->priv; + struct v4l2_captureparm *cparm = &a->parm.capture; + int ret = 0; + + pr_debug("In ov2640:ioctl_g_parm\n"); + + switch (a->type) { + /* This is the only case currently handled. */ + case V4L2_BUF_TYPE_VIDEO_CAPTURE: + pr_debug(" type is V4L2_BUF_TYPE_VIDEO_CAPTURE\n"); + memset(a, 0, sizeof(*a)); + a->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + cparm->capability = sensor->streamcap.capability; + cparm->timeperframe = sensor->streamcap.timeperframe; + cparm->capturemode = sensor->streamcap.capturemode; + ret = 0; + break; + + /* These are all the possible cases. */ + case V4L2_BUF_TYPE_VIDEO_OUTPUT: + case V4L2_BUF_TYPE_VIDEO_OVERLAY: + case V4L2_BUF_TYPE_VBI_CAPTURE: + case V4L2_BUF_TYPE_VBI_OUTPUT: + case V4L2_BUF_TYPE_SLICED_VBI_CAPTURE: + case V4L2_BUF_TYPE_SLICED_VBI_OUTPUT: + pr_err(" type is not V4L2_BUF_TYPE_VIDEO_CAPTURE " \ + "but %d\n", a->type); + ret = -EINVAL; + break; + + default: + pr_err(" type is unknown - %d\n", a->type); + ret = -EINVAL; + break; + } + + return ret; +} + +/*! + * ioctl_s_parm - V4L2 sensor interface handler for VIDIOC_S_PARM ioctl + * @s: pointer to standard V4L2 device structure + * @a: pointer to standard V4L2 VIDIOC_S_PARM ioctl structure + * + * Configures the sensor to use the input parameters, if possible. If + * not possible, reverts to the old parameters and returns the + * appropriate error code. + */ +static int ioctl_s_parm(struct v4l2_int_device *s, struct v4l2_streamparm *a) +{ + struct sensor *sensor = s->priv; + struct v4l2_fract *timeperframe = &a->parm.capture.timeperframe; + u32 tgt_fps; /* target frames per secound */ + int ret = 0; + + pr_debug("In ov2640:ioctl_s_parm\n"); + + switch (a->type) { + /* This is the only case currently handled. */ + case V4L2_BUF_TYPE_VIDEO_CAPTURE: + pr_debug(" type is V4L2_BUF_TYPE_VIDEO_CAPTURE\n"); + + /* Check that the new frame rate is allowed. */ + if ((timeperframe->numerator == 0) + || (timeperframe->denominator == 0)) { + timeperframe->denominator = DEFAULT_FPS; + timeperframe->numerator = 1; + } + tgt_fps = timeperframe->denominator + / timeperframe->numerator; + + if (tgt_fps > MAX_FPS) { + timeperframe->denominator = MAX_FPS; + timeperframe->numerator = 1; + } else if (tgt_fps < MIN_FPS) { + timeperframe->denominator = MIN_FPS; + timeperframe->numerator = 1; + } + sensor->streamcap.timeperframe = *timeperframe; + sensor->streamcap.capturemode = + (u32)a->parm.capture.capturemode; + + ret = ov2640_init_mode(sensor); + if (tgt_fps == 15) + ov2640_set_fps(sensor, tgt_fps); + break; + + /* These are all the possible cases. */ + case V4L2_BUF_TYPE_VIDEO_OUTPUT: + case V4L2_BUF_TYPE_VIDEO_OVERLAY: + case V4L2_BUF_TYPE_VBI_CAPTURE: + case V4L2_BUF_TYPE_VBI_OUTPUT: + case V4L2_BUF_TYPE_SLICED_VBI_CAPTURE: + case V4L2_BUF_TYPE_SLICED_VBI_OUTPUT: + pr_err(" type is not V4L2_BUF_TYPE_VIDEO_CAPTURE " \ + "but %d\n", a->type); + ret = -EINVAL; + break; + + default: + pr_err(" type is unknown - %d\n", a->type); + ret = -EINVAL; + break; + } + + return ret; +} + +/*! + * ioctl_s_fmt_cap - V4L2 sensor interface handler for ioctl_s_fmt_cap + * set camera output format and resolution format + * + * @s: pointer to standard V4L2 device structure + * @arg: pointer to parameter, according this to set camera + * + * Returns 0 if set succeed, else return -1 + */ +static int ioctl_s_fmt_cap(struct v4l2_int_device *s, struct v4l2_format *f) +{ + struct sensor *sensor = s->priv; + u32 format = f->fmt.pix.pixelformat; + int size = 0, ret = 0; + + size = f->fmt.pix.width * f->fmt.pix.height; + switch (format) { + case V4L2_PIX_FMT_RGB565: + if (size > 640 * 480) + sensor->streamcap.capturemode = V4L2_MODE_HIGHQUALITY; + else + sensor->streamcap.capturemode = 0; + ret = ov2640_init_mode(sensor); + + ret = ov2640_set_format(sensor, V4L2_PIX_FMT_RGB565); + break; + case V4L2_PIX_FMT_UYVY: + if (size > 640 * 480) + sensor->streamcap.capturemode = V4L2_MODE_HIGHQUALITY; + else + sensor->streamcap.capturemode = 0; + ret = ov2640_init_mode(sensor); + break; + case V4L2_PIX_FMT_YUV420: + if (size > 640 * 480) + sensor->streamcap.capturemode = V4L2_MODE_HIGHQUALITY; + else + sensor->streamcap.capturemode = 0; + ret = ov2640_init_mode(sensor); + + /* YUYV: width * 2, YY: width */ + ret = ov2640_set_format(sensor, V4L2_PIX_FMT_YUV420); + break; + default: + pr_debug("case not supported\n"); + break; + } + + return ret; +} + +/*! + * ioctl_g_fmt_cap - V4L2 sensor interface handler for ioctl_g_fmt_cap + * @s: pointer to standard V4L2 device structure + * @f: pointer to standard V4L2 v4l2_format structure + * + * Returns the sensor's current pixel format in the v4l2_format + * parameter. + */ +static int ioctl_g_fmt_cap(struct v4l2_int_device *s, struct v4l2_format *f) +{ + struct sensor *sensor = s->priv; + + pr_debug("In ov2640:ioctl_g_fmt_cap.\n"); + + f->fmt.pix = sensor->pix; + + return 0; +} + +/*! + * ioctl_g_ctrl - V4L2 sensor interface handler for VIDIOC_G_CTRL ioctl + * @s: pointer to standard V4L2 device structure + * @vc: standard V4L2 VIDIOC_G_CTRL ioctl structure + * + * If the requested control is supported, returns the control's current + * value from the video_control[] array. Otherwise, returns -EINVAL + * if the control is not supported. + */ +static int ioctl_g_ctrl(struct v4l2_int_device *s, struct v4l2_control *vc) +{ + int ret = 0; + + pr_debug("In ov2640:ioctl_g_ctrl\n"); + + switch (vc->id) { + case V4L2_CID_BRIGHTNESS: + vc->value = ov2640_data.brightness; + break; + case V4L2_CID_HUE: + vc->value = ov2640_data.hue; + break; + case V4L2_CID_CONTRAST: + vc->value = ov2640_data.contrast; + break; + case V4L2_CID_SATURATION: + vc->value = ov2640_data.saturation; + break; + case V4L2_CID_RED_BALANCE: + vc->value = ov2640_data.red; + break; + case V4L2_CID_BLUE_BALANCE: + vc->value = ov2640_data.blue; + break; + case V4L2_CID_EXPOSURE: + vc->value = ov2640_data.ae_mode; + break; + default: + ret = -EINVAL; + } + + return ret; +} + +/*! + * ioctl_s_ctrl - V4L2 sensor interface handler for VIDIOC_S_CTRL ioctl + * @s: pointer to standard V4L2 device structure + * @vc: standard V4L2 VIDIOC_S_CTRL ioctl structure + * + * If the requested control is supported, sets the control's current + * value in HW (and updates the video_control[] array). Otherwise, + * returns -EINVAL if the control is not supported. + */ +static int ioctl_s_ctrl(struct v4l2_int_device *s, struct v4l2_control *vc) +{ + int retval = 0; + + pr_debug("In ov2640:ioctl_s_ctrl %d\n", vc->id); + + switch (vc->id) { + case V4L2_CID_BRIGHTNESS: + pr_debug(" V4L2_CID_BRIGHTNESS\n"); + break; + case V4L2_CID_CONTRAST: + pr_debug(" V4L2_CID_CONTRAST\n"); + break; + case V4L2_CID_SATURATION: + pr_debug(" V4L2_CID_SATURATION\n"); + break; + case V4L2_CID_HUE: + pr_debug(" V4L2_CID_HUE\n"); + break; + case V4L2_CID_AUTO_WHITE_BALANCE: + pr_debug( + " V4L2_CID_AUTO_WHITE_BALANCE\n"); + break; + case V4L2_CID_DO_WHITE_BALANCE: + pr_debug( + " V4L2_CID_DO_WHITE_BALANCE\n"); + break; + case V4L2_CID_RED_BALANCE: + pr_debug(" V4L2_CID_RED_BALANCE\n"); + break; + case V4L2_CID_BLUE_BALANCE: + pr_debug(" V4L2_CID_BLUE_BALANCE\n"); + break; + case V4L2_CID_GAMMA: + pr_debug(" V4L2_CID_GAMMA\n"); + break; + case V4L2_CID_EXPOSURE: + pr_debug(" V4L2_CID_EXPOSURE\n"); + break; + case V4L2_CID_AUTOGAIN: + pr_debug(" V4L2_CID_AUTOGAIN\n"); + break; + case V4L2_CID_GAIN: + pr_debug(" V4L2_CID_GAIN\n"); + break; + case V4L2_CID_HFLIP: + pr_debug(" V4L2_CID_HFLIP\n"); + break; + case V4L2_CID_VFLIP: + pr_debug(" V4L2_CID_VFLIP\n"); + break; + default: + pr_debug(" Default case\n"); + retval = -EPERM; + break; + } + + return retval; +} + +/*! + * ioctl_init - V4L2 sensor interface handler for VIDIOC_INT_INIT + * @s: pointer to standard V4L2 device structure + */ +static int ioctl_init(struct v4l2_int_device *s) +{ + pr_debug("In ov2640:ioctl_init\n"); + + return 0; +} + +/*! + * ioctl_dev_init - V4L2 sensor interface handler for vidioc_int_dev_init_num + * @s: pointer to standard V4L2 device structure + * + * Initialise the device when slave attaches to the master. + */ +static int ioctl_dev_init(struct v4l2_int_device *s) +{ + struct sensor *sensor = s->priv; + u32 tgt_xclk; /* target xclk */ + + pr_debug("In ov2640:ioctl_dev_init\n"); + + gpio_sensor_active(); + ov2640_data.on = true; + + tgt_xclk = ov2640_data.mclk; + tgt_xclk = min(tgt_xclk, (u32)OV2640_XCLK_MAX); + tgt_xclk = max(tgt_xclk, (u32)OV2640_XCLK_MIN); + ov2640_data.mclk = tgt_xclk; + + pr_debug(" Setting mclk to %d MHz\n", + tgt_xclk / 1000000); + set_mclk_rate(&ov2640_data.mclk); + + return ov2640_init_mode(sensor); +} + +/*! + * ioctl_dev_exit - V4L2 sensor interface handler for vidioc_int_dev_exit_num + * @s: pointer to standard V4L2 device structure + * + * Delinitialise the device when slave detaches to the master. + */ +static int ioctl_dev_exit(struct v4l2_int_device *s) +{ + pr_debug("In ov2640:ioctl_dev_exit\n"); + + gpio_sensor_inactive(); + + return 0; +} + +/*! + * This structure defines all the ioctls for this module and links them to the + * enumeration. + */ +static struct v4l2_int_ioctl_desc ov2640_ioctl_desc[] = { + {vidioc_int_dev_init_num, (v4l2_int_ioctl_func*)ioctl_dev_init}, + {vidioc_int_dev_exit_num, (v4l2_int_ioctl_func*)ioctl_dev_exit}, + {vidioc_int_s_power_num, (v4l2_int_ioctl_func*)ioctl_s_power}, + {vidioc_int_g_ifparm_num, (v4l2_int_ioctl_func*)ioctl_g_ifparm}, +/* {vidioc_int_g_needs_reset_num, + (v4l2_int_ioctl_func *)ioctl_g_needs_reset}, */ +/* {vidioc_int_reset_num, (v4l2_int_ioctl_func *)ioctl_reset}, */ + {vidioc_int_init_num, (v4l2_int_ioctl_func*)ioctl_init}, +/* {vidioc_int_enum_fmt_cap_num, + (v4l2_int_ioctl_func *)ioctl_enum_fmt_cap}, */ +/* {vidioc_int_try_fmt_cap_num, + (v4l2_int_ioctl_func *)ioctl_try_fmt_cap}, */ + {vidioc_int_g_fmt_cap_num, (v4l2_int_ioctl_func*)ioctl_g_fmt_cap}, + {vidioc_int_s_fmt_cap_num, (v4l2_int_ioctl_func*)ioctl_s_fmt_cap}, + {vidioc_int_g_parm_num, (v4l2_int_ioctl_func*)ioctl_g_parm}, + {vidioc_int_s_parm_num, (v4l2_int_ioctl_func*)ioctl_s_parm}, +/* {vidioc_int_queryctrl_num, (v4l2_int_ioctl_func *)ioctl_queryctrl}, */ + {vidioc_int_g_ctrl_num, (v4l2_int_ioctl_func*)ioctl_g_ctrl}, + {vidioc_int_s_ctrl_num, (v4l2_int_ioctl_func*)ioctl_s_ctrl}, +}; + +static struct v4l2_int_slave ov2640_slave = { + .ioctls = ov2640_ioctl_desc, + .num_ioctls = ARRAY_SIZE(ov2640_ioctl_desc), +}; + +static struct v4l2_int_device ov2640_int_device = { + .module = THIS_MODULE, + .name = "ov2640", + .type = v4l2_int_type_slave, + .u = { + .slave = &ov2640_slave, + }, +}; + +/*! + * ov2640 I2C attach function + * Function set in i2c_driver struct. + * Called by insmod ov2640_camera.ko. + * + * @param client struct i2c_client* + * @return Error code indicating success or failure + */ +static int ov2640_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + int retval; + struct mxc_camera_platform_data *plat_data = client->dev.platform_data; + + pr_debug("In ov2640_probe (RH_BT565)\n"); + + /* Set initial values for the sensor struct. */ + memset(&ov2640_data, 0, sizeof(ov2640_data)); + ov2640_data.i2c_client = client; + ov2640_data.mclk = 24000000; + ov2640_data.mclk = plat_data->mclk; + ov2640_data.pix.pixelformat = V4L2_PIX_FMT_UYVY; + ov2640_data.pix.width = 800; + ov2640_data.pix.height = 600; + ov2640_data.streamcap.capability = V4L2_MODE_HIGHQUALITY + | V4L2_CAP_TIMEPERFRAME; + ov2640_data.streamcap.capturemode = 0; + ov2640_data.streamcap.timeperframe.denominator = DEFAULT_FPS; + ov2640_data.streamcap.timeperframe.numerator = 1; + + if (plat_data->io_regulator) { + io_regulator = + regulator_get(&client->dev, plat_data->io_regulator); + if (!IS_ERR(io_regulator)) { + regulator_set_voltage(io_regulator, 2800000, 2800000); + if (regulator_enable(io_regulator) != 0) { + pr_err("%s:io set voltage error\n", __func__); + goto err1; + } else { + dev_dbg(&client->dev, + "%s:io set voltage ok\n", __func__); + } + } else + io_regulator = NULL; + } + + if (plat_data->core_regulator) { + core_regulator = + regulator_get(&client->dev, plat_data->core_regulator); + if (!IS_ERR(core_regulator)) { + regulator_set_voltage(core_regulator, + 1300000, 1300000); + if (regulator_enable(core_regulator) != 0) { + pr_err("%s:core set voltage error\n", __func__); + goto err2; + } else { + dev_dbg(&client->dev, + "%s:core set voltage ok\n", __func__); + } + } else + core_regulator = NULL; + } + + if (plat_data->analog_regulator) { + analog_regulator = + regulator_get(&client->dev, plat_data->analog_regulator); + if (!IS_ERR(analog_regulator)) { + regulator_set_voltage(analog_regulator, 2000000, 2000000); + if (regulator_enable(analog_regulator) != 0) { + pr_err("%s:analog set voltage error\n", + __func__); + goto err3; + } else { + dev_dbg(&client->dev, + "%s:analog set voltage ok\n", __func__); + } + } else + analog_regulator = NULL; + } + + if (plat_data->gpo_regulator) { + gpo_regulator = + regulator_get(&client->dev, plat_data->gpo_regulator); + if (!IS_ERR(gpo_regulator)) { + if (regulator_enable(gpo_regulator) != 0) { + pr_err("%s:gpo3 set voltage error\n", __func__); + goto err4; + } else { + dev_dbg(&client->dev, + "%s:gpo3 set voltage ok\n", __func__); + } + } else + gpo_regulator = NULL; + } + + /* This function attaches this structure to the /dev/video0 device. + * The pointer in priv points to the ov2640_data structure here.*/ + ov2640_int_device.priv = &ov2640_data; + retval = v4l2_int_device_register(&ov2640_int_device); + + return retval; + +err4: + if (analog_regulator) { + regulator_disable(analog_regulator); + regulator_put(analog_regulator); + } +err3: + if (core_regulator) { + regulator_disable(core_regulator); + regulator_put(core_regulator); + } +err2: + if (io_regulator) { + regulator_disable(io_regulator); + regulator_put(io_regulator); + } +err1: + return -1; +} + +/*! + * ov2640 I2C detach function + * Called on rmmod ov2640_camera.ko + * + * @param client struct i2c_client* + * @return Error code indicating success or failure + */ +static int ov2640_remove(struct i2c_client *client) +{ + pr_debug("In ov2640_remove\n"); + + v4l2_int_device_unregister(&ov2640_int_device); + + if (gpo_regulator) { + regulator_disable(gpo_regulator); + regulator_put(gpo_regulator); + } + + if (analog_regulator) { + regulator_disable(analog_regulator); + regulator_put(analog_regulator); + } + + if (core_regulator) { + regulator_disable(core_regulator); + regulator_put(core_regulator); + } + + if (io_regulator) { + regulator_disable(io_regulator); + regulator_put(io_regulator); + } + + return 0; +} + +static const struct i2c_device_id ov2640_id[] = { + {"ov2640", 0}, + {}, +}; + +MODULE_DEVICE_TABLE(i2c, ov2640_id); + +static struct i2c_driver ov2640_i2c_driver = { + .driver = { + .owner = THIS_MODULE, + .name = "ov2640", + }, + .probe = ov2640_probe, + .remove = ov2640_remove, + .id_table = ov2640_id, +/* To add power management add .suspend and .resume functions */ +}; + +/*! + * ov2640 init function + * Called by insmod ov2640_camera.ko. + * + * @return Error code indicating success or failure + */ +static __init int ov2640_init(void) +{ + u8 err; + + pr_debug("In ov2640_init\n"); + + err = i2c_add_driver(&ov2640_i2c_driver); + if (err != 0) + pr_err("%s:driver registration failed, error=%d \n", + __func__, err); + + return err; +} + +/*! + * OV2640 cleanup function + * Called on rmmod ov2640_camera.ko + * + * @return Error code indicating success or failure + */ +static void __exit ov2640_clean(void) +{ + pr_debug("In ov2640_clean\n"); + i2c_del_driver(&ov2640_i2c_driver); +} + +module_init(ov2640_init); +module_exit(ov2640_clean); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("OV2640 Camera Driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/media/video/mxc/capture/ov3640.c b/drivers/media/video/mxc/capture/ov3640.c new file mode 100644 index 000000000000..e6d869d259b0 --- /dev/null +++ b/drivers/media/video/mxc/capture/ov3640.c @@ -0,0 +1,1429 @@ +/* + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "mxc_v4l2_capture.h" + +#define OV3640_VOLTAGE_ANALOG 2800000 +#define OV3640_VOLTAGE_DIGITAL_CORE 1500000 +#define OV3640_VOLTAGE_DIGITAL_IO 1800000 + + +/* Check these values! */ +#define MIN_FPS 15 +#define MAX_FPS 30 +#define DEFAULT_FPS 30 + +#define OV3640_XCLK_MIN 6000000 +#define OV3640_XCLK_MAX 24000000 + +enum ov3640_mode { + ov3640_mode_MIN = 0, + ov3640_mode_VGA_640_480 = 0, + ov3640_mode_QVGA_320_240 = 1, + ov3640_mode_XGA_1024_768 = 2, + ov3640_mode_QXGA_2048_1536 = 3, + ov3640_mode_NTSC_720_480 = 4, + ov3640_mode_PAL_720_576 = 5, + ov3640_mode_MAX = 5 +}; + +enum ov3640_frame_rate { + ov3640_15_fps, + ov3640_30_fps +}; + +struct reg_value { + u16 u16RegAddr; + u8 u8Val; + u8 u8Mask; + u32 u32Delay_ms; +}; + +struct ov3640_mode_info { + enum ov3640_mode mode; + u32 width; + u32 height; + struct reg_value *init_data_ptr; + u32 init_data_size; +}; + +/*! + * Maintains the information on the current state of the sesor. + */ +struct sensor { + const struct ov3640_platform_data *platform_data; + struct v4l2_int_device *v4l2_int_device; + struct i2c_client *i2c_client; + struct v4l2_pix_format pix; + struct v4l2_captureparm streamcap; + bool on; + + /* control settings */ + int brightness; + int hue; + int contrast; + int saturation; + int red; + int green; + int blue; + int ae_mode; + + u32 mclk; + int csi; +} ov3640_data; + +static struct reg_value ov3640_setting_15fps_QXGA_2048_1536[] = { +#if 0 + /* The true 15fps QXGA setting. */ + {0x3012, 0x80, 0, 0}, {0x304d, 0x41, 0, 0}, {0x3087, 0x16, 0, 0}, + {0x30aa, 0x45, 0, 0}, {0x30b0, 0xff, 0, 0}, {0x30b1, 0xff, 0, 0}, + {0x30b2, 0x13, 0, 0}, {0x30d7, 0x10, 0, 0}, {0x309e, 0x00, 0, 0}, + {0x3602, 0x26, 0, 0}, {0x3603, 0x4D, 0, 0}, {0x364c, 0x04, 0, 0}, + {0x360c, 0x12, 0, 0}, {0x361e, 0x00, 0, 0}, {0x361f, 0x11, 0, 0}, + {0x3633, 0x03, 0, 0}, {0x3629, 0x3c, 0, 0}, {0x300e, 0x33, 0, 0}, + {0x300f, 0x21, 0, 0}, {0x3010, 0x20, 0, 0}, {0x3011, 0x00, 0, 0}, + {0x304c, 0x81, 0, 0}, {0x3029, 0x47, 0, 0}, {0x3070, 0x00, 0, 0}, + {0x3071, 0xEC, 0, 0}, {0x301C, 0x06, 0, 0}, {0x3072, 0x00, 0, 0}, + {0x3073, 0xC5, 0, 0}, {0x301D, 0x07, 0, 0}, {0x3018, 0x38, 0, 0}, + {0x3019, 0x30, 0, 0}, {0x301a, 0x61, 0, 0}, {0x307d, 0x00, 0, 0}, + {0x3087, 0x02, 0, 0}, {0x3082, 0x20, 0, 0}, {0x303c, 0x08, 0, 0}, + {0x303d, 0x18, 0, 0}, {0x303e, 0x06, 0, 0}, {0x303F, 0x0c, 0, 0}, + {0x3030, 0x62, 0, 0}, {0x3031, 0x26, 0, 0}, {0x3032, 0xe6, 0, 0}, + {0x3033, 0x6e, 0, 0}, {0x3034, 0xea, 0, 0}, {0x3035, 0xae, 0, 0}, + {0x3036, 0xa6, 0, 0}, {0x3037, 0x6a, 0, 0}, {0x3015, 0x12, 0, 0}, + {0x3014, 0x04, 0, 0}, {0x3013, 0xf7, 0, 0}, {0x3104, 0x02, 0, 0}, + {0x3105, 0xfd, 0, 0}, {0x3106, 0x00, 0, 0}, {0x3107, 0xff, 0, 0}, + {0x3308, 0xa5, 0, 0}, {0x3316, 0xff, 0, 0}, {0x3317, 0x00, 0, 0}, + {0x3087, 0x02, 0, 0}, {0x3082, 0x20, 0, 0}, {0x3300, 0x13, 0, 0}, + {0x3301, 0xd6, 0, 0}, {0x3302, 0xef, 0, 0}, {0x30b8, 0x20, 0, 0}, + {0x30b9, 0x17, 0, 0}, {0x30ba, 0x04, 0, 0}, {0x30bb, 0x08, 0, 0}, + {0x3100, 0x02, 0, 0}, {0x3304, 0x00, 0, 0}, {0x3400, 0x00, 0, 0}, + {0x3404, 0x02, 0, 0}, {0x3020, 0x01, 0, 0}, {0x3021, 0x1d, 0, 0}, + {0x3022, 0x00, 0, 0}, {0x3023, 0x0a, 0, 0}, {0x3024, 0x08, 0, 0}, + {0x3025, 0x18, 0, 0}, {0x3026, 0x06, 0, 0}, {0x3027, 0x0c, 0, 0}, + {0x335f, 0x68, 0, 0}, {0x3360, 0x18, 0, 0}, {0x3361, 0x0c, 0, 0}, + {0x3362, 0x68, 0, 0}, {0x3363, 0x08, 0, 0}, {0x3364, 0x04, 0, 0}, + {0x3403, 0x42, 0, 0}, {0x3088, 0x08, 0, 0}, {0x3089, 0x00, 0, 0}, + {0x308a, 0x06, 0, 0}, {0x308b, 0x00, 0, 0}, {0x3507, 0x06, 0, 0}, + {0x350a, 0x4f, 0, 0}, {0x3600, 0xc4, 0, 0}, +#endif + /* + * Only support 7.5fps for QXGA to workaround screen tearing issue + * for 15fps when capturing still image. + */ + {0x3012, 0x80, 0, 0}, {0x304d, 0x45, 0, 0}, {0x30a7, 0x5e, 0, 0}, + {0x3087, 0x16, 0, 0}, {0x309c, 0x1a, 0, 0}, {0x30a2, 0xe4, 0, 0}, + {0x30aa, 0x42, 0, 0}, {0x30b0, 0xff, 0, 0}, {0x30b1, 0xff, 0, 0}, + {0x30b2, 0x10, 0, 0}, {0x300e, 0x32, 0, 0}, {0x300f, 0x21, 0, 0}, + {0x3010, 0x20, 0, 0}, {0x3011, 0x00, 0, 0}, {0x304c, 0x81, 0, 0}, + {0x30d7, 0x10, 0, 0}, {0x30d9, 0x0d, 0, 0}, {0x30db, 0x08, 0, 0}, + {0x3016, 0x82, 0, 0}, {0x3018, 0x38, 0, 0}, {0x3019, 0x30, 0, 0}, + {0x301a, 0x61, 0, 0}, {0x307d, 0x00, 0, 0}, {0x3087, 0x02, 0, 0}, + {0x3082, 0x20, 0, 0}, {0x3015, 0x12, 0, 0}, {0x3014, 0x04, 0, 0}, + {0x3013, 0xf7, 0, 0}, {0x303c, 0x08, 0, 0}, {0x303d, 0x18, 0, 0}, + {0x303e, 0x06, 0, 0}, {0x303f, 0x0c, 0, 0}, {0x3030, 0x62, 0, 0}, + {0x3031, 0x26, 0, 0}, {0x3032, 0xe6, 0, 0}, {0x3033, 0x6e, 0, 0}, + {0x3034, 0xea, 0, 0}, {0x3035, 0xae, 0, 0}, {0x3036, 0xa6, 0, 0}, + {0x3037, 0x6a, 0, 0}, {0x3104, 0x02, 0, 0}, {0x3105, 0xfd, 0, 0}, + {0x3106, 0x00, 0, 0}, {0x3107, 0xff, 0, 0}, {0x3300, 0x12, 0, 0}, + {0x3301, 0xde, 0, 0}, {0x3302, 0xcf, 0, 0}, {0x3312, 0x26, 0, 0}, + {0x3314, 0x42, 0, 0}, {0x3313, 0x2b, 0, 0}, {0x3315, 0x42, 0, 0}, + {0x3310, 0xd0, 0, 0}, {0x3311, 0xbd, 0, 0}, {0x330c, 0x18, 0, 0}, + {0x330d, 0x18, 0, 0}, {0x330e, 0x56, 0, 0}, {0x330f, 0x5c, 0, 0}, + {0x330b, 0x1c, 0, 0}, {0x3306, 0x5c, 0, 0}, {0x3307, 0x11, 0, 0}, + {0x336a, 0x52, 0, 0}, {0x3370, 0x46, 0, 0}, {0x3376, 0x38, 0, 0}, + {0x30b8, 0x20, 0, 0}, {0x30b9, 0x17, 0, 0}, {0x30ba, 0x04, 0, 0}, + {0x30bb, 0x08, 0, 0}, {0x3507, 0x06, 0, 0}, {0x350a, 0x4f, 0, 0}, + {0x3100, 0x02, 0, 0}, {0x3301, 0xde, 0, 0}, {0x3304, 0x00, 0, 0}, + {0x3400, 0x00, 0, 0}, {0x3404, 0x02, 0, 0}, {0x3600, 0xc4, 0, 0}, + {0x3088, 0x08, 0, 0}, {0x3089, 0x00, 0, 0}, {0x308a, 0x06, 0, 0}, + {0x308b, 0x00, 0, 0}, {0x308d, 0x04, 0, 0}, {0x3086, 0x03, 0, 0}, + {0x3086, 0x00, 0, 0}, {0x3011, 0x01, 0, 0}, +}; + +static struct reg_value ov3640_setting_15fps_XGA_1024_768[] = { + {0x3012, 0x80, 0, 0}, {0x304d, 0x45, 0, 0}, {0x30a7, 0x5e, 0, 0}, + {0x3087, 0x16, 0, 0}, {0x309c, 0x1a, 0, 0}, {0x30a2, 0xe4, 0, 0}, + {0x30aa, 0x42, 0, 0}, {0x30b0, 0xff, 0, 0}, {0x30b1, 0xff, 0, 0}, + {0x30b2, 0x10, 0, 0}, {0x300e, 0x32, 0, 0}, {0x300f, 0x21, 0, 0}, + {0x3010, 0x20, 0, 0}, {0x3011, 0x00, 0, 0}, {0x304c, 0x81, 0, 0}, + {0x3016, 0x82, 0, 0}, {0x3018, 0x38, 0, 0}, {0x3019, 0x30, 0, 0}, + {0x301a, 0x61, 0, 0}, {0x307d, 0x00, 0, 0}, {0x3087, 0x02, 0, 0}, + {0x3082, 0x20, 0, 0}, {0x3015, 0x12, 0, 0}, {0x3014, 0x04, 0, 0}, + {0x3013, 0xf7, 0, 0}, {0x303c, 0x08, 0, 0}, {0x303d, 0x18, 0, 0}, + {0x303e, 0x06, 0, 0}, {0x303f, 0x0c, 0, 0}, {0x3030, 0x62, 0, 0}, + {0x3031, 0x26, 0, 0}, {0x3032, 0xe6, 0, 0}, {0x3033, 0x6e, 0, 0}, + {0x3034, 0xea, 0, 0}, {0x3035, 0xae, 0, 0}, {0x3036, 0xa6, 0, 0}, + {0x3037, 0x6a, 0, 0}, {0x3104, 0x02, 0, 0}, {0x3105, 0xfd, 0, 0}, + {0x3106, 0x00, 0, 0}, {0x3107, 0xff, 0, 0}, {0x3300, 0x12, 0, 0}, + {0x3301, 0xde, 0, 0}, {0x3302, 0xcf, 0, 0}, {0x3312, 0x26, 0, 0}, + {0x3314, 0x42, 0, 0}, {0x3313, 0x2b, 0, 0}, {0x3315, 0x42, 0, 0}, + {0x3310, 0xd0, 0, 0}, {0x3311, 0xbd, 0, 0}, {0x330c, 0x18, 0, 0}, + {0x330d, 0x18, 0, 0}, {0x330e, 0x56, 0, 0}, {0x330f, 0x5c, 0, 0}, + {0x330b, 0x1c, 0, 0}, {0x3306, 0x5c, 0, 0}, {0x3307, 0x11, 0, 0}, + {0x336a, 0x52, 0, 0}, {0x3370, 0x46, 0, 0}, {0x3376, 0x38, 0, 0}, + {0x30b8, 0x20, 0, 0}, {0x30b9, 0x17, 0, 0}, {0x30ba, 0x04, 0, 0}, + {0x30bb, 0x08, 0, 0}, {0x3507, 0x06, 0, 0}, {0x350a, 0x4f, 0, 0}, + {0x3100, 0x02, 0, 0}, {0x3301, 0xde, 0, 0}, {0x3304, 0x00, 0, 0}, + {0x3400, 0x01, 0, 0}, {0x3404, 0x1d, 0, 0}, {0x3600, 0xc4, 0, 0}, + {0x3302, 0xef, 0, 0}, {0x3020, 0x01, 0, 0}, {0x3021, 0x1d, 0, 0}, + {0x3022, 0x00, 0, 0}, {0x3023, 0x0a, 0, 0}, {0x3024, 0x08, 0, 0}, + {0x3025, 0x00, 0, 0}, {0x3026, 0x06, 0, 0}, {0x3027, 0x00, 0, 0}, + {0x335f, 0x68, 0, 0}, {0x3360, 0x00, 0, 0}, {0x3361, 0x00, 0, 0}, + {0x3362, 0x34, 0, 0}, {0x3363, 0x00, 0, 0}, {0x3364, 0x00, 0, 0}, + {0x3403, 0x00, 0, 0}, {0x3088, 0x04, 0, 0}, {0x3089, 0x00, 0, 0}, + {0x308a, 0x03, 0, 0}, {0x308b, 0x00, 0, 0}, {0x307c, 0x10, 0, 0}, + {0x3090, 0xc0, 0, 0}, {0x304c, 0x84, 0, 0}, {0x308d, 0x04, 0, 0}, + {0x3086, 0x03, 0, 0}, {0x3086, 0x00, 0, 0}, {0x3011, 0x01, 0, 0}, +}; + +static struct reg_value ov3640_setting_30fps_XGA_1024_768[] = { + {0x0, 0x0, 0} +}; + +static struct reg_value ov3640_setting_15fps_VGA_640_480[] = { + {0x3012, 0x80, 0, 0}, {0x304d, 0x45, 0, 0}, {0x30a7, 0x5e, 0, 0}, + {0x3087, 0x16, 0, 0}, {0x309c, 0x1a, 0, 0}, {0x30a2, 0xe4, 0, 0}, + {0x30aa, 0x42, 0, 0}, {0x30b0, 0xff, 0, 0}, {0x30b1, 0xff, 0, 0}, + {0x30b2, 0x10, 0, 0}, {0x300e, 0x32, 0, 0}, {0x300f, 0x21, 0, 0}, + {0x3010, 0x20, 0, 0}, {0x3011, 0x00, 0, 0}, {0x304c, 0x81, 0, 0}, + {0x30d7, 0x10, 0, 0}, {0x30d9, 0x0d, 0, 0}, {0x30db, 0x08, 0, 0}, + {0x3016, 0x82, 0, 0}, {0x3018, 0x38, 0, 0}, {0x3019, 0x30, 0, 0}, + {0x301a, 0x61, 0, 0}, {0x307d, 0x00, 0, 0}, {0x3087, 0x02, 0, 0}, + {0x3082, 0x20, 0, 0}, {0x3015, 0x12, 0, 0}, {0x3014, 0x04, 0, 0}, + {0x3013, 0xf7, 0, 0}, {0x303c, 0x08, 0, 0}, {0x303d, 0x18, 0, 0}, + {0x303e, 0x06, 0, 0}, {0x303f, 0x0c, 0, 0}, {0x3030, 0x62, 0, 0}, + {0x3031, 0x26, 0, 0}, {0x3032, 0xe6, 0, 0}, {0x3033, 0x6e, 0, 0}, + {0x3034, 0xea, 0, 0}, {0x3035, 0xae, 0, 0}, {0x3036, 0xa6, 0, 0}, + {0x3037, 0x6a, 0, 0}, {0x3104, 0x02, 0, 0}, {0x3105, 0xfd, 0, 0}, + {0x3106, 0x00, 0, 0}, {0x3107, 0xff, 0, 0}, {0x3300, 0x12, 0, 0}, + {0x3301, 0xde, 0, 0}, {0x3302, 0xcf, 0, 0}, {0x3312, 0x26, 0, 0}, + {0x3314, 0x42, 0, 0}, {0x3313, 0x2b, 0, 0}, {0x3315, 0x42, 0, 0}, + {0x3310, 0xd0, 0, 0}, {0x3311, 0xbd, 0, 0}, {0x330c, 0x18, 0, 0}, + {0x330d, 0x18, 0, 0}, {0x330e, 0x56, 0, 0}, {0x330f, 0x5c, 0, 0}, + {0x330b, 0x1c, 0, 0}, {0x3306, 0x5c, 0, 0}, {0x3307, 0x11, 0, 0}, + {0x336a, 0x52, 0, 0}, {0x3370, 0x46, 0, 0}, {0x3376, 0x38, 0, 0}, + {0x30b8, 0x20, 0, 0}, {0x30b9, 0x17, 0, 0}, {0x30ba, 0x04, 0, 0}, + {0x30bb, 0x08, 0, 0}, {0x3507, 0x06, 0, 0}, {0x350a, 0x4f, 0, 0}, + {0x3100, 0x02, 0, 0}, {0x3301, 0xde, 0, 0}, {0x3304, 0x00, 0, 0}, + {0x3400, 0x00, 0, 0}, {0x3404, 0x42, 0, 0}, {0x3600, 0xc4, 0, 0}, + {0x3302, 0xef, 0, 0}, {0x3020, 0x01, 0, 0}, {0x3021, 0x1d, 0, 0}, + {0x3022, 0x00, 0, 0}, {0x3023, 0x0a, 0, 0}, {0x3024, 0x08, 0, 0}, + {0x3025, 0x00, 0, 0}, {0x3026, 0x06, 0, 0}, {0x3027, 0x00, 0, 0}, + {0x335f, 0x68, 0, 0}, {0x3360, 0x00, 0, 0}, {0x3361, 0x00, 0, 0}, + {0x3362, 0x12, 0, 0}, {0x3363, 0x80, 0, 0}, {0x3364, 0xe0, 0, 0}, + {0x3403, 0x00, 0, 0}, {0x3088, 0x02, 0, 0}, {0x3089, 0x80, 0, 0}, + {0x308a, 0x01, 0, 0}, {0x308b, 0xe0, 0, 0}, {0x307c, 0x10, 0, 0}, + {0x3090, 0xc0, 0, 0}, {0x304c, 0x84, 0, 0}, {0x308d, 0x04, 0, 0}, + {0x3086, 0x03, 0, 0}, {0x3086, 0x00, 0, 0}, {0x3011, 0x00, 0, 0}, +}; + +static struct reg_value ov3640_setting_30fps_VGA_640_480[] = { + {0x3012, 0x80, 0, 0}, {0x304d, 0x45, 0, 0}, {0x30a7, 0x5e, 0, 0}, + {0x3087, 0x16, 0, 0}, {0x309c, 0x1a, 0, 0}, {0x30a2, 0xe4, 0, 0}, + {0x30aa, 0x42, 0, 0}, {0x30b0, 0xff, 0, 0}, {0x30b1, 0xff, 0, 0}, + {0x30b2, 0x10, 0, 0}, {0x300e, 0x32, 0, 0}, {0x300f, 0x21, 0, 0}, + {0x3010, 0x20, 0, 0}, {0x3011, 0x01, 0, 0}, {0x304c, 0x82, 0, 0}, + {0x30d7, 0x10, 0, 0}, {0x30d9, 0x0d, 0, 0}, {0x30db, 0x08, 0, 0}, + {0x3016, 0x82, 0, 0}, {0x3018, 0x38, 0, 0}, {0x3019, 0x30, 0, 0}, + {0x301a, 0x61, 0, 0}, {0x307d, 0x00, 0, 0}, {0x3087, 0x02, 0, 0}, + {0x3082, 0x20, 0, 0}, {0x3015, 0x12, 0, 0}, {0x3014, 0x0c, 0, 0}, + {0x3013, 0xf7, 0, 0}, {0x303c, 0x08, 0, 0}, {0x303d, 0x18, 0, 0}, + {0x303e, 0x06, 0, 0}, {0x303f, 0x0c, 0, 0}, {0x3030, 0x62, 0, 0}, + {0x3031, 0x26, 0, 0}, {0x3032, 0xe6, 0, 0}, {0x3033, 0x6e, 0, 0}, + {0x3034, 0xea, 0, 0}, {0x3035, 0xae, 0, 0}, {0x3036, 0xa6, 0, 0}, + {0x3037, 0x6a, 0, 0}, {0x3104, 0x02, 0, 0}, {0x3105, 0xfd, 0, 0}, + {0x3106, 0x00, 0, 0}, {0x3107, 0xff, 0, 0}, {0x3300, 0x12, 0, 0}, + {0x3301, 0xde, 0, 0}, {0x3302, 0xcf, 0, 0}, {0x3312, 0x26, 0, 0}, + {0x3314, 0x42, 0, 0}, {0x3313, 0x2b, 0, 0}, {0x3315, 0x42, 0, 0}, + {0x3310, 0xd0, 0, 0}, {0x3311, 0xbd, 0, 0}, {0x330c, 0x18, 0, 0}, + {0x330d, 0x18, 0, 0}, {0x330e, 0x56, 0, 0}, {0x330f, 0x5c, 0, 0}, + {0x330b, 0x1c, 0, 0}, {0x3306, 0x5c, 0, 0}, {0x3307, 0x11, 0, 0}, + {0x336a, 0x52, 0, 0}, {0x3370, 0x46, 0, 0}, {0x3376, 0x38, 0, 0}, + {0x3300, 0x13, 0, 0}, {0x30b8, 0x20, 0, 0}, {0x30b9, 0x17, 0, 0}, + {0x30ba, 0x04, 0, 0}, {0x30bb, 0x08, 0, 0}, {0x3100, 0x02, 0, 0}, + {0x3301, 0x10, 0x30, 0}, {0x3304, 0x00, 0x03, 0}, {0x3400, 0x00, 0, 0}, + {0x3404, 0x02, 0, 0}, {0x3600, 0xc0, 0, 0}, {0x308d, 0x04, 0, 0}, + {0x3086, 0x03, 0, 0}, {0x3086, 0x00, 0, 0}, {0x3012, 0x10, 0, 0}, + {0x3023, 0x06, 0, 0}, {0x3026, 0x03, 0, 0}, {0x3027, 0x04, 0, 0}, + {0x302a, 0x03, 0, 0}, {0x302b, 0x10, 0, 0}, {0x3075, 0x24, 0, 0}, + {0x300d, 0x01, 0, 0}, {0x30d7, 0x80, 0x80, 0}, {0x3069, 0x00, 0x40, 0}, + {0x303e, 0x00, 0, 0}, {0x303f, 0xc0, 0, 0}, {0x3302, 0x20, 0x20, 0}, + {0x335f, 0x34, 0, 0}, {0x3360, 0x0c, 0, 0}, {0x3361, 0x04, 0, 0}, + {0x3362, 0x12, 0, 0}, {0x3363, 0x88, 0, 0}, {0x3364, 0xe4, 0, 0}, + {0x3403, 0x42, 0, 0}, {0x3088, 0x02, 0, 0}, {0x3089, 0x80, 0, 0}, + {0x308a, 0x01, 0, 0}, {0x308b, 0xe0, 0, 0}, {0x3362, 0x12, 0, 0}, + {0x3363, 0x88, 0, 0}, {0x3364, 0xe4, 0, 0}, {0x3403, 0x42, 0, 0}, + {0x3088, 0x02, 0, 0}, {0x3089, 0x80, 0, 0}, {0x308a, 0x01, 0, 0}, + {0x308b, 0xe0, 0, 0}, {0x300e, 0x37, 0, 0}, {0x300f, 0xe1, 0, 0}, + {0x3010, 0x22, 0, 0}, {0x3011, 0x01, 0, 0}, {0x304c, 0x84, 0, 0}, + {0x3014, 0x04, 0, 0}, {0x3015, 0x02, 0, 0}, {0x302e, 0x00, 0, 0}, + {0x302d, 0x00, 0, 0}, +}; + +static struct reg_value ov3640_setting_15fps_QVGA_320_240[] = { + {0x3012, 0x80, 0, 0}, {0x304d, 0x45, 0, 0}, {0x30a7, 0x5e, 0, 0}, + {0x3087, 0x16, 0, 0}, {0x309c, 0x1a, 0, 0}, {0x30a2, 0xe4, 0, 0}, + {0x30aa, 0x42, 0, 0}, {0x30b0, 0xff, 0, 0}, {0x30b1, 0xff, 0, 0}, + {0x30b2, 0x10, 0, 0}, {0x300e, 0x32, 0, 0}, {0x300f, 0x21, 0, 0}, + {0x3010, 0x20, 0, 0}, {0x3011, 0x00, 0, 0}, {0x304c, 0x81, 0, 0}, + {0x30d7, 0x10, 0, 0}, {0x30d9, 0x0d, 0, 0}, {0x30db, 0x08, 0, 0}, + {0x3016, 0x82, 0, 0}, {0x3018, 0x38, 0, 0}, {0x3019, 0x30, 0, 0}, + {0x301a, 0x61, 0, 0}, {0x307d, 0x00, 0, 0}, {0x3087, 0x02, 0, 0}, + {0x3082, 0x20, 0, 0}, {0x3015, 0x12, 0, 0}, {0x3014, 0x04, 0, 0}, + {0x3013, 0xf7, 0, 0}, {0x303c, 0x08, 0, 0}, {0x303d, 0x18, 0, 0}, + {0x303e, 0x06, 0, 0}, {0x303f, 0x0c, 0, 0}, {0x3030, 0x62, 0, 0}, + {0x3031, 0x26, 0, 0}, {0x3032, 0xe6, 0, 0}, {0x3033, 0x6e, 0, 0}, + {0x3034, 0xea, 0, 0}, {0x3035, 0xae, 0, 0}, {0x3036, 0xa6, 0, 0}, + {0x3037, 0x6a, 0, 0}, {0x3104, 0x02, 0, 0}, {0x3105, 0xfd, 0, 0}, + {0x3106, 0x00, 0, 0}, {0x3107, 0xff, 0, 0}, {0x3300, 0x12, 0, 0}, + {0x3301, 0xde, 0, 0}, {0x3302, 0xcf, 0, 0}, {0x3312, 0x26, 0, 0}, + {0x3314, 0x42, 0, 0}, {0x3313, 0x2b, 0, 0}, {0x3315, 0x42, 0, 0}, + {0x3310, 0xd0, 0, 0}, {0x3311, 0xbd, 0, 0}, {0x330c, 0x18, 0, 0}, + {0x330d, 0x18, 0, 0}, {0x330e, 0x56, 0, 0}, {0x330f, 0x5c, 0, 0}, + {0x330b, 0x1c, 0, 0}, {0x3306, 0x5c, 0, 0}, {0x3307, 0x11, 0, 0}, + {0x336a, 0x52, 0, 0}, {0x3370, 0x46, 0, 0}, {0x3376, 0x38, 0, 0}, + {0x30b8, 0x20, 0, 0}, {0x30b9, 0x17, 0, 0}, {0x30ba, 0x04, 0, 0}, + {0x30bb, 0x08, 0, 0}, {0x3507, 0x06, 0, 0}, {0x350a, 0x4f, 0, 0}, + {0x3100, 0x02, 0, 0}, {0x3301, 0xde, 0, 0}, {0x3304, 0x00, 0, 0}, + {0x3400, 0x00, 0, 0}, {0x3404, 0x42, 0, 0}, {0x3600, 0xc4, 0, 0}, + {0x3302, 0xef, 0, 0}, {0x3020, 0x01, 0, 0}, {0x3021, 0x1d, 0, 0}, + {0x3022, 0x00, 0, 0}, {0x3023, 0x0a, 0, 0}, {0x3024, 0x08, 0, 0}, + {0x3025, 0x00, 0, 0}, {0x3026, 0x06, 0, 0}, {0x3027, 0x00, 0, 0}, + {0x335f, 0x68, 0, 0}, {0x3360, 0x00, 0, 0}, {0x3361, 0x00, 0, 0}, + {0x3362, 0x01, 0, 0}, {0x3363, 0x40, 0, 0}, {0x3364, 0xf0, 0, 0}, + {0x3403, 0x00, 0, 0}, {0x3088, 0x01, 0, 0}, {0x3089, 0x40, 0, 0}, + {0x308a, 0x00, 0, 0}, {0x308b, 0xf0, 0, 0}, {0x307c, 0x10, 0, 0}, + {0x3090, 0xc0, 0, 0}, {0x304c, 0x84, 0, 0}, {0x308d, 0x04, 0, 0}, + {0x3086, 0x03, 0, 0}, {0x3086, 0x00, 0, 0}, {0x3011, 0x01, 0, 0}, +}; + +static struct reg_value ov3640_setting_30fps_QVGA_320_240[] = { + {0x3012, 0x80, 0, 0}, {0x304d, 0x45, 0, 0}, {0x30a7, 0x5e, 0, 0}, + {0x3087, 0x16, 0, 0}, {0x309c, 0x1a, 0, 0}, {0x30a2, 0xe4, 0, 0}, + {0x30aa, 0x42, 0, 0}, {0x30b0, 0xff, 0, 0}, {0x30b1, 0xff, 0, 0}, + {0x30b2, 0x10, 0, 0}, {0x300e, 0x32, 0, 0}, {0x300f, 0x21, 0, 0}, + {0x3010, 0x20, 0, 0}, {0x3011, 0x01, 0, 0}, {0x304c, 0x82, 0, 0}, + {0x30d7, 0x10, 0, 0}, {0x30d9, 0x0d, 0, 0}, {0x30db, 0x08, 0, 0}, + {0x3016, 0x82, 0, 0}, {0x3018, 0x38, 0, 0}, {0x3019, 0x30, 0, 0}, + {0x301a, 0x61, 0, 0}, {0x307d, 0x00, 0, 0}, {0x3087, 0x02, 0, 0}, + {0x3082, 0x20, 0, 0}, {0x3015, 0x12, 0, 0}, {0x3014, 0x0c, 0, 0}, + {0x3013, 0xf7, 0, 0}, {0x303c, 0x08, 0, 0}, {0x303d, 0x18, 0, 0}, + {0x303e, 0x06, 0, 0}, {0x303f, 0x0c, 0, 0}, {0x3030, 0x62, 0, 0}, + {0x3031, 0x26, 0, 0}, {0x3032, 0xe6, 0, 0}, {0x3033, 0x6e, 0, 0}, + {0x3034, 0xea, 0, 0}, {0x3035, 0xae, 0, 0}, {0x3036, 0xa6, 0, 0}, + {0x3037, 0x6a, 0, 0}, {0x3104, 0x02, 0, 0}, {0x3105, 0xfd, 0, 0}, + {0x3106, 0x00, 0, 0}, {0x3107, 0xff, 0, 0}, {0x3300, 0x12, 0, 0}, + {0x3301, 0xde, 0, 0}, {0x3302, 0xcf, 0, 0}, {0x3312, 0x26, 0, 0}, + {0x3314, 0x42, 0, 0}, {0x3313, 0x2b, 0, 0}, {0x3315, 0x42, 0, 0}, + {0x3310, 0xd0, 0, 0}, {0x3311, 0xbd, 0, 0}, {0x330c, 0x18, 0, 0}, + {0x330d, 0x18, 0, 0}, {0x330e, 0x56, 0, 0}, {0x330f, 0x5c, 0, 0}, + {0x330b, 0x1c, 0, 0}, {0x3306, 0x5c, 0, 0}, {0x3307, 0x11, 0, 0}, + {0x336a, 0x52, 0, 0}, {0x3370, 0x46, 0, 0}, {0x3376, 0x38, 0, 0}, + {0x3300, 0x13, 0, 0}, {0x30b8, 0x20, 0, 0}, {0x30b9, 0x17, 0, 0}, + {0x30ba, 0x04, 0, 0}, {0x30bb, 0x08, 0, 0}, {0x3100, 0x02, 0, 0}, + {0x3301, 0x10, 0x30, 0}, {0x3304, 0x00, 0x03, 0}, {0x3400, 0x00, 0, 0}, + {0x3404, 0x02, 0, 0}, {0x3600, 0xc0, 0, 0}, {0x308d, 0x04, 0, 0}, + {0x3086, 0x03, 0, 0}, {0x3086, 0x00, 0, 0}, {0x3012, 0x10, 0, 0}, + {0x3023, 0x06, 0, 0}, {0x3026, 0x03, 0, 0}, {0x3027, 0x04, 0, 0}, + {0x302a, 0x03, 0, 0}, {0x302b, 0x10, 0, 0}, {0x3075, 0x24, 0, 0}, + {0x300d, 0x01, 0, 0}, {0x30d7, 0x80, 0x80, 0}, {0x3069, 0x00, 0x40, 0}, + {0x303e, 0x00, 0, 0}, {0x303f, 0xc0, 0, 0}, {0x3302, 0x20, 0x20, 0}, + {0x335f, 0x34, 0, 0}, {0x3360, 0x0c, 0, 0}, {0x3361, 0x04, 0, 0}, + {0x3362, 0x34, 0, 0}, {0x3363, 0x08, 0, 0}, {0x3364, 0x04, 0, 0}, + {0x3403, 0x42, 0, 0}, {0x3088, 0x04, 0, 0}, {0x3089, 0x00, 0, 0}, + {0x308a, 0x03, 0, 0}, {0x308b, 0x00, 0, 0}, {0x3362, 0x12, 0, 0}, + {0x3363, 0x88, 0, 0}, {0x3364, 0xe4, 0, 0}, {0x3403, 0x42, 0, 0}, + {0x3088, 0x02, 0, 0}, {0x3089, 0x80, 0, 0}, {0x308a, 0x01, 0, 0}, + {0x308b, 0xe0, 0, 0}, {0x300e, 0x37, 0, 0}, {0x300f, 0xe1, 0, 0}, + {0x3010, 0x22, 0, 0}, {0x3011, 0x01, 0, 0}, {0x304c, 0x84, 0, 0}, +}; + +static struct reg_value ov3640_setting_15fps_NTSC_720_480[] = { + {0x3012, 0x80, 0, 0}, {0x304d, 0x45, 0, 0}, {0x30a7, 0x5e, 0, 0}, + {0x3087, 0x16, 0, 0}, {0x309C, 0x1a, 0, 0}, {0x30a2, 0xe4, 0, 0}, + {0x30aa, 0x42, 0, 0}, {0x30b0, 0xff, 0, 0}, {0x30b1, 0xff, 0, 0}, + {0x30b2, 0x10, 0, 0}, {0x300e, 0x39, 0, 0}, {0x300f, 0x21, 0, 0}, + {0x3010, 0x20, 0, 0}, {0x304c, 0x81, 0, 0}, {0x30d7, 0x10, 0, 0}, + {0x30d9, 0x0d, 0, 0}, {0x30db, 0x08, 0, 0}, {0x3016, 0x82, 0, 0}, + {0x3018, 0x48, 0, 0}, {0x3019, 0x40, 0, 0}, {0x301a, 0x82, 0, 0}, + {0x307d, 0x00, 0, 0}, {0x3087, 0x02, 0, 0}, {0x3082, 0x20, 0, 0}, + {0x3015, 0x12, 0, 0}, {0x3014, 0x84, 0, 0}, {0x3013, 0xf7, 0, 0}, + {0x303c, 0x08, 0, 0}, {0x303d, 0x18, 0, 0}, {0x303e, 0x06, 0, 0}, + {0x303F, 0x0c, 0, 0}, {0x3030, 0x62, 0, 0}, {0x3031, 0x26, 0, 0}, + {0x3032, 0xe6, 0, 0}, {0x3033, 0x6e, 0, 0}, {0x3034, 0xea, 0, 0}, + {0x3035, 0xae, 0, 0}, {0x3036, 0xa6, 0, 0}, {0x3037, 0x6a, 0, 0}, + {0x3104, 0x02, 0, 0}, {0x3105, 0xfd, 0, 0}, {0x3106, 0x00, 0, 0}, + {0x3107, 0xff, 0, 0}, {0x3300, 0x13, 0, 0}, {0x3301, 0xde, 0, 0}, + {0x3302, 0xcf, 0, 0}, {0x3312, 0x26, 0, 0}, {0x3314, 0x42, 0, 0}, + {0x3313, 0x2b, 0, 0}, {0x3315, 0x42, 0, 0}, {0x3310, 0xd0, 0, 0}, + {0x3311, 0xbd, 0, 0}, {0x330c, 0x18, 0, 0}, {0x330d, 0x18, 0, 0}, + {0x330e, 0x56, 0, 0}, {0x330f, 0x5c, 0, 0}, {0x330b, 0x1c, 0, 0}, + {0x3306, 0x5c, 0, 0}, {0x3307, 0x11, 0, 0}, {0x336a, 0x52, 0, 0}, + {0x3370, 0x46, 0, 0}, {0x3376, 0x38, 0, 0}, {0x30b8, 0x20, 0, 0}, + {0x30b9, 0x17, 0, 0}, {0x30ba, 0x04, 0, 0}, {0x30bb, 0x08, 0, 0}, + {0x3507, 0x06, 0, 0}, {0x350a, 0x4f, 0, 0}, {0x3100, 0x02, 0, 0}, + {0x3301, 0xde, 0, 0}, {0x3304, 0xfc, 0, 0}, {0x3400, 0x00, 0, 0}, + {0x3404, 0x00, 0, 0}, {0x3600, 0xc0, 0, 0}, {0x3088, 0x08, 0, 0}, + {0x3089, 0x00, 0, 0}, {0x308a, 0x06, 0, 0}, {0x308b, 0x00, 0, 0}, + {0x308d, 0x04, 0, 0}, {0x3086, 0x03, 0, 0}, {0x3086, 0x00, 0, 0}, + {0x30a9, 0xb5, 0, 0}, {0x3317, 0x04, 0, 0}, {0x3316, 0xf8, 0, 0}, + {0x3312, 0x17, 0, 0}, {0x3314, 0x30, 0, 0}, {0x3313, 0x23, 0, 0}, + {0x3315, 0x3e, 0, 0}, {0x3311, 0x9e, 0, 0}, {0x3310, 0xc0, 0, 0}, + {0x330c, 0x18, 0, 0}, {0x330d, 0x18, 0, 0}, {0x330e, 0x5e, 0, 0}, + {0x330f, 0x6c, 0, 0}, {0x330b, 0x1c, 0, 0}, {0x3306, 0x5c, 0, 0}, + {0x3307, 0x11, 0, 0}, {0x3308, 0x25, 0, 0}, {0x3340, 0x20, 0, 0}, + {0x3341, 0x50, 0, 0}, {0x3342, 0x18, 0, 0}, {0x3343, 0x23, 0, 0}, + {0x3344, 0xad, 0, 0}, {0x3345, 0xd0, 0, 0}, {0x3346, 0xb8, 0, 0}, + {0x3347, 0xb4, 0, 0}, {0x3348, 0x04, 0, 0}, {0x3349, 0x98, 0, 0}, + {0x3355, 0x02, 0, 0}, {0x3358, 0x44, 0, 0}, {0x3359, 0x44, 0, 0}, + {0x3300, 0x13, 0, 0}, {0x3367, 0x23, 0, 0}, {0x3368, 0xBB, 0, 0}, + {0x3369, 0xD6, 0, 0}, {0x336A, 0x2A, 0, 0}, {0x336B, 0x07, 0, 0}, + {0x336C, 0x00, 0, 0}, {0x336D, 0x23, 0, 0}, {0x336E, 0xC3, 0, 0}, + {0x336F, 0xDE, 0, 0}, {0x3370, 0x2b, 0, 0}, {0x3371, 0x07, 0, 0}, + {0x3372, 0x00, 0, 0}, {0x3373, 0x23, 0, 0}, {0x3374, 0x9e, 0, 0}, + {0x3375, 0xD6, 0, 0}, {0x3376, 0x29, 0, 0}, {0x3377, 0x07, 0, 0}, + {0x3378, 0x00, 0, 0}, {0x332a, 0x1d, 0, 0}, {0x331b, 0x08, 0, 0}, + {0x331c, 0x16, 0, 0}, {0x331d, 0x2d, 0, 0}, {0x331e, 0x54, 0, 0}, + {0x331f, 0x66, 0, 0}, {0x3320, 0x73, 0, 0}, {0x3321, 0x80, 0, 0}, + {0x3322, 0x8c, 0, 0}, {0x3323, 0x95, 0, 0}, {0x3324, 0x9d, 0, 0}, + {0x3325, 0xac, 0, 0}, {0x3326, 0xb8, 0, 0}, {0x3327, 0xcc, 0, 0}, + {0x3328, 0xdd, 0, 0}, {0x3329, 0xee, 0, 0}, {0x332e, 0x04, 0, 0}, + {0x332f, 0x04, 0, 0}, {0x3331, 0x02, 0, 0}, {0x3100, 0x02, 0, 0}, + {0x3301, 0xde, 0, 0}, {0x3304, 0xfc, 0, 0}, {0x3400, 0x00, 0, 0}, + {0x3404, 0x00, 0, 0}, {0x3610, 0x40, 0, 0}, {0x304c, 0x81, 0, 0}, + {0x307C, 0x10, 0, 0}, {0x3012, 0x10, 0, 0}, {0x3023, 0x06, 0, 0}, + {0x3026, 0x03, 0, 0}, {0x3027, 0x04, 0, 0}, {0x302a, 0x03, 0, 0}, + {0x302b, 0x10, 0, 0}, {0x3075, 0x24, 0, 0}, {0x300d, 0x01, 0, 0}, + {0x30d7, 0x90, 0, 0}, {0x3069, 0x04, 0, 0}, {0x303e, 0x00, 0, 0}, + {0x303f, 0xc0, 0, 0}, {0x3302, 0xef, 0, 0}, {0x335f, 0x34, 0, 0}, + {0x3360, 0x0c, 0, 0}, {0x3361, 0x04, 0, 0}, {0x3362, 0x34, 0, 0}, + {0x3363, 0x08, 0, 0}, {0x3364, 0x04, 0, 0}, {0x3403, 0x42, 0, 0}, + {0x3088, 0x04, 0, 0}, {0x3089, 0x00, 0, 0}, {0x308a, 0x03, 0, 0}, + {0x308b, 0x00, 0, 0}, {0x300e, 0x32, 0, 0}, {0x300f, 0x21, 0, 0}, + {0x3010, 0x20, 0, 0}, {0x3011, 0x01, 0, 0}, {0x304c, 0x82, 0, 0}, + {0x3302, 0xef, 0, 0}, {0x335f, 0x34, 0, 0}, {0x3360, 0x0c, 0, 0}, + {0x3361, 0x04, 0, 0}, {0x3362, 0x23, 0, 0}, {0x3363, 0x28, 0, 0}, + {0x3364, 0x5c, 0, 0}, {0x3403, 0x42, 0, 0}, {0x3088, 0x02, 0, 0}, + {0x3089, 0xD0, 0, 0}, {0x308a, 0x01, 0, 0}, {0x308b, 0xe0, 0, 0}, + {0x304c, 0x83, 0, 0}, {0x300e, 0x39, 0, 0}, {0x300f, 0x21, 0, 0}, + {0x3011, 0x00, 0, 0}, {0x3010, 0x81, 0, 0}, {0x302e, 0x00, 0, 0}, + {0x302d, 0x00, 0, 0}, {0x3071, 0xeb, 0, 0}, {0x301C, 0x02, 0, 0}, + {0x3404, 0x02, 0, 0}, +}; + +static struct reg_value ov3640_setting_15fps_PAL_720_576[] = { + {0x3012, 0x80, 0, 0}, {0x304d, 0x45, 0, 0}, {0x30a7, 0x5e, 0, 0}, + {0x3087, 0x16, 0, 0}, {0x309C, 0x1a, 0, 0}, {0x30a2, 0xe4, 0, 0}, + {0x30aa, 0x42, 0, 0}, {0x30b0, 0xff, 0, 0}, {0x30b1, 0xff, 0, 0}, + {0x30b2, 0x10, 0, 0}, {0x300e, 0x39, 0, 0}, {0x300f, 0x21, 0, 0}, + {0x3010, 0x20, 0, 0}, {0x304c, 0x81, 0, 0}, {0x30d7, 0x10, 0, 0}, + {0x30d9, 0x0d, 0, 0}, {0x30db, 0x08, 0, 0}, {0x3016, 0x82, 0, 0}, + {0x3018, 0x48, 0, 0}, {0x3019, 0x40, 0, 0}, {0x301a, 0x82, 0, 0}, + {0x307d, 0x00, 0, 0}, {0x3087, 0x02, 0, 0}, {0x3082, 0x20, 0, 0}, + {0x3015, 0x12, 0, 0}, {0x3014, 0x84, 0, 0}, {0x3013, 0xf7, 0, 0}, + {0x303c, 0x08, 0, 0}, {0x303d, 0x18, 0, 0}, {0x303e, 0x06, 0, 0}, + {0x303F, 0x0c, 0, 0}, {0x3030, 0x62, 0, 0}, {0x3031, 0x26, 0, 0}, + {0x3032, 0xe6, 0, 0}, {0x3033, 0x6e, 0, 0}, {0x3034, 0xea, 0, 0}, + {0x3035, 0xae, 0, 0}, {0x3036, 0xa6, 0, 0}, {0x3037, 0x6a, 0, 0}, + {0x3104, 0x02, 0, 0}, {0x3105, 0xfd, 0, 0}, {0x3106, 0x00, 0, 0}, + {0x3107, 0xff, 0, 0}, {0x3300, 0x13, 0, 0}, {0x3301, 0xde, 0, 0}, + {0x3302, 0xcf, 0, 0}, {0x3312, 0x26, 0, 0}, {0x3314, 0x42, 0, 0}, + {0x3313, 0x2b, 0, 0}, {0x3315, 0x42, 0, 0}, {0x3310, 0xd0, 0, 0}, + {0x3311, 0xbd, 0, 0}, {0x330c, 0x18, 0, 0}, {0x330d, 0x18, 0, 0}, + {0x330e, 0x56, 0, 0}, {0x330f, 0x5c, 0, 0}, {0x330b, 0x1c, 0, 0}, + {0x3306, 0x5c, 0, 0}, {0x3307, 0x11, 0, 0}, {0x336a, 0x52, 0, 0}, + {0x3370, 0x46, 0, 0}, {0x3376, 0x38, 0, 0}, {0x30b8, 0x20, 0, 0}, + {0x30b9, 0x17, 0, 0}, {0x30ba, 0x04, 0, 0}, {0x30bb, 0x08, 0, 0}, + {0x3507, 0x06, 0, 0}, {0x350a, 0x4f, 0, 0}, {0x3100, 0x02, 0, 0}, + {0x3301, 0xde, 0, 0}, {0x3304, 0xfc, 0, 0}, {0x3400, 0x00, 0, 0}, + {0x3404, 0x00, 0, 0}, {0x3600, 0xc0, 0, 0}, {0x3088, 0x08, 0, 0}, + {0x3089, 0x00, 0, 0}, {0x308a, 0x06, 0, 0}, {0x308b, 0x00, 0, 0}, + {0x308d, 0x04, 0, 0}, {0x3086, 0x03, 0, 0}, {0x3086, 0x00, 0, 0}, + {0x30a9, 0xb5, 0, 0}, {0x3317, 0x04, 0, 0}, {0x3316, 0xf8, 0, 0}, + {0x3312, 0x17, 0, 0}, {0x3314, 0x30, 0, 0}, {0x3313, 0x23, 0, 0}, + {0x3315, 0x3e, 0, 0}, {0x3311, 0x9e, 0, 0}, {0x3310, 0xc0, 0, 0}, + {0x330c, 0x18, 0, 0}, {0x330d, 0x18, 0, 0}, {0x330e, 0x5e, 0, 0}, + {0x330f, 0x6c, 0, 0}, {0x330b, 0x1c, 0, 0}, {0x3306, 0x5c, 0, 0}, + {0x3307, 0x11, 0, 0}, {0x3308, 0x25, 0, 0}, {0x3340, 0x20, 0, 0}, + {0x3341, 0x50, 0, 0}, {0x3342, 0x18, 0, 0}, {0x3343, 0x23, 0, 0}, + {0x3344, 0xad, 0, 0}, {0x3345, 0xd0, 0, 0}, {0x3346, 0xb8, 0, 0}, + {0x3347, 0xb4, 0, 0}, {0x3348, 0x04, 0, 0}, {0x3349, 0x98, 0, 0}, + {0x3355, 0x02, 0, 0}, {0x3358, 0x44, 0, 0}, {0x3359, 0x44, 0, 0}, + {0x3300, 0x13, 0, 0}, {0x3367, 0x23, 0, 0}, {0x3368, 0xBB, 0, 0}, + {0x3369, 0xD6, 0, 0}, {0x336A, 0x2A, 0, 0}, {0x336B, 0x07, 0, 0}, + {0x336C, 0x00, 0, 0}, {0x336D, 0x23, 0, 0}, {0x336E, 0xC3, 0, 0}, + {0x336F, 0xDE, 0, 0}, {0x3370, 0x2b, 0, 0}, {0x3371, 0x07, 0, 0}, + {0x3372, 0x00, 0, 0}, {0x3373, 0x23, 0, 0}, {0x3374, 0x9e, 0, 0}, + {0x3375, 0xD6, 0, 0}, {0x3376, 0x29, 0, 0}, {0x3377, 0x07, 0, 0}, + {0x3378, 0x00, 0, 0}, {0x332a, 0x1d, 0, 0}, {0x331b, 0x08, 0, 0}, + {0x331c, 0x16, 0, 0}, {0x331d, 0x2d, 0, 0}, {0x331e, 0x54, 0, 0}, + {0x331f, 0x66, 0, 0}, {0x3320, 0x73, 0, 0}, {0x3321, 0x80, 0, 0}, + {0x3322, 0x8c, 0, 0}, {0x3323, 0x95, 0, 0}, {0x3324, 0x9d, 0, 0}, + {0x3325, 0xac, 0, 0}, {0x3326, 0xb8, 0, 0}, {0x3327, 0xcc, 0, 0}, + {0x3328, 0xdd, 0, 0}, {0x3329, 0xee, 0, 0}, {0x332e, 0x04, 0, 0}, + {0x332f, 0x04, 0, 0}, {0x3331, 0x02, 0, 0}, {0x3100, 0x02, 0, 0}, + {0x3301, 0xde, 0, 0}, {0x3304, 0xfc, 0, 0}, {0x3400, 0x00, 0, 0}, + {0x3404, 0x00, 0, 0}, {0x3610, 0x40, 0, 0}, {0x304c, 0x81, 0, 0}, + {0x307C, 0x10, 0, 0}, {0x3012, 0x10, 0, 0}, {0x3023, 0x06, 0, 0}, + {0x3026, 0x03, 0, 0}, {0x3027, 0x04, 0, 0}, {0x302a, 0x03, 0, 0}, + {0x302b, 0x10, 0, 0}, {0x3075, 0x24, 0, 0}, {0x300d, 0x01, 0, 0}, + {0x30d7, 0x90, 0, 0}, {0x3069, 0x04, 0, 0}, {0x303e, 0x00, 0, 0}, + {0x303f, 0xc0, 0, 0}, {0x3302, 0xef, 0, 0}, {0x335f, 0x34, 0, 0}, + {0x3360, 0x0c, 0, 0}, {0x3361, 0x04, 0, 0}, {0x3362, 0x34, 0, 0}, + {0x3363, 0x08, 0, 0}, {0x3364, 0x04, 0, 0}, {0x3403, 0x42, 0, 0}, + {0x3088, 0x04, 0, 0}, {0x3089, 0x00, 0, 0}, {0x308a, 0x03, 0, 0}, + {0x308b, 0x00, 0, 0}, {0x300e, 0x32, 0, 0}, {0x300f, 0x21, 0, 0}, + {0x3010, 0x20, 0, 0}, {0x3011, 0x01, 0, 0}, {0x304c, 0x82, 0, 0}, + {0x3302, 0xef, 0, 0}, {0x335f, 0x34, 0, 0}, {0x3360, 0x0c, 0, 0}, + {0x3361, 0x04, 0, 0}, {0x3362, 0x23, 0, 0}, {0x3363, 0x28, 0, 0}, + {0x3364, 0x5c, 0, 0}, {0x3403, 0x42, 0, 0}, {0x3088, 0x02, 0, 0}, + {0x3089, 0xD0, 0, 0}, {0x308a, 0x02, 0, 0}, {0x308b, 0x40, 0, 0}, + {0x304c, 0x83, 0, 0}, {0x300e, 0x39, 0, 0}, {0x300f, 0x21, 0, 0}, + {0x3011, 0x00, 0, 0}, {0x3010, 0x81, 0, 0}, {0x302e, 0x00, 0, 0}, + {0x302d, 0x00, 0, 0}, {0x3071, 0xeb, 0, 0}, {0x301C, 0x02, 0, 0}, + {0x3404, 0x02, 0, 0}, +}; + +static struct reg_value ov3640_setting_30fps_NTSC_720_480[] = { + {0x3012, 0x80, 0, 0}, {0x304d, 0x45, 0, 0}, {0x30a7, 0x5e, 0, 0}, + {0x3087, 0x16, 0, 0}, {0x309C, 0x1a, 0, 0}, {0x30a2, 0xe4, 0, 0}, + {0x30aa, 0x42, 0, 0}, {0x30b0, 0xff, 0, 0}, {0x30b1, 0xff, 0, 0}, + {0x30b2, 0x10, 0, 0}, {0x300e, 0x39, 0, 0}, {0x300f, 0x21, 0, 0}, + {0x3010, 0x20, 0, 0}, {0x304c, 0x81, 0, 0}, {0x30d7, 0x10, 0, 0}, + {0x30d9, 0x0d, 0, 0}, {0x30db, 0x08, 0, 0}, {0x3016, 0x82, 0, 0}, + {0x3018, 0x48, 0, 0}, {0x3019, 0x40, 0, 0}, {0x301a, 0x82, 0, 0}, + {0x307d, 0x00, 0, 0}, {0x3087, 0x02, 0, 0}, {0x3082, 0x20, 0, 0}, + {0x3015, 0x12, 0, 0}, {0x3014, 0x84, 0, 0}, {0x3013, 0xf7, 0, 0}, + {0x303c, 0x08, 0, 0}, {0x303d, 0x18, 0, 0}, {0x303e, 0x06, 0, 0}, + {0x303F, 0x0c, 0, 0}, {0x3030, 0x62, 0, 0}, {0x3031, 0x26, 0, 0}, + {0x3032, 0xe6, 0, 0}, {0x3033, 0x6e, 0, 0}, {0x3034, 0xea, 0, 0}, + {0x3035, 0xae, 0, 0}, {0x3036, 0xa6, 0, 0}, {0x3037, 0x6a, 0, 0}, + {0x3104, 0x02, 0, 0}, {0x3105, 0xfd, 0, 0}, {0x3106, 0x00, 0, 0}, + {0x3107, 0xff, 0, 0}, {0x3300, 0x13, 0, 0}, {0x3301, 0xde, 0, 0}, + {0x3302, 0xcf, 0, 0}, {0x3312, 0x26, 0, 0}, {0x3314, 0x42, 0, 0}, + {0x3313, 0x2b, 0, 0}, {0x3315, 0x42, 0, 0}, {0x3310, 0xd0, 0, 0}, + {0x3311, 0xbd, 0, 0}, {0x330c, 0x18, 0, 0}, {0x330d, 0x18, 0, 0}, + {0x330e, 0x56, 0, 0}, {0x330f, 0x5c, 0, 0}, {0x330b, 0x1c, 0, 0}, + {0x3306, 0x5c, 0, 0}, {0x3307, 0x11, 0, 0}, {0x336a, 0x52, 0, 0}, + {0x3370, 0x46, 0, 0}, {0x3376, 0x38, 0, 0}, {0x30b8, 0x20, 0, 0}, + {0x30b9, 0x17, 0, 0}, {0x30ba, 0x04, 0, 0}, {0x30bb, 0x08, 0, 0}, + {0x3507, 0x06, 0, 0}, {0x350a, 0x4f, 0, 0}, {0x3100, 0x02, 0, 0}, + {0x3301, 0xde, 0, 0}, {0x3304, 0xfc, 0, 0}, {0x3400, 0x00, 0, 0}, + {0x3404, 0x00, 0, 0}, {0x3600, 0xc0, 0, 0}, {0x3088, 0x08, 0, 0}, + {0x3089, 0x00, 0, 0}, {0x308a, 0x06, 0, 0}, {0x308b, 0x00, 0, 0}, + {0x308d, 0x04, 0, 0}, {0x3086, 0x03, 0, 0}, {0x3086, 0x00, 0, 0}, + {0x30a9, 0xb5, 0, 0}, {0x3317, 0x04, 0, 0}, {0x3316, 0xf8, 0, 0}, + {0x3312, 0x17, 0, 0}, {0x3314, 0x30, 0, 0}, {0x3313, 0x23, 0, 0}, + {0x3315, 0x3e, 0, 0}, {0x3311, 0x9e, 0, 0}, {0x3310, 0xc0, 0, 0}, + {0x330c, 0x18, 0, 0}, {0x330d, 0x18, 0, 0}, {0x330e, 0x5e, 0, 0}, + {0x330f, 0x6c, 0, 0}, {0x330b, 0x1c, 0, 0}, {0x3306, 0x5c, 0, 0}, + {0x3307, 0x11, 0, 0}, {0x3308, 0x25, 0, 0}, {0x3340, 0x20, 0, 0}, + {0x3341, 0x50, 0, 0}, {0x3342, 0x18, 0, 0}, {0x3343, 0x23, 0, 0}, + {0x3344, 0xad, 0, 0}, {0x3345, 0xd0, 0, 0}, {0x3346, 0xb8, 0, 0}, + {0x3347, 0xb4, 0, 0}, {0x3348, 0x04, 0, 0}, {0x3349, 0x98, 0, 0}, + {0x3355, 0x02, 0, 0}, {0x3358, 0x44, 0, 0}, {0x3359, 0x44, 0, 0}, + {0x3300, 0x13, 0, 0}, {0x3367, 0x23, 0, 0}, {0x3368, 0xBB, 0, 0}, + {0x3369, 0xD6, 0, 0}, {0x336A, 0x2A, 0, 0}, {0x336B, 0x07, 0, 0}, + {0x336C, 0x00, 0, 0}, {0x336D, 0x23, 0, 0}, {0x336E, 0xC3, 0, 0}, + {0x336F, 0xDE, 0, 0}, {0x3370, 0x2b, 0, 0}, {0x3371, 0x07, 0, 0}, + {0x3372, 0x00, 0, 0}, {0x3373, 0x23, 0, 0}, {0x3374, 0x9e, 0, 0}, + {0x3375, 0xD6, 0, 0}, {0x3376, 0x29, 0, 0}, {0x3377, 0x07, 0, 0}, + {0x3378, 0x00, 0, 0}, {0x332a, 0x1d, 0, 0}, {0x331b, 0x08, 0, 0}, + {0x331c, 0x16, 0, 0}, {0x331d, 0x2d, 0, 0}, {0x331e, 0x54, 0, 0}, + {0x331f, 0x66, 0, 0}, {0x3320, 0x73, 0, 0}, {0x3321, 0x80, 0, 0}, + {0x3322, 0x8c, 0, 0}, {0x3323, 0x95, 0, 0}, {0x3324, 0x9d, 0, 0}, + {0x3325, 0xac, 0, 0}, {0x3326, 0xb8, 0, 0}, {0x3327, 0xcc, 0, 0}, + {0x3328, 0xdd, 0, 0}, {0x3329, 0xee, 0, 0}, {0x332e, 0x04, 0, 0}, + {0x332f, 0x04, 0, 0}, {0x3331, 0x02, 0, 0}, {0x3100, 0x02, 0, 0}, + {0x3301, 0xde, 0, 0}, {0x3304, 0xfc, 0, 0}, {0x3400, 0x00, 0, 0}, + {0x3404, 0x00, 0, 0}, {0x3610, 0x40, 0, 0}, {0x304c, 0x81, 0, 0}, + {0x307C, 0x10, 0, 0}, {0x3012, 0x10, 0, 0}, {0x3023, 0x06, 0, 0}, + {0x3026, 0x03, 0, 0}, {0x3027, 0x04, 0, 0}, {0x302a, 0x03, 0, 0}, + {0x302b, 0x10, 0, 0}, {0x3075, 0x24, 0, 0}, {0x300d, 0x01, 0, 0}, + {0x30d7, 0x90, 0, 0}, {0x3069, 0x04, 0, 0}, {0x303e, 0x00, 0, 0}, + {0x303f, 0xc0, 0, 0}, {0x3302, 0xef, 0, 0}, {0x335f, 0x34, 0, 0}, + {0x3360, 0x0c, 0, 0}, {0x3361, 0x04, 0, 0}, {0x3362, 0x34, 0, 0}, + {0x3363, 0x08, 0, 0}, {0x3364, 0x04, 0, 0}, {0x3403, 0x42, 0, 0}, + {0x3088, 0x04, 0, 0}, {0x3089, 0x00, 0, 0}, {0x308a, 0x03, 0, 0}, + {0x308b, 0x00, 0, 0}, {0x300e, 0x32, 0, 0}, {0x300f, 0x21, 0, 0}, + {0x3010, 0x20, 0, 0}, {0x3011, 0x01, 0, 0}, {0x304c, 0x82, 0, 0}, + {0x3302, 0xef, 0, 0}, {0x335f, 0x34, 0, 0}, {0x3360, 0x0c, 0, 0}, + {0x3361, 0x04, 0, 0}, {0x3362, 0x23, 0, 0}, {0x3363, 0x28, 0, 0}, + {0x3364, 0x5c, 0, 0}, {0x3403, 0x42, 0, 0}, {0x3088, 0x02, 0, 0}, + {0x3089, 0xD0, 0, 0}, {0x308a, 0x01, 0, 0}, {0x308b, 0xe0, 0, 0}, + {0x304c, 0x83, 0, 0}, {0x300e, 0x39, 0, 0}, {0x300f, 0xA1, 0, 0}, + {0x3011, 0x00, 0, 0}, {0x3010, 0x81, 0, 0}, {0x3014, 0x84, 0, 0}, + {0x302e, 0x00, 0, 0}, {0x302d, 0x00, 0, 0}, {0x3071, 0xeb, 0, 0}, + {0x301C, 0x02, 0, 0}, {0x3404, 0x02, 0, 0}, +}; + +static struct reg_value ov3640_setting_30fps_PAL_720_576[] = { + {0x3012, 0x80, 0, 0}, {0x304d, 0x45, 0, 0}, {0x30a7, 0x5e, 0, 0}, + {0x3086, 0x16, 0, 0}, {0x309C, 0x1a, 0, 0}, {0x30a2, 0xe4, 0, 0}, + {0x30aa, 0x42, 0, 0}, {0x30b0, 0xff, 0, 0}, {0x30b1, 0xff, 0, 0}, + {0x30b2, 0x10, 0, 0}, {0x300e, 0x39, 0, 0}, {0x300f, 0x21, 0, 0}, + {0x3010, 0x20, 0, 0}, {0x304c, 0x81, 0, 0}, {0x30d7, 0x10, 0, 0}, + {0x30d9, 0x0d, 0, 0}, {0x30db, 0x08, 0, 0}, {0x3016, 0x82, 0, 0}, + {0x3018, 0x48, 0, 0}, {0x3019, 0x40, 0, 0}, {0x301a, 0x82, 0, 0}, + {0x307d, 0x00, 0, 0}, {0x3087, 0x02, 0, 0}, {0x3082, 0x20, 0, 0}, + {0x3015, 0x12, 0, 0}, {0x3014, 0x84, 0, 0}, {0x3013, 0xf7, 0, 0}, + {0x303c, 0x08, 0, 0}, {0x303d, 0x18, 0, 0}, {0x303e, 0x06, 0, 0}, + {0x303F, 0x0c, 0, 0}, {0x3030, 0x62, 0, 0}, {0x3031, 0x26, 0, 0}, + {0x3032, 0xe6, 0, 0}, {0x3033, 0x6e, 0, 0}, {0x3034, 0xea, 0, 0}, + {0x3035, 0xae, 0, 0}, {0x3036, 0xa6, 0, 0}, {0x3037, 0x6a, 0, 0}, + {0x3104, 0x02, 0, 0}, {0x3105, 0xfd, 0, 0}, {0x3106, 0x00, 0, 0}, + {0x3107, 0xff, 0, 0}, {0x3300, 0x13, 0, 0}, {0x3301, 0xde, 0, 0}, + {0x3302, 0xcf, 0, 0}, {0x3312, 0x26, 0, 0}, {0x3314, 0x42, 0, 0}, + {0x3313, 0x2b, 0, 0}, {0x3315, 0x42, 0, 0}, {0x3310, 0xd0, 0, 0}, + {0x3311, 0xbd, 0, 0}, {0x330c, 0x18, 0, 0}, {0x330d, 0x18, 0, 0}, + {0x330e, 0x56, 0, 0}, {0x330f, 0x5c, 0, 0}, {0x330b, 0x1c, 0, 0}, + {0x3306, 0x5c, 0, 0}, {0x3307, 0x11, 0, 0}, {0x336a, 0x52, 0, 0}, + {0x3370, 0x46, 0, 0}, {0x3376, 0x38, 0, 0}, {0x30b8, 0x20, 0, 0}, + {0x30b9, 0x17, 0, 0}, {0x30ba, 0x04, 0, 0}, {0x30bb, 0x08, 0, 0}, + {0x3507, 0x06, 0, 0}, {0x350a, 0x4f, 0, 0}, {0x3100, 0x02, 0, 0}, + {0x3301, 0xde, 0, 0}, {0x3304, 0xfc, 0, 0}, {0x3400, 0x00, 0, 0}, + {0x3404, 0x00, 0, 0}, {0x3600, 0xc0, 0, 0}, {0x3088, 0x08, 0, 0}, + {0x3089, 0x00, 0, 0}, {0x308a, 0x06, 0, 0}, {0x308b, 0x00, 0, 0}, + {0x308d, 0x04, 0, 0}, {0x3086, 0x03, 0, 0}, {0x3086, 0x00, 0, 0}, + {0x30a9, 0xb5, 0, 0}, {0x3317, 0x04, 0, 0}, {0x3316, 0xf8, 0, 0}, + {0x3312, 0x17, 0, 0}, {0x3314, 0x30, 0, 0}, {0x3313, 0x23, 0, 0}, + {0x3315, 0x3e, 0, 0}, {0x3311, 0x9e, 0, 0}, {0x3310, 0xc0, 0, 0}, + {0x330c, 0x18, 0, 0}, {0x330d, 0x18, 0, 0}, {0x330e, 0x5e, 0, 0}, + {0x330f, 0x6c, 0, 0}, {0x330b, 0x1c, 0, 0}, {0x3306, 0x5c, 0, 0}, + {0x3307, 0x11, 0, 0}, {0x3308, 0x25, 0, 0}, {0x3340, 0x20, 0, 0}, + {0x3341, 0x50, 0, 0}, {0x3342, 0x18, 0, 0}, {0x3343, 0x23, 0, 0}, + {0x3344, 0xad, 0, 0}, {0x3345, 0xd0, 0, 0}, {0x3346, 0xb8, 0, 0}, + {0x3347, 0xb4, 0, 0}, {0x3348, 0x04, 0, 0}, {0x3349, 0x98, 0, 0}, + {0x3355, 0x02, 0, 0}, {0x3358, 0x44, 0, 0}, {0x3359, 0x44, 0, 0}, + {0x3300, 0x13, 0, 0}, {0x3367, 0x23, 0, 0}, {0x3368, 0xBB, 0, 0}, + {0x3369, 0xD6, 0, 0}, {0x336A, 0x2A, 0, 0}, {0x336B, 0x07, 0, 0}, + {0x336C, 0x00, 0, 0}, {0x336D, 0x23, 0, 0}, {0x336E, 0xC3, 0, 0}, + {0x336F, 0xDE, 0, 0}, {0x3370, 0x2b, 0, 0}, {0x3371, 0x07, 0, 0}, + {0x3372, 0x00, 0, 0}, {0x3373, 0x23, 0, 0}, {0x3374, 0x9e, 0, 0}, + {0x3375, 0xD6, 0, 0}, {0x3376, 0x29, 0, 0}, {0x3377, 0x07, 0, 0}, + {0x3378, 0x00, 0, 0}, {0x332a, 0x1d, 0, 0}, {0x331b, 0x08, 0, 0}, + {0x331c, 0x16, 0, 0}, {0x331d, 0x2d, 0, 0}, {0x331e, 0x54, 0, 0}, + {0x331f, 0x66, 0, 0}, {0x3320, 0x73, 0, 0}, {0x3321, 0x80, 0, 0}, + {0x3322, 0x8c, 0, 0}, {0x3323, 0x95, 0, 0}, {0x3324, 0x9d, 0, 0}, + {0x3325, 0xac, 0, 0}, {0x3326, 0xb8, 0, 0}, {0x3327, 0xcc, 0, 0}, + {0x3328, 0xdd, 0, 0}, {0x3329, 0xee, 0, 0}, {0x332e, 0x04, 0, 0}, + {0x332f, 0x04, 0, 0}, {0x3331, 0x02, 0, 0}, {0x3100, 0x02, 0, 0}, + {0x3301, 0xde, 0, 0}, {0x3304, 0xfc, 0, 0}, {0x3400, 0x00, 0, 0}, + {0x3404, 0x00, 0, 0}, {0x3610, 0x40, 0, 0}, {0x304c, 0x81, 0, 0}, + {0x307C, 0x10, 0, 0}, {0x3012, 0x10, 0, 0}, {0x3023, 0x06, 0, 0}, + {0x3026, 0x03, 0, 0}, {0x3027, 0x04, 0, 0}, {0x302a, 0x03, 0, 0}, + {0x302b, 0x10, 0, 0}, {0x3075, 0x24, 0, 0}, {0x300d, 0x01, 0, 0}, + {0x30d7, 0x90, 0, 0}, {0x3069, 0x04, 0, 0}, {0x303e, 0x00, 0, 0}, + {0x303f, 0xc0, 0, 0}, {0x3302, 0xef, 0, 0}, {0x335f, 0x34, 0, 0}, + {0x3360, 0x0c, 0, 0}, {0x3361, 0x04, 0, 0}, {0x3362, 0x34, 0, 0}, + {0x3363, 0x08, 0, 0}, {0x3364, 0x04, 0, 0}, {0x3403, 0x42, 0, 0}, + {0x3088, 0x04, 0, 0}, {0x3089, 0x00, 0, 0}, {0x308a, 0x03, 0, 0}, + {0x308b, 0x00, 0, 0}, {0x300e, 0x32, 0, 0}, {0x300f, 0x21, 0, 0}, + {0x3010, 0x20, 0, 0}, {0x3011, 0x01, 0, 0}, {0x304c, 0x82, 0, 0}, + {0x3302, 0xef, 0, 0}, {0x335f, 0x34, 0, 0}, {0x3360, 0x0c, 0, 0}, + {0x3361, 0x04, 0, 0}, {0x3362, 0x23, 0, 0}, {0x3363, 0x28, 0, 0}, + {0x3364, 0x5c, 0, 0}, {0x3403, 0x42, 0, 0}, {0x3088, 0x02, 0, 0}, + {0x3089, 0xD0, 0, 0}, {0x308a, 0x02, 0, 0}, {0x308b, 0x40, 0, 0}, + {0x304c, 0x83, 0, 0}, {0x300e, 0x39, 0, 0}, {0x300f, 0xA1, 0, 0}, + {0x3011, 0x00, 0, 0}, {0x3010, 0x81, 0, 0}, {0x3014, 0x84, 0, 0}, + {0x302e, 0x00, 0, 0}, {0x302d, 0x00, 0, 0}, {0x3071, 0xeb, 0, 0}, + {0x301C, 0x02, 0, 0}, {0x3404, 0x02, 0, 0}, +}; + +static struct ov3640_mode_info ov3640_mode_info_data[2][ov3640_mode_MAX + 1] = { + { + {ov3640_mode_VGA_640_480, 640, 480, + ov3640_setting_15fps_VGA_640_480, + ARRAY_SIZE(ov3640_setting_15fps_VGA_640_480)}, + {ov3640_mode_QVGA_320_240, 320, 240, + ov3640_setting_15fps_QVGA_320_240, + ARRAY_SIZE(ov3640_setting_15fps_QVGA_320_240)}, + {ov3640_mode_XGA_1024_768, 1024, 768, + ov3640_setting_15fps_XGA_1024_768, + ARRAY_SIZE(ov3640_setting_15fps_XGA_1024_768)}, + {ov3640_mode_QXGA_2048_1536, 2048, 1536, + ov3640_setting_15fps_QXGA_2048_1536, + ARRAY_SIZE(ov3640_setting_15fps_QXGA_2048_1536)}, + {ov3640_mode_NTSC_720_480, 720, 480, + ov3640_setting_15fps_NTSC_720_480, + ARRAY_SIZE(ov3640_setting_15fps_NTSC_720_480)}, + {ov3640_mode_PAL_720_576, 720, 576, + ov3640_setting_15fps_PAL_720_576, + ARRAY_SIZE(ov3640_setting_15fps_PAL_720_576)}, + }, + { + {ov3640_mode_VGA_640_480, 640, 480, + ov3640_setting_30fps_VGA_640_480, + ARRAY_SIZE(ov3640_setting_30fps_VGA_640_480)}, + {ov3640_mode_QVGA_320_240, 320, 240, + ov3640_setting_30fps_QVGA_320_240, + ARRAY_SIZE(ov3640_setting_30fps_QVGA_320_240)}, + {ov3640_mode_XGA_1024_768, 1024, 768, + ov3640_setting_30fps_XGA_1024_768, + ARRAY_SIZE(ov3640_setting_30fps_XGA_1024_768)}, + {ov3640_mode_QXGA_2048_1536, 0, 0, NULL, 0}, + {ov3640_mode_NTSC_720_480, 720, 480, + ov3640_setting_30fps_NTSC_720_480, + ARRAY_SIZE(ov3640_setting_30fps_NTSC_720_480)}, + {ov3640_mode_PAL_720_576, 720, 576, + ov3640_setting_30fps_PAL_720_576, + ARRAY_SIZE(ov3640_setting_30fps_PAL_720_576)}, + }, +}; + +static struct regulator *io_regulator; +static struct regulator *core_regulator; +static struct regulator *analog_regulator; +static struct regulator *gpo_regulator; +static struct mxc_camera_platform_data *camera_plat; + +static int ov3640_probe(struct i2c_client *adapter, + const struct i2c_device_id *device_id); +static int ov3640_remove(struct i2c_client *client); + +static s32 ov3640_read_reg(u16 reg, u8 *val); +static s32 ov3640_write_reg(u16 reg, u8 val); + +static const struct i2c_device_id ov3640_id[] = { + {"ov3640", 0}, + {}, +}; + +MODULE_DEVICE_TABLE(i2c, ov3640_id); + +static struct i2c_driver ov3640_i2c_driver = { + .driver = { + .owner = THIS_MODULE, + .name = "ov3640", + }, + .probe = ov3640_probe, + .remove = ov3640_remove, + .id_table = ov3640_id, +}; + +extern void gpio_sensor_active(unsigned int csi_index); +extern void gpio_sensor_inactive(unsigned int csi); + +static s32 ov3640_write_reg(u16 reg, u8 val) +{ + u8 au8Buf[3] = {0}; + + au8Buf[0] = reg >> 8; + au8Buf[1] = reg & 0xff; + au8Buf[2] = val; + + if (i2c_master_send(ov3640_data.i2c_client, au8Buf, 3) < 0) { + pr_err("%s:write reg error:reg=%x,val=%x\n", + __func__, reg, val); + return -1; + } + + return 0; +} + +static s32 ov3640_read_reg(u16 reg, u8 *val) +{ + u8 au8RegBuf[2] = {0}; + u8 u8RdVal = 0; + + au8RegBuf[0] = reg >> 8; + au8RegBuf[1] = reg & 0xff; + + if (2 != i2c_master_send(ov3640_data.i2c_client, au8RegBuf, 2)) { + pr_err("%s:write reg error:reg=%x\n", + __func__, reg); + return -1; + } + + if (1 != i2c_master_recv(ov3640_data.i2c_client, &u8RdVal, 1)) { + pr_err("%s:read reg error:reg=%x,val=%x\n", + __func__, reg, u8RdVal); + return -1; + } + + *val = u8RdVal; + + return u8RdVal; +} + +static int ov3640_init_mode(enum ov3640_frame_rate frame_rate, + enum ov3640_mode mode) +{ + struct reg_value *pModeSetting = NULL; + s32 i = 0; + s32 iModeSettingArySize = 0; + register u32 Delay_ms = 0; + register u16 RegAddr = 0; + register u8 Mask = 0; + register u8 Val = 0; + u8 RegVal = 0; + int retval = 0; + + if (mode > ov3640_mode_MAX || mode < ov3640_mode_MIN) { + pr_err("Wrong ov3640 mode detected!\n"); + return -1; + } + + pModeSetting = ov3640_mode_info_data[frame_rate][mode].init_data_ptr; + iModeSettingArySize = + ov3640_mode_info_data[frame_rate][mode].init_data_size; + + ov3640_data.pix.width = ov3640_mode_info_data[frame_rate][mode].width; + ov3640_data.pix.height = ov3640_mode_info_data[frame_rate][mode].height; + + for (i = 0; i < iModeSettingArySize; ++i, ++pModeSetting) { + Delay_ms = pModeSetting->u32Delay_ms; + RegAddr = pModeSetting->u16RegAddr; + Val = pModeSetting->u8Val; + Mask = pModeSetting->u8Mask; + + if (Mask) { + retval = ov3640_read_reg(RegAddr, &RegVal); + if (retval < 0) + goto err; + + RegVal &= ~(u8)Mask; + Val &= Mask; + Val |= RegVal; + } + + retval = ov3640_write_reg(RegAddr, Val); + if (retval < 0) + goto err; + + if (Delay_ms) + msleep(Delay_ms); + } +err: + return retval; +} + +/* --------------- IOCTL functions from v4l2_int_ioctl_desc --------------- */ + +static int ioctl_g_ifparm(struct v4l2_int_device *s, struct v4l2_ifparm *p) +{ + if (s == NULL) { + pr_err(" ERROR!! no slave device set!\n"); + return -1; + } + + memset(p, 0, sizeof(*p)); + p->u.bt656.clock_curr = ov3640_data.mclk; + pr_debug(" clock_curr=mclk=%d\n", ov3640_data.mclk); + p->if_type = V4L2_IF_TYPE_BT656; + p->u.bt656.mode = V4L2_IF_TYPE_BT656_MODE_NOBT_8BIT; + p->u.bt656.clock_min = OV3640_XCLK_MIN; + p->u.bt656.clock_max = OV3640_XCLK_MAX; + p->u.bt656.bt_sync_correct = 1; /* Indicate external vsync */ + + return 0; +} + +/*! + * ioctl_s_power - V4L2 sensor interface handler for VIDIOC_S_POWER ioctl + * @s: pointer to standard V4L2 device structure + * @on: indicates power mode (on or off) + * + * Turns the power on or off, depending on the value of on and returns the + * appropriate error code. + */ +static int ioctl_s_power(struct v4l2_int_device *s, int on) +{ + struct sensor *sensor = s->priv; + + if (on && !sensor->on) { + gpio_sensor_active(ov3640_data.csi); + if (io_regulator) + if (regulator_enable(io_regulator) != 0) + return -EIO; + if (core_regulator) + if (regulator_enable(core_regulator) != 0) + return -EIO; + if (gpo_regulator) + if (regulator_enable(gpo_regulator) != 0) + return -EIO; + if (analog_regulator) + if (regulator_enable(analog_regulator) != 0) + return -EIO; + /* Make sure power on */ + if (camera_plat->pwdn) + camera_plat->pwdn(0); + + } else if (!on && sensor->on) { + if (analog_regulator) + regulator_disable(analog_regulator); + if (core_regulator) + regulator_disable(core_regulator); + if (io_regulator) + regulator_disable(io_regulator); + if (gpo_regulator) + regulator_disable(gpo_regulator); + gpio_sensor_inactive(ov3640_data.csi); + } + + sensor->on = on; + + return 0; +} + +/*! + * ioctl_g_parm - V4L2 sensor interface handler for VIDIOC_G_PARM ioctl + * @s: pointer to standard V4L2 device structure + * @a: pointer to standard V4L2 VIDIOC_G_PARM ioctl structure + * + * Returns the sensor's video CAPTURE parameters. + */ +static int ioctl_g_parm(struct v4l2_int_device *s, struct v4l2_streamparm *a) +{ + struct sensor *sensor = s->priv; + struct v4l2_captureparm *cparm = &a->parm.capture; + int ret = 0; + + switch (a->type) { + /* This is the only case currently handled. */ + case V4L2_BUF_TYPE_VIDEO_CAPTURE: + memset(a, 0, sizeof(*a)); + a->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + cparm->capability = sensor->streamcap.capability; + cparm->timeperframe = sensor->streamcap.timeperframe; + cparm->capturemode = sensor->streamcap.capturemode; + ret = 0; + break; + + /* These are all the possible cases. */ + case V4L2_BUF_TYPE_VIDEO_OUTPUT: + case V4L2_BUF_TYPE_VIDEO_OVERLAY: + case V4L2_BUF_TYPE_VBI_CAPTURE: + case V4L2_BUF_TYPE_VBI_OUTPUT: + case V4L2_BUF_TYPE_SLICED_VBI_CAPTURE: + case V4L2_BUF_TYPE_SLICED_VBI_OUTPUT: + ret = -EINVAL; + break; + + default: + pr_debug(" type is unknown - %d\n", a->type); + ret = -EINVAL; + break; + } + + return ret; +} + +/*! + * ioctl_s_parm - V4L2 sensor interface handler for VIDIOC_S_PARM ioctl + * @s: pointer to standard V4L2 device structure + * @a: pointer to standard V4L2 VIDIOC_S_PARM ioctl structure + * + * Configures the sensor to use the input parameters, if possible. If + * not possible, reverts to the old parameters and returns the + * appropriate error code. + */ +static int ioctl_s_parm(struct v4l2_int_device *s, struct v4l2_streamparm *a) +{ + struct sensor *sensor = s->priv; + struct v4l2_fract *timeperframe = &a->parm.capture.timeperframe; + u32 tgt_fps; /* target frames per secound */ + enum ov3640_frame_rate frame_rate; + int ret = 0; + + /* Make sure power on */ + if (camera_plat->pwdn) + camera_plat->pwdn(0); + + switch (a->type) { + /* This is the only case currently handled. */ + case V4L2_BUF_TYPE_VIDEO_CAPTURE: + /* Check that the new frame rate is allowed. */ + if ((timeperframe->numerator == 0) || + (timeperframe->denominator == 0)) { + timeperframe->denominator = DEFAULT_FPS; + timeperframe->numerator = 1; + } + + tgt_fps = timeperframe->denominator / + timeperframe->numerator; + + if (tgt_fps > MAX_FPS) { + timeperframe->denominator = MAX_FPS; + timeperframe->numerator = 1; + } else if (tgt_fps < MIN_FPS) { + timeperframe->denominator = MIN_FPS; + timeperframe->numerator = 1; + } + + /* Actual frame rate we use */ + tgt_fps = timeperframe->denominator / + timeperframe->numerator; + + if (tgt_fps == 15) + frame_rate = ov3640_15_fps; + else if (tgt_fps == 30) + frame_rate = ov3640_30_fps; + else { + pr_err(" The camera frame rate is not supported!\n"); + return -EINVAL; + } + + sensor->streamcap.timeperframe = *timeperframe; + sensor->streamcap.capturemode = + (u32)a->parm.capture.capturemode; + + ret = ov3640_init_mode(frame_rate, + sensor->streamcap.capturemode); + break; + + /* These are all the possible cases. */ + case V4L2_BUF_TYPE_VIDEO_OUTPUT: + case V4L2_BUF_TYPE_VIDEO_OVERLAY: + case V4L2_BUF_TYPE_VBI_CAPTURE: + case V4L2_BUF_TYPE_VBI_OUTPUT: + case V4L2_BUF_TYPE_SLICED_VBI_CAPTURE: + case V4L2_BUF_TYPE_SLICED_VBI_OUTPUT: + pr_debug(" type is not " \ + "V4L2_BUF_TYPE_VIDEO_CAPTURE but %d\n", + a->type); + ret = -EINVAL; + break; + + default: + pr_debug(" type is unknown - %d\n", a->type); + ret = -EINVAL; + break; + } + + return ret; +} + +/*! + * ioctl_g_fmt_cap - V4L2 sensor interface handler for ioctl_g_fmt_cap + * @s: pointer to standard V4L2 device structure + * @f: pointer to standard V4L2 v4l2_format structure + * + * Returns the sensor's current pixel format in the v4l2_format + * parameter. + */ +static int ioctl_g_fmt_cap(struct v4l2_int_device *s, struct v4l2_format *f) +{ + struct sensor *sensor = s->priv; + + f->fmt.pix = sensor->pix; + + return 0; +} + +/*! + * ioctl_g_ctrl - V4L2 sensor interface handler for VIDIOC_G_CTRL ioctl + * @s: pointer to standard V4L2 device structure + * @vc: standard V4L2 VIDIOC_G_CTRL ioctl structure + * + * If the requested control is supported, returns the control's current + * value from the video_control[] array. Otherwise, returns -EINVAL + * if the control is not supported. + */ +static int ioctl_g_ctrl(struct v4l2_int_device *s, struct v4l2_control *vc) +{ + int ret = 0; + + switch (vc->id) { + case V4L2_CID_BRIGHTNESS: + vc->value = ov3640_data.brightness; + break; + case V4L2_CID_HUE: + vc->value = ov3640_data.hue; + break; + case V4L2_CID_CONTRAST: + vc->value = ov3640_data.contrast; + break; + case V4L2_CID_SATURATION: + vc->value = ov3640_data.saturation; + break; + case V4L2_CID_RED_BALANCE: + vc->value = ov3640_data.red; + break; + case V4L2_CID_BLUE_BALANCE: + vc->value = ov3640_data.blue; + break; + case V4L2_CID_EXPOSURE: + vc->value = ov3640_data.ae_mode; + break; + default: + ret = -EINVAL; + } + + return ret; +} + +/*! + * ioctl_s_ctrl - V4L2 sensor interface handler for VIDIOC_S_CTRL ioctl + * @s: pointer to standard V4L2 device structure + * @vc: standard V4L2 VIDIOC_S_CTRL ioctl structure + * + * If the requested control is supported, sets the control's current + * value in HW (and updates the video_control[] array). Otherwise, + * returns -EINVAL if the control is not supported. + */ +static int ioctl_s_ctrl(struct v4l2_int_device *s, struct v4l2_control *vc) +{ + int retval = 0; + + pr_debug("In ov3640:ioctl_s_ctrl %d\n", + vc->id); + + switch (vc->id) { + case V4L2_CID_BRIGHTNESS: + break; + case V4L2_CID_CONTRAST: + break; + case V4L2_CID_SATURATION: + break; + case V4L2_CID_HUE: + break; + case V4L2_CID_AUTO_WHITE_BALANCE: + break; + case V4L2_CID_DO_WHITE_BALANCE: + break; + case V4L2_CID_RED_BALANCE: + break; + case V4L2_CID_BLUE_BALANCE: + break; + case V4L2_CID_GAMMA: + break; + case V4L2_CID_EXPOSURE: + break; + case V4L2_CID_AUTOGAIN: + break; + case V4L2_CID_GAIN: + break; + case V4L2_CID_HFLIP: + break; + case V4L2_CID_VFLIP: + break; + default: + retval = -EPERM; + break; + } + + return retval; +} + +/*! + * ioctl_init - V4L2 sensor interface handler for VIDIOC_INT_INIT + * @s: pointer to standard V4L2 device structure + */ +static int ioctl_init(struct v4l2_int_device *s) +{ + + return 0; +} + +/*! + * ioctl_dev_init - V4L2 sensor interface handler for vidioc_int_dev_init_num + * @s: pointer to standard V4L2 device structure + * + * Initialise the device when slave attaches to the master. + */ +static int ioctl_dev_init(struct v4l2_int_device *s) +{ + struct sensor *sensor = s->priv; + u32 tgt_xclk; /* target xclk */ + u32 tgt_fps; /* target frames per secound */ + enum ov3640_frame_rate frame_rate; + + gpio_sensor_active(ov3640_data.csi); + ov3640_data.on = true; + + /* mclk */ + tgt_xclk = ov3640_data.mclk; + tgt_xclk = min(tgt_xclk, (u32)OV3640_XCLK_MAX); + tgt_xclk = max(tgt_xclk, (u32)OV3640_XCLK_MIN); + ov3640_data.mclk = tgt_xclk; + + pr_debug(" Setting mclk to %d MHz\n", tgt_xclk / 1000000); + set_mclk_rate(&ov3640_data.mclk, ov3640_data.csi); + + /* Default camera frame rate is set in probe */ + tgt_fps = sensor->streamcap.timeperframe.denominator / + sensor->streamcap.timeperframe.numerator; + + if (tgt_fps == 15) + frame_rate = ov3640_15_fps; + else if (tgt_fps == 30) + frame_rate = ov3640_30_fps; + else + return -EINVAL; /* Only support 15fps or 30fps now. */ + + return ov3640_init_mode(frame_rate, + sensor->streamcap.capturemode); +} + +/*! + * ioctl_dev_exit - V4L2 sensor interface handler for vidioc_int_dev_exit_num + * @s: pointer to standard V4L2 device structure + * + * Delinitialise the device when slave detaches to the master. + */ +static int ioctl_dev_exit(struct v4l2_int_device *s) +{ + gpio_sensor_inactive(ov3640_data.csi); + + return 0; +} + +/*! + * This structure defines all the ioctls for this module and links them to the + * enumeration. + */ +static struct v4l2_int_ioctl_desc ov3640_ioctl_desc[] = { + {vidioc_int_dev_init_num, (v4l2_int_ioctl_func*)ioctl_dev_init}, + {vidioc_int_dev_exit_num, ioctl_dev_exit}, + {vidioc_int_s_power_num, (v4l2_int_ioctl_func*)ioctl_s_power}, + {vidioc_int_g_ifparm_num, (v4l2_int_ioctl_func*)ioctl_g_ifparm}, +/* {vidioc_int_g_needs_reset_num, + (v4l2_int_ioctl_func *)ioctl_g_needs_reset}, */ +/* {vidioc_int_reset_num, (v4l2_int_ioctl_func *)ioctl_reset}, */ + {vidioc_int_init_num, (v4l2_int_ioctl_func*)ioctl_init}, +/* {vidioc_int_enum_fmt_cap_num, + (v4l2_int_ioctl_func *)ioctl_enum_fmt_cap}, */ +/* {vidioc_int_try_fmt_cap_num, + (v4l2_int_ioctl_func *)ioctl_try_fmt_cap}, */ + {vidioc_int_g_fmt_cap_num, (v4l2_int_ioctl_func*)ioctl_g_fmt_cap}, +/* {vidioc_int_s_fmt_cap_num, (v4l2_int_ioctl_func *)ioctl_s_fmt_cap}, */ + {vidioc_int_g_parm_num, (v4l2_int_ioctl_func*)ioctl_g_parm}, + {vidioc_int_s_parm_num, (v4l2_int_ioctl_func*)ioctl_s_parm}, +/* {vidioc_int_queryctrl_num, (v4l2_int_ioctl_func *)ioctl_queryctrl}, */ + {vidioc_int_g_ctrl_num, (v4l2_int_ioctl_func*)ioctl_g_ctrl}, + {vidioc_int_s_ctrl_num, (v4l2_int_ioctl_func*)ioctl_s_ctrl}, +}; + +static struct v4l2_int_slave ov3640_slave = { + .ioctls = ov3640_ioctl_desc, + .num_ioctls = ARRAY_SIZE(ov3640_ioctl_desc), +}; + +static struct v4l2_int_device ov3640_int_device = { + .module = THIS_MODULE, + .name = "ov3640", + .type = v4l2_int_type_slave, + .u = { + .slave = &ov3640_slave, + }, +}; + +/*! + * ov3640 I2C probe function + * + * @param adapter struct i2c_adapter * + * @return Error code indicating success or failure + */ +static int ov3640_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + int retval; + struct mxc_camera_platform_data *plat_data = client->dev.platform_data; + + /* Set initial values for the sensor struct. */ + memset(&ov3640_data, 0, sizeof(ov3640_data)); + ov3640_data.mclk = 24000000; /* 6 - 54 MHz, typical 24MHz */ + ov3640_data.mclk = plat_data->mclk; + ov3640_data.csi = plat_data->csi; + + ov3640_data.i2c_client = client; + ov3640_data.pix.pixelformat = V4L2_PIX_FMT_UYVY; + ov3640_data.pix.width = 640; + ov3640_data.pix.height = 480; + ov3640_data.streamcap.capability = V4L2_MODE_HIGHQUALITY | + V4L2_CAP_TIMEPERFRAME; + ov3640_data.streamcap.capturemode = 0; + ov3640_data.streamcap.timeperframe.denominator = DEFAULT_FPS; + ov3640_data.streamcap.timeperframe.numerator = 1; + + if (plat_data->io_regulator) { + io_regulator = regulator_get(&client->dev, + plat_data->io_regulator); + if (!IS_ERR(io_regulator)) { + regulator_set_voltage(io_regulator, + OV3640_VOLTAGE_DIGITAL_IO, + OV3640_VOLTAGE_DIGITAL_IO); + if (regulator_enable(io_regulator) != 0) { + pr_err("%s:io set voltage error\n", __func__); + goto err1; + } else { + dev_dbg(&client->dev, + "%s:io set voltage ok\n", __func__); + } + } else + io_regulator = NULL; + } + + if (plat_data->core_regulator) { + core_regulator = regulator_get(&client->dev, + plat_data->core_regulator); + if (!IS_ERR(core_regulator)) { + regulator_set_voltage(core_regulator, + OV3640_VOLTAGE_DIGITAL_CORE, + OV3640_VOLTAGE_DIGITAL_CORE); + if (regulator_enable(core_regulator) != 0) { + pr_err("%s:core set voltage error\n", __func__); + goto err2; + } else { + dev_dbg(&client->dev, + "%s:core set voltage ok\n", __func__); + } + } else + core_regulator = NULL; + } + + if (plat_data->analog_regulator) { + analog_regulator = regulator_get(&client->dev, + plat_data->analog_regulator); + if (!IS_ERR(analog_regulator)) { + regulator_set_voltage(analog_regulator, + OV3640_VOLTAGE_ANALOG, + OV3640_VOLTAGE_ANALOG); + if (regulator_enable(analog_regulator) != 0) { + pr_err("%s:analog set voltage error\n", + __func__); + goto err3; + } else { + dev_dbg(&client->dev, + "%s:analog set voltage ok\n", __func__); + } + } else + analog_regulator = NULL; + } + + if (plat_data->gpo_regulator) { + gpo_regulator = regulator_get(&client->dev, + plat_data->gpo_regulator); + if (!IS_ERR(gpo_regulator)) { + if (regulator_enable(gpo_regulator) != 0) { + pr_err("%s:gpo3 enable error\n", __func__); + goto err4; + } else { + dev_dbg(&client->dev, + "%s:gpo3 enable ok\n", __func__); + } + } else + gpo_regulator = NULL; + } + + if (plat_data->pwdn) + plat_data->pwdn(0); + + camera_plat = plat_data; + + ov3640_int_device.priv = &ov3640_data; + retval = v4l2_int_device_register(&ov3640_int_device); + + return retval; + +err4: + if (analog_regulator) { + regulator_disable(analog_regulator); + regulator_put(analog_regulator); + } +err3: + if (core_regulator) { + regulator_disable(core_regulator); + regulator_put(core_regulator); + } +err2: + if (io_regulator) { + regulator_disable(io_regulator); + regulator_put(io_regulator); + } +err1: + return -1; +} + +/*! + * ov3640 I2C detach function + * + * @param client struct i2c_client * + * @return Error code indicating success or failure + */ +static int ov3640_remove(struct i2c_client *client) +{ + v4l2_int_device_unregister(&ov3640_int_device); + + if (gpo_regulator) { + regulator_disable(gpo_regulator); + regulator_put(gpo_regulator); + } + + if (analog_regulator) { + regulator_disable(analog_regulator); + regulator_put(analog_regulator); + } + + if (core_regulator) { + regulator_disable(core_regulator); + regulator_put(core_regulator); + } + + if (io_regulator) { + regulator_disable(io_regulator); + regulator_put(io_regulator); + } + + return 0; +} + +/*! + * ov3640 init function + * Called by insmod ov3640_camera.ko. + * + * @return Error code indicating success or failure + */ +static __init int ov3640_init(void) +{ + u8 err; + + err = i2c_add_driver(&ov3640_i2c_driver); + if (err != 0) + pr_err("%s:driver registration failed, error=%d \n", + __func__, err); + + return err; +} + +/*! + * OV3640 cleanup function + * Called on rmmod ov3640_camera.ko + * + * @return Error code indicating success or failure + */ +static void __exit ov3640_clean(void) +{ + i2c_del_driver(&ov3640_i2c_driver); +} + +module_init(ov3640_init); +module_exit(ov3640_clean); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("OV3640 Camera Driver"); +MODULE_LICENSE("GPL"); +MODULE_VERSION("1.0"); +MODULE_ALIAS("CSI"); diff --git a/drivers/media/video/mxc/capture/sensor_clock.c b/drivers/media/video/mxc/capture/sensor_clock.c new file mode 100644 index 000000000000..643919a45fbd --- /dev/null +++ b/drivers/media/video/mxc/capture/sensor_clock.c @@ -0,0 +1,97 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file sensor_clock.c + * + * @brief camera clock function + * + * @ingroup Camera + */ +#include +#include +#include +#include +#include +#include + +#if defined(CONFIG_MXC_IPU_V1) || defined(CONFIG_VIDEO_MXC_EMMA_CAMERA) \ + || defined(CONFIG_VIDEO_MXC_CSI_CAMERA_MODULE) \ + || defined(CONFIG_VIDEO_MXC_CSI_CAMERA) +/* + * set_mclk_rate + * + * @param p_mclk_freq mclk frequence + * + */ +void set_mclk_rate(uint32_t *p_mclk_freq) +{ + struct clk *clk; + uint32_t freq = 0; + + clk = clk_get(NULL, "csi_clk"); + + freq = clk_round_rate(clk, *p_mclk_freq); + clk_set_rate(clk, freq); + + *p_mclk_freq = freq; + + clk_put(clk); + pr_debug("mclk frequency = %d\n", *p_mclk_freq); +} +#else +/* + * set_mclk_rate + * + * @param p_mclk_freq mclk frequence + * @param csi csi 0 or csi 1 + * + */ +void set_mclk_rate(uint32_t *p_mclk_freq, uint32_t csi) +{ + struct clk *clk; + uint32_t freq = 0; + char *mclk; + + if (cpu_is_mx53()) { + if (csi == 0) + mclk = "ssi_ext1_clk"; + else { + pr_err("invalid csi num %d\n", csi); + return; + } + } else { + if (csi == 0) { + mclk = "csi_mclk1"; + } else if (csi == 1) { + mclk = "csi_mclk2"; + } else { + pr_err("invalid csi num %d\n", csi); + return; + } + } + + clk = clk_get(NULL, mclk); + + freq = clk_round_rate(clk, *p_mclk_freq); + clk_set_rate(clk, freq); + + *p_mclk_freq = freq; + + clk_put(clk); + pr_debug("%s frequency = %d\n", mclk, *p_mclk_freq); +} +#endif + +/* Exported symbols for modules. */ +EXPORT_SYMBOL(set_mclk_rate); diff --git a/drivers/media/video/mxc/output/Kconfig b/drivers/media/video/mxc/output/Kconfig new file mode 100644 index 000000000000..2153ad248907 --- /dev/null +++ b/drivers/media/video/mxc/output/Kconfig @@ -0,0 +1,28 @@ +config VIDEO_MXC_IPU_OUTPUT + bool "IPU v4l2 support" + depends on VIDEO_MXC_OUTPUT && MXC_IPU + default y + ---help--- + This is the video4linux2 driver for IPU post processing video output. + +config VIDEO_MXC_IPUV1_WVGA_OUTPUT + bool "IPUv1 WVGA v4l2 display support" + depends on VIDEO_MXC_OUTPUT && MXC_IPU + default n + ---help--- + This is the video4linux2 driver for IPUv1 WVGA post processing video output. + +config VIDEO_MXC_EMMA_OUTPUT + bool + depends on VIDEO_MXC_OUTPUT && MXC_EMMA && FB_MXC_SYNC_PANEL + default y + ---help--- + This is the video4linux2 driver for EMMA post processing video output. + +config VIDEO_MXC_OUTPUT_FBSYNC + bool "Synchronize the output with LCDC refresh" + depends on VIDEO_MXC_EMMA_OUTPUT + default y + ---help--- + Synchronize the post-processing with LCDC EOF (End of Frame) to + prevent tearing issue. If unsure, say Y. diff --git a/drivers/media/video/mxc/output/Makefile b/drivers/media/video/mxc/output/Makefile new file mode 100644 index 000000000000..1713fa3bf3ab --- /dev/null +++ b/drivers/media/video/mxc/output/Makefile @@ -0,0 +1,11 @@ +ifeq ($(CONFIG_VIDEO_MXC_EMMA_OUTPUT),y) + mx27_output-objs := mx27_v4l2_output.o mx27_pp.o + obj-$(CONFIG_VIDEO_MXC_OUTPUT) += mx27_output.o +endif + +ifeq ($(CONFIG_VIDEO_MXC_IPU_OUTPUT),y) + obj-$(CONFIG_VIDEO_MXC_OUTPUT) += mxc_v4l2_output.o +endif +ifeq ($(CONFIG_VIDEO_MXC_IPUV1_WVGA_OUTPUT),y) + obj-$(CONFIG_VIDEO_MXC_OUTPUT) += mx31_v4l2_wvga_output.o +endif diff --git a/drivers/media/video/mxc/output/mx31_v4l2_wvga_output.c b/drivers/media/video/mxc/output/mx31_v4l2_wvga_output.c new file mode 100644 index 000000000000..fe4346ee56dd --- /dev/null +++ b/drivers/media/video/mxc/output/mx31_v4l2_wvga_output.c @@ -0,0 +1,1928 @@ +/* + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file drivers/media/video/mxc/output/mxc_v4l2_output.c + * + * @brief MXC V4L2 Video Output Driver + * + * Video4Linux2 Output Device using MXC IPU Post-processing functionality. + * + * @ingroup MXC_V4L2_OUTPUT + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "mxc_v4l2_output.h" + +vout_data *g_vout; +#define SDC_FG_FB_FORMAT IPU_PIX_FMT_RGB565 + +struct v4l2_output mxc_outputs[2] = { + { + .index = MXC_V4L2_OUT_2_SDC, + .name = "DISP3 Video Out", + .type = V4L2_OUTPUT_TYPE_ANALOG, /* not really correct, + but no other choice */ + .audioset = 0, + .modulator = 0, + .std = V4L2_STD_UNKNOWN}, + { + .index = MXC_V4L2_OUT_2_ADC, + .name = "DISPx Video Out", + .type = V4L2_OUTPUT_TYPE_ANALOG, /* not really correct, + but no other choice */ + .audioset = 0, + .modulator = 0, + .std = V4L2_STD_UNKNOWN} +}; + +static int video_nr = 16; +static DEFINE_SPINLOCK(g_lock); +static unsigned int g_pp_out_number; +static unsigned int g_pp_in_number; + +/* debug counters */ +uint32_t g_irq_cnt; +uint32_t g_buf_output_cnt; +uint32_t g_buf_q_cnt; +uint32_t g_buf_dq_cnt; + +static inline uint32_t channel_2_dma(ipu_channel_t ch, ipu_buffer_t type) +{ + return ((type == IPU_INPUT_BUFFER) ? ((uint32_t) ch & 0xFF) : + ((type == IPU_OUTPUT_BUFFER) ? (((uint32_t) ch >> 8) & 0xFF) + : (((uint32_t) ch >> 16) & 0xFF))); +}; + +static inline uint32_t DMAParamAddr(uint32_t dma_ch) +{ + return 0x10000 | (dma_ch << 4); +}; + +#define QUEUE_SIZE (MAX_FRAME_NUM + 1) +static inline int queue_size(v4l_queue *q) +{ + if (q->tail >= q->head) + return q->tail - q->head; + else + return (q->tail + QUEUE_SIZE) - q->head; +} + +static inline int queue_buf(v4l_queue *q, int idx) +{ + if (((q->tail + 1) % QUEUE_SIZE) == q->head) + return -1; /* queue full */ + q->list[q->tail] = idx; + q->tail = (q->tail + 1) % QUEUE_SIZE; + return 0; +} + +static inline int dequeue_buf(v4l_queue *q) +{ + int ret; + if (q->tail == q->head) + return -1; /* queue empty */ + ret = q->list[q->head]; + q->head = (q->head + 1) % QUEUE_SIZE; + return ret; +} + +static inline int peek_next_buf(v4l_queue *q) +{ + if (q->tail == q->head) + return -1; /* queue empty */ + return q->list[q->head]; +} + +static inline unsigned long get_jiffies(struct timeval *t) +{ + struct timeval cur; + + if (t->tv_usec >= 1000000) { + t->tv_sec += t->tv_usec / 1000000; + t->tv_usec = t->tv_usec % 1000000; + } + + do_gettimeofday(&cur); + if ((t->tv_sec < cur.tv_sec) + || ((t->tv_sec == cur.tv_sec) && (t->tv_usec < cur.tv_usec))) + return jiffies; + + if (t->tv_usec < cur.tv_usec) { + cur.tv_sec = t->tv_sec - cur.tv_sec - 1; + cur.tv_usec = t->tv_usec + 1000000 - cur.tv_usec; + } else { + cur.tv_sec = t->tv_sec - cur.tv_sec; + cur.tv_usec = t->tv_usec - cur.tv_usec; + } + + return jiffies + timeval_to_jiffies(&cur); +} + +/*! + * Private function to free buffers + * + * @param bufs_paddr Array of physical address of buffers to be freed + * + * @param bufs_vaddr Array of virtual address of buffers to be freed + * + * @param num_buf Number of buffers to be freed + * + * @param size Size for each buffer to be free + * + * @return status 0 success. + */ +static int mxc_free_buffers(dma_addr_t bufs_paddr[], void *bufs_vaddr[], + int num_buf, int size) +{ + int i; + + for (i = 0; i < num_buf; i++) { + if (bufs_vaddr[i] != 0) { + dma_free_coherent(0, size, bufs_vaddr[i], + bufs_paddr[i]); + pr_debug("freed @ paddr=0x%08X\n", (u32) bufs_paddr[i]); + bufs_paddr[i] = 0; + bufs_vaddr[i] = NULL; + } + } + return 0; +} + +/*! + * Private function to allocate buffers + * + * @param bufs_paddr Output array of physical address of buffers allocated + * + * @param bufs_vaddr Output array of virtual address of buffers allocated + * + * @param num_buf Input number of buffers to allocate + * + * @param size Input size for each buffer to allocate + * + * @return status -0 Successfully allocated a buffer, -ENOBUFS failed. + */ +static int mxc_allocate_buffers(dma_addr_t bufs_paddr[], void *bufs_vaddr[], + int num_buf, int size) +{ + int i; + + for (i = 0; i < num_buf; i++) { + bufs_vaddr[i] = dma_alloc_coherent(0, size, + &bufs_paddr[i], + GFP_DMA | GFP_KERNEL); + + if (bufs_vaddr[i] == 0) { + mxc_free_buffers(bufs_paddr, bufs_vaddr, i, size); + printk(KERN_ERR "dma_alloc_coherent failed.\n"); + return -ENOBUFS; + } + pr_debug("allocated @ paddr=0x%08X, size=%d.\n", + (u32) bufs_paddr[i], size); + } + + return 0; +} + +/* + * Returns bits per pixel for given pixel format + * + * @param pixelformat V4L2_PIX_FMT_RGB565, + * V4L2_PIX_FMT_BGR24 or V4L2_PIX_FMT_BGR32 + * + * @return bits per pixel of pixelformat + */ +static u32 fmt_to_bpp(u32 pixelformat) +{ + u32 bpp; + + switch (pixelformat) { + case V4L2_PIX_FMT_RGB565: + bpp = 16; + break; + case V4L2_PIX_FMT_BGR24: + case V4L2_PIX_FMT_RGB24: + bpp = 24; + break; + case V4L2_PIX_FMT_BGR32: + case V4L2_PIX_FMT_RGB32: + bpp = 32; + break; + default: + bpp = 8; + break; + } + return bpp; +} + +static u32 bpp_to_fmt(struct fb_info *fbi) +{ + if (fbi->var.nonstd) + return fbi->var.nonstd; + + if (fbi->var.bits_per_pixel == 24) + return V4L2_PIX_FMT_BGR24; + else if (fbi->var.bits_per_pixel == 32) + return V4L2_PIX_FMT_BGR32; + else if (fbi->var.bits_per_pixel == 16) + return V4L2_PIX_FMT_RGB565; + + return 0; +} + +static void mxc_v4l2out_timer_handler(unsigned long arg) +{ + int index; + unsigned long timeout; + unsigned long lock_flags = 0; + vout_data *vout = (vout_data *) arg; + + dev_dbg(vout->video_dev->dev, "timer handler: %lu\n", jiffies); + + spin_lock_irqsave(&g_lock, lock_flags); + + if ((vout->state == STATE_STREAM_STOPPING) + || (vout->state == STATE_STREAM_OFF)) + goto exit0; + /* + * If timer occurs before IPU h/w is ready, then set the state to + * paused and the timer will be set again when next buffer is queued + * or PP comletes + */ + if (vout->ipu_buf[0] != -1) { + dev_dbg(vout->video_dev->dev, "IPU buffer busy\n"); + vout->state = STATE_STREAM_PAUSED; + goto exit0; + } + + /* One frame buffer should be ready here */ + if (vout->frame_count % 2 == 1) { + /* set BUF0 rdy */ + if (ipu_select_buffer(vout->display_ch, IPU_INPUT_BUFFER, 0) < + 0) + pr_debug("error selecting display buf 0"); + } else { + if (ipu_select_buffer(vout->display_ch, IPU_INPUT_BUFFER, 1) < + 0) + pr_debug("error selecting display buf 1"); + } + + /* Dequeue buffer and pass to IPU */ + index = dequeue_buf(&vout->ready_q); + if (index == -1) { /* no buffers ready, should never occur */ + dev_err(vout->video_dev->dev, + "mxc_v4l2out: timer - no queued buffers ready\n"); + goto exit0; + } + + g_buf_dq_cnt++; + vout->frame_count++; + vout->ipu_buf[1] = vout->ipu_buf[0] = index; + + if (ipu_update_channel_buffer(vout->post_proc_ch, IPU_INPUT_BUFFER, + 0, + vout->v4l2_bufs[vout->ipu_buf[0]].m. + offset) < 0) + goto exit0; + + if (ipu_update_channel_buffer(vout->post_proc_ch, IPU_INPUT_BUFFER, + 1, + vout->v4l2_bufs[vout->ipu_buf[0]].m. + offset + vout->v2f.fmt.pix.width / 2) < 0) + goto exit0; + + /* All buffer should now ready in IPU out, tranfer to display buf */ + if (ipu_update_channel_buffer(vout->post_proc_ch, IPU_OUTPUT_BUFFER, + 0, + vout-> + display_bufs[(vout->frame_count - + 1) % 2]) < 0) { + dev_err(vout->video_dev->dev, + "unable to update buffer %d address\n", + vout->next_rdy_ipu_buf); + goto exit0; + } + if (ipu_update_channel_buffer(vout->post_proc_ch, IPU_OUTPUT_BUFFER, + 1, + vout-> + display_bufs[(vout->frame_count - + 1) % 2] + + vout->crop_current.width / 2 * + bytes_per_pixel(SDC_FG_FB_FORMAT)) < 0) { + dev_err(vout->video_dev->dev, + "unable to update buffer %d address\n", + vout->next_rdy_ipu_buf); + goto exit0; + } + + if (ipu_select_buffer(vout->post_proc_ch, IPU_INPUT_BUFFER, 0) < 0) { + dev_err(vout->video_dev->dev, + "unable to set IPU buffer ready\n"); + goto exit0; + } + + if (ipu_select_buffer(vout->post_proc_ch, IPU_OUTPUT_BUFFER, 0) < 0) { + dev_err(vout->video_dev->dev, + "unable to set IPU buffer ready\n"); + goto exit0; + } + + /* Setup timer for next buffer */ + index = peek_next_buf(&vout->ready_q); + if (index != -1) { + /* if timestamp is 0, then default to 30fps */ + if ((vout->v4l2_bufs[index].timestamp.tv_sec == 0) + && (vout->v4l2_bufs[index].timestamp.tv_usec == 0)) + timeout = + vout->start_jiffies + vout->frame_count * HZ / 30; + else + timeout = + get_jiffies(&vout->v4l2_bufs[index].timestamp); + + if (jiffies >= timeout) { + dev_dbg(vout->video_dev->dev, + "warning: timer timeout already expired.\n"); + } + if (mod_timer(&vout->output_timer, timeout)) + dev_dbg(vout->video_dev->dev, + "warning: timer was already set\n"); + + dev_dbg(vout->video_dev->dev, + "timer handler next schedule: %lu\n", timeout); + } else { + vout->state = STATE_STREAM_PAUSED; + } + +exit0: + spin_unlock_irqrestore(&g_lock, lock_flags); +} + +extern void _ipu_write_param_mem(uint32_t addr, uint32_t *data, + uint32_t numWords); + +static irqreturn_t mxc_v4l2out_pp_in_irq_handler(int irq, void *dev_id) +{ + unsigned long lock_flags = 0; + vout_data *vout = dev_id; + uint32_t u_offset; + uint32_t v_offset; + uint32_t local_params[4]; + uint32_t width, height; + uint32_t dma_chan; + + spin_lock_irqsave(&g_lock, lock_flags); + g_irq_cnt++; + + dma_chan = channel_2_dma(vout->post_proc_ch, IPU_INPUT_BUFFER); + memset(&local_params, 0, sizeof(local_params)); + + if (g_pp_in_number % 2 == 1) { + u_offset = vout->offset.u_offset - vout->v2f.fmt.pix.width / 4; + v_offset = vout->offset.v_offset - vout->v2f.fmt.pix.width / 4; + width = vout->v2f.fmt.pix.width / 2; + height = vout->v2f.fmt.pix.height; + local_params[3] = + (uint32_t) ((width - 1) << 12) | ((uint32_t) (height - + 1) << 24); + local_params[1] = (1UL << (46 - 32)) | (u_offset << (53 - 32)); + local_params[2] = u_offset >> (64 - 53); + local_params[2] |= v_offset << (79 - 64); + local_params[3] |= v_offset >> (96 - 79); + _ipu_write_param_mem(DMAParamAddr(dma_chan), local_params, 4); + + if (ipu_select_buffer(vout->post_proc_ch, IPU_INPUT_BUFFER, 1) < + 0) { + dev_err(vout->video_dev->dev, + "unable to set IPU buffer ready\n"); + } + } else { + u_offset = vout->offset.u_offset; + v_offset = vout->offset.v_offset; + width = vout->v2f.fmt.pix.width / 2; + height = vout->v2f.fmt.pix.height; + local_params[3] = + (uint32_t) ((width - 1) << 12) | ((uint32_t) (height - + 1) << 24); + local_params[1] = (1UL << (46 - 32)) | (u_offset << (53 - 32)); + local_params[2] = u_offset >> (64 - 53); + local_params[2] |= v_offset << (79 - 64); + local_params[3] |= v_offset >> (96 - 79); + _ipu_write_param_mem(DMAParamAddr(dma_chan), local_params, 4); + } + g_pp_in_number++; + + spin_unlock_irqrestore(&g_lock, lock_flags); + + return IRQ_HANDLED; +} + +static irqreturn_t mxc_v4l2out_pp_out_irq_handler(int irq, void *dev_id) +{ + vout_data *vout = dev_id; + int index; + unsigned long timeout; + u32 lock_flags = 0; + + spin_lock_irqsave(&g_lock, lock_flags); + + if (g_pp_out_number % 2 == 1) { + if (ipu_select_buffer(vout->post_proc_ch, IPU_OUTPUT_BUFFER, 1) + < 0) { + dev_err(vout->video_dev->dev, + "unable to set IPU buffer ready\n"); + } + } else { + if (vout->ipu_buf[0] != -1) { + vout->v4l2_bufs[vout->ipu_buf[0]].flags = + V4L2_BUF_FLAG_DONE; + queue_buf(&vout->done_q, vout->ipu_buf[0]); + wake_up_interruptible(&vout->v4l_bufq); + vout->ipu_buf[0] = -1; + } + index = peek_next_buf(&vout->ready_q); + if (vout->state == STATE_STREAM_STOPPING) { + if ((vout->ipu_buf[0] == -1) + && (vout->ipu_buf[1] == -1)) + vout->state = STATE_STREAM_OFF; + } else if ((vout->state == STATE_STREAM_PAUSED) + && (index != -1)) { + /*! + * Setup timer for next buffer, + * when stream has been paused + */ + pr_debug("next index %d\n", index); + + /* if timestamp is 0, then default to 30fps */ + if ((vout->v4l2_bufs[index].timestamp.tv_sec == 0) + && (vout->v4l2_bufs[index].timestamp.tv_usec == 0)) + timeout = + vout->start_jiffies + + vout->frame_count * HZ / 30; + else + timeout = + get_jiffies(&vout->v4l2_bufs[index]. + timestamp); + + if (jiffies >= timeout) { + pr_debug + ("warning: timer timeout" + "already expired.\n"); + } + + vout->state = STATE_STREAM_ON; + + if (mod_timer(&vout->output_timer, timeout)) + pr_debug("warning: timer was already set\n"); + + pr_debug("timer handler next schedule: %lu\n", timeout); + } + } + g_pp_out_number++; + + spin_unlock_irqrestore(&g_lock, lock_flags); + return IRQ_HANDLED; +} + +/*! + * Start the output stream + * + * @param vout structure vout_data * + * + * @return status 0 Success + */ +static int mxc_v4l2out_streamon(vout_data *vout) +{ + struct device *dev = vout->video_dev->dev; + ipu_channel_params_t params; + struct mxcfb_pos fb_pos; + struct fb_var_screeninfo fbvar; + struct fb_info *fbi = + registered_fb[vout->output_fb_num[vout->cur_disp_output]]; + int pp_in_buf[2]; + u16 out_width; + u16 out_height; + ipu_channel_t display_input_ch = MEM_PP_MEM; + bool use_direct_adc = false; + mm_segment_t old_fs; + + if (!vout) + return -EINVAL; + + if (vout->state != STATE_STREAM_OFF) + return -EBUSY; + + if (queue_size(&vout->ready_q) < 2) { + dev_err(dev, "2 buffers not been queued yet!\n"); + return -EINVAL; + } + + out_width = vout->crop_current.width; + out_height = vout->crop_current.height; + + vout->next_done_ipu_buf = vout->next_rdy_ipu_buf = 0; + vout->ipu_buf[0] = pp_in_buf[0] = dequeue_buf(&vout->ready_q); + vout->ipu_buf[1] = pp_in_buf[1] = vout->ipu_buf[0]; + vout->frame_count = 1; + g_pp_out_number = 1; + g_pp_in_number = 1; + + ipu_enable_irq(IPU_IRQ_PP_IN_EOF); + ipu_enable_irq(IPU_IRQ_PP_OUT_EOF); + + /* Init Display Channel */ +#ifdef CONFIG_FB_MXC_ASYNC_PANEL + if (vout->cur_disp_output < DISP3) { + mxcfb_set_refresh_mode(fbi, MXCFB_REFRESH_OFF, 0); + fbi = NULL; + if (ipu_can_rotate_in_place(vout->rotate)) { + dev_dbg(dev, "Using PP direct to ADC channel\n"); + use_direct_adc = true; + vout->display_ch = MEM_PP_ADC; + vout->post_proc_ch = MEM_PP_ADC; + + memset(¶ms, 0, sizeof(params)); + params.mem_pp_adc.in_width = vout->v2f.fmt.pix.width; + params.mem_pp_adc.in_height = vout->v2f.fmt.pix.height; + params.mem_pp_adc.in_pixel_fmt = + vout->v2f.fmt.pix.pixelformat; + params.mem_pp_adc.out_width = out_width; + params.mem_pp_adc.out_height = out_height; + params.mem_pp_adc.out_pixel_fmt = SDC_FG_FB_FORMAT; +#ifdef CONFIG_FB_MXC_EPSON_PANEL + params.mem_pp_adc.out_left = + 2 + vout->crop_current.left; +#else + params.mem_pp_adc.out_left = + 12 + vout->crop_current.left; +#endif + params.mem_pp_adc.out_top = vout->crop_current.top; + if (ipu_init_channel( + vout->post_proc_ch, ¶ms) != 0) { + dev_err(dev, "Error initializing PP chan\n"); + return -EINVAL; + } + + if (ipu_init_channel_buffer(vout->post_proc_ch, + IPU_INPUT_BUFFER, + params.mem_pp_adc. + in_pixel_fmt, + params.mem_pp_adc.in_width, + params.mem_pp_adc.in_height, + vout->v2f.fmt.pix. + bytesperline / + bytes_per_pixel(params. + mem_pp_adc. + in_pixel_fmt), + vout->rotate, + vout-> + v4l2_bufs[pp_in_buf[0]].m. + offset, + vout-> + v4l2_bufs[pp_in_buf[1]].m. + offset, + vout->offset.u_offset, + vout->offset.v_offset) != + 0) { + dev_err(dev, "Error initializing PP in buf\n"); + return -EINVAL; + } + + if (ipu_init_channel_buffer(vout->post_proc_ch, + IPU_OUTPUT_BUFFER, + params.mem_pp_adc. + out_pixel_fmt, out_width, + out_height, out_width, + vout->rotate, 0, 0, 0, + 0) != 0) { + dev_err(dev, + "Error initializing PP" + "output buffer\n"); + return -EINVAL; + } + + } else { + dev_dbg(dev, "Using ADC SYS2 channel\n"); + vout->display_ch = ADC_SYS2; + vout->post_proc_ch = MEM_PP_MEM; + + if (vout->display_bufs[0]) { + mxc_free_buffers(vout->display_bufs, + vout->display_bufs_vaddr, + 2, vout->display_buf_size); + } + + vout->display_buf_size = vout->crop_current.width * + vout->crop_current.height * + fmt_to_bpp(SDC_FG_FB_FORMAT) / 8; + mxc_allocate_buffers(vout->display_bufs, + vout->display_bufs_vaddr, + 2, vout->display_buf_size); + + memset(¶ms, 0, sizeof(params)); + params.adc_sys2.disp = vout->cur_disp_output; + params.adc_sys2.ch_mode = WriteTemplateNonSeq; +#ifdef CONFIG_FB_MXC_EPSON_PANEL + params.adc_sys2.out_left = 2 + vout->crop_current.left; +#else + params.adc_sys2.out_left = 12 + vout->crop_current.left; +#endif + params.adc_sys2.out_top = vout->crop_current.top; + if (ipu_init_channel(ADC_SYS2, ¶ms) < 0) + return -EINVAL; + + if (ipu_init_channel_buffer(vout->display_ch, + IPU_INPUT_BUFFER, + SDC_FG_FB_FORMAT, + out_width, out_height, + out_width, IPU_ROTATE_NONE, + vout->display_bufs[0], + vout->display_bufs[1], 0, + 0) != 0) { + dev_err(dev, + "Error initializing SDC FG buffer\n"); + return -EINVAL; + } + } + } else +#endif + { /* Use SDC */ + dev_dbg(dev, "Using SDC channel\n"); + + fbvar = fbi->var; + if (vout->cur_disp_output == 3) { + vout->display_ch = MEM_FG_SYNC; + fbvar.bits_per_pixel = 16; + fbvar.nonstd = IPU_PIX_FMT_UYVY; + + fbvar.xres = fbvar.xres_virtual = out_width; + fbvar.yres = out_height; + fbvar.yres_virtual = out_height * 2; + } else if (vout->cur_disp_output == 5) { + vout->display_ch = MEM_DC_SYNC; + fbvar.bits_per_pixel = 16; + fbvar.nonstd = IPU_PIX_FMT_UYVY; + + fbvar.xres = fbvar.xres_virtual = out_width; + fbvar.yres = out_height; + fbvar.yres_virtual = out_height * 2; + } else { + vout->display_ch = MEM_BG_SYNC; + } + + fbvar.activate |= FB_ACTIVATE_FORCE; + fb_set_var(fbi, &fbvar); + + fb_pos.x = vout->crop_current.left; + fb_pos.y = vout->crop_current.top; + if (fbi->fbops->fb_ioctl) { + old_fs = get_fs(); + set_fs(KERNEL_DS); + fbi->fbops->fb_ioctl(fbi, MXCFB_SET_OVERLAY_POS, + (unsigned long)&fb_pos); + set_fs(old_fs); + } + + vout->display_bufs[1] = fbi->fix.smem_start; + vout->display_bufs[0] = fbi->fix.smem_start + + (fbi->fix.line_length * fbi->var.yres); + vout->display_buf_size = vout->crop_current.width * + vout->crop_current.height * fbi->var.bits_per_pixel / 8; + + vout->post_proc_ch = MEM_PP_MEM; + } + + /* Init PP */ + if (use_direct_adc == false) { + if (vout->rotate >= IPU_ROTATE_90_RIGHT) { + out_width = vout->crop_current.height; + out_height = vout->crop_current.width; + } + memset(¶ms, 0, sizeof(params)); + params.mem_pp_mem.in_width = vout->v2f.fmt.pix.width / 2; + params.mem_pp_mem.in_height = vout->v2f.fmt.pix.height; + params.mem_pp_mem.in_pixel_fmt = vout->v2f.fmt.pix.pixelformat; + params.mem_pp_mem.out_width = out_width / 2; + params.mem_pp_mem.out_height = out_height; + if (vout->display_ch == ADC_SYS2) + params.mem_pp_mem.out_pixel_fmt = SDC_FG_FB_FORMAT; + else + params.mem_pp_mem.out_pixel_fmt = bpp_to_fmt(fbi); + if (ipu_init_channel(vout->post_proc_ch, ¶ms) != 0) { + dev_err(dev, "Error initializing PP channel\n"); + return -EINVAL; + } + + if (ipu_init_channel_buffer(vout->post_proc_ch, + IPU_INPUT_BUFFER, + params.mem_pp_mem.in_pixel_fmt, + params.mem_pp_mem.in_width, + params.mem_pp_mem.in_height, + vout->v2f.fmt.pix.bytesperline / + bytes_per_pixel(params.mem_pp_mem. + in_pixel_fmt), + IPU_ROTATE_NONE, + vout->v4l2_bufs[pp_in_buf[0]].m. + offset, + vout->v4l2_bufs[pp_in_buf[0]].m. + offset + params.mem_pp_mem.in_width, + vout->offset.u_offset, + vout->offset.v_offset) != 0) { + dev_err(dev, "Error initializing PP input buffer\n"); + return -EINVAL; + } + + if (!ipu_can_rotate_in_place(vout->rotate)) { + if (vout->rot_pp_bufs[0]) { + mxc_free_buffers(vout->rot_pp_bufs, + vout->rot_pp_bufs_vaddr, 2, + vout->display_buf_size); + } + if (mxc_allocate_buffers + (vout->rot_pp_bufs, vout->rot_pp_bufs_vaddr, 2, + vout->display_buf_size) < 0) + return -ENOBUFS; + + if (ipu_init_channel_buffer(vout->post_proc_ch, + IPU_OUTPUT_BUFFER, + params.mem_pp_mem. + out_pixel_fmt, out_width, + out_height, out_width, + IPU_ROTATE_NONE, + vout->rot_pp_bufs[0], + vout->rot_pp_bufs[1], 0, + 0) != 0) { + dev_err(dev, + "Error initializing" + "PP output buffer\n"); + return -EINVAL; + } + + if (ipu_init_channel(MEM_ROT_PP_MEM, NULL) != 0) { + dev_err(dev, + "Error initializing PP ROT channel\n"); + return -EINVAL; + } + + if (ipu_init_channel_buffer(MEM_ROT_PP_MEM, + IPU_INPUT_BUFFER, + params.mem_pp_mem. + out_pixel_fmt, out_width, + out_height, out_width, + vout->rotate, + vout->rot_pp_bufs[0], + vout->rot_pp_bufs[1], 0, + 0) != 0) { + dev_err(dev, + "Error initializing PP ROT" + "input buffer\n"); + return -EINVAL; + } + + /* swap width and height */ + if (vout->rotate >= IPU_ROTATE_90_RIGHT) { + out_width = vout->crop_current.width; + out_height = vout->crop_current.height; + } + + if (ipu_init_channel_buffer(MEM_ROT_PP_MEM, + IPU_OUTPUT_BUFFER, + params.mem_pp_mem. + out_pixel_fmt, out_width, + out_height, out_width, + IPU_ROTATE_NONE, + vout->display_bufs[0], + vout->display_bufs[1], 0, + 0) != 0) { + dev_err(dev, + "Error initializing PP" + "output buffer\n"); + return -EINVAL; + } + + if (ipu_link_channels(vout->post_proc_ch, + MEM_ROT_PP_MEM) < 0) + return -EINVAL; + + ipu_select_buffer(MEM_ROT_PP_MEM, IPU_OUTPUT_BUFFER, 0); + ipu_select_buffer(MEM_ROT_PP_MEM, IPU_OUTPUT_BUFFER, 1); + + ipu_enable_channel(MEM_ROT_PP_MEM); + + display_input_ch = MEM_ROT_PP_MEM; + } else { + if (ipu_init_channel_buffer(vout->post_proc_ch, + IPU_OUTPUT_BUFFER, + params.mem_pp_mem. + out_pixel_fmt, + out_width / 2, + out_height, + out_width, + vout->rotate, + vout->display_bufs[0], + vout->display_bufs[0] + + + out_width / 2 * + bytes_per_pixel + (SDC_FG_FB_FORMAT), 0, + 0) != 0) { + dev_err(dev, + "Error initializing PP" + "output buffer\n"); + return -EINVAL; + } + } + if (ipu_unlink_channels( + display_input_ch, vout->display_ch) < 0) { + dev_err(dev, "Error linking ipu channels\n"); + return -EINVAL; + } + } + + vout->state = STATE_STREAM_PAUSED; + + ipu_select_buffer(vout->post_proc_ch, IPU_INPUT_BUFFER, 0); + + if (use_direct_adc == false) { + ipu_select_buffer(vout->post_proc_ch, IPU_OUTPUT_BUFFER, 0); + ipu_enable_channel(vout->post_proc_ch); + + if (fbi) { + acquire_console_sem(); + fb_blank(fbi, FB_BLANK_UNBLANK); + release_console_sem(); + } else { + ipu_enable_channel(vout->display_ch); + } + } else { + ipu_enable_channel(vout->post_proc_ch); + } + + vout->start_jiffies = jiffies; + dev_dbg(dev, + "streamon: start time = %lu jiffies\n", vout->start_jiffies); + + return 0; +} + +/*! + * Shut down the voutera + * + * @param vout structure vout_data * + * + * @return status 0 Success + */ +static int mxc_v4l2out_streamoff(vout_data *vout) +{ + struct fb_info *fbi = + registered_fb[vout->output_fb_num[vout->cur_disp_output]]; + int i, retval = 0; + unsigned long lockflag = 0; + + if (!vout) + return -EINVAL; + + if (vout->state == STATE_STREAM_OFF) + return 0; + + spin_lock_irqsave(&g_lock, lockflag); + + del_timer(&vout->output_timer); + + if (vout->state == STATE_STREAM_ON) + vout->state = STATE_STREAM_STOPPING; + + ipu_disable_irq(IPU_IRQ_PP_IN_EOF); + ipu_disable_irq(IPU_IRQ_PP_OUT_EOF); + + spin_unlock_irqrestore(&g_lock, lockflag); + + if (vout->post_proc_ch == MEM_PP_MEM) { /* SDC or ADC with Rotation */ + if (!ipu_can_rotate_in_place(vout->rotate)) { + ipu_unlink_channels(MEM_PP_MEM, MEM_ROT_PP_MEM); + ipu_unlink_channels(MEM_ROT_PP_MEM, vout->display_ch); + ipu_disable_channel(MEM_ROT_PP_MEM, true); + + if (vout->rot_pp_bufs[0]) { + mxc_free_buffers(vout->rot_pp_bufs, + vout->rot_pp_bufs_vaddr, 2, + vout->display_buf_size); + } + } else { + ipu_unlink_channels(MEM_PP_MEM, vout->display_ch); + } + ipu_disable_channel(MEM_PP_MEM, true); + + if (vout->display_ch == ADC_SYS2) { + ipu_disable_channel(vout->display_ch, true); + ipu_uninit_channel(vout->display_ch); + } else { + fbi->var.activate |= FB_ACTIVATE_FORCE; + fb_set_var(fbi, &fbi->var); + + if (vout->display_ch == MEM_FG_SYNC) { + acquire_console_sem(); + fb_blank(fbi, FB_BLANK_POWERDOWN); + release_console_sem(); + } + + vout->display_bufs[0] = 0; + vout->display_bufs[1] = 0; + } + + ipu_uninit_channel(MEM_PP_MEM); + if (!ipu_can_rotate_in_place(vout->rotate)) + ipu_uninit_channel(MEM_ROT_PP_MEM); + } else { /* ADC Direct */ + ipu_disable_channel(MEM_PP_ADC, true); + ipu_uninit_channel(MEM_PP_ADC); + } + vout->ready_q.head = vout->ready_q.tail = 0; + vout->done_q.head = vout->done_q.tail = 0; + for (i = 0; i < vout->buffer_cnt; i++) { + vout->v4l2_bufs[i].flags = 0; + vout->v4l2_bufs[i].timestamp.tv_sec = 0; + vout->v4l2_bufs[i].timestamp.tv_usec = 0; + } + + vout->state = STATE_STREAM_OFF; + +#ifdef CONFIG_FB_MXC_ASYNC_PANEL + if (vout->cur_disp_output < DISP3) { + if (vout->display_bufs[0] != 0) { + mxc_free_buffers(vout->display_bufs, + vout->display_bufs_vaddr, 2, + vout->display_buf_size); + } + + mxcfb_set_refresh_mode(registered_fb + [vout-> + output_fb_num[vout->cur_disp_output]], + MXCFB_REFRESH_PARTIAL, 0); + } +#endif + + return retval; +} + +/* + * Valid whether the palette is supported + * + * @param palette V4L2_PIX_FMT_RGB565, V4L2_PIX_FMT_BGR24 or V4L2_PIX_FMT_BGR32 + * + * @return 1 if supported, 0 if failed + */ +static inline int valid_mode(u32 palette) +{ + return ((palette == V4L2_PIX_FMT_RGB565) || + (palette == V4L2_PIX_FMT_BGR24) || + (palette == V4L2_PIX_FMT_RGB24) || + (palette == V4L2_PIX_FMT_BGR32) || + (palette == V4L2_PIX_FMT_RGB32) || + (palette == V4L2_PIX_FMT_NV12) || + (palette == V4L2_PIX_FMT_YUV422P) || + (palette == V4L2_PIX_FMT_YUV420)); +} + +/* + * V4L2 - Handles VIDIOC_G_FMT Ioctl + * + * @param vout structure vout_data * + * + * @param v4l2_format structure v4l2_format * + * + * @return status 0 success, EINVAL failed + */ +static int mxc_v4l2out_g_fmt(vout_data *vout, struct v4l2_format *f) +{ + if (f->type != V4L2_BUF_TYPE_VIDEO_OUTPUT) + return -EINVAL; + *f = vout->v2f; + return 0; +} + +/* + * V4L2 - Handles VIDIOC_S_FMT Ioctl + * + * @param vout structure vout_data * + * + * @param v4l2_format structure v4l2_format * + * + * @return status 0 success, EINVAL failed + */ +static int mxc_v4l2out_s_fmt(vout_data *vout, struct v4l2_format *f) +{ + int retval = 0; + u32 size = 0; + u32 bytesperline; + + if (f->type != V4L2_BUF_TYPE_VIDEO_OUTPUT) { + retval = -EINVAL; + goto err0; + } + if (!valid_mode(f->fmt.pix.pixelformat)) { + dev_err(vout->video_dev->dev, "pixel format not supported\n"); + retval = -EINVAL; + goto err0; + } + + bytesperline = (f->fmt.pix.width * fmt_to_bpp(f->fmt.pix.pixelformat)) / + 8; + if (f->fmt.pix.bytesperline < bytesperline) { + f->fmt.pix.bytesperline = bytesperline; + } else { + bytesperline = f->fmt.pix.bytesperline; + } + + switch (f->fmt.pix.pixelformat) { + case V4L2_PIX_FMT_YUV422P: + /* byteperline for YUV planar formats is for + Y plane only */ + size = bytesperline * f->fmt.pix.height * 2; + break; + case V4L2_PIX_FMT_YUV420: + case V4L2_PIX_FMT_NV12: + size = (bytesperline * f->fmt.pix.height * 3) / 2; + break; + default: + size = bytesperline * f->fmt.pix.height; + break; + } + + /* Return the actual size of the image to the app */ + if (f->fmt.pix.sizeimage < size) + f->fmt.pix.sizeimage = size; + else + size = f->fmt.pix.sizeimage; + + vout->v2f.fmt.pix = f->fmt.pix; + if (vout->v2f.fmt.pix.priv != 0) { + if (copy_from_user(&vout->offset, + (void *)vout->v2f.fmt.pix.priv, + sizeof(vout->offset))) { + retval = -EFAULT; + goto err0; + } + } else { + vout->offset.u_offset = 0; + vout->offset.v_offset = 0; + } + + retval = 0; +err0: + return retval; +} + +/* + * V4L2 - Handles VIDIOC_G_CTRL Ioctl + * + * @param vout structure vout_data * + * + * @param c structure v4l2_control * + * + * @return status 0 success, EINVAL failed + */ +static int mxc_get_v42lout_control(vout_data *vout, struct v4l2_control *c) +{ + switch (c->id) { + case V4L2_CID_HFLIP: + return (vout->rotate & IPU_ROTATE_HORIZ_FLIP) ? 1 : 0; + case V4L2_CID_VFLIP: + return (vout->rotate & IPU_ROTATE_VERT_FLIP) ? 1 : 0; + case (V4L2_CID_PRIVATE_BASE + 1): + return vout->rotate; + default: + return -EINVAL; + } +} + +/* + * V4L2 - Handles VIDIOC_S_CTRL Ioctl + * + * @param vout structure vout_data * + * + * @param c structure v4l2_control * + * + * @return status 0 success, EINVAL failed + */ +static int mxc_set_v42lout_control(vout_data *vout, struct v4l2_control *c) +{ + switch (c->id) { + case V4L2_CID_HFLIP: + vout->rotate |= c->value ? IPU_ROTATE_HORIZ_FLIP : + IPU_ROTATE_NONE; + break; + case V4L2_CID_VFLIP: + vout->rotate |= c->value ? IPU_ROTATE_VERT_FLIP : + IPU_ROTATE_NONE; + break; + case V4L2_CID_MXC_ROT: + vout->rotate = c->value; + break; + default: + return -EINVAL; + } + return 0; +} + +/*! + * V4L2 interface - open function + * + * @param inode structure inode * + * + * @param file structure file * + * + * @return status 0 success, ENODEV invalid device instance, + * ENODEV timeout, ERESTARTSYS interrupted by user + */ +static int mxc_v4l2out_open(struct inode *inode, struct file *file) +{ + struct video_device *dev = video_devdata(file); + vout_data *vout = video_get_drvdata(dev); + int err; + + if (!vout) + return -ENODEV; + + down(&vout->busy_lock); + + err = -EINTR; + if (signal_pending(current)) + goto oops; + + if (vout->open_count++ == 0) { + ipu_request_irq(IPU_IRQ_PP_IN_EOF, + mxc_v4l2out_pp_in_irq_handler, + 0, dev->name, vout); + ipu_request_irq(IPU_IRQ_PP_OUT_EOF, + mxc_v4l2out_pp_out_irq_handler, + 0, dev->name, vout); + + init_waitqueue_head(&vout->v4l_bufq); + + init_timer(&vout->output_timer); + vout->output_timer.function = mxc_v4l2out_timer_handler; + vout->output_timer.data = (unsigned long)vout; + + vout->state = STATE_STREAM_OFF; + vout->rotate = IPU_ROTATE_NONE; + g_irq_cnt = g_buf_output_cnt = g_buf_q_cnt = g_buf_dq_cnt = 0; + + } + + file->private_data = dev; + + up(&vout->busy_lock); + + return 0; + +oops: + up(&vout->busy_lock); + return err; +} + +/*! + * V4L2 interface - close function + * + * @param inode struct inode * + * + * @param file struct file * + * + * @return 0 success + */ +static int mxc_v4l2out_close(struct inode *inode, struct file *file) +{ + struct video_device *dev = video_devdata(file); + vout_data *vout = video_get_drvdata(dev); + + if (--vout->open_count == 0) { + if (vout->state != STATE_STREAM_OFF) + mxc_v4l2out_streamoff(vout); + + ipu_free_irq(IPU_IRQ_PP_IN_EOF, vout); + ipu_free_irq(IPU_IRQ_PP_OUT_EOF, vout); + + file->private_data = NULL; + + mxc_free_buffers(vout->queue_buf_paddr, vout->queue_buf_vaddr, + vout->buffer_cnt, vout->queue_buf_size); + vout->buffer_cnt = 0; + mxc_free_buffers(vout->rot_pp_bufs, vout->rot_pp_bufs_vaddr, 2, + vout->display_buf_size); + + /* capture off */ + wake_up_interruptible(&vout->v4l_bufq); + } + + return 0; +} + +/*! + * V4L2 interface - ioctl function + * + * @param inode struct inode * + * + * @param file struct file * + * + * @param ioctlnr unsigned int + * + * @param arg void * + * + * @return 0 success, ENODEV for invalid device instance, + * -1 for other errors. + */ +static int +mxc_v4l2out_do_ioctl(struct inode *inode, struct file *file, + unsigned int ioctlnr, void *arg) +{ + struct video_device *vdev = file->private_data; + vout_data *vout = video_get_drvdata(vdev); + int retval = 0; + int i = 0; + + if (!vout) + return -EBADF; + + /* make this _really_ smp-safe */ + if (down_interruptible(&vout->busy_lock)) + return -EBUSY; + + switch (ioctlnr) { + case VIDIOC_QUERYCAP: + { + struct v4l2_capability *cap = arg; + strcpy(cap->driver, "mxc_v4l2_output"); + cap->version = 0; + cap->capabilities = + V4L2_CAP_VIDEO_OUTPUT | V4L2_CAP_STREAMING; + cap->card[0] = '\0'; + cap->bus_info[0] = '\0'; + retval = 0; + break; + } + case VIDIOC_G_FMT: + { + struct v4l2_format *gf = arg; + retval = mxc_v4l2out_g_fmt(vout, gf); + break; + } + case VIDIOC_S_FMT: + { + struct v4l2_format *sf = arg; + if (vout->state != STATE_STREAM_OFF) { + retval = -EBUSY; + break; + } + retval = mxc_v4l2out_s_fmt(vout, sf); + break; + } + case VIDIOC_REQBUFS: + { + struct v4l2_requestbuffers *req = arg; + if ((req->type != V4L2_BUF_TYPE_VIDEO_OUTPUT) || + (req->memory != V4L2_MEMORY_MMAP)) { + dev_dbg(vdev->dev, + "VIDIOC_REQBUFS: incorrect" + "buffer type\n"); + retval = -EINVAL; + break; + } + + if (req->count == 0) + mxc_v4l2out_streamoff(vout); + + if (vout->state == STATE_STREAM_OFF) { + if (vout->queue_buf_paddr[0] != 0) { + mxc_free_buffers(vout->queue_buf_paddr, + vout->queue_buf_vaddr, + vout->buffer_cnt, + vout->queue_buf_size); + dev_dbg(vdev->dev, + "VIDIOC_REQBUFS:" + "freed buffers\n"); + } + vout->buffer_cnt = 0; + } else { + dev_dbg(vdev->dev, + "VIDIOC_REQBUFS: Buffer is in use\n"); + retval = -EBUSY; + break; + } + + if (req->count == 0) + break; + + if (req->count < MIN_FRAME_NUM) + req->count = MIN_FRAME_NUM; + else if (req->count > MAX_FRAME_NUM) + req->count = MAX_FRAME_NUM; + vout->buffer_cnt = req->count; + vout->queue_buf_size = + PAGE_ALIGN(vout->v2f.fmt.pix.sizeimage); + + retval = mxc_allocate_buffers(vout->queue_buf_paddr, + vout->queue_buf_vaddr, + vout->buffer_cnt, + vout->queue_buf_size); + if (retval < 0) + break; + + /* Init buffer queues */ + vout->done_q.head = 0; + vout->done_q.tail = 0; + vout->ready_q.head = 0; + vout->ready_q.tail = 0; + + for (i = 0; i < vout->buffer_cnt; i++) { + memset(&(vout->v4l2_bufs[i]), 0, + sizeof(vout->v4l2_bufs[i])); + vout->v4l2_bufs[i].flags = 0; + vout->v4l2_bufs[i].memory = V4L2_MEMORY_MMAP; + vout->v4l2_bufs[i].index = i; + vout->v4l2_bufs[i].type = + V4L2_BUF_TYPE_VIDEO_OUTPUT; + vout->v4l2_bufs[i].length = + PAGE_ALIGN(vout->v2f.fmt.pix.sizeimage); + vout->v4l2_bufs[i].m.offset = + (unsigned long)vout->queue_buf_paddr[i]; + vout->v4l2_bufs[i].timestamp.tv_sec = 0; + vout->v4l2_bufs[i].timestamp.tv_usec = 0; + } + break; + } + case VIDIOC_QUERYBUF: + { + struct v4l2_buffer *buf = arg; + u32 type = buf->type; + int index = buf->index; + + if ((type != V4L2_BUF_TYPE_VIDEO_OUTPUT) || + (index >= vout->buffer_cnt)) { + dev_dbg(vdev->dev, + "VIDIOC_QUERYBUFS: incorrect" + "buffer type\n"); + retval = -EINVAL; + break; + } + down(&vout->param_lock); + memcpy(buf, &(vout->v4l2_bufs[index]), sizeof(*buf)); + up(&vout->param_lock); + break; + } + case VIDIOC_QBUF: + { + struct v4l2_buffer *buf = arg; + int index = buf->index; + unsigned long lock_flags; + + if ((buf->type != V4L2_BUF_TYPE_VIDEO_OUTPUT) || + (index >= vout->buffer_cnt)) { + retval = -EINVAL; + break; + } + + dev_dbg(vdev->dev, "VIDIOC_QBUF: %d\n", buf->index); + + /* mmapped buffers are L1 WB cached, + * so we need to clean them */ + if (buf->flags & V4L2_BUF_FLAG_MAPPED) + flush_cache_all(); + + spin_lock_irqsave(&g_lock, lock_flags); + + memcpy(&(vout->v4l2_bufs[index]), buf, sizeof(*buf)); + vout->v4l2_bufs[index].flags |= V4L2_BUF_FLAG_QUEUED; + + g_buf_q_cnt++; + queue_buf(&vout->ready_q, index); + if (vout->state == STATE_STREAM_PAUSED) { + unsigned long timeout; + + index = peek_next_buf(&vout->ready_q); + + /* if timestamp is 0, then default to 30fps */ + if ((vout->v4l2_bufs[index].timestamp.tv_sec == + 0) + && (vout->v4l2_bufs[index].timestamp. + tv_usec == 0)) + timeout = + vout->start_jiffies + + vout->frame_count * HZ / 30; + else + timeout = + get_jiffies(&vout->v4l2_bufs[index]. + timestamp); + + if (jiffies >= timeout) { + dev_dbg(vout->video_dev->dev, + "warning: timer timeout" + "already expired.\n"); + } + vout->output_timer.expires = timeout; + dev_dbg(vdev->dev, + "QBUF: frame #%u timeout @" + " %lu jiffies, current = %lu\n", + vout->frame_count, timeout, jiffies); + add_timer(&vout->output_timer); + vout->state = STATE_STREAM_ON; + } + + spin_unlock_irqrestore(&g_lock, lock_flags); + break; + } + case VIDIOC_DQBUF: + { + struct v4l2_buffer *buf = arg; + int idx; + + if ((queue_size(&vout->done_q) == 0) && + (file->f_flags & O_NONBLOCK)) { + retval = -EAGAIN; + break; + } + + if (!wait_event_interruptible_timeout(vout->v4l_bufq, + queue_size(&vout-> + done_q) + != 0, 10 * HZ)) { + dev_dbg(vdev->dev, "VIDIOC_DQBUF: timeout\n"); + retval = -ETIME; + break; + } else if (signal_pending(current)) { + dev_dbg(vdev->dev, + "VIDIOC_DQBUF: interrupt received\n"); + retval = -ERESTARTSYS; + break; + } + idx = dequeue_buf(&vout->done_q); + if (idx == -1) { /* No frame free */ + dev_dbg(vdev->dev, + "VIDIOC_DQBUF: no free buffers\n"); + retval = -EAGAIN; + break; + } + if ((vout->v4l2_bufs[idx].flags & V4L2_BUF_FLAG_DONE) == + 0) + dev_dbg(vdev->dev, + "VIDIOC_DQBUF: buffer in done q, " + "but not flagged as done\n"); + + vout->v4l2_bufs[idx].flags = 0; + memcpy(buf, &(vout->v4l2_bufs[idx]), sizeof(*buf)); + dev_dbg(vdev->dev, "VIDIOC_DQBUF: %d\n", buf->index); + break; + } + case VIDIOC_STREAMON: + { + retval = mxc_v4l2out_streamon(vout); + break; + } + case VIDIOC_STREAMOFF: + { + retval = mxc_v4l2out_streamoff(vout); + break; + } + case VIDIOC_G_CTRL: + { + retval = mxc_get_v42lout_control(vout, arg); + break; + } + case VIDIOC_S_CTRL: + { + retval = mxc_set_v42lout_control(vout, arg); + break; + } + case VIDIOC_CROPCAP: + { + struct v4l2_cropcap *cap = arg; + + if (cap->type != V4L2_BUF_TYPE_VIDEO_OUTPUT) { + retval = -EINVAL; + break; + } + + cap->bounds = vout->crop_bounds[vout->cur_disp_output]; + cap->defrect = vout->crop_bounds[vout->cur_disp_output]; + retval = 0; + break; + } + case VIDIOC_G_CROP: + { + struct v4l2_crop *crop = arg; + + if (crop->type != V4L2_BUF_TYPE_VIDEO_OUTPUT) { + retval = -EINVAL; + break; + } + crop->c = vout->crop_current; + break; + } + case VIDIOC_S_CROP: + { + struct v4l2_crop *crop = arg; + struct v4l2_rect *b = + &(vout->crop_bounds[vout->cur_disp_output]); + + if (crop->type != V4L2_BUF_TYPE_VIDEO_OUTPUT) { + retval = -EINVAL; + break; + } + if (crop->c.height < 0) { + retval = -EINVAL; + break; + } + if (crop->c.width < 0) { + retval = -EINVAL; + break; + } + + /* only full screen supported for SDC BG */ + if (vout->cur_disp_output == 4) { + crop->c = vout->crop_current; + break; + } + + if (crop->c.top < b->top) + crop->c.top = b->top; + if (crop->c.top >= b->top + b->height) + crop->c.top = b->top + b->height - 1; + if (crop->c.height > b->top - crop->c.top + b->height) + crop->c.height = + b->top - crop->c.top + b->height; + + if (crop->c.left < b->left) + crop->c.left = b->left; + if (crop->c.left >= b->left + b->width) + crop->c.left = b->left + b->width - 1; + if (crop->c.width > b->left - crop->c.left + b->width) + crop->c.width = + b->left - crop->c.left + b->width; + + /* stride line limitation */ + crop->c.height -= crop->c.height % 8; + crop->c.width -= crop->c.width % 8; + + vout->crop_current = crop->c; + break; + } + case VIDIOC_ENUMOUTPUT: + { + struct v4l2_output *output = arg; + + if ((output->index >= 5) || + (vout->output_enabled[output->index] == false)) { + retval = -EINVAL; + break; + } + + if (output->index < 3) { + *output = mxc_outputs[MXC_V4L2_OUT_2_ADC]; + output->name[4] = '0' + output->index; + } else { + *output = mxc_outputs[MXC_V4L2_OUT_2_SDC]; + } + break; + } + case VIDIOC_G_OUTPUT: + { + int *p_output_num = arg; + + *p_output_num = vout->cur_disp_output; + break; + } + case VIDIOC_S_OUTPUT: + { + int *p_output_num = arg; + int fbnum; + struct v4l2_rect *b; + + if ((*p_output_num >= MXC_V4L2_OUT_NUM_OUTPUTS) || + (vout->output_enabled[*p_output_num] == false)) { + retval = -EINVAL; + break; + } + + if (vout->state != STATE_STREAM_OFF) { + retval = -EBUSY; + break; + } + + vout->cur_disp_output = *p_output_num; + + /* Update bounds in case they have changed */ + b = &vout->crop_bounds[vout->cur_disp_output]; + + fbnum = vout->output_fb_num[vout->cur_disp_output]; + if (vout->cur_disp_output == 3) + fbnum = vout->output_fb_num[4]; + + b->width = registered_fb[fbnum]->var.xres; + b->height = registered_fb[fbnum]->var.yres; + + vout->crop_current = *b; + break; + } + case VIDIOC_ENUM_FMT: + case VIDIOC_TRY_FMT: + case VIDIOC_QUERYCTRL: + case VIDIOC_G_PARM: + case VIDIOC_ENUMSTD: + case VIDIOC_G_STD: + case VIDIOC_S_STD: + case VIDIOC_G_TUNER: + case VIDIOC_S_TUNER: + case VIDIOC_G_FREQUENCY: + case VIDIOC_S_FREQUENCY: + default: + retval = -EINVAL; + break; + } + + up(&vout->busy_lock); + return retval; +} + +/* + * V4L2 interface - ioctl function + * + * @return None + */ +static int +mxc_v4l2out_ioctl(struct inode *inode, struct file *file, + unsigned int cmd, unsigned long arg) +{ + return video_usercopy(inode, file, cmd, arg, mxc_v4l2out_do_ioctl); +} + +/*! + * V4L2 interface - mmap function + * + * @param file structure file * + * + * @param vma structure vm_area_struct * + * + * @return status 0 Success, EINTR busy lock error, + * ENOBUFS remap_page error + */ +static int mxc_v4l2out_mmap(struct file *file, struct vm_area_struct *vma) +{ + struct video_device *vdev = video_devdata(file); + unsigned long size = vma->vm_end - vma->vm_start; + int res = 0; + int i; + vout_data *vout = video_get_drvdata(vdev); + + dev_dbg(vdev->dev, "pgoff=0x%lx, start=0x%lx, end=0x%lx\n", + vma->vm_pgoff, vma->vm_start, vma->vm_end); + + /* make this _really_ smp-safe */ + if (down_interruptible(&vout->busy_lock)) + return -EINTR; + + for (i = 0; i < vout->buffer_cnt; i++) { + if ((vout->v4l2_bufs[i].m.offset == + (vma->vm_pgoff << PAGE_SHIFT)) && + (vout->v4l2_bufs[i].length >= size)) { + vout->v4l2_bufs[i].flags |= V4L2_BUF_FLAG_MAPPED; + break; + } + } + if (i == vout->buffer_cnt) { + res = -ENOBUFS; + goto mxc_mmap_exit; + } + + /* make buffers inner write-back, outer write-thru cacheable */ + vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot); + + if (remap_pfn_range(vma, vma->vm_start, + vma->vm_pgoff, size, vma->vm_page_prot)) { + dev_dbg(vdev->dev, "mmap remap_pfn_range failed\n"); + res = -ENOBUFS; + goto mxc_mmap_exit; + } + + vma->vm_flags &= ~VM_IO; /* using shared anonymous pages */ + +mxc_mmap_exit: + up(&vout->busy_lock); + return res; +} + +/*! + * V4L2 interface - poll function + * + * @param file structure file * + * + * @param wait structure poll_table * + * + * @return status POLLIN | POLLRDNORM + */ +static unsigned int mxc_v4l2out_poll(struct file *file, poll_table * wait) +{ + struct video_device *dev = video_devdata(file); + vout_data *vout = video_get_drvdata(dev); + + wait_queue_head_t *queue = NULL; + int res = POLLIN | POLLRDNORM; + + if (down_interruptible(&vout->busy_lock)) + return -EINTR; + + queue = &vout->v4l_bufq; + poll_wait(file, queue, wait); + + up(&vout->busy_lock); + return res; +} + +static struct +file_operations mxc_v4l2out_fops = { + .owner = THIS_MODULE, + .open = mxc_v4l2out_open, + .release = mxc_v4l2out_close, + .ioctl = mxc_v4l2out_ioctl, + .mmap = mxc_v4l2out_mmap, + .poll = mxc_v4l2out_poll, +}; + +static struct video_device mxc_v4l2out_template = { + .owner = THIS_MODULE, + .name = "MXC Video Output", + .type = 0, + .type2 = V4L2_CAP_VIDEO_OUTPUT | V4L2_CAP_STREAMING, + .fops = &mxc_v4l2out_fops, + .release = video_device_release, +}; + +/*! + * Probe routine for the framebuffer driver. It is called during the + * driver binding process. The following functions are performed in + * this routine: Framebuffer initialization, Memory allocation and + * mapping, Framebuffer registration, IPU initialization. + * + * @return Appropriate error code to the kernel common code + */ +static int mxc_v4l2out_probe(struct platform_device *pdev) +{ + int i; + vout_data *vout; + + /* + * Allocate sufficient memory for the fb structure + */ + g_vout = vout = kmalloc(sizeof(vout_data), GFP_KERNEL); + + if (!vout) + return 0; + + memset(vout, 0, sizeof(vout_data)); + + vout->video_dev = video_device_alloc(); + if (vout->video_dev == NULL) + return -1; + vout->video_dev->dev = &pdev->dev; + vout->video_dev->minor = -1; + + *(vout->video_dev) = mxc_v4l2out_template; + + /* register v4l device */ + if (video_register_device(vout->video_dev, + VFL_TYPE_GRABBER, video_nr) == -1) { + dev_dbg(&pdev->dev, "video_register_device failed\n"); + return 0; + } + dev_info(&pdev->dev, "Registered device video%d\n", + vout->video_dev->minor & 0x1f); + vout->video_dev->dev = &pdev->dev; + + video_set_drvdata(vout->video_dev, vout); + + init_MUTEX(&vout->param_lock); + init_MUTEX(&vout->busy_lock); + + /* setup outputs and cropping */ + vout->cur_disp_output = -1; + for (i = 0; i < num_registered_fb; i++) { + char *idstr = registered_fb[i]->fix.id; + if (strncmp(idstr, "DISP", 4) == 0) { + int disp_num = idstr[4] - '0'; + if (disp_num == 3) { + if (strcmp(idstr, "DISP3 BG - DI1") == 0) + disp_num = 5; + else if (strncmp(idstr, "DISP3 BG", 8) == 0) + disp_num = 4; + } + vout->crop_bounds[disp_num].left = 0; + vout->crop_bounds[disp_num].top = 0; + vout->crop_bounds[disp_num].width = + registered_fb[i]->var.xres; + vout->crop_bounds[disp_num].height = + registered_fb[i]->var.yres; + vout->output_enabled[disp_num] = true; + vout->output_fb_num[disp_num] = i; + if (vout->cur_disp_output == -1) + vout->cur_disp_output = disp_num; + } + + } + vout->crop_current = vout->crop_bounds[vout->cur_disp_output]; + + platform_set_drvdata(pdev, vout); + + return 0; +} + +static int mxc_v4l2out_remove(struct platform_device *pdev) +{ + vout_data *vout = platform_get_drvdata(pdev); + + if (vout->video_dev) { + if (-1 != vout->video_dev->minor) + video_unregister_device(vout->video_dev); + else + video_device_release(vout->video_dev); + vout->video_dev = NULL; + } + + platform_set_drvdata(pdev, NULL); + + kfree(vout); + + return 0; +} + +/*! + * This structure contains pointers to the power management callback functions. + */ +static struct platform_driver mxc_v4l2out_driver = { + .driver = { + .name = "MXC Video Output", + }, + .probe = mxc_v4l2out_probe, + .remove = mxc_v4l2out_remove, +}; + +static struct platform_device mxc_v4l2out_device = { + .name = "MXC Video Output", + .id = 0, +}; + +/*! + * mxc v4l2 init function + * + */ +static int mxc_v4l2out_init(void) +{ + u8 err = 0; + + err = platform_driver_register(&mxc_v4l2out_driver); + if (err == 0) + platform_device_register(&mxc_v4l2out_device); + return err; +} + +/*! + * mxc v4l2 cleanup function + * + */ +static void mxc_v4l2out_clean(void) +{ + video_unregister_device(g_vout->video_dev); + + platform_driver_unregister(&mxc_v4l2out_driver); + platform_device_unregister(&mxc_v4l2out_device); + kfree(g_vout); + g_vout = NULL; +} + +module_init(mxc_v4l2out_init); +module_exit(mxc_v4l2out_clean); + +module_param(video_nr, int, 0444); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("V4L2-driver for MXC video output"); +MODULE_LICENSE("GPL"); +MODULE_SUPPORTED_DEVICE("video"); diff --git a/drivers/media/video/mxc/output/mxc_v4l2_output.c b/drivers/media/video/mxc/output/mxc_v4l2_output.c new file mode 100644 index 000000000000..28c7fac90140 --- /dev/null +++ b/drivers/media/video/mxc/output/mxc_v4l2_output.c @@ -0,0 +1,2616 @@ +/* + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file drivers/media/video/mxc/output/mxc_v4l2_output.c + * + * @brief MXC V4L2 Video Output Driver + * + * Video4Linux2 Output Device using MXC IPU Post-processing functionality. + * + * @ingroup MXC_V4L2_OUTPUT + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "mxc_v4l2_output.h" + +#define INTERLACED_CONTENT(vout) (((cpu_is_mx51_rev(CHIP_REV_2_0) >= 1) || \ + cpu_is_mx53()) && \ + (((vout)->field_fmt == V4L2_FIELD_INTERLACED_TB) || \ + ((vout)->field_fmt == V4L2_FIELD_INTERLACED_BT))) +#define LOAD_3FIELDS(vout) ((INTERLACED_CONTENT(vout)) && \ + ((vout)->motion_sel != HIGH_MOTION)) + +struct v4l2_output mxc_outputs[1] = { + { + .index = MXC_V4L2_OUT_2_SDC, + .name = "DISP3 Video Out", + .type = V4L2_OUTPUT_TYPE_ANALOG, /* not really correct, + but no other choice */ + .audioset = 0, + .modulator = 0, + .std = V4L2_STD_UNKNOWN} +}; + +static int video_nr = 16; +static DEFINE_SPINLOCK(g_lock); +static int last_index_n; +static unsigned int ipu_ic_out_max_width_size; +static unsigned int ipu_ic_out_max_height_size; +/* debug counters */ +uint32_t g_irq_cnt; +uint32_t g_buf_output_cnt; +uint32_t g_buf_q_cnt; +uint32_t g_buf_dq_cnt; + +#define QUEUE_SIZE (MAX_FRAME_NUM + 1) +static __inline int queue_size(v4l_queue *q) +{ + if (q->tail >= q->head) + return q->tail - q->head; + else + return (q->tail + QUEUE_SIZE) - q->head; +} + +static __inline int queue_buf(v4l_queue *q, int idx) +{ + if (((q->tail + 1) % QUEUE_SIZE) == q->head) + return -1; /* queue full */ + q->list[q->tail] = idx; + q->tail = (q->tail + 1) % QUEUE_SIZE; + return 0; +} + +static __inline int dequeue_buf(v4l_queue *q) +{ + int ret; + if (q->tail == q->head) + return -1; /* queue empty */ + ret = q->list[q->head]; + q->head = (q->head + 1) % QUEUE_SIZE; + return ret; +} + +static __inline int peek_next_buf(v4l_queue *q) +{ + if (q->tail == q->head) + return -1; /* queue empty */ + return q->list[q->head]; +} + +static __inline unsigned long get_jiffies(struct timeval *t) +{ + struct timeval cur; + + if (t->tv_usec >= 1000000) { + t->tv_sec += t->tv_usec / 1000000; + t->tv_usec = t->tv_usec % 1000000; + } + + do_gettimeofday(&cur); + if ((t->tv_sec < cur.tv_sec) + || ((t->tv_sec == cur.tv_sec) && (t->tv_usec < cur.tv_usec))) + return jiffies; + + if (t->tv_usec < cur.tv_usec) { + cur.tv_sec = t->tv_sec - cur.tv_sec - 1; + cur.tv_usec = t->tv_usec + 1000000 - cur.tv_usec; + } else { + cur.tv_sec = t->tv_sec - cur.tv_sec; + cur.tv_usec = t->tv_usec - cur.tv_usec; + } + + return jiffies + timeval_to_jiffies(&cur); +} + +/*! + * Private function to free buffers + * + * @param bufs_paddr Array of physical address of buffers to be freed + * + * @param bufs_vaddr Array of virtual address of buffers to be freed + * + * @param num_buf Number of buffers to be freed + * + * @param size Size for each buffer to be free + * + * @return status 0 success. + */ +static int mxc_free_buffers(dma_addr_t bufs_paddr[], void *bufs_vaddr[], + int num_buf, int size) +{ + int i; + + for (i = 0; i < num_buf; i++) { + if (bufs_vaddr[i] != 0) { + dma_free_coherent(0, size, bufs_vaddr[i], + bufs_paddr[i]); + pr_debug("freed @ paddr=0x%08X\n", (u32) bufs_paddr[i]); + bufs_paddr[i] = 0; + bufs_vaddr[i] = NULL; + } + } + return 0; +} + +/*! + * Private function to allocate buffers + * + * @param bufs_paddr Output array of physical address of buffers allocated + * + * @param bufs_vaddr Output array of virtual address of buffers allocated + * + * @param num_buf Input number of buffers to allocate + * + * @param size Input size for each buffer to allocate + * + * @return status -0 Successfully allocated a buffer, -ENOBUFS failed. + */ +static int mxc_allocate_buffers(dma_addr_t bufs_paddr[], void *bufs_vaddr[], + int num_buf, int size) +{ + int i; + + for (i = 0; i < num_buf; i++) { + bufs_vaddr[i] = dma_alloc_coherent(0, size, + &bufs_paddr[i], + GFP_DMA | GFP_KERNEL); + + if (bufs_vaddr[i] == 0) { + mxc_free_buffers(bufs_paddr, bufs_vaddr, i, size); + printk(KERN_ERR "dma_alloc_coherent failed.\n"); + return -ENOBUFS; + } + pr_debug("allocated @ paddr=0x%08X, size=%d.\n", + (u32) bufs_paddr[i], size); + } + + return 0; +} + +/* + * Returns bits per pixel for given pixel format + * + * @param pixelformat V4L2_PIX_FMT_RGB565, V4L2_PIX_FMT_BGR24 or V4L2_PIX_FMT_BGR32 + * + * @return bits per pixel of pixelformat + */ +static u32 fmt_to_bpp(u32 pixelformat) +{ + u32 bpp; + + bpp = 8 * bytes_per_pixel(pixelformat); + return bpp; +} + +static bool format_is_yuv(u32 pixelformat) +{ + switch (pixelformat) { + case V4L2_PIX_FMT_YUV420: + case V4L2_PIX_FMT_UYVY: + case V4L2_PIX_FMT_YUYV: + case V4L2_PIX_FMT_YUV422P: + case V4L2_PIX_FMT_YVU420: + case V4L2_PIX_FMT_NV12: + return true; + break; + } + return false; +} + +static u32 bpp_to_fmt(struct fb_info *fbi) +{ + if (fbi->var.nonstd) + return fbi->var.nonstd; + + if (fbi->var.bits_per_pixel == 24) + return V4L2_PIX_FMT_BGR24; + else if (fbi->var.bits_per_pixel == 32) + return V4L2_PIX_FMT_BGR32; + else if (fbi->var.bits_per_pixel == 16) + return V4L2_PIX_FMT_RGB565; + + return 0; +} + +/* + * we are using double buffer for video playback, ipu need make + * sure current buffer should not be the same buffer of next display + * one. + */ +static int select_display_buffer(vout_data *vout, int next_buf) +{ + int ret = 0; + + if (ipu_get_cur_buffer_idx(vout->display_ch, IPU_INPUT_BUFFER) + != next_buf) + ret = ipu_select_buffer(vout->display_ch, IPU_INPUT_BUFFER, + next_buf); + else + dev_dbg(&vout->video_dev->dev, + "display buffer not ready for select\n"); + return ret; +} + +static void setup_next_buf_timer(vout_data *vout, int index) +{ + unsigned long timeout; + + /* Setup timer for next buffer */ + /* if timestamp is 0, then default to 30fps */ + if ((vout->v4l2_bufs[index].timestamp.tv_sec == 0) + && (vout->v4l2_bufs[index].timestamp.tv_usec == 0) + && vout->start_jiffies) + timeout = + vout->start_jiffies + vout->frame_count * HZ / 30; + else + timeout = + get_jiffies(&vout->v4l2_bufs[index].timestamp); + + if (jiffies >= timeout) { + dev_dbg(&vout->video_dev->dev, + "warning: timer timeout already expired.\n"); + } + if (mod_timer(&vout->output_timer, timeout)) + dev_dbg(&vout->video_dev->dev, + "warning: timer was already set\n"); + + dev_dbg(&vout->video_dev->dev, + "timer handler next schedule: %lu\n", timeout); +} + +static int finish_previous_frame(vout_data *vout) +{ + struct fb_info *fbi = + registered_fb[vout->output_fb_num[vout->cur_disp_output]]; + mm_segment_t old_fs; + int ret = 0; + + /* make sure buf[next_done_ipu_buf] showed */ + while (ipu_check_buffer_busy(vout->display_ch, + IPU_INPUT_BUFFER, vout->next_done_ipu_buf)) { + /* wait for display frame finish */ + if (fbi->fbops->fb_ioctl) { + old_fs = get_fs(); + set_fs(KERNEL_DS); + ret = fbi->fbops->fb_ioctl(fbi, MXCFB_WAIT_FOR_VSYNC, + (unsigned int)NULL); + set_fs(old_fs); + + if (ret < 0) { + /* ic_bypass need clear display buffer ready for next update*/ + ipu_clear_buffer_ready(vout->display_ch, IPU_INPUT_BUFFER, + vout->next_done_ipu_buf); + } + } + } + + return ret; +} + +static int show_current_frame(vout_data *vout) +{ + struct fb_info *fbi = + registered_fb[vout->output_fb_num[vout->cur_disp_output]]; + mm_segment_t old_fs; + int ret = 0; + + /* make sure buf[next_rdy_ipu_buf] begin to show */ + if (ipu_get_cur_buffer_idx(vout->display_ch, IPU_INPUT_BUFFER) + != vout->next_rdy_ipu_buf) { + /* wait for display frame finish */ + if (fbi->fbops->fb_ioctl) { + old_fs = get_fs(); + set_fs(KERNEL_DS); + ret = fbi->fbops->fb_ioctl(fbi, MXCFB_WAIT_FOR_VSYNC, + (unsigned int)NULL); + set_fs(old_fs); + } + } + + return ret; +} + +static void timer_work_func(struct work_struct *work) +{ + vout_data *vout = + container_of(work, vout_data, timer_work); + int index, ret; + int last_buf; + unsigned long lock_flags = 0; + + finish_previous_frame(vout); + + spin_lock_irqsave(&g_lock, lock_flags); + + if (g_buf_output_cnt == 0) { + ipu_select_buffer(vout->display_ch, IPU_INPUT_BUFFER, 1); + } else { + index = dequeue_buf(&vout->ready_q); + if (index == -1) { /* no buffers ready, should never occur */ + dev_err(&vout->video_dev->dev, + "mxc_v4l2out: timer - no queued buffers ready\n"); + goto exit; + } + g_buf_dq_cnt++; + vout->frame_count++; + + vout->ipu_buf[vout->next_rdy_ipu_buf] = index; + ret = ipu_update_channel_buffer(vout->display_ch, IPU_INPUT_BUFFER, + vout->next_rdy_ipu_buf, + vout->v4l2_bufs[index].m.offset); + ret += select_display_buffer(vout, vout->next_rdy_ipu_buf); + if (ret < 0) { + dev_err(&vout->video_dev->dev, + "unable to update buffer %d address rc=%d\n", + vout->next_rdy_ipu_buf, ret); + goto exit; + } + spin_unlock_irqrestore(&g_lock, lock_flags); + show_current_frame(vout); + spin_lock_irqsave(&g_lock, lock_flags); + vout->next_rdy_ipu_buf = !vout->next_rdy_ipu_buf; + } + + last_buf = vout->ipu_buf[vout->next_done_ipu_buf]; + if (last_buf != -1) { + g_buf_output_cnt++; + vout->v4l2_bufs[last_buf].flags = V4L2_BUF_FLAG_DONE; + queue_buf(&vout->done_q, last_buf); + wake_up_interruptible(&vout->v4l_bufq); + vout->ipu_buf[vout->next_done_ipu_buf] = -1; + vout->next_done_ipu_buf = !vout->next_done_ipu_buf; + } + + if (g_buf_output_cnt > 0) { + /* Setup timer for next buffer */ + index = peek_next_buf(&vout->ready_q); + if (index != -1) + setup_next_buf_timer(vout, index); + else + vout->state = STATE_STREAM_PAUSED; + + if (vout->state == STATE_STREAM_STOPPING) { + if ((vout->ipu_buf[0] == -1) && (vout->ipu_buf[1] == -1)) { + vout->state = STATE_STREAM_OFF; + } + } + } +exit: + spin_unlock_irqrestore(&g_lock, lock_flags); +} + +static void mxc_v4l2out_timer_handler(unsigned long arg) +{ + int index, ret; + unsigned long lock_flags = 0; + vout_data *vout = (vout_data *) arg; + + spin_lock_irqsave(&g_lock, lock_flags); + + if ((vout->state == STATE_STREAM_STOPPING) + || (vout->state == STATE_STREAM_OFF)) + goto exit0; + + /* + * If timer occurs before IPU h/w is ready, then set the state to + * paused and the timer will be set again when next buffer is queued + * or PP comletes + */ + if (vout->ipu_buf[vout->next_rdy_ipu_buf] != -1) { + dev_dbg(&vout->video_dev->dev, "IPU buffer busy\n"); + vout->state = STATE_STREAM_PAUSED; + goto exit0; + } + + /* VDI need both buffer done before update buffer? */ + if (INTERLACED_CONTENT(vout) && + (vout->ipu_buf[!vout->next_rdy_ipu_buf] != -1)) { + dev_dbg(&vout->video_dev->dev, "IPU buffer busy\n"); + vout->state = STATE_STREAM_PAUSED; + goto exit0; + } + + /* Handle ic bypass mode in work queue */ + if (vout->ic_bypass) { + if (queue_work(vout->v4l_wq, &vout->timer_work) == 0) { + dev_err(&vout->video_dev->dev, "work was in queue already!\n "); + vout->state = STATE_STREAM_PAUSED; + } + goto exit0; + } + + /* Dequeue buffer and pass to IPU */ + index = dequeue_buf(&vout->ready_q); + if (index == -1) { /* no buffers ready, should never occur */ + dev_err(&vout->video_dev->dev, + "mxc_v4l2out: timer - no queued buffers ready\n"); + goto exit0; + } + g_buf_dq_cnt++; + vout->frame_count++; + + /* update next buffer */ + if (LOAD_3FIELDS(vout)) { + int index_n = index; + int index_p = last_index_n; + vout->ipu_buf_p[vout->next_rdy_ipu_buf] = last_index_n; + vout->ipu_buf[vout->next_rdy_ipu_buf] = index; + vout->ipu_buf_n[vout->next_rdy_ipu_buf] = index; + ret = ipu_update_channel_buffer(vout->post_proc_ch, + IPU_INPUT_BUFFER, + vout->next_rdy_ipu_buf, + vout->v4l2_bufs[index].m.offset); + ret += ipu_update_channel_buffer(MEM_VDI_PRP_VF_MEM_P, + IPU_INPUT_BUFFER, + vout->next_rdy_ipu_buf, + vout->v4l2_bufs[index_p].m.offset + vout->bytesperline); + ret += ipu_update_channel_buffer(MEM_VDI_PRP_VF_MEM_N, + IPU_INPUT_BUFFER, + vout->next_rdy_ipu_buf, + vout->v4l2_bufs[index_n].m.offset) + vout->bytesperline; + last_index_n = index; + } else { + vout->ipu_buf[vout->next_rdy_ipu_buf] = index; + if (vout->pp_split) { + vout->ipu_buf[!vout->next_rdy_ipu_buf] = index; + /* always left stripe */ + ret = ipu_update_channel_buffer(vout->post_proc_ch, + IPU_INPUT_BUFFER, + 0,/* vout->next_rdy_ipu_buf,*/ + (vout->v4l2_bufs[index].m.offset) + + vout->pp_left_stripe.input_column + + vout->pp_up_stripe.input_column * vout->bytesperline); + + /* the U/V offset has to be updated inside of IDMAC */ + /* according to stripe offset */ + ret += ipu_update_channel_offset(vout->post_proc_ch, + IPU_INPUT_BUFFER, + vout->v2f.fmt.pix.pixelformat, + vout->v2f.fmt.pix.width, + vout->v2f.fmt.pix.height, + vout->bytesperline, + vout->offset.u_offset, + vout->offset.v_offset, + vout->pp_up_stripe.input_column, + vout->pp_left_stripe.input_column); + } else + ret = ipu_update_channel_buffer(vout->post_proc_ch, + IPU_INPUT_BUFFER, + vout->next_rdy_ipu_buf, + vout->v4l2_bufs[index].m.offset); + } + + if (ret < 0) { + dev_err(&vout->video_dev->dev, + "unable to update buffer %d address rc=%d\n", + vout->next_rdy_ipu_buf, ret); + goto exit0; + } + + /* set next buffer ready */ + if (LOAD_3FIELDS(vout)) + ret = ipu_select_multi_vdi_buffer(vout->next_rdy_ipu_buf); + else + ret = ipu_select_buffer(vout->post_proc_ch, IPU_INPUT_BUFFER, + vout->next_rdy_ipu_buf); + if (ret < 0) { + dev_err(&vout->video_dev->dev, + "unable to set IPU buffer ready\n"); + goto exit0; + } + + /* Non IC split action */ + if (!vout->pp_split) + vout->next_rdy_ipu_buf = !vout->next_rdy_ipu_buf; + + /* Setup timer for next buffer */ + index = peek_next_buf(&vout->ready_q); + if (index != -1) + setup_next_buf_timer(vout, index); + else + vout->state = STATE_STREAM_PAUSED; + + if (vout->state == STATE_STREAM_STOPPING) { + if ((vout->ipu_buf[0] == -1) && (vout->ipu_buf[1] == -1)) { + vout->state = STATE_STREAM_OFF; + } + } + + spin_unlock_irqrestore(&g_lock, lock_flags); + + return; + +exit0: + spin_unlock_irqrestore(&g_lock, lock_flags); +} + +static irqreturn_t mxc_v4l2out_work_irq_handler(int irq, void *dev_id) +{ + int last_buf; + int index; + unsigned long lock_flags = 0; + vout_data *vout = dev_id; + int pp_out_buf_left_right = 0; + int disp_buf_num = 0; + int disp_buf_num_next = 1; + int local_buffer = 0; + int pp_out_buf_offset = 0; + int pp_out_buf_up_down = 0; + int release_buffer = 0; + u32 eba_offset = 0; + u32 vertical_offset = 0; + u16 x_pos; + u16 y_pos; + int ret = -1; + + spin_lock_irqsave(&g_lock, lock_flags); + + g_irq_cnt++; + + /* Process previous buffer */ + if (LOAD_3FIELDS(vout)) + last_buf = vout->ipu_buf_p[vout->next_done_ipu_buf]; + else + last_buf = vout->ipu_buf[vout->next_done_ipu_buf]; + + if (last_buf != -1) { + /* If IC split mode on, update output buffer number */ + if (vout->pp_split) { + pp_out_buf_up_down = vout->pp_split_buf_num & 1;/* left/right stripe */ + pp_out_buf_left_right = (vout->pp_split_buf_num >> 1) & 1; /* up/down */ + local_buffer = (vout->pp_split == 1) ? pp_out_buf_up_down : + pp_out_buf_left_right; + disp_buf_num = vout->pp_split_buf_num >> 2; + disp_buf_num_next = + ((vout->pp_split_buf_num + (vout->pp_split << 0x1)) & 7) >> 2; + if ((!pp_out_buf_left_right) || + ((!pp_out_buf_up_down) && (vout->pp_split == 1))) { + if (vout->pp_split == 1) { + eba_offset = ((pp_out_buf_left_right + pp_out_buf_up_down) & 1) ? + vout->pp_right_stripe.input_column : + vout->pp_left_stripe.input_column; + vertical_offset = pp_out_buf_up_down ? + vout->pp_up_stripe.input_column : + vout->pp_down_stripe.input_column; + + } else { + eba_offset = pp_out_buf_left_right ? + vout->pp_left_stripe.input_column : + vout->pp_right_stripe.input_column; + vertical_offset = pp_out_buf_left_right ? + vout->pp_up_stripe.input_column : + vout->pp_down_stripe.input_column; + } + + ret = ipu_update_channel_buffer(vout->post_proc_ch, + IPU_INPUT_BUFFER, + (1 - local_buffer), + (vout->v4l2_bufs[vout->ipu_buf[disp_buf_num]].m.offset) + + eba_offset + vertical_offset * vout->bytesperline); + ret += ipu_update_channel_offset(vout->post_proc_ch, + IPU_INPUT_BUFFER, + vout->v2f.fmt.pix.pixelformat, + vout->v2f.fmt.pix.width, + vout->v2f.fmt.pix.height, + vout->bytesperline, + vout->offset.u_offset, + vout->offset.v_offset, + vertical_offset, + eba_offset); + + /* select right stripe */ + ret += ipu_select_buffer(vout->post_proc_ch, IPU_INPUT_BUFFER, + (1 - local_buffer)); + if (ret < 0) + dev_err(&vout->video_dev->dev, + "unable to set IPU buffer ready\n"); + vout->next_rdy_ipu_buf = !vout->next_rdy_ipu_buf; + + } else {/* last stripe is done, run display refresh */ + select_display_buffer(vout, disp_buf_num); + vout->ipu_buf[vout->next_done_ipu_buf] = -1; + vout->next_done_ipu_buf = !vout->next_done_ipu_buf; + vout->next_rdy_ipu_buf = !vout->next_rdy_ipu_buf; + } + + /* offset for next buffer's EBA */ + eba_offset = 0; + if (vout->pp_split == 1) { + pp_out_buf_offset = ((vout->pp_split_buf_num >> 1) & 1) ? + vout->pp_left_stripe.output_column : + vout->pp_right_stripe.output_column; + + eba_offset = ((vout->pp_split_buf_num & 1) ? + vout->pp_down_stripe.output_column : + vout->pp_up_stripe.output_column); + + } else { + pp_out_buf_offset = ((vout->pp_split_buf_num >> 1) & 1) ? + vout->pp_right_stripe.output_column : + vout->pp_left_stripe.output_column; + eba_offset = ((vout->pp_split_buf_num >> 1) & 1) ? + vout->pp_down_stripe.output_column : + vout->pp_up_stripe.output_column; + } + + if (vout->cur_disp_output == 5) { + x_pos = (vout->crop_current.left / 8) * 8; + y_pos = vout->crop_current.top; + eba_offset += (vout->xres * y_pos + x_pos) * vout->bpp / 8; + } + + + /* next buffer update */ + eba_offset = vout->display_bufs[disp_buf_num_next] + + pp_out_buf_offset + eba_offset; + + ipu_update_channel_buffer(vout->post_proc_ch, IPU_OUTPUT_BUFFER, + local_buffer, eba_offset); + + /* next buffer ready */ + ret = ipu_select_buffer(vout->post_proc_ch, IPU_OUTPUT_BUFFER, local_buffer); + + /* next stripe_buffer index 0..7 */ + vout->pp_split_buf_num = (vout->pp_split_buf_num + vout->pp_split) & 0x7; + + + } else { + /* show to display */ + select_display_buffer(vout, vout->next_done_ipu_buf); + ret += ipu_select_buffer(vout->display_input_ch, IPU_OUTPUT_BUFFER, + vout->next_done_ipu_buf); + } + + /* release buffer. For split mode: if second stripe is done */ + release_buffer = vout->pp_split ? (!(vout->pp_split_buf_num & 0x3)) : 1; + if (release_buffer) { + g_buf_output_cnt++; + vout->v4l2_bufs[last_buf].flags = V4L2_BUF_FLAG_DONE; + queue_buf(&vout->done_q, last_buf); + wake_up_interruptible(&vout->v4l_bufq); + vout->ipu_buf[vout->next_done_ipu_buf] = -1; + if (LOAD_3FIELDS(vout)) { + vout->ipu_buf_p[vout->next_done_ipu_buf] = -1; + vout->ipu_buf_n[vout->next_done_ipu_buf] = -1; + } + vout->next_done_ipu_buf = !vout->next_done_ipu_buf; + } + } /* end of last_buf != -1 */ + + index = peek_next_buf(&vout->ready_q); + if (vout->state == STATE_STREAM_STOPPING) { + if ((vout->ipu_buf[0] == -1) && (vout->ipu_buf[1] == -1)) { + vout->state = STATE_STREAM_OFF; + } + } else if ((vout->state == STATE_STREAM_PAUSED) + && (index != -1)) { + /* Setup timer for next buffer, when stream has been paused */ + pr_debug("next index %d\n", index); + setup_next_buf_timer(vout, index); + vout->state = STATE_STREAM_ON; + } + + spin_unlock_irqrestore(&g_lock, lock_flags); + + return IRQ_HANDLED; +} + +/*! + * Initialize VDI channels + * + * @param vout structure vout_data * + * + * @return status 0 Success + */ +static int init_VDI_channel(vout_data *vout, ipu_channel_params_t params) +{ + struct device *dev = &vout->video_dev->dev; + + if (ipu_init_channel(MEM_VDI_PRP_VF_MEM, ¶ms) != 0) { + dev_dbg(dev, "Error initializing VDI current channel\n"); + return -EINVAL; + } + if (LOAD_3FIELDS(vout)) { + if (ipu_init_channel(MEM_VDI_PRP_VF_MEM_P, ¶ms) != 0) { + dev_err(dev, "Error initializing VDI previous channel\n"); + return -EINVAL; + } + if (ipu_init_channel(MEM_VDI_PRP_VF_MEM_N, ¶ms) != 0) { + dev_err(dev, "Error initializing VDI next channel\n"); + return -EINVAL; + } + } + return 0; +} + +/*! + * Initialize VDI channel buffers + * + * @param vout structure vout_data * + * + * @return status 0 Success + */ +static int init_VDI_in_channel_buffer(vout_data *vout, uint32_t in_pixel_fmt, + uint16_t in_width, uint16_t in_height, + uint32_t stride, + uint32_t u_offset, uint32_t v_offset) +{ + struct device *dev = &vout->video_dev->dev; + + if (ipu_init_channel_buffer(MEM_VDI_PRP_VF_MEM, IPU_INPUT_BUFFER, + in_pixel_fmt, in_width, in_height, stride, + IPU_ROTATE_NONE, + vout->v4l2_bufs[vout->ipu_buf[0]].m.offset, + vout->v4l2_bufs[vout->ipu_buf[0]].m.offset, + u_offset, v_offset) != 0) { + dev_err(dev, "Error initializing VDI current input buffer\n"); + return -EINVAL; + } + if (LOAD_3FIELDS(vout)) { + if (ipu_init_channel_buffer(MEM_VDI_PRP_VF_MEM_P, + IPU_INPUT_BUFFER, + in_pixel_fmt, in_width, in_height, + stride, IPU_ROTATE_NONE, + vout->v4l2_bufs[vout->ipu_buf_p[0]].m.offset+vout->bytesperline, + vout->v4l2_bufs[vout->ipu_buf_p[0]].m.offset+vout->bytesperline, + u_offset, v_offset) != 0) { + dev_err(dev, "Error initializing VDI previous input buffer\n"); + return -EINVAL; + } + if (ipu_init_channel_buffer(MEM_VDI_PRP_VF_MEM_N, + IPU_INPUT_BUFFER, + in_pixel_fmt, in_width, in_height, + stride, IPU_ROTATE_NONE, + vout->v4l2_bufs[vout->ipu_buf_n[0]].m.offset+vout->bytesperline, + vout->v4l2_bufs[vout->ipu_buf_n[0]].m.offset+vout->bytesperline, + u_offset, v_offset) != 0) { + dev_err(dev, "Error initializing VDI next input buffer\n"); + return -EINVAL; + } + } + return 0; +} + +/*! + * Initialize VDI path + * + * @param vout structure vout_data * + * + * @return status 0 Success + */ +static int init_VDI(ipu_channel_params_t params, vout_data *vout, + struct device *dev, struct fb_info *fbi, + u16 out_width, u16 out_height) +{ + params.mem_prp_vf_mem.in_width = vout->v2f.fmt.pix.width; + params.mem_prp_vf_mem.in_height = vout->v2f.fmt.pix.height; + params.mem_prp_vf_mem.motion_sel = vout->motion_sel; + params.mem_prp_vf_mem.field_fmt = vout->field_fmt; + params.mem_prp_vf_mem.in_pixel_fmt = vout->v2f.fmt.pix.pixelformat; + params.mem_prp_vf_mem.out_width = out_width; + params.mem_prp_vf_mem.out_height = out_height; + params.mem_prp_vf_mem.out_pixel_fmt = bpp_to_fmt(fbi); + + if (init_VDI_channel(vout, params) != 0) { + dev_err(dev, "Error init_VDI_channel channel\n"); + return -EINVAL; + } + + if (init_VDI_in_channel_buffer(vout, + params.mem_prp_vf_mem.in_pixel_fmt, + params.mem_prp_vf_mem.in_width, + params.mem_prp_vf_mem.in_height, + bytes_per_pixel(params.mem_prp_vf_mem. + in_pixel_fmt), + vout->offset.u_offset, + vout->offset.v_offset) != 0) { + return -EINVAL; + } + + if (!ipu_can_rotate_in_place(vout->rotate)) { + if (vout->rot_pp_bufs[0]) { + mxc_free_buffers(vout->rot_pp_bufs, + vout->rot_pp_bufs_vaddr, 2, + vout->display_buf_size); + } + if (mxc_allocate_buffers + (vout->rot_pp_bufs, vout->rot_pp_bufs_vaddr, 2, + vout->display_buf_size) < 0) { + return -ENOBUFS; + } + + if (ipu_init_channel_buffer(vout->post_proc_ch, + IPU_OUTPUT_BUFFER, + params.mem_prp_vf_mem. + out_pixel_fmt, out_width, + out_height, out_width, + IPU_ROTATE_NONE, + vout->rot_pp_bufs[0], + vout->rot_pp_bufs[1], 0, 0) != 0) { + dev_err(dev, "Error initializing PRP output buffer\n"); + return -EINVAL; + } + + if (ipu_init_channel(MEM_ROT_VF_MEM, NULL) != 0) { + dev_err(dev, "Error initializing PP ROT channel\n"); + return -EINVAL; + } + if (ipu_init_channel_buffer(MEM_ROT_VF_MEM, + IPU_INPUT_BUFFER, + params.mem_prp_vf_mem. + out_pixel_fmt, out_width, + out_height, out_width, + vout->rotate, + vout->rot_pp_bufs[0], + vout->rot_pp_bufs[1], 0, 0) != 0) { + dev_err(dev, + "Error initializing PP ROT input buffer\n"); + return -EINVAL; + } + + /* swap width and height */ + if (vout->rotate >= IPU_ROTATE_90_RIGHT) { + out_width = vout->crop_current.width; + out_height = vout->crop_current.height; + } + + if (ipu_init_channel_buffer(MEM_ROT_VF_MEM, + IPU_OUTPUT_BUFFER, + params.mem_prp_vf_mem. + out_pixel_fmt, out_width, + out_height, out_width, + IPU_ROTATE_NONE, + vout->display_bufs[0], + vout->display_bufs[1], 0, 0) != 0) { + dev_err(dev, + "Error initializing PP-VDI output buffer\n"); + return -EINVAL; + } + + if (ipu_link_channels(vout->post_proc_ch, MEM_ROT_VF_MEM) < 0) + return -EINVAL; + + vout->display_input_ch = MEM_ROT_VF_MEM; + ipu_enable_channel(MEM_ROT_VF_MEM); + ipu_select_buffer(MEM_ROT_VF_MEM, IPU_OUTPUT_BUFFER, 0); + ipu_select_buffer(MEM_ROT_VF_MEM, IPU_OUTPUT_BUFFER, 1); + } else { + if (ipu_init_channel_buffer(vout->post_proc_ch, + IPU_OUTPUT_BUFFER, + params.mem_prp_vf_mem. + out_pixel_fmt, out_width, + out_height, out_width, + vout->rotate, + vout->display_bufs[0], + vout->display_bufs[1], 0, 0) != 0) { + dev_err(dev, + "Error initializing PP-VDI output buffer\n"); + return -EINVAL; + } + } + return 0; +} + +/*! + * Initialize PP path + * + * @param params structure ipu_channel_params_t + * + * @param vout structure vout_data * + * + * @return status 0 Success + */ +static int init_PP(ipu_channel_params_t *params, vout_data *vout, + struct device *dev, struct fb_info *fbi, + u16 out_width, u16 out_height) +{ + u16 in_width, out_stride; /* stride of output channel */ + u32 eba_offset; + u16 x_pos; + u16 y_pos; + eba_offset = 0; + x_pos = 0; + y_pos = 0; + + params->mem_pp_mem.out_pixel_fmt = bpp_to_fmt(fbi); + + if (vout->cur_disp_output == 5) { + x_pos = (vout->crop_current.left / 8) * 8; + y_pos = vout->crop_current.top; + eba_offset = (vout->xres*y_pos + x_pos) * + bytes_per_pixel(params->mem_pp_mem.out_pixel_fmt); + } + + vout->bpp = fmt_to_bpp(params->mem_pp_mem.out_pixel_fmt); + out_stride = vout->xres * + bytes_per_pixel(params->mem_pp_mem.out_pixel_fmt); + in_width = params->mem_pp_mem.in_width = vout->v2f.fmt.pix.width; + params->mem_pp_mem.in_height = vout->v2f.fmt.pix.height; + params->mem_pp_mem.in_pixel_fmt = vout->v2f.fmt.pix.pixelformat; + params->mem_pp_mem.out_width = out_width; + params->mem_pp_mem.out_height = out_height; + params->mem_pp_mem.outh_resize_ratio = 0; /* 0 means unused */ + params->mem_pp_mem.outv_resize_ratio = 0; /* 0 means unused */ + /* split IC by two stripes, the by pass is impossible*/ + if (vout->pp_split) { + vout->pp_left_stripe.input_column = 0; + vout->pp_left_stripe.output_column = 0; + vout->pp_right_stripe.input_column = 0; + vout->pp_right_stripe.output_column = 0; + vout->pp_up_stripe.input_column = 0; + vout->pp_up_stripe.output_column = 0; + vout->pp_down_stripe.input_column = 0; + vout->pp_down_stripe.output_column = 0; + if (vout->pp_split != 3) { + ipu_calc_stripes_sizes( + params->mem_pp_mem.in_width, /* input frame width;>1 */ + params->mem_pp_mem.out_width, /* output frame width; >1 */ + ipu_ic_out_max_width_size, + (((unsigned long long)1) << 32), /* 32bit for fractional*/ + 1, /* equal stripes */ + params->mem_pp_mem.in_pixel_fmt, + params->mem_pp_mem.out_pixel_fmt, + &(vout->pp_left_stripe), + &(vout->pp_right_stripe)); + + vout->pp_left_stripe.input_column = vout->pp_left_stripe.input_column * + fmt_to_bpp(vout->v2f.fmt.pix.pixelformat) / 8; + vout->pp_left_stripe.output_column = vout->pp_left_stripe.output_column * + fmt_to_bpp(params->mem_pp_mem.out_pixel_fmt) / 8; + vout->pp_right_stripe.input_column = vout->pp_right_stripe.input_column * + fmt_to_bpp(vout->v2f.fmt.pix.pixelformat) / 8; + vout->pp_right_stripe.output_column = vout->pp_right_stripe.output_column * + fmt_to_bpp(params->mem_pp_mem.out_pixel_fmt) / 8; + + + /* updare parameters */ + params->mem_pp_mem.in_width = vout->pp_left_stripe.input_width; + params->mem_pp_mem.out_width = vout->pp_left_stripe.output_width; + out_width = vout->pp_left_stripe.output_width; + /* for using in ic_init*/ + params->mem_pp_mem.outh_resize_ratio = vout->pp_left_stripe.irr; + } + if (vout->pp_split != 2) { + ipu_calc_stripes_sizes( + params->mem_pp_mem.in_height, /* input frame width;>1 */ + params->mem_pp_mem.out_height, /* output frame width; >1 */ + ipu_ic_out_max_height_size, + (((unsigned long long)1) << 32),/* 32bit for fractional */ + 1, /* equal stripes */ + params->mem_pp_mem.in_pixel_fmt, + params->mem_pp_mem.out_pixel_fmt, + &(vout->pp_up_stripe), + &(vout->pp_down_stripe)); + vout->pp_down_stripe.output_column = vout->pp_down_stripe.output_column * out_stride; + vout->pp_up_stripe.output_column = vout->pp_up_stripe.output_column * out_stride; + params->mem_pp_mem.outv_resize_ratio = vout->pp_up_stripe.irr; + params->mem_pp_mem.in_height = vout->pp_up_stripe.input_width;/*height*/ + out_height = vout->pp_up_stripe.output_width;/*height*/ + if (vout->pp_split == 3) + vout->pp_split = 2;/*2 vertical stripe as two horizontal stripes */ + } + vout->pp_split_buf_num = 0; + } + + if (ipu_init_channel(vout->post_proc_ch, params) != 0) { + dev_err(dev, "Error initializing PP channel\n"); + return -EINVAL; + } + + if (ipu_init_channel_buffer(vout->post_proc_ch, + IPU_INPUT_BUFFER, + params->mem_pp_mem.in_pixel_fmt, + params->mem_pp_mem.in_width, + params->mem_pp_mem.in_height, + vout->v2f.fmt.pix.bytesperline / + bytes_per_pixel(params->mem_pp_mem. + in_pixel_fmt), + IPU_ROTATE_NONE, + vout->v4l2_bufs[vout->ipu_buf[0]].m.offset, + vout->v4l2_bufs[vout->ipu_buf[1]].m.offset, + vout->offset.u_offset, + vout->offset.v_offset) != 0) { + dev_err(dev, "Error initializing PP input buffer\n"); + return -EINVAL; + } + + if (!ipu_can_rotate_in_place(vout->rotate)) { + if (vout->rot_pp_bufs[0]) { + mxc_free_buffers(vout->rot_pp_bufs, + vout->rot_pp_bufs_vaddr, 2, + vout->display_buf_size); + } + if (mxc_allocate_buffers + (vout->rot_pp_bufs, vout->rot_pp_bufs_vaddr, 2, + vout->display_buf_size) < 0) { + return -ENOBUFS; + } + + if (ipu_init_channel_buffer(vout->post_proc_ch, + IPU_OUTPUT_BUFFER, + params->mem_pp_mem. + out_pixel_fmt, out_width, + out_height, out_stride, + IPU_ROTATE_NONE, + vout->rot_pp_bufs[0] + eba_offset, + vout->rot_pp_bufs[1] + eba_offset, 0, 0) != 0) { + dev_err(dev, "Error initializing PP output buffer\n"); + return -EINVAL; + } + + if (ipu_init_channel(MEM_ROT_PP_MEM, NULL) != 0) { + dev_err(dev, "Error initializing PP ROT channel\n"); + return -EINVAL; + } + if (ipu_init_channel_buffer(MEM_ROT_PP_MEM, + IPU_INPUT_BUFFER, + params->mem_pp_mem. + out_pixel_fmt, out_width, + out_height, out_stride, + vout->rotate, + vout->rot_pp_bufs[0], + vout->rot_pp_bufs[1], 0, 0) != 0) { + dev_err(dev, + "Error initializing PP ROT input buffer\n"); + return -EINVAL; + } + + /* swap width and height */ + if (vout->rotate >= IPU_ROTATE_90_RIGHT) { + out_width = vout->crop_current.width; + out_height = vout->crop_current.height; + } + + if (ipu_init_channel_buffer(MEM_ROT_PP_MEM, + IPU_OUTPUT_BUFFER, + params->mem_pp_mem. + out_pixel_fmt, out_width, + out_height, out_stride, + IPU_ROTATE_NONE, + vout->display_bufs[0] + eba_offset, + vout->display_bufs[1] + eba_offset, 0, 0) != 0) { + dev_err(dev, "Error initializing PP output buffer\n"); + return -EINVAL; + } + + if (ipu_link_channels(vout->post_proc_ch, MEM_ROT_PP_MEM) < 0) + return -EINVAL; + + vout->display_input_ch = MEM_ROT_PP_MEM; + ipu_enable_channel(MEM_ROT_PP_MEM); + ipu_select_buffer(MEM_ROT_PP_MEM, IPU_OUTPUT_BUFFER, 0); + ipu_select_buffer(MEM_ROT_PP_MEM, IPU_OUTPUT_BUFFER, 1); + } else { + if (ipu_init_channel_buffer(vout->post_proc_ch, + IPU_OUTPUT_BUFFER, + params->mem_pp_mem. + out_pixel_fmt, out_width, + out_height, out_stride, + vout->rotate, + vout->display_bufs[0] + eba_offset, + vout->display_bufs[1] + eba_offset, 0, 0) != 0) { + dev_err(dev, "Error initializing PP output buffer\n"); + return -EINVAL; + } + } + + /* fix EBAs for IDMAC channels */ + if (vout->pp_split) { + ipu_update_channel_buffer(vout->post_proc_ch, IPU_INPUT_BUFFER, + 0, + vout->v4l2_bufs[vout->ipu_buf[0]].m.offset + + vout->pp_left_stripe.input_column + + vout->pp_up_stripe.input_column * vout->bytesperline); + + + ipu_update_channel_buffer(vout->post_proc_ch, IPU_INPUT_BUFFER, + 1, + vout->v4l2_bufs[vout->ipu_buf[0]].m.offset + + vout->pp_right_stripe.input_column + + vout->pp_up_stripe.input_column * vout->bytesperline); + + ipu_update_channel_buffer(vout->post_proc_ch, IPU_OUTPUT_BUFFER, + 0, + vout->display_bufs[0] + eba_offset + + vout->pp_left_stripe.output_column + + vout->pp_up_stripe.output_column); + + ipu_update_channel_buffer(vout->post_proc_ch, IPU_OUTPUT_BUFFER, + 1, + vout->display_bufs[0] + eba_offset + + vout->pp_right_stripe.output_column + + vout->pp_up_stripe.output_column); + } + + return 0; +} + +/*! + * Start the output stream + * + * @param vout structure vout_data * + * + * @return status 0 Success + */ +static int mxc_v4l2out_streamon(vout_data *vout) +{ + struct device *dev = &vout->video_dev->dev; + ipu_channel_params_t params; + struct mxcfb_pos fb_pos; + struct fb_var_screeninfo fbvar; + struct fb_info *fbi = + registered_fb[vout->output_fb_num[vout->cur_disp_output]]; + u16 out_width; + u16 out_height; + mm_segment_t old_fs; + unsigned int ipu_ch = CHAN_NONE; + int rc = 0; + + dev_dbg(dev, "mxc_v4l2out_streamon: field format=%d\n", + vout->field_fmt); + + if (!vout) + return -EINVAL; + + if (vout->state != STATE_STREAM_OFF) + return -EBUSY; + + if (queue_size(&vout->ready_q) < 2) { + dev_err(dev, "2 buffers not been queued yet!\n"); + return -EINVAL; + } + + if ((vout->field_fmt == V4L2_FIELD_BOTTOM) || (vout->field_fmt == V4L2_FIELD_TOP)) { + dev_err(dev, "4 queued buffers need, not supported yet!\n"); + return -EINVAL; + } + + /* + * params init, check whether operation exceed the IC limitation: + * whether split mode used ( ipu version >= ipuv3 only) + */ + g_irq_cnt = g_buf_output_cnt = g_buf_q_cnt = g_buf_dq_cnt = 0; + out_width = vout->crop_current.width; + out_height = vout->crop_current.height; + vout->next_done_ipu_buf = 0; + vout->next_rdy_ipu_buf = 1; + vout->pp_split = 0; + ipu_ic_out_max_height_size = 1024; +#ifdef CONFIG_MXC_IPU_V1 + if (cpu_is_mx35()) + ipu_ic_out_max_width_size = 800; + else + ipu_ic_out_max_width_size = 720; +#else + ipu_ic_out_max_width_size = 1024; +#endif + if ((out_width > ipu_ic_out_max_width_size) || + (out_height > ipu_ic_out_max_height_size)) + vout->pp_split = 4; + if (!INTERLACED_CONTENT(vout)) { + vout->next_done_ipu_buf = vout->next_rdy_ipu_buf = 0; + vout->ipu_buf[0] = dequeue_buf(&vout->ready_q); + /* split IC by two stripes, the by pass is impossible*/ + if ((out_width != vout->v2f.fmt.pix.width || + out_height != vout->v2f.fmt.pix.height) && + vout->pp_split) { + vout->ipu_buf[1] = vout->ipu_buf[0]; + vout->frame_count = 1; + if ((out_width > ipu_ic_out_max_width_size) && + (out_height > ipu_ic_out_max_height_size)) + vout->pp_split = 1; /*4 stripes*/ + else if (!(out_height > ipu_ic_out_max_height_size)) + vout->pp_split = 2; /*two horizontal stripes */ + else + vout->pp_split = 3; /*2 vertical stripes*/ + } else { + vout->ipu_buf[1] = dequeue_buf(&vout->ready_q); + vout->frame_count = 2; + } + } else if (!LOAD_3FIELDS(vout)) { + vout->ipu_buf[0] = dequeue_buf(&vout->ready_q); + vout->ipu_buf[1] = -1; + vout->frame_count = 1; + } else { + vout->ipu_buf_p[0] = dequeue_buf(&vout->ready_q); + vout->ipu_buf[0] = dequeue_buf(&vout->ready_q); + vout->ipu_buf_n[0] = vout->ipu_buf[0]; + vout->ipu_buf_p[1] = -1; + vout->ipu_buf[1] = -1; + vout->ipu_buf_n[1] = -1; + last_index_n = vout->ipu_buf_n[0]; + vout->frame_count = 2; + } + + /* + * Bypass IC if resizing and rotation are not needed + * Meanwhile, apply IC bypass to SDC only + */ + fbvar = fbi->var; + vout->xres = fbvar.xres; + vout->yres = fbvar.yres; + + if (vout->cur_disp_output == 3 || vout->cur_disp_output == 5) { + fbvar.bits_per_pixel = 16; + if (format_is_yuv(vout->v2f.fmt.pix.pixelformat)) + fbvar.nonstd = IPU_PIX_FMT_UYVY; + else + fbvar.nonstd = 0; + if (vout->cur_disp_output == 3) { + fbvar.xres = out_width; + fbvar.yres = out_height; + vout->xres = fbvar.xres; + vout->yres = fbvar.yres; + } + + fbvar.xres_virtual = fbvar.xres; + fbvar.yres_virtual = fbvar.yres * 2; + } + + if (out_width == vout->v2f.fmt.pix.width && + out_height == vout->v2f.fmt.pix.height && + vout->xres == out_width && + vout->yres == out_height && + ipu_can_rotate_in_place(vout->rotate) && + (vout->bytesperline == + bytes_per_pixel(vout->v2f.fmt.pix.pixelformat) * out_width) && + !INTERLACED_CONTENT(vout)) { + vout->ic_bypass = 1; + } else { + vout->ic_bypass = 0; + } + +#ifdef CONFIG_MXC_IPU_V1 + /* IPUv1 needs IC to do CSC */ + if (format_is_yuv(vout->v2f.fmt.pix.pixelformat) != + format_is_yuv(bpp_to_fmt(fbi))) + vout->ic_bypass = 0; +#endif + + if (fbi->fbops->fb_ioctl) { + old_fs = get_fs(); + set_fs(KERNEL_DS); + fbi->fbops->fb_ioctl(fbi, MXCFB_GET_FB_IPU_CHAN, + (unsigned long)&ipu_ch); + set_fs(old_fs); + } + + if (ipu_ch == CHAN_NONE) { + dev_err(dev, "Can not get display ipu channel\n"); + return -EINVAL; + } + + vout->display_ch = ipu_ch; + + if (vout->ic_bypass) { + pr_debug("Bypassing IC\n"); + vout->pp_split = 0; + switch (vout->v2f.fmt.pix.pixelformat) { + case V4L2_PIX_FMT_YUV420: + case V4L2_PIX_FMT_YVU420: + case V4L2_PIX_FMT_NV12: + fbvar.bits_per_pixel = 12; + break; + case V4L2_PIX_FMT_YUV422P: + fbvar.bits_per_pixel = 16; + break; + default: + fbvar.bits_per_pixel = 8* + bytes_per_pixel(vout->v2f.fmt.pix.pixelformat); + } + fbvar.nonstd = vout->v2f.fmt.pix.pixelformat; + } + + /* Init display channel through fb API */ + fbvar.activate |= FB_ACTIVATE_FORCE; + fb_set_var(fbi, &fbvar); + + if (fbi->fbops->fb_ioctl && vout->display_ch == MEM_FG_SYNC) { + fb_pos.x = vout->crop_current.left; + fb_pos.y = vout->crop_current.top; + old_fs = get_fs(); + set_fs(KERNEL_DS); + fbi->fbops->fb_ioctl(fbi, MXCFB_SET_OVERLAY_POS, + (unsigned long)&fb_pos); + set_fs(old_fs); + } + + vout->display_bufs[1] = fbi->fix.smem_start; + vout->display_bufs[0] = fbi->fix.smem_start + + (fbi->fix.line_length * vout->yres); + vout->display_buf_size = vout->xres * + vout->yres * fbi->var.bits_per_pixel / 8; + + /* fill black color for init fb, we assume fb has double buffer*/ + if (format_is_yuv(vout->v2f.fmt.pix.pixelformat)) { + int i; + + if ((vout->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_UYVY) || + (vout->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_YUYV) || + (!vout->ic_bypass)) { + short * tmp = (short *) fbi->screen_base; + short color; + if (vout->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_YUYV) + color = 0x8000; + else + color = 0x80; + for (i = 0; i < (fbi->fix.line_length * fbi->var.yres_virtual)/2; + i++, tmp++) + *tmp = color; + } else if ((vout->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_YUV420) || + (vout->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_YVU420) || + (vout->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_NV12)) { + char * base = (char *)fbi->screen_base; + int j, screen_size = fbi->var.xres * fbi->var.yres; + + for (j = 0; j < 2; j++) { + memset(base, 0, screen_size); + base += screen_size; + for (i = 0; i < screen_size/2; i++, base++) + *base = 0x80; + } + } else if (vout->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_YUV422P) { + char * base = (char *)fbi->screen_base; + int j, screen_size = fbi->var.xres * fbi->var.yres; + + for (j = 0; j < 2; j++) { + memset(base, 0, screen_size); + base += screen_size; + for (i = 0; i < screen_size; i++, base++) + *base = 0x80; + } + } + } else + memset(fbi->screen_base, 0x0, + fbi->fix.line_length * fbi->var.yres_virtual); + + if (INTERLACED_CONTENT(vout)) + vout->post_proc_ch = MEM_VDI_PRP_VF_MEM; + else if (!vout->ic_bypass) + vout->post_proc_ch = MEM_PP_MEM; + + /* Init IC channel */ + if (!vout->ic_bypass) { + if (vout->rotate >= IPU_ROTATE_90_RIGHT) { + out_width = vout->crop_current.height; + out_height = vout->crop_current.width; + } + vout->display_input_ch = vout->post_proc_ch; + memset(¶ms, 0, sizeof(params)); + if (INTERLACED_CONTENT(vout)) { + if (vout->pp_split) { + dev_err(&vout->video_dev->dev, "VDI split has not supported yet.\n"); + return -1; + } else + rc = init_VDI(params, vout, dev, fbi, out_width, out_height); + } else { + rc = init_PP(¶ms, vout, dev, fbi, out_width, out_height); + } + if (rc < 0) + return rc; + } + + if (!vout->ic_bypass) { + switch (vout->display_input_ch) { + case MEM_PP_MEM: + vout->work_irq = IPU_IRQ_PP_OUT_EOF; + break; + case MEM_VDI_PRP_VF_MEM: + vout->work_irq = IPU_IRQ_PRP_VF_OUT_EOF; + break; + case MEM_ROT_VF_MEM: + vout->work_irq = IPU_IRQ_PRP_VF_ROT_OUT_EOF; + break; + case MEM_ROT_PP_MEM: + vout->work_irq = IPU_IRQ_PP_ROT_OUT_EOF; + break; + default: + dev_err(&vout->video_dev->dev, + "not support channel, should not be here\n"); + } + } else + vout->work_irq = -1; + + if (!vout->ic_bypass && (vout->work_irq > 0)) { + ipu_clear_irq(vout->work_irq); + ipu_request_irq(vout->work_irq, + mxc_v4l2out_work_irq_handler, + 0, vout->video_dev->name, vout); + } + + vout->state = STATE_STREAM_PAUSED; + + /* Enable display and IC channels */ + if (fbi) { + acquire_console_sem(); + fb_blank(fbi, FB_BLANK_UNBLANK); + release_console_sem(); + } else { + ipu_enable_channel(vout->display_ch); + } + if (!vout->ic_bypass) { +#ifndef CONFIG_MXC_IPU_V1 + ipu_enable_channel(vout->post_proc_ch); +#endif + if (LOAD_3FIELDS(vout)) { + ipu_enable_channel(MEM_VDI_PRP_VF_MEM_P); + ipu_enable_channel(MEM_VDI_PRP_VF_MEM_N); + ipu_select_multi_vdi_buffer(0); + } else if (INTERLACED_CONTENT(vout)) { + ipu_select_buffer(vout->post_proc_ch, IPU_INPUT_BUFFER, 0); + } else { + ipu_select_buffer(vout->post_proc_ch, IPU_INPUT_BUFFER, 0); + if (!vout->pp_split) + ipu_select_buffer(vout->post_proc_ch, IPU_INPUT_BUFFER, 1); + } + ipu_select_buffer(vout->post_proc_ch, IPU_OUTPUT_BUFFER, 0); + ipu_select_buffer(vout->post_proc_ch, IPU_OUTPUT_BUFFER, 1); +#ifdef CONFIG_MXC_IPU_V1 + ipu_enable_channel(vout->post_proc_ch); +#endif + } else { + ipu_update_channel_buffer(vout->display_ch, + IPU_INPUT_BUFFER, + 0, vout->v4l2_bufs[vout->ipu_buf[0]].m.offset); + ipu_update_channel_buffer(vout->display_ch, + IPU_INPUT_BUFFER, + 1, vout->v4l2_bufs[vout->ipu_buf[1]].m.offset); + if (vout->offset.u_offset || vout->offset.v_offset) + /* only update u/v offset */ + ipu_update_channel_offset(vout->display_ch, + IPU_INPUT_BUFFER, + vout->v2f.fmt.pix.pixelformat, + vout->v2f.fmt.pix.width, + vout->v2f.fmt.pix.height, + vout->bytesperline, + vout->offset.u_offset, + vout->offset.v_offset, + 0, + 0); + ipu_select_buffer(vout->display_ch, IPU_INPUT_BUFFER, 0); + queue_work(vout->v4l_wq, &vout->timer_work); + } + + vout->start_jiffies = jiffies; + + msleep(1); + + dev_dbg(dev, + "streamon: start time = %lu jiffies\n", vout->start_jiffies); + + return 0; +} + +/*! + * Shut down the voutera + * + * @param vout structure vout_data * + * + * @return status 0 Success + */ +static int mxc_v4l2out_streamoff(vout_data *vout) +{ + struct fb_info *fbi = + registered_fb[vout->output_fb_num[vout->cur_disp_output]]; + int i, retval = 0; + unsigned long lockflag = 0; + + if (!vout) + return -EINVAL; + + if (vout->state == STATE_STREAM_OFF) { + return 0; + } + + if (!vout->ic_bypass) + ipu_free_irq(vout->work_irq, vout); + + if (vout->ic_bypass) + cancel_work_sync(&vout->timer_work); + + spin_lock_irqsave(&g_lock, lockflag); + + del_timer(&vout->output_timer); + + if (vout->state == STATE_STREAM_ON) { + vout->state = STATE_STREAM_STOPPING; + } + + spin_unlock_irqrestore(&g_lock, lockflag); + + if (vout->display_ch == MEM_FG_SYNC) { + struct mxcfb_pos fb_pos; + mm_segment_t old_fs; + + fb_pos.x = 0; + fb_pos.y = 0; + if (fbi->fbops->fb_ioctl) { + old_fs = get_fs(); + set_fs(KERNEL_DS); + fbi->fbops->fb_ioctl(fbi, MXCFB_SET_OVERLAY_POS, + (unsigned long)&fb_pos); + set_fs(old_fs); + } + } + + if (vout->ic_bypass) { + fbi->var.activate |= FB_ACTIVATE_FORCE; + fb_set_var(fbi, &fbi->var); + + if (vout->display_ch == MEM_FG_SYNC) { + acquire_console_sem(); + fb_blank(fbi, FB_BLANK_POWERDOWN); + release_console_sem(); + } + + vout->display_bufs[0] = 0; + vout->display_bufs[1] = 0; + } else if (vout->post_proc_ch == MEM_PP_MEM || + vout->post_proc_ch == MEM_PRP_VF_MEM) { + /* SDC with Rotation */ + if (!ipu_can_rotate_in_place(vout->rotate)) { + ipu_unlink_channels(MEM_PP_MEM, MEM_ROT_PP_MEM); + ipu_disable_channel(MEM_ROT_PP_MEM, true); + + if (vout->rot_pp_bufs[0]) { + mxc_free_buffers(vout->rot_pp_bufs, + vout->rot_pp_bufs_vaddr, 2, + vout->display_buf_size); + } + } + ipu_disable_channel(MEM_PP_MEM, true); + + fbi->var.activate |= FB_ACTIVATE_FORCE; + fb_set_var(fbi, &fbi->var); + + if (vout->display_ch == MEM_FG_SYNC) { + acquire_console_sem(); + fb_blank(fbi, FB_BLANK_POWERDOWN); + release_console_sem(); + } + + vout->display_bufs[0] = 0; + vout->display_bufs[1] = 0; + + ipu_uninit_channel(MEM_PP_MEM); + if (!ipu_can_rotate_in_place(vout->rotate)) + ipu_uninit_channel(MEM_ROT_PP_MEM); + } else if (INTERLACED_CONTENT(vout) && + (vout->post_proc_ch == MEM_VDI_PRP_VF_MEM)) { + if (!ipu_can_rotate_in_place(vout->rotate)) { + ipu_unlink_channels(MEM_VDI_PRP_VF_MEM, + MEM_ROT_VF_MEM); + ipu_disable_channel(MEM_ROT_VF_MEM, true); + + if (vout->rot_pp_bufs[0]) { + mxc_free_buffers(vout->rot_pp_bufs, + vout->rot_pp_bufs_vaddr, 2, + vout->display_buf_size); + } + } + + ipu_disable_channel(MEM_VDI_PRP_VF_MEM, true); + if (LOAD_3FIELDS(vout)) { + ipu_disable_channel(MEM_VDI_PRP_VF_MEM_P, true); + ipu_disable_channel(MEM_VDI_PRP_VF_MEM_N, true); + } + + fbi->var.activate |= FB_ACTIVATE_FORCE; + fb_set_var(fbi, &fbi->var); + + if (vout->display_ch == MEM_FG_SYNC) { + acquire_console_sem(); + fb_blank(fbi, FB_BLANK_POWERDOWN); + release_console_sem(); + } + + vout->display_bufs[0] = 0; + vout->display_bufs[1] = 0; + + ipu_uninit_channel(MEM_VDI_PRP_VF_MEM); + if (LOAD_3FIELDS(vout)) { + ipu_uninit_channel(MEM_VDI_PRP_VF_MEM_P); + ipu_uninit_channel(MEM_VDI_PRP_VF_MEM_N); + } + if (!ipu_can_rotate_in_place(vout->rotate)) + ipu_uninit_channel(MEM_ROT_VF_MEM); + } + + vout->ready_q.head = vout->ready_q.tail = 0; + vout->done_q.head = vout->done_q.tail = 0; + for (i = 0; i < vout->buffer_cnt; i++) { + vout->v4l2_bufs[i].flags = 0; + vout->v4l2_bufs[i].timestamp.tv_sec = 0; + vout->v4l2_bufs[i].timestamp.tv_usec = 0; + } + + vout->post_proc_ch = CHAN_NONE; + vout->state = STATE_STREAM_OFF; + + return retval; +} + +/* + * Valid whether the palette is supported + * + * @param palette V4L2_PIX_FMT_RGB565, V4L2_PIX_FMT_BGR24 or V4L2_PIX_FMT_BGR32 + * + * @return 1 if supported, 0 if failed + */ +static inline int valid_mode(u32 palette) +{ + return ((palette == V4L2_PIX_FMT_RGB565) || + (palette == V4L2_PIX_FMT_BGR24) || + (palette == V4L2_PIX_FMT_RGB24) || + (palette == V4L2_PIX_FMT_BGR32) || + (palette == V4L2_PIX_FMT_RGB32) || + (palette == V4L2_PIX_FMT_NV12) || + (palette == V4L2_PIX_FMT_UYVY) || + (palette == V4L2_PIX_FMT_YUYV) || + (palette == V4L2_PIX_FMT_YUV422P) || + (palette == V4L2_PIX_FMT_YUV420)); +} + +/* + * V4L2 - Handles VIDIOC_G_FMT Ioctl + * + * @param vout structure vout_data * + * + * @param v4l2_format structure v4l2_format * + * + * @return status 0 success, EINVAL failed + */ +static int mxc_v4l2out_g_fmt(vout_data *vout, struct v4l2_format *f) +{ + if (f->type != V4L2_BUF_TYPE_VIDEO_OUTPUT) { + return -EINVAL; + } + *f = vout->v2f; + return 0; +} + +/* + * V4L2 - Handles VIDIOC_S_FMT Ioctl + * + * @param vout structure vout_data * + * + * @param v4l2_format structure v4l2_format * + * + * @return status 0 success, EINVAL failed + */ +static int mxc_v4l2out_s_fmt(vout_data *vout, struct v4l2_format *f) +{ + int retval = 0; + u32 size = 0; + u32 bytesperline; + + if (f->type != V4L2_BUF_TYPE_VIDEO_OUTPUT) { + retval = -EINVAL; + goto err0; + } + if (!valid_mode(f->fmt.pix.pixelformat)) { + dev_err(&vout->video_dev->dev, "pixel format not supported\n"); + retval = -EINVAL; + goto err0; + } + + bytesperline = (f->fmt.pix.width * fmt_to_bpp(f->fmt.pix.pixelformat)) / + 8; + if (f->fmt.pix.bytesperline < bytesperline) { + f->fmt.pix.bytesperline = bytesperline; + } else { + bytesperline = f->fmt.pix.bytesperline; + } + vout->bytesperline = bytesperline; + + /* Based on http://v4l2spec.bytesex.org/spec/x6386.htm#V4L2-FIELD */ + vout->field_fmt = f->fmt.pix.field; + switch (vout->field_fmt) { + /* Images are in progressive format, not interlaced */ + case V4L2_FIELD_NONE: + break; + /* The two fields of a frame are passed in separate buffers, + in temporal order, i. e. the older one first. */ + case V4L2_FIELD_ALTERNATE: + dev_err(&vout->video_dev->dev, + "V4L2_FIELD_ALTERNATE field format not supported yet!\n"); + break; + case V4L2_FIELD_INTERLACED_TB: + if (cpu_is_mx51() || cpu_is_mx53()) + break; + dev_err(&vout->video_dev->dev, + "De-interlacing not supported in this device!\n"); + vout->field_fmt = V4L2_FIELD_NONE; + case V4L2_FIELD_INTERLACED_BT: + dev_err(&vout->video_dev->dev, + "V4L2_FIELD_INTERLACED_BT field format not supported yet!\n"); + default: + vout->field_fmt = V4L2_FIELD_NONE; + break; + } + + switch (f->fmt.pix.pixelformat) { + case V4L2_PIX_FMT_YUV422P: + /* byteperline for YUV planar formats is for + Y plane only */ + size = bytesperline * f->fmt.pix.height * 2; + break; + case V4L2_PIX_FMT_YUV420: + case V4L2_PIX_FMT_NV12: + size = (bytesperline * f->fmt.pix.height * 3) / 2; + break; + default: + size = bytesperline * f->fmt.pix.height; + break; + } + + /* Return the actual size of the image to the app */ + if (f->fmt.pix.sizeimage < size) { + f->fmt.pix.sizeimage = size; + } else { + size = f->fmt.pix.sizeimage; + } + + vout->v2f.fmt.pix = f->fmt.pix; + if (vout->v2f.fmt.pix.priv != 0) { + if (copy_from_user(&vout->offset, + (void *)vout->v2f.fmt.pix.priv, + sizeof(vout->offset))) { + retval = -EFAULT; + goto err0; + } + } else { + vout->offset.u_offset = 0; + vout->offset.v_offset = 0; + } + + retval = 0; + err0: + return retval; +} + +/* + * V4L2 - Handles VIDIOC_G_CTRL Ioctl + * + * @param vout structure vout_data * + * + * @param c structure v4l2_control * + * + * @return status 0 success, EINVAL failed + */ +static int mxc_get_v42lout_control(vout_data *vout, struct v4l2_control *c) +{ + switch (c->id) { + case V4L2_CID_HFLIP: + return (vout->rotate & IPU_ROTATE_HORIZ_FLIP) ? 1 : 0; + case V4L2_CID_VFLIP: + return (vout->rotate & IPU_ROTATE_VERT_FLIP) ? 1 : 0; + case (V4L2_CID_PRIVATE_BASE + 1): + return vout->rotate; + default: + return -EINVAL; + } +} + +/* + * V4L2 - Handles VIDIOC_S_CTRL Ioctl + * + * @param vout structure vout_data * + * + * @param c structure v4l2_control * + * + * @return status 0 success, EINVAL failed + */ +static int mxc_set_v42lout_control(vout_data *vout, struct v4l2_control *c) +{ + switch (c->id) { + case V4L2_CID_HFLIP: + vout->rotate |= c->value ? IPU_ROTATE_HORIZ_FLIP : + IPU_ROTATE_NONE; + break; + case V4L2_CID_VFLIP: + vout->rotate |= c->value ? IPU_ROTATE_VERT_FLIP : + IPU_ROTATE_NONE; + break; + case V4L2_CID_MXC_ROT: + vout->rotate = c->value; + break; + case V4L2_CID_MXC_MOTION: + vout->motion_sel = c->value; + break; + default: + return -EINVAL; + } + return 0; +} + +/*! + * V4L2 interface - open function + * + * @param file structure file * + * + * @return status 0 success, ENODEV invalid device instance, + * ENODEV timeout, ERESTARTSYS interrupted by user + */ +static int mxc_v4l2out_open(struct file *file) +{ + struct video_device *dev = video_devdata(file); + vout_data *vout = video_get_drvdata(dev); + int err; + + if (!vout) { + return -ENODEV; + } + + down(&vout->busy_lock); + + err = -EINTR; + if (signal_pending(current)) + goto oops; + + + if (vout->open_count++ == 0) { + init_waitqueue_head(&vout->v4l_bufq); + + init_timer(&vout->output_timer); + vout->output_timer.function = mxc_v4l2out_timer_handler; + vout->output_timer.data = (unsigned long)vout; + + vout->state = STATE_STREAM_OFF; + vout->rotate = IPU_ROTATE_NONE; + + vout->v4l_wq = create_singlethread_workqueue("v4l2q"); + if (!vout->v4l_wq) { + dev_dbg(&dev->dev, + "Could not create work queue\n"); + err = -ENOMEM; + goto oops; + } + + INIT_WORK(&vout->timer_work, timer_work_func); + } + + file->private_data = dev; + + up(&vout->busy_lock); + + return 0; + + oops: + up(&vout->busy_lock); + return err; +} + +/*! + * V4L2 interface - close function + * + * @param file struct file * + * + * @return 0 success + */ +static int mxc_v4l2out_close(struct file *file) +{ + struct video_device *dev = video_devdata(file); + vout_data *vout = video_get_drvdata(dev); + + if (--vout->open_count == 0) { + if (vout->state != STATE_STREAM_OFF) + mxc_v4l2out_streamoff(vout); + + file->private_data = NULL; + + mxc_free_buffers(vout->queue_buf_paddr, vout->queue_buf_vaddr, + vout->buffer_cnt, vout->queue_buf_size); + vout->buffer_cnt = 0; + mxc_free_buffers(vout->rot_pp_bufs, vout->rot_pp_bufs_vaddr, 2, + vout->display_buf_size); + + /* capture off */ + wake_up_interruptible(&vout->v4l_bufq); + + flush_workqueue(vout->v4l_wq); + destroy_workqueue(vout->v4l_wq); + } + + return 0; +} + +/*! + * V4L2 interface - ioctl function + * + * @param file struct file * + * + * @param ioctlnr unsigned int + * + * @param arg void * + * + * @return 0 success, ENODEV for invalid device instance, + * -1 for other errors. + */ +static long +mxc_v4l2out_do_ioctl(struct file *file, + unsigned int ioctlnr, void *arg) +{ + struct video_device *vdev = file->private_data; + vout_data *vout = video_get_drvdata(vdev); + int retval = 0; + int i = 0; + + if (!vout) + return -EBADF; + + /* make this _really_ smp-safe */ + if (down_interruptible(&vout->busy_lock)) + return -EBUSY; + + switch (ioctlnr) { + case VIDIOC_QUERYCAP: + { + struct v4l2_capability *cap = arg; + strcpy(cap->driver, "mxc_v4l2_output"); + cap->version = 0; + cap->capabilities = + V4L2_CAP_VIDEO_OUTPUT | V4L2_CAP_STREAMING; + cap->card[0] = '\0'; + cap->bus_info[0] = '\0'; + retval = 0; + break; + } + case VIDIOC_G_FMT: + { + struct v4l2_format *gf = arg; + retval = mxc_v4l2out_g_fmt(vout, gf); + break; + } + case VIDIOC_S_FMT: + { + struct v4l2_format *sf = arg; + if (vout->state != STATE_STREAM_OFF) { + retval = -EBUSY; + break; + } + retval = mxc_v4l2out_s_fmt(vout, sf); + break; + } + case VIDIOC_REQBUFS: + { + struct v4l2_requestbuffers *req = arg; + if ((req->type != V4L2_BUF_TYPE_VIDEO_OUTPUT) || + (req->memory != V4L2_MEMORY_MMAP)) { + dev_dbg(&vdev->dev, + "VIDIOC_REQBUFS: incorrect buffer type\n"); + retval = -EINVAL; + break; + } + + if (req->count == 0) + mxc_v4l2out_streamoff(vout); + + if (vout->state == STATE_STREAM_OFF) { + if (vout->queue_buf_paddr[0] != 0) { + mxc_free_buffers(vout->queue_buf_paddr, + vout->queue_buf_vaddr, + vout->buffer_cnt, + vout->queue_buf_size); + dev_dbg(&vdev->dev, + "VIDIOC_REQBUFS: freed buffers\n"); + } + vout->buffer_cnt = 0; + } else { + dev_dbg(&vdev->dev, + "VIDIOC_REQBUFS: Buffer is in use\n"); + retval = -EBUSY; + break; + } + + if (req->count == 0) + break; + + if (req->count < MIN_FRAME_NUM) { + req->count = MIN_FRAME_NUM; + } else if (req->count > MAX_FRAME_NUM) { + req->count = MAX_FRAME_NUM; + } + vout->buffer_cnt = req->count; + vout->queue_buf_size = + PAGE_ALIGN(vout->v2f.fmt.pix.sizeimage); + + retval = mxc_allocate_buffers(vout->queue_buf_paddr, + vout->queue_buf_vaddr, + vout->buffer_cnt, + vout->queue_buf_size); + if (retval < 0) + break; + + /* Init buffer queues */ + vout->done_q.head = 0; + vout->done_q.tail = 0; + vout->ready_q.head = 0; + vout->ready_q.tail = 0; + + for (i = 0; i < vout->buffer_cnt; i++) { + memset(&(vout->v4l2_bufs[i]), 0, + sizeof(vout->v4l2_bufs[i])); + vout->v4l2_bufs[i].flags = 0; + vout->v4l2_bufs[i].memory = V4L2_MEMORY_MMAP; + vout->v4l2_bufs[i].index = i; + vout->v4l2_bufs[i].type = + V4L2_BUF_TYPE_VIDEO_OUTPUT; + vout->v4l2_bufs[i].length = + PAGE_ALIGN(vout->v2f.fmt.pix.sizeimage); + vout->v4l2_bufs[i].m.offset = + (unsigned long)vout->queue_buf_paddr[i]; + vout->v4l2_bufs[i].timestamp.tv_sec = 0; + vout->v4l2_bufs[i].timestamp.tv_usec = 0; + } + break; + } + case VIDIOC_QUERYBUF: + { + struct v4l2_buffer *buf = arg; + u32 type = buf->type; + int index = buf->index; + + if ((type != V4L2_BUF_TYPE_VIDEO_OUTPUT) || + (index >= vout->buffer_cnt)) { + dev_dbg(&vdev->dev, + "VIDIOC_QUERYBUFS: incorrect buffer type\n"); + retval = -EINVAL; + break; + } + down(&vout->param_lock); + memcpy(buf, &(vout->v4l2_bufs[index]), sizeof(*buf)); + up(&vout->param_lock); + break; + } + case VIDIOC_QBUF: + { + struct v4l2_buffer *buf = arg; + int index = buf->index; + unsigned long lock_flags; + int param[5][3]; + + if ((buf->type != V4L2_BUF_TYPE_VIDEO_OUTPUT) || + (index >= vout->buffer_cnt)) { + retval = -EINVAL; + break; + } + + dev_dbg(&vdev->dev, "VIDIOC_QBUF: %d field = %d\n", buf->index, buf->field); + + /* mmapped buffers are L1 WB cached, + * so we need to clean them */ + if (buf->memory & V4L2_MEMORY_MMAP) { + flush_cache_all(); + } + + spin_lock_irqsave(&g_lock, lock_flags); + + memcpy(&(vout->v4l2_bufs[index]), buf, sizeof(*buf)); + vout->v4l2_bufs[index].flags |= V4L2_BUF_FLAG_QUEUED; + + g_buf_q_cnt++; + if (vout->v4l2_bufs[index].reserved) + if (!copy_from_user(¶m[0][0], + (void *)vout-> + v4l2_bufs[index] + .reserved, sizeof(param))) + ipu_set_csc_coefficients(vout-> + display_ch, + param); + queue_buf(&vout->ready_q, index); + if (vout->state == STATE_STREAM_PAUSED) { + index = peek_next_buf(&vout->ready_q); + setup_next_buf_timer(vout, index); + vout->state = STATE_STREAM_ON; + } + + spin_unlock_irqrestore(&g_lock, lock_flags); + break; + } + case VIDIOC_DQBUF: + { + struct v4l2_buffer *buf = arg; + int idx; + + if ((queue_size(&vout->done_q) == 0) && + (file->f_flags & O_NONBLOCK)) { + retval = -EAGAIN; + break; + } + + if (!wait_event_interruptible_timeout(vout->v4l_bufq, + queue_size(&vout-> + done_q) + != 0, 10 * HZ)) { + dev_dbg(&vdev->dev, "VIDIOC_DQBUF: timeout\n"); + retval = -ETIME; + break; + } else if (signal_pending(current)) { + dev_dbg(&vdev->dev, + "VIDIOC_DQBUF: interrupt received\n"); + retval = -ERESTARTSYS; + break; + } + idx = dequeue_buf(&vout->done_q); + if (idx == -1) { /* No frame free */ + dev_dbg(&vdev->dev, + "VIDIOC_DQBUF: no free buffers, returning\n"); + retval = -EAGAIN; + break; + } + if ((vout->v4l2_bufs[idx].flags & V4L2_BUF_FLAG_DONE) == + 0) + dev_dbg(&vdev->dev, + "VIDIOC_DQBUF: buffer in done q, but not " + "flagged as done\n"); + + vout->v4l2_bufs[idx].flags = 0; + memcpy(buf, &(vout->v4l2_bufs[idx]), sizeof(*buf)); + dev_dbg(&vdev->dev, "VIDIOC_DQBUF: %d\n", buf->index); + break; + } + case VIDIOC_STREAMON: + { + retval = mxc_v4l2out_streamon(vout); + break; + } + case VIDIOC_STREAMOFF: + { + retval = mxc_v4l2out_streamoff(vout); + break; + } + case VIDIOC_G_CTRL: + { + retval = mxc_get_v42lout_control(vout, arg); + break; + } + case VIDIOC_S_CTRL: + { + retval = mxc_set_v42lout_control(vout, arg); + break; + } + case VIDIOC_CROPCAP: + { + struct v4l2_cropcap *cap = arg; + + if (cap->type != V4L2_BUF_TYPE_VIDEO_OUTPUT) { + retval = -EINVAL; + break; + } + + cap->bounds = vout->crop_bounds[vout->cur_disp_output]; + cap->defrect = vout->crop_bounds[vout->cur_disp_output]; + retval = 0; + break; + } + case VIDIOC_G_CROP: + { + struct v4l2_crop *crop = arg; + + if (crop->type != V4L2_BUF_TYPE_VIDEO_OUTPUT) { + retval = -EINVAL; + break; + } + crop->c = vout->crop_current; + break; + } + case VIDIOC_S_CROP: + { + struct v4l2_crop *crop = arg; + struct v4l2_rect *b = + &(vout->crop_bounds[vout->cur_disp_output]); + + if (crop->type != V4L2_BUF_TYPE_VIDEO_OUTPUT) { + retval = -EINVAL; + break; + } + if (crop->c.height < 0) { + retval = -EINVAL; + break; + } + if (crop->c.width < 0) { + retval = -EINVAL; + break; + } + + /* only full screen supported for SDC BG and SDC DC */ + if (vout->cur_disp_output == 4) { + crop->c = vout->crop_current; + break; + } + + if (crop->c.top < b->top) + crop->c.top = b->top; + if (crop->c.top >= b->top + b->height) + crop->c.top = b->top + b->height - 1; + if (crop->c.height > b->top - crop->c.top + b->height) + crop->c.height = + b->top - crop->c.top + b->height; + + if (crop->c.left < b->left) + crop->c.left = b->left; + if (crop->c.left >= b->left + b->width) + crop->c.left = b->left + b->width - 1; + if (crop->c.width > b->left - crop->c.left + b->width) + crop->c.width = + b->left - crop->c.left + b->width; + + /* stride line limitation */ + crop->c.height -= crop->c.height % 8; + crop->c.width -= crop->c.width % 8; + + vout->crop_current = crop->c; + break; + } + case VIDIOC_ENUMOUTPUT: + { + struct v4l2_output *output = arg; + + if ((output->index >= 5) || + (vout->output_enabled[output->index] == false)) { + retval = -EINVAL; + break; + } + + if (output->index >= 3) + *output = mxc_outputs[MXC_V4L2_OUT_2_SDC]; + break; + } + case VIDIOC_G_OUTPUT: + { + int *p_output_num = arg; + + *p_output_num = vout->cur_disp_output; + break; + } + case VIDIOC_S_OUTPUT: + { + int *p_output_num = arg; + int fbnum; + struct v4l2_rect *b; + + if ((*p_output_num >= MXC_V4L2_OUT_NUM_OUTPUTS) || + (vout->output_enabled[*p_output_num] == false)) { + retval = -EINVAL; + break; + } + + if (vout->state != STATE_STREAM_OFF) { + retval = -EBUSY; + break; + } + + vout->cur_disp_output = *p_output_num; + + /* Update bounds in case they have changed */ + b = &vout->crop_bounds[vout->cur_disp_output]; + + fbnum = vout->output_fb_num[vout->cur_disp_output]; + + /* + * For FG overlay, it uses BG window parameter as + * limitation reference; and BG must be enabled to + * support FG. + */ + if (vout->cur_disp_output == 3) { + unsigned int i, ipu_ch = CHAN_NONE; + struct fb_info *fbi; + mm_segment_t old_fs; + + for (i = 0; i < num_registered_fb; i++) { + fbi = registered_fb[i]; + if (fbi->fbops->fb_ioctl) { + old_fs = get_fs(); + set_fs(KERNEL_DS); + fbi->fbops->fb_ioctl(fbi, + MXCFB_GET_FB_IPU_CHAN, + (unsigned long)&ipu_ch); + set_fs(old_fs); + } + if (ipu_ch == CHAN_NONE) { + dev_err(&vdev->dev, + "Can't get disp ipu channel\n"); + retval = -EINVAL; + break; + } + + if (ipu_ch == MEM_BG_SYNC) { + fbnum = i; + break; + } + } + } + + b->width = registered_fb[fbnum]->var.xres; + b->height = registered_fb[fbnum]->var.yres; + + vout->crop_current = *b; + break; + } + case VIDIOC_ENUM_FMT: + case VIDIOC_TRY_FMT: + case VIDIOC_QUERYCTRL: + case VIDIOC_G_PARM: + case VIDIOC_ENUMSTD: + case VIDIOC_G_STD: + case VIDIOC_S_STD: + case VIDIOC_G_TUNER: + case VIDIOC_S_TUNER: + case VIDIOC_G_FREQUENCY: + case VIDIOC_S_FREQUENCY: + default: + retval = -EINVAL; + break; + } + + up(&vout->busy_lock); + return retval; +} + +/* + * V4L2 interface - ioctl function + * + * @return None + */ +static long +mxc_v4l2out_ioctl(struct file *file, + unsigned int cmd, unsigned long arg) +{ + return video_usercopy(file, cmd, arg, mxc_v4l2out_do_ioctl); +} + +/*! + * V4L2 interface - mmap function + * + * @param file structure file * + * + * @param vma structure vm_area_struct * + * + * @return status 0 Success, EINTR busy lock error, + * ENOBUFS remap_page error + */ +static int mxc_v4l2out_mmap(struct file *file, struct vm_area_struct *vma) +{ + struct video_device *vdev = video_devdata(file); + unsigned long size = vma->vm_end - vma->vm_start; + int res = 0; + int i; + vout_data *vout = video_get_drvdata(vdev); + + dev_dbg(&vdev->dev, "pgoff=0x%lx, start=0x%lx, end=0x%lx\n", + vma->vm_pgoff, vma->vm_start, vma->vm_end); + + /* make this _really_ smp-safe */ + if (down_interruptible(&vout->busy_lock)) + return -EINTR; + + for (i = 0; i < vout->buffer_cnt; i++) { + if ((vout->v4l2_bufs[i].m.offset == + (vma->vm_pgoff << PAGE_SHIFT)) && + (vout->v4l2_bufs[i].length >= size)) { + vout->v4l2_bufs[i].flags |= V4L2_BUF_FLAG_MAPPED; + break; + } + } + if (i == vout->buffer_cnt) { + res = -ENOBUFS; + goto mxc_mmap_exit; + } + + /* make buffers inner write-back, outer write-thru cacheable */ + /* vma->vm_page_prot = pgprot_outer_wrthru(vma->vm_page_prot);*/ + + if (remap_pfn_range(vma, vma->vm_start, + vma->vm_pgoff, size, vma->vm_page_prot)) { + dev_dbg(&vdev->dev, "mmap remap_pfn_range failed\n"); + res = -ENOBUFS; + goto mxc_mmap_exit; + } + + vma->vm_flags &= ~VM_IO; /* using shared anonymous pages */ + + mxc_mmap_exit: + up(&vout->busy_lock); + return res; +} + +/*! + * V4L2 interface - poll function + * + * @param file structure file * + * + * @param wait structure poll_table_struct * + * + * @return status POLLIN | POLLRDNORM + */ +static unsigned int mxc_v4l2out_poll(struct file *file, struct poll_table_struct * wait) +{ + struct video_device *dev = video_devdata(file); + vout_data *vout = video_get_drvdata(dev); + + wait_queue_head_t *queue = NULL; + int res = POLLIN | POLLRDNORM; + + if (down_interruptible(&vout->busy_lock)) + return -EINTR; + + queue = &vout->v4l_bufq; + poll_wait(file, queue, wait); + + up(&vout->busy_lock); + return res; +} + +static struct +v4l2_file_operations mxc_v4l2out_fops = { + .owner = THIS_MODULE, + .open = mxc_v4l2out_open, + .release = mxc_v4l2out_close, + .ioctl = mxc_v4l2out_ioctl, + .mmap = mxc_v4l2out_mmap, + .poll = mxc_v4l2out_poll, +}; + +static struct video_device mxc_v4l2out_template = { + .name = "MXC Video Output", + .vfl_type = V4L2_CAP_VIDEO_OUTPUT | V4L2_CAP_STREAMING, + .fops = &mxc_v4l2out_fops, + .release = video_device_release, +}; + +/*! + * Probe routine for the framebuffer driver. It is called during the + * driver binding process. The following functions are performed in + * this routine: Framebuffer initialization, Memory allocation and + * mapping, Framebuffer registration, IPU initialization. + * + * @return Appropriate error code to the kernel common code + */ +static int mxc_v4l2out_probe(struct platform_device *pdev) +{ + int i; + vout_data *vout; + + /* + * Allocate sufficient memory for the fb structure + */ + vout = kmalloc(sizeof(vout_data), GFP_KERNEL); + + if (!vout) + return 0; + + memset(vout, 0, sizeof(vout_data)); + + vout->video_dev = video_device_alloc(); + if (vout->video_dev == NULL) + return -1; + vout->video_dev->minor = -1; + + *(vout->video_dev) = mxc_v4l2out_template; + + /* register v4l device */ + if (video_register_device(vout->video_dev, + VFL_TYPE_GRABBER, video_nr) == -1) { + dev_dbg(&pdev->dev, "video_register_device failed\n"); + return 0; + } + dev_info(&pdev->dev, "Registered device video%d\n", + vout->video_dev->minor & 0x1f); + /*vout->video_dev->dev = &pdev->dev;*/ + + video_set_drvdata(vout->video_dev, vout); + + init_MUTEX(&vout->param_lock); + init_MUTEX(&vout->busy_lock); + + /* setup outputs and cropping */ + vout->cur_disp_output = -1; + for (i = 0; i < num_registered_fb; i++) { + char *idstr = registered_fb[i]->fix.id; + if (strncmp(idstr, "DISP", 4) == 0) { + int disp_num = idstr[4] - '0'; + if (disp_num == 3) { + if (strcmp(idstr, "DISP3 BG - DI1") == 0) + disp_num = 5; + else if (strncmp(idstr, "DISP3 BG", 8) == 0) + disp_num = 4; + } + vout->crop_bounds[disp_num].left = 0; + vout->crop_bounds[disp_num].top = 0; + vout->crop_bounds[disp_num].width = + registered_fb[i]->var.xres; + vout->crop_bounds[disp_num].height = + registered_fb[i]->var.yres; + vout->output_enabled[disp_num] = true; + vout->output_fb_num[disp_num] = i; + if (vout->cur_disp_output == -1) { + vout->cur_disp_output = disp_num; + } + } + + } + vout->crop_current = vout->crop_bounds[vout->cur_disp_output]; + + platform_set_drvdata(pdev, vout); + + return 0; +} + +static int mxc_v4l2out_remove(struct platform_device *pdev) +{ + vout_data *vout = platform_get_drvdata(pdev); + + if (vout->video_dev) { + video_unregister_device(vout->video_dev); + vout->video_dev = NULL; + } + + platform_set_drvdata(pdev, NULL); + + kfree(vout); + + return 0; +} + +/*! + * This structure contains pointers to the power management callback functions. + */ +static struct platform_driver mxc_v4l2out_driver = { + .driver = { + .name = "mxc_v4l2_output", + }, + .probe = mxc_v4l2out_probe, + .remove = mxc_v4l2out_remove, +}; + +/*! + * mxc v4l2 init function + * + */ +static int mxc_v4l2out_init(void) +{ + return platform_driver_register(&mxc_v4l2out_driver); +} + +/*! + * mxc v4l2 cleanup function + * + */ +static void mxc_v4l2out_clean(void) +{ + platform_driver_unregister(&mxc_v4l2out_driver); +} + +module_init(mxc_v4l2out_init); +module_exit(mxc_v4l2out_clean); + +module_param(video_nr, int, 0444); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("V4L2-driver for MXC video output"); +MODULE_LICENSE("GPL"); +MODULE_SUPPORTED_DEVICE("video"); diff --git a/drivers/media/video/mxc/output/mxc_v4l2_output.h b/drivers/media/video/mxc/output/mxc_v4l2_output.h new file mode 100644 index 000000000000..096dc3b17a06 --- /dev/null +++ b/drivers/media/video/mxc/output/mxc_v4l2_output.h @@ -0,0 +1,154 @@ +/* + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @defgroup MXC_V4L2_OUTPUT MXC V4L2 Video Output Driver + */ +/*! + * @file mxc_v4l2_output.h + * + * @brief MXC V4L2 Video Output Driver Header file + * + * Video4Linux2 Output Device using MXC IPU Post-processing functionality. + * + * @ingroup MXC_V4L2_OUTPUT + */ +#ifndef __MXC_V4L2_OUTPUT_H__ +#define __MXC_V4L2_OUTPUT_H__ + +#include + +#ifdef __KERNEL__ + +#include +#include +#include + +#define MIN_FRAME_NUM 2 +#define MAX_FRAME_NUM 30 + +#define MXC_V4L2_OUT_NUM_OUTPUTS 6 +#define MXC_V4L2_OUT_2_SDC 0 + + +typedef struct { + int list[MAX_FRAME_NUM + 1]; + int head; + int tail; +} v4l_queue; + +/*! + * States for the video stream + */ +typedef enum { + STATE_STREAM_OFF, + STATE_STREAM_ON, + STATE_STREAM_PAUSED, + STATE_STREAM_STOPPING, +} v4lout_state; + +/*! + * common v4l2 driver structure. + */ +typedef struct _vout_data { + struct video_device *video_dev; + /*! + * semaphore guard against SMP multithreading + */ + struct semaphore busy_lock; + + /*! + * number of process that have device open + */ + int open_count; + + /*! + * params lock for this camera + */ + struct semaphore param_lock; + + struct timer_list output_timer; + struct workqueue_struct *v4l_wq; + struct work_struct timer_work; + unsigned long start_jiffies; + u32 frame_count; + + v4l_queue ready_q; + v4l_queue done_q; + + s8 next_rdy_ipu_buf; + s8 next_done_ipu_buf; + s8 ipu_buf[2]; + s8 ipu_buf_p[2]; + s8 ipu_buf_n[2]; + volatile v4lout_state state; + + int cur_disp_output; + int output_fb_num[MXC_V4L2_OUT_NUM_OUTPUTS]; + int output_enabled[MXC_V4L2_OUT_NUM_OUTPUTS]; + struct v4l2_framebuffer v4l2_fb; + int ic_bypass; + u32 work_irq; + ipu_channel_t display_ch; + ipu_channel_t post_proc_ch; + ipu_channel_t display_input_ch; + + /*! + * FRAME_NUM-buffering, so we need a array + */ + int buffer_cnt; + dma_addr_t queue_buf_paddr[MAX_FRAME_NUM]; + void *queue_buf_vaddr[MAX_FRAME_NUM]; + u32 queue_buf_size; + struct v4l2_buffer v4l2_bufs[MAX_FRAME_NUM]; + u32 display_buf_size; + dma_addr_t display_bufs[2]; + void *display_bufs_vaddr[2]; + dma_addr_t rot_pp_bufs[2]; + void *rot_pp_bufs_vaddr[2]; + + /*! + * Poll wait queue + */ + wait_queue_head_t v4l_bufq; + + /*! + * v4l2 format + */ + struct v4l2_format v2f; + struct v4l2_mxc_offset offset; + ipu_rotate_mode_t rotate; + + /* crop */ + struct v4l2_rect crop_bounds[MXC_V4L2_OUT_NUM_OUTPUTS]; + struct v4l2_rect crop_current; + u32 bytesperline; + enum v4l2_field field_fmt; + ipu_motion_sel motion_sel; + + /* PP split fot two stripes*/ + int pp_split; /* 0,1 */ + struct stripe_param pp_left_stripe; + struct stripe_param pp_right_stripe; /* struct for split parameters */ + struct stripe_param pp_up_stripe; + struct stripe_param pp_down_stripe; + /* IC ouput buffer number. Counting from 0 to 7 */ + int pp_split_buf_num; /* 0..7 */ + u16 bpp ; /* bit per pixel */ + u16 xres; /* width of physical frame (BGs) */ + u16 yres; /* heigth of physical frame (BGs)*/ + +} vout_data; + +#endif +#endif /* __MXC_V4L2_OUTPUT_H__ */ diff --git a/drivers/media/video/mxs_pxp.c b/drivers/media/video/mxs_pxp.c new file mode 100644 index 000000000000..93549ffe4198 --- /dev/null +++ b/drivers/media/video/mxs_pxp.c @@ -0,0 +1,1414 @@ +/* + * Freescale MXS PxP driver + * + * Author: Matt Porter + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. + * Copyright 2008-2009 Embedded Alley Solutions, Inc All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +#include "mxs_pxp.h" + +#define PXP_BASE_ADDR IO_ADDRESS(PXP_PHYS_ADDR) + +#define PXP_DRIVER_NAME "mxs-pxp" +#define PXP_DRIVER_MAJOR 1 +#define PXP_DRIVER_MINOR 0 + +#define PXP_DEF_BUFS 2 +#define PXP_MIN_PIX 8 + +#define V4L2_OUTPUT_TYPE_INTERNAL 4 + +#define PXP_WAITCON ((__raw_readl(PXP_BASE_ADDR + HW_PXP_NEXT) & \ + BM_PXP_NEXT_ENABLED) != BM_PXP_NEXT_ENABLED) + +#define REG_OFFSET 0x10 +#define REGS1_NUMS 16 +#define REGS2_NUMS 5 +#define REGS3_NUMS 32 +static u32 regs1[REGS1_NUMS]; +static u32 regs2[REGS2_NUMS]; +static u32 regs3[REGS3_NUMS]; + +static struct pxp_data_format pxp_s0_formats[] = { + { + .name = "24-bit RGB", + .bpp = 4, + .fourcc = V4L2_PIX_FMT_RGB24, + .colorspace = V4L2_COLORSPACE_SRGB, + .ctrl_s0_fmt = BV_PXP_CTRL_S0_FORMAT__RGB888, + }, + { + .name = "16-bit RGB 5:6:5", + .bpp = 2, + .fourcc = V4L2_PIX_FMT_RGB565, + .colorspace = V4L2_COLORSPACE_SRGB, + .ctrl_s0_fmt = BV_PXP_CTRL_S0_FORMAT__RGB565, + }, + { + .name = "16-bit RGB 5:5:5", + .bpp = 2, + .fourcc = V4L2_PIX_FMT_RGB555, + .colorspace = V4L2_COLORSPACE_SRGB, + .ctrl_s0_fmt = BV_PXP_CTRL_S0_FORMAT__RGB555, + }, + { + .name = "YUV 4:2:0 Planar", + .bpp = 2, + .fourcc = V4L2_PIX_FMT_YUV420, + .colorspace = V4L2_COLORSPACE_JPEG, + .ctrl_s0_fmt = BV_PXP_CTRL_S0_FORMAT__YUV420, + }, + { + .name = "YUV 4:2:2 Planar", + .bpp = 2, + .fourcc = V4L2_PIX_FMT_YUV422P, + .colorspace = V4L2_COLORSPACE_JPEG, + .ctrl_s0_fmt = BV_PXP_CTRL_S0_FORMAT__YUV422, + }, +}; + +struct v4l2_queryctrl pxp_controls[] = { + { + .id = V4L2_CID_HFLIP, + .type = V4L2_CTRL_TYPE_BOOLEAN, + .name = "Horizontal Flip", + .minimum = 0, + .maximum = 1, + .step = 1, + .default_value = 0, + .flags = 0, + }, + { + .id = V4L2_CID_VFLIP, + .type = V4L2_CTRL_TYPE_BOOLEAN, + .name = "Vertical Flip", + .minimum = 0, + .maximum = 1, + .step = 1, + .default_value = 0, + .flags = 0, + }, + { + .id = V4L2_CID_PRIVATE_BASE, + .type = V4L2_CTRL_TYPE_INTEGER, + .name = "Rotation", + .minimum = 0, + .maximum = 270, + .step = 90, + .default_value = 0, + .flags = 0, + }, + { + .id = V4L2_CID_PRIVATE_BASE + 1, + .name = "Background Color", + .minimum = 0, + .maximum = 0xFFFFFF, + .step = 1, + .default_value = 0, + .flags = 0, + .type = V4L2_CTRL_TYPE_INTEGER, + }, + { + .id = V4L2_CID_PRIVATE_BASE + 2, + .name = "Set S0 Chromakey", + .minimum = -1, + .maximum = 0xFFFFFF, + .step = 1, + .default_value = -1, + .flags = 0, + .type = V4L2_CTRL_TYPE_INTEGER, + }, + { + .id = V4L2_CID_PRIVATE_BASE + 3, + .name = "YUV Colorspace", + .minimum = 0, + .maximum = 1, + .step = 1, + .default_value = 0, + .flags = 0, + .type = V4L2_CTRL_TYPE_BOOLEAN, + }, +}; + +static void pxp_set_ctrl(struct pxps *pxp) +{ + u32 ctrl; + + ctrl = BF_PXP_CTRL_S0_FORMAT(pxp->s0_fmt->ctrl_s0_fmt); + ctrl |= BF_PXP_CTRL_OUTBUF_FORMAT(BV_PXP_CTRL_OUTBUF_FORMAT__RGB888); + ctrl |= BM_PXP_CTRL_CROP; + + if (pxp->scaling) + ctrl |= BM_PXP_CTRL_SCALE; + if (pxp->vflip) + ctrl |= BM_PXP_CTRL_VFLIP; + if (pxp->hflip) + ctrl |= BM_PXP_CTRL_HFLIP; + if (pxp->rotate) + ctrl |= BF_PXP_CTRL_ROTATE(pxp->rotate / 90); + + ctrl |= BM_PXP_CTRL_IRQ_ENABLE; + if (pxp->active) + ctrl |= BM_PXP_CTRL_ENABLE; + + __raw_writel(ctrl, PXP_BASE_ADDR + HW_PXP_CTRL); + pxp->regs_virt->ctrl = ctrl; +} + +static void pxp_set_outbuf(struct pxps *pxp) +{ + pxp->regs_virt->outbuf = pxp->outb_phys; + /* Always equal to the FB size */ + if (pxp->rotate % 180) + pxp->regs_virt->outsize = + BF_PXP_OUTSIZE_WIDTH(pxp->fb.fmt.height) | + BF_PXP_OUTSIZE_HEIGHT(pxp->fb.fmt.width); + else + pxp->regs_virt->outsize = + BF_PXP_OUTSIZE_WIDTH(pxp->fb.fmt.width) | + BF_PXP_OUTSIZE_HEIGHT(pxp->fb.fmt.height); +} + +static void pxp_set_s0colorkey(struct pxps *pxp) +{ + /* Low and high are set equal. V4L does not allow a chromakey range */ + if (pxp->s0_chromakey == -1) { + /* disable color key */ + pxp->regs_virt->s0colorkeylow = 0xFFFFFF; + pxp->regs_virt->s0colorkeyhigh = 0; + } else { + pxp->regs_virt->s0colorkeylow = pxp->s0_chromakey; + pxp->regs_virt->s0colorkeyhigh = pxp->s0_chromakey; + } +} + +static void pxp_set_s1colorkey(struct pxps *pxp) +{ + /* Low and high are set equal. V4L does not allow a chromakey range */ + if (pxp->s1_chromakey_state != 0 && pxp->s1_chromakey != -1) { + pxp->regs_virt->olcolorkeylow = pxp->s1_chromakey; + pxp->regs_virt->olcolorkeyhigh = pxp->s1_chromakey; + } else { + /* disable color key */ + pxp->regs_virt->olcolorkeylow = 0xFFFFFF; + pxp->regs_virt->olcolorkeyhigh = 0; + } +} + +static void pxp_set_oln(struct pxps *pxp) +{ + pxp->regs_virt->ol0.ol = (u32) pxp->fb.base; + if (pxp->rotate % 180) + pxp->regs_virt->ol0.olsize = + BF_PXP_OLnSIZE_WIDTH(pxp->fb.fmt.height >> 3) | + BF_PXP_OLnSIZE_HEIGHT(pxp->fb.fmt.width >> 3); + else + pxp->regs_virt->ol0.olsize = + BF_PXP_OLnSIZE_WIDTH(pxp->fb.fmt.width >> 3) | + BF_PXP_OLnSIZE_HEIGHT(pxp->fb.fmt.height >> 3); +} + +static void pxp_set_olparam(struct pxps *pxp) +{ + u32 olparam; + struct v4l2_pix_format *fmt = &pxp->fb.fmt; + + olparam = BF_PXP_OLnPARAM_ALPHA(pxp->global_alpha); + if (fmt->pixelformat == V4L2_PIX_FMT_RGB24) + olparam |= + BF_PXP_OLnPARAM_FORMAT(BV_PXP_OLnPARAM_FORMAT__RGB888); + else + olparam |= + BF_PXP_OLnPARAM_FORMAT(BV_PXP_OLnPARAM_FORMAT__RGB565); + if (pxp->global_alpha_state) + olparam |= + BF_PXP_OLnPARAM_ALPHA_CNTL + (BV_PXP_OLnPARAM_ALPHA_CNTL__Override); + if (pxp->s1_chromakey_state) + olparam |= BM_PXP_OLnPARAM_ENABLE_COLORKEY; + if (pxp->overlay_state) + olparam |= BM_PXP_OLnPARAM_ENABLE; + + pxp->regs_virt->ol0.olparam = olparam; +} + +static void pxp_set_s0param(struct pxps *pxp) +{ + u32 s0param; + + s0param = BF_PXP_S0PARAM_XBASE(pxp->drect.left >> 3); + s0param |= BF_PXP_S0PARAM_YBASE(pxp->drect.top >> 3); + s0param |= BF_PXP_S0PARAM_WIDTH(pxp->s0_width >> 3); + s0param |= BF_PXP_S0PARAM_HEIGHT(pxp->s0_height >> 3); + pxp->regs_virt->s0param = s0param; +} + +static void pxp_set_s0crop(struct pxps *pxp) +{ + u32 s0crop; + + s0crop = BF_PXP_S0CROP_XBASE(pxp->srect.left >> 3); + s0crop |= BF_PXP_S0CROP_YBASE(pxp->srect.top >> 3); + s0crop |= BF_PXP_S0CROP_WIDTH(pxp->drect.width >> 3); + s0crop |= BF_PXP_S0CROP_HEIGHT(pxp->drect.height >> 3); + pxp->regs_virt->s0crop = s0crop; +} + +static int pxp_set_scaling(struct pxps *pxp) +{ + int ret = 0; + u32 xscale, yscale, s0scale; + + if ((pxp->s0_fmt->fourcc != V4L2_PIX_FMT_YUV420) && + (pxp->s0_fmt->fourcc != V4L2_PIX_FMT_YUV422P)) { + pxp->scaling = 0; + ret = -EINVAL; + goto out; + } + + if ((pxp->srect.width == pxp->drect.width) && + (pxp->srect.height == pxp->drect.height)) { + pxp->regs_virt->s0scale = 0x10001000; + pxp->scaling = 0; + goto out; + } + + pxp->scaling = 1; + xscale = pxp->srect.width * 0x1000 / pxp->drect.width; + yscale = pxp->srect.height * 0x1000 / pxp->drect.height; + if (xscale > PXP_DOWNSCALE_THRESHOLD) + xscale = PXP_DOWNSCALE_THRESHOLD; + if (yscale > PXP_DOWNSCALE_THRESHOLD) + yscale = PXP_DOWNSCALE_THRESHOLD; + s0scale = BF_PXP_S0SCALE_YSCALE(yscale) | BF_PXP_S0SCALE_XSCALE(xscale); + pxp->regs_virt->s0scale = s0scale; + +out: + pxp_set_ctrl(pxp); + + return ret; +} + +static int pxp_set_fbinfo(struct pxps *pxp) +{ + struct fb_var_screeninfo var; + struct fb_fix_screeninfo fix; + struct v4l2_framebuffer *fb = &pxp->fb; + int err; + + err = mxsfb_get_info(&var, &fix); + + fb->fmt.width = var.xres; + fb->fmt.height = var.yres; + if (var.bits_per_pixel == 16) + fb->fmt.pixelformat = V4L2_PIX_FMT_RGB565; + else + fb->fmt.pixelformat = V4L2_PIX_FMT_RGB24; + fb->base = (void *)fix.smem_start; + return err; +} + +static void pxp_set_s0bg(struct pxps *pxp) +{ + pxp->regs_virt->s0background = pxp->s0_bgcolor; +} + +static void pxp_set_csc(struct pxps *pxp) +{ + if (pxp->yuv) { + /* YUV colorspace */ + __raw_writel(0x04030000, PXP_BASE_ADDR + HW_PXP_CSCCOEFF0); + __raw_writel(0x01230208, PXP_BASE_ADDR + HW_PXP_CSCCOEFF1); + __raw_writel(0x076b079b, PXP_BASE_ADDR + HW_PXP_CSCCOEFF2); + } else { + /* YCrCb colorspace */ + __raw_writel(0x84ab01f0, PXP_BASE_ADDR + HW_PXP_CSCCOEFF0); + __raw_writel(0x01230204, PXP_BASE_ADDR + HW_PXP_CSCCOEFF1); + __raw_writel(0x0730079c, PXP_BASE_ADDR + HW_PXP_CSCCOEFF2); + } +} + +static int pxp_set_cstate(struct pxps *pxp, struct v4l2_control *vc) +{ + + if (vc->id == V4L2_CID_HFLIP) + pxp->hflip = vc->value; + else if (vc->id == V4L2_CID_VFLIP) + pxp->vflip = vc->value; + else if (vc->id == V4L2_CID_PRIVATE_BASE) { + if (vc->value % 90) + return -ERANGE; + pxp->rotate = vc->value; + } else if (vc->id == V4L2_CID_PRIVATE_BASE + 1) { + pxp->s0_bgcolor = vc->value; + pxp_set_s0bg(pxp); + } else if (vc->id == V4L2_CID_PRIVATE_BASE + 2) { + pxp->s0_chromakey = vc->value; + pxp_set_s0colorkey(pxp); + } else if (vc->id == V4L2_CID_PRIVATE_BASE + 3) { + pxp->yuv = vc->value; + pxp_set_csc(pxp); + } + + pxp_set_ctrl(pxp); + + return 0; +} + +static int pxp_get_cstate(struct pxps *pxp, struct v4l2_control *vc) +{ + if (vc->id == V4L2_CID_HFLIP) + vc->value = pxp->hflip; + else if (vc->id == V4L2_CID_VFLIP) + vc->value = pxp->vflip; + else if (vc->id == V4L2_CID_PRIVATE_BASE) + vc->value = pxp->rotate; + else if (vc->id == V4L2_CID_PRIVATE_BASE + 1) + vc->value = pxp->s0_bgcolor; + else if (vc->id == V4L2_CID_PRIVATE_BASE + 2) + vc->value = pxp->s0_chromakey; + else if (vc->id == V4L2_CID_PRIVATE_BASE + 3) + vc->value = pxp->yuv; + + return 0; +} + +static int pxp_enumoutput(struct file *file, void *fh, struct v4l2_output *o) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + + if ((o->index < 0) || (o->index > 1)) + return -EINVAL; + + memset(o, 0, sizeof(struct v4l2_output)); + if (o->index == 0) { + strcpy(o->name, "PxP Display Output"); + pxp->output = 0; + } else { + strcpy(o->name, "PxP Virtual Output"); + pxp->output = 1; + } + o->type = V4L2_OUTPUT_TYPE_INTERNAL; + o->std = 0; + o->reserved[0] = pxp->outb_phys; + + return 0; +} + +static int pxp_g_output(struct file *file, void *fh, unsigned int *i) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + + *i = pxp->output; + + return 0; +} + +static int pxp_s_output(struct file *file, void *fh, unsigned int i) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + struct v4l2_pix_format *fmt = &pxp->fb.fmt; + int bpp; + + if ((i < 0) || (i > 1)) + return -EINVAL; + + if (pxp->outb) + goto out; + + /* Output buffer is same format as fbdev */ + if (fmt->pixelformat == V4L2_PIX_FMT_RGB24) + bpp = 4; + else + bpp = 2; + + pxp->outb = kmalloc(fmt->width * fmt->height * bpp, GFP_KERNEL); + pxp->outb_phys = virt_to_phys(pxp->outb); + dma_map_single(NULL, pxp->outb, + fmt->width * fmt->height * bpp, DMA_TO_DEVICE); + +out: + pxp_set_outbuf(pxp); + + return 0; +} + +static int pxp_enum_fmt_video_output(struct file *file, void *fh, + struct v4l2_fmtdesc *fmt) +{ + enum v4l2_buf_type type = fmt->type; + int index = fmt->index; + + if ((fmt->index < 0) || (fmt->index >= ARRAY_SIZE(pxp_s0_formats))) + return -EINVAL; + + memset(fmt, 0, sizeof(struct v4l2_fmtdesc)); + fmt->index = index; + fmt->type = type; + fmt->pixelformat = pxp_s0_formats[index].fourcc; + strcpy(fmt->description, pxp_s0_formats[index].name); + + return 0; +} + +static int pxp_g_fmt_video_output(struct file *file, void *fh, + struct v4l2_format *f) +{ + struct v4l2_pix_format *pf = &f->fmt.pix; + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + struct pxp_data_format *fmt = pxp->s0_fmt; + + pf->width = pxp->s0_width; + pf->height = pxp->s0_height; + pf->pixelformat = fmt->fourcc; + pf->field = V4L2_FIELD_NONE; + pf->bytesperline = fmt->bpp * pf->width; + pf->sizeimage = pf->bytesperline * pf->height; + pf->colorspace = fmt->colorspace; + pf->priv = 0; + + return 0; +} + +static struct pxp_data_format *pxp_get_format(struct v4l2_format *f) +{ + struct pxp_data_format *fmt; + int i; + + for (i = 0; i < ARRAY_SIZE(pxp_s0_formats); i++) { + fmt = &pxp_s0_formats[i]; + if (fmt->fourcc == f->fmt.pix.pixelformat) + break; + } + + if (i == ARRAY_SIZE(pxp_s0_formats)) + return NULL; + + return &pxp_s0_formats[i]; +} + +static int pxp_try_fmt_video_output(struct file *file, void *fh, + struct v4l2_format *f) +{ + int w = f->fmt.pix.width; + int h = f->fmt.pix.height; + struct pxp_data_format *fmt = pxp_get_format(f); + + if (!fmt) + return -EINVAL; + + w = min(w, 2040); + w = max(w, 8); + h = min(h, 2040); + h = max(h, 8); + f->fmt.pix.field = V4L2_FIELD_NONE; + f->fmt.pix.width = w; + f->fmt.pix.height = h; + f->fmt.pix.pixelformat = fmt->fourcc; + + return 0; +} + +static int pxp_s_fmt_video_output(struct file *file, void *fh, + struct v4l2_format *f) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + struct v4l2_pix_format *pf = &f->fmt.pix; + int ret = pxp_try_fmt_video_output(file, fh, f); + + if (ret == 0) { + pxp->s0_fmt = pxp_get_format(f); + pxp->s0_width = pf->width; + pxp->s0_height = pf->height; + pxp_set_ctrl(pxp); + pxp_set_s0param(pxp); + } + + return ret; +} + +static int pxp_g_fmt_output_overlay(struct file *file, void *fh, + struct v4l2_format *f) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + struct v4l2_window *wf = &f->fmt.win; + + memset(wf, 0, sizeof(struct v4l2_window)); + wf->chromakey = pxp->s1_chromakey; + wf->global_alpha = pxp->global_alpha; + wf->field = V4L2_FIELD_NONE; + wf->clips = NULL; + wf->clipcount = 0; + wf->bitmap = NULL; + wf->w.left = pxp->srect.left; + wf->w.top = pxp->srect.top; + wf->w.width = pxp->srect.width; + wf->w.height = pxp->srect.height; + + return 0; +} + +static int pxp_try_fmt_output_overlay(struct file *file, void *fh, + struct v4l2_format *f) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + struct v4l2_window *wf = &f->fmt.win; + struct v4l2_rect srect; + u32 s1_chromakey = wf->chromakey; + u8 global_alpha = wf->global_alpha; + + memcpy(&srect, &(wf->w), sizeof(struct v4l2_rect)); + + pxp_g_fmt_output_overlay(file, fh, f); + + wf->chromakey = s1_chromakey; + wf->global_alpha = global_alpha; + + /* Constrain parameters to the input buffer */ + wf->w.left = srect.left; + wf->w.top = srect.top; + wf->w.width = min(srect.width, ((__s32) pxp->s0_width - wf->w.left)); + wf->w.height = min(srect.height, ((__s32) pxp->s0_height - wf->w.top)); + + return 0; +} + +static int pxp_s_fmt_output_overlay(struct file *file, void *fh, + struct v4l2_format *f) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + struct v4l2_window *wf = &f->fmt.win; + int ret = pxp_try_fmt_output_overlay(file, fh, f); + + if (ret == 0) { + pxp->srect.left = wf->w.left; + pxp->srect.top = wf->w.top; + pxp->srect.width = wf->w.width; + pxp->srect.height = wf->w.height; + pxp->global_alpha = wf->global_alpha; + pxp->s1_chromakey = wf->chromakey; + pxp_set_s0param(pxp); + pxp_set_s0crop(pxp); + pxp_set_scaling(pxp); + pxp_set_olparam(pxp); + pxp_set_s1colorkey(pxp); + } + + return ret; +} + +static int pxp_reqbufs(struct file *file, void *priv, + struct v4l2_requestbuffers *r) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + + return videobuf_reqbufs(&pxp->s0_vbq, r); +} + +static int pxp_querybuf(struct file *file, void *priv, struct v4l2_buffer *b) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + + return videobuf_querybuf(&pxp->s0_vbq, b); +} + +static int pxp_qbuf(struct file *file, void *priv, struct v4l2_buffer *b) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + + return videobuf_qbuf(&pxp->s0_vbq, b); +} + +static int pxp_dqbuf(struct file *file, void *priv, struct v4l2_buffer *b) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + + return videobuf_dqbuf(&pxp->s0_vbq, b, file->f_flags & O_NONBLOCK); +} + +static int pxp_streamon(struct file *file, void *priv, enum v4l2_buf_type t) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + int ret = 0; + + if ((t != V4L2_BUF_TYPE_VIDEO_OUTPUT)) + return -EINVAL; + + pxp_set_outbuf(pxp); + ret = videobuf_streamon(&pxp->s0_vbq); + msleep(20); + + if (!ret && (pxp->output == 0)) + mxsfb_cfg_pxp(1, pxp->outb_phys); + + return ret; +} + +static int pxp_streamoff(struct file *file, void *priv, enum v4l2_buf_type t) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + int ret = 0; + + if ((t != V4L2_BUF_TYPE_VIDEO_OUTPUT)) + return -EINVAL; + + cancel_work_sync(&pxp->work); + ret = videobuf_streamoff(&pxp->s0_vbq); + msleep(20); + + if (!ret) + mxsfb_cfg_pxp(0, 0); + + return ret; +} + +static int pxp_buf_setup(struct videobuf_queue *q, + unsigned int *count, unsigned *size) +{ + struct pxps *pxp = q->priv_data; + + *size = pxp->s0_width * pxp->s0_height * pxp->s0_fmt->bpp; + + if (0 == *count) + *count = PXP_DEF_BUFS; + + return 0; +} + +static void pxp_buf_free(struct videobuf_queue *q, struct videobuf_buffer *vb) +{ + if (in_interrupt()) + BUG(); + + videobuf_dma_contig_free(q, vb); + + vb->state = VIDEOBUF_NEEDS_INIT; +} + +static int pxp_buf_prepare(struct videobuf_queue *q, + struct videobuf_buffer *vb, enum v4l2_field field) +{ + struct pxps *pxp = q->priv_data; + int ret = 0; + + vb->width = pxp->s0_width; + vb->height = pxp->s0_height; + vb->size = vb->width * vb->height * pxp->s0_fmt->bpp; + vb->field = V4L2_FIELD_NONE; + vb->state = VIDEOBUF_NEEDS_INIT; + + ret = videobuf_iolock(q, vb, NULL); + if (ret) + goto fail; + vb->state = VIDEOBUF_PREPARED; + + return 0; + +fail: + pxp_buf_free(q, vb); + return ret; +} + +static void pxp_buf_next(struct pxps *pxp) +{ + dma_addr_t Y, U, V; + + if (pxp->active) { + pxp->active->state = VIDEOBUF_ACTIVE; + Y = videobuf_to_dma_contig(pxp->active); + pxp->regs_virt->s0buf = Y; + if ((pxp->s0_fmt->fourcc == V4L2_PIX_FMT_YUV420) || + (pxp->s0_fmt->fourcc == V4L2_PIX_FMT_YUV422P)) { + int s = 1; /* default to YUV 4:2:2 */ + if (pxp->s0_fmt->fourcc == V4L2_PIX_FMT_YUV420) + s = 2; + U = Y + (pxp->s0_width * pxp->s0_height); + V = U + ((pxp->s0_width * pxp->s0_height) >> s); + pxp->regs_virt->s0ubuf = U; + pxp->regs_virt->s0vbuf = V; + } + pxp->regs_virt->ctrl = + __raw_readl(PXP_BASE_ADDR + + HW_PXP_CTRL) | BM_PXP_CTRL_ENABLE; + } + + __raw_writel(pxp->regs_phys, PXP_BASE_ADDR + HW_PXP_NEXT); +} + +static void pxp_next_handle(struct work_struct *w) +{ + struct pxps *pxp = container_of(w, struct pxps, work); + struct pxp_buffer *buf, *next; + unsigned long flags; + + if (pxp->next_queue_ended == 1) + return; + + spin_lock_irqsave(&pxp->lock, flags); + + while (!list_empty(&pxp->nextq)) { + spin_unlock_irqrestore(&pxp->lock, flags); + + if (!wait_event_interruptible_timeout(pxp->done, PXP_WAITCON, + 5 * HZ) + || signal_pending(current)) { + spin_lock_irqsave(&pxp->lock, flags); + list_for_each_entry_safe(buf, next, &pxp->nextq, queue) + list_del(&buf->queue); + spin_unlock_irqrestore(&pxp->lock, flags); + pxp->next_queue_ended = 1; + return; + } + + spin_lock_irqsave(&pxp->lock, flags); + buf = list_entry(pxp->nextq.next, struct pxp_buffer, queue); + list_del_init(&buf->queue); + pxp->active = &buf->vb; + pxp->active->state = VIDEOBUF_QUEUED; + pxp_buf_next(pxp); + } + + spin_unlock_irqrestore(&pxp->lock, flags); +} + +static void pxp_buf_queue(struct videobuf_queue *q, struct videobuf_buffer *vb) +{ + struct pxps *pxp = q->priv_data; + struct pxp_buffer *buf; + unsigned long flags; + + spin_lock_irqsave(&pxp->lock, flags); + + if (list_empty(&pxp->outq)) { + list_add_tail(&vb->queue, &pxp->outq); + vb->state = VIDEOBUF_QUEUED; + + pxp->active = vb; + pxp_buf_next(pxp); + } else { + list_add_tail(&vb->queue, &pxp->outq); + + buf = container_of(vb, struct pxp_buffer, vb); + list_add_tail(&buf->queue, &pxp->nextq); + queue_work(pxp->workqueue, &pxp->work); + } + + spin_unlock_irqrestore(&pxp->lock, flags); +} + +static void pxp_buf_release(struct videobuf_queue *q, + struct videobuf_buffer *vb) +{ + pxp_buf_free(q, vb); +} + +static struct videobuf_queue_ops pxp_vbq_ops = { + .buf_setup = pxp_buf_setup, + .buf_prepare = pxp_buf_prepare, + .buf_queue = pxp_buf_queue, + .buf_release = pxp_buf_release, +}; + +static int pxp_querycap(struct file *file, void *fh, + struct v4l2_capability *cap) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + + memset(cap, 0, sizeof(*cap)); + strcpy(cap->driver, "pxp"); + strcpy(cap->card, "pxp"); + strlcpy(cap->bus_info, dev_name(&pxp->pdev->dev), + sizeof(cap->bus_info)); + + cap->version = (PXP_DRIVER_MAJOR << 8) + PXP_DRIVER_MINOR; + + cap->capabilities = V4L2_CAP_VIDEO_OUTPUT | + V4L2_CAP_VIDEO_OUTPUT_OVERLAY | V4L2_CAP_STREAMING; + + return 0; +} + +static int pxp_g_fbuf(struct file *file, void *priv, + struct v4l2_framebuffer *fb) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + + memset(fb, 0, sizeof(*fb)); + + fb->capability = V4L2_FBUF_CAP_EXTERNOVERLAY | + V4L2_FBUF_CAP_CHROMAKEY | + V4L2_FBUF_CAP_LOCAL_ALPHA | V4L2_FBUF_CAP_GLOBAL_ALPHA; + + if (pxp->global_alpha_state) + fb->flags |= V4L2_FBUF_FLAG_GLOBAL_ALPHA; + if (pxp->local_alpha_state) + fb->flags |= V4L2_FBUF_FLAG_LOCAL_ALPHA; + if (pxp->s1_chromakey_state) + fb->flags |= V4L2_FBUF_FLAG_CHROMAKEY; + + return 0; +} + +static int pxp_s_fbuf(struct file *file, void *priv, + struct v4l2_framebuffer *fb) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + + pxp->overlay_state = (fb->flags & V4L2_FBUF_FLAG_OVERLAY) != 0; + pxp->global_alpha_state = + (fb->flags & V4L2_FBUF_FLAG_GLOBAL_ALPHA) != 0; + pxp->local_alpha_state = (fb->flags & V4L2_FBUF_FLAG_LOCAL_ALPHA) != 0; + /* Global alpha overrides local alpha if both are requested */ + if (pxp->global_alpha_state && pxp->local_alpha_state) + pxp->local_alpha_state = 0; + pxp->s1_chromakey_state = (fb->flags & V4L2_FBUF_FLAG_CHROMAKEY) != 0; + + pxp_set_olparam(pxp); + pxp_set_s0crop(pxp); + pxp_set_scaling(pxp); + + return 0; +} + +static int pxp_g_crop(struct file *file, void *fh, struct v4l2_crop *c) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + + if (c->type != V4L2_BUF_TYPE_VIDEO_OUTPUT_OVERLAY) + return -EINVAL; + + c->c.left = pxp->drect.left; + c->c.top = pxp->drect.top; + c->c.width = pxp->drect.width; + c->c.height = pxp->drect.height; + + return 0; +} + +static int pxp_s_crop(struct file *file, void *fh, struct v4l2_crop *c) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + int l = c->c.left; + int t = c->c.top; + int w = c->c.width; + int h = c->c.height; + int fbw = pxp->fb.fmt.width; + int fbh = pxp->fb.fmt.height; + + if (c->type != V4L2_BUF_TYPE_VIDEO_OUTPUT_OVERLAY) + return -EINVAL; + + /* Constrain parameters to FB limits */ + w = min(w, fbw); + w = max(w, PXP_MIN_PIX); + h = min(h, fbh); + h = max(h, PXP_MIN_PIX); + if ((l + w) > fbw) + l = 0; + if ((t + h) > fbh) + t = 0; + + /* Round up values to PxP pixel block */ + l = roundup(l, PXP_MIN_PIX); + t = roundup(t, PXP_MIN_PIX); + w = roundup(w, PXP_MIN_PIX); + h = roundup(h, PXP_MIN_PIX); + + pxp->drect.left = l; + pxp->drect.top = t; + pxp->drect.width = w; + pxp->drect.height = h; + + pxp_set_s0param(pxp); + pxp_set_s0crop(pxp); + pxp_set_scaling(pxp); + + return 0; +} + +static int pxp_queryctrl(struct file *file, void *priv, + struct v4l2_queryctrl *qc) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(pxp_controls); i++) + if (qc->id && qc->id == pxp_controls[i].id) { + memcpy(qc, &(pxp_controls[i]), sizeof(*qc)); + return 0; + } + + return -EINVAL; +} + +static int pxp_g_ctrl(struct file *file, void *priv, struct v4l2_control *vc) +{ + int i; + + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + + for (i = 0; i < ARRAY_SIZE(pxp_controls); i++) + if (vc->id == pxp_controls[i].id) + return pxp_get_cstate(pxp, vc); + + return -EINVAL; +} + +static int pxp_s_ctrl(struct file *file, void *priv, struct v4l2_control *vc) +{ + int i; + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + + for (i = 0; i < ARRAY_SIZE(pxp_controls); i++) + if (vc->id == pxp_controls[i].id) { + if (vc->value < pxp_controls[i].minimum || + vc->value > pxp_controls[i].maximum) + return -ERANGE; + return pxp_set_cstate(pxp, vc); + } + + return -EINVAL; +} + +void pxp_release(struct video_device *vfd) +{ + struct pxps *pxp = video_get_drvdata(vfd); + + spin_lock(&pxp->lock); + video_device_release(vfd); + spin_unlock(&pxp->lock); +} + +static int pxp_hw_init(struct pxps *pxp) +{ + struct fb_var_screeninfo var; + struct fb_fix_screeninfo fix; + int err; + + err = mxsfb_get_info(&var, &fix); + if (err) + return err; + + /* Pull PxP out of reset */ + __raw_writel(0, PXP_BASE_ADDR + HW_PXP_CTRL); + + /* Config defaults */ + pxp->active = NULL; + + pxp->s0_fmt = &pxp_s0_formats[0]; + pxp->drect.left = pxp->srect.left = 0; + pxp->drect.top = pxp->srect.top = 0; + pxp->drect.width = pxp->srect.width = pxp->s0_width = var.xres; + pxp->drect.height = pxp->srect.height = pxp->s0_height = var.yres; + pxp->s0_bgcolor = 0; + + pxp->output = 0; + err = pxp_set_fbinfo(pxp); + if (err) + return err; + + pxp->scaling = 0; + pxp->hflip = 0; + pxp->vflip = 0; + pxp->rotate = 0; + pxp->yuv = 0; + + pxp->overlay_state = 0; + pxp->global_alpha_state = 0; + pxp->global_alpha = 0; + pxp->local_alpha_state = 0; + pxp->s1_chromakey_state = 0; + pxp->s1_chromakey = -1; + pxp->s0_chromakey = -1; + + /* Write default h/w config */ + pxp_set_ctrl(pxp); + pxp_set_s0param(pxp); + pxp_set_s0crop(pxp); + pxp_set_oln(pxp); + pxp_set_olparam(pxp); + pxp_set_s0colorkey(pxp); + pxp_set_s1colorkey(pxp); + pxp_set_csc(pxp); + + return 0; +} + +static int pxp_open(struct file *file) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + int ret = 0; + + mutex_lock(&pxp->mutex); + pxp->users++; + + if (pxp->users > 1) { + pxp->users--; + ret = -EBUSY; + goto out; + } +out: + mutex_unlock(&pxp->mutex); + if (ret) + return ret; + + pxp->next_queue_ended = 0; + pxp->workqueue = create_singlethread_workqueue("pxp"); + + videobuf_queue_dma_contig_init(&pxp->s0_vbq, + &pxp_vbq_ops, + &pxp->pdev->dev, + &pxp->lock, + V4L2_BUF_TYPE_VIDEO_OUTPUT, + V4L2_FIELD_NONE, + sizeof(struct pxp_buffer), pxp); + + return 0; +} + +static int pxp_close(struct file *file) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + + if (pxp->workqueue) { + flush_workqueue(pxp->workqueue); + destroy_workqueue(pxp->workqueue); + } + + videobuf_stop(&pxp->s0_vbq); + videobuf_mmap_free(&pxp->s0_vbq); + pxp->active = NULL; + + mutex_lock(&pxp->mutex); + pxp->users--; + mutex_unlock(&pxp->mutex); + + return 0; +} + +static int pxp_mmap(struct file *file, struct vm_area_struct *vma) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + int ret; + + ret = videobuf_mmap_mapper(&pxp->s0_vbq, vma); + + return ret; +} + +static const struct v4l2_file_operations pxp_fops = { + .owner = THIS_MODULE, + .open = pxp_open, + .release = pxp_close, + .ioctl = video_ioctl2, + .mmap = pxp_mmap, +}; + +static const struct v4l2_ioctl_ops pxp_ioctl_ops = { + .vidioc_querycap = pxp_querycap, + + .vidioc_reqbufs = pxp_reqbufs, + .vidioc_querybuf = pxp_querybuf, + .vidioc_qbuf = pxp_qbuf, + .vidioc_dqbuf = pxp_dqbuf, + + .vidioc_streamon = pxp_streamon, + .vidioc_streamoff = pxp_streamoff, + + .vidioc_enum_output = pxp_enumoutput, + .vidioc_g_output = pxp_g_output, + .vidioc_s_output = pxp_s_output, + + .vidioc_enum_fmt_vid_out = pxp_enum_fmt_video_output, + .vidioc_try_fmt_vid_out = pxp_try_fmt_video_output, + .vidioc_g_fmt_vid_out = pxp_g_fmt_video_output, + .vidioc_s_fmt_vid_out = pxp_s_fmt_video_output, + + .vidioc_try_fmt_vid_out_overlay = pxp_try_fmt_output_overlay, + .vidioc_g_fmt_vid_out_overlay = pxp_g_fmt_output_overlay, + .vidioc_s_fmt_vid_out_overlay = pxp_s_fmt_output_overlay, + + .vidioc_g_fbuf = pxp_g_fbuf, + .vidioc_s_fbuf = pxp_s_fbuf, + + .vidioc_g_crop = pxp_g_crop, + .vidioc_s_crop = pxp_s_crop, + + .vidioc_queryctrl = pxp_queryctrl, + .vidioc_g_ctrl = pxp_g_ctrl, + .vidioc_s_ctrl = pxp_s_ctrl, +}; + +static const struct video_device pxp_template = { + .name = "PxP", + .vfl_type = V4L2_CAP_VIDEO_OUTPUT | + V4L2_CAP_VIDEO_OVERLAY | + V4L2_CAP_STREAMING, + .fops = &pxp_fops, + .release = pxp_release, + .minor = -1, + .ioctl_ops = &pxp_ioctl_ops, +}; + +static irqreturn_t pxp_irq(int irq, void *dev_id) +{ + struct pxps *pxp = (struct pxps *)dev_id; + struct videobuf_buffer *vb; + unsigned long flags; + + spin_lock_irqsave(&pxp->lock, flags); + + __raw_writel(BM_PXP_STAT_IRQ, PXP_BASE_ADDR + HW_PXP_STAT_CLR); + + if (list_empty(&pxp->outq)) { + pr_warning("irq: outq empty!!!\n"); + goto out; + } + + vb = list_entry(pxp->outq.next, struct videobuf_buffer, queue); + list_del_init(&vb->queue); + + vb->state = VIDEOBUF_DONE; + do_gettimeofday(&vb->ts); + vb->field_count++; + + wake_up(&vb->done); + wake_up(&pxp->done); +out: + spin_unlock_irqrestore(&pxp->lock, flags); + + return IRQ_HANDLED; +} + +static int pxp_probe(struct platform_device *pdev) +{ + struct pxps *pxp; + struct resource *res; + int irq; + int err = 0; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + irq = platform_get_irq(pdev, 0); + if (!res || irq < 0) { + err = -ENODEV; + goto exit; + } + + pxp = kzalloc(sizeof(*pxp), GFP_KERNEL); + if (!pxp) { + dev_err(&pdev->dev, "failed to allocate control object\n"); + err = -ENOMEM; + goto exit; + } + + dev_set_drvdata(&pdev->dev, pxp); + pxp->res = res; + pxp->irq = irq; + + pxp->regs_virt = dma_alloc_coherent(NULL, + PAGE_ALIGN(sizeof + (struct pxp_registers)), + &pxp->regs_phys, GFP_KERNEL); + if (pxp->regs_virt == NULL) { + dev_err(&pdev->dev, "failed to allocate pxp_register object\n"); + err = -ENOMEM; + goto exit; + } + + init_waitqueue_head(&pxp->done); + + INIT_WORK(&pxp->work, pxp_next_handle); + INIT_LIST_HEAD(&pxp->outq); + INIT_LIST_HEAD(&pxp->nextq); + spin_lock_init(&pxp->lock); + mutex_init(&pxp->mutex); + + if (!request_mem_region(res->start, res->end - res->start + 1, + PXP_DRIVER_NAME)) { + err = -EBUSY; + goto freepxp; + } + + pxp->regs = (void __iomem *)res->start; /* it is already ioremapped */ + pxp->pdev = pdev; + + err = request_irq(pxp->irq, pxp_irq, 0, PXP_DRIVER_NAME, pxp); + + if (err) { + dev_err(&pdev->dev, "interrupt register failed\n"); + goto release; + } + + pxp->vdev = video_device_alloc(); + if (!pxp->vdev) { + dev_err(&pdev->dev, "video_device_alloc() failed\n"); + err = -ENOMEM; + goto freeirq; + } + + memcpy(pxp->vdev, &pxp_template, sizeof(pxp_template)); + video_set_drvdata(pxp->vdev, pxp); + + err = video_register_device(pxp->vdev, VFL_TYPE_GRABBER, 0); + if (err) { + dev_err(&pdev->dev, "failed to register video device\n"); + goto freevdev; + } + + err = pxp_hw_init(pxp); + if (err) { + dev_err(&pdev->dev, "failed to initialize hardware\n"); + goto freevdev; + } + + dev_info(&pdev->dev, "initialized\n"); + +exit: + return err; + +freevdev: + video_device_release(pxp->vdev); + +freeirq: + free_irq(pxp->irq, pxp); + +release: + release_mem_region(res->start, res->end - res->start + 1); + +freepxp: + kfree(pxp); + + return err; +} + +static int __devexit pxp_remove(struct platform_device *pdev) +{ + struct pxps *pxp = platform_get_drvdata(pdev); + + video_unregister_device(pxp->vdev); + video_device_release(pxp->vdev); + + if (pxp->regs_virt) + dma_free_coherent(0, PAGE_ALIGN(sizeof(struct pxp_registers)), + pxp->regs_virt, pxp->regs_phys); + kfree(pxp->outb); + kfree(pxp); + + return 0; +} + +#ifdef CONFIG_PM +static int pxp_suspend(struct platform_device *pdev, pm_message_t state) +{ + int i; + + while (__raw_readl(PXP_BASE_ADDR + HW_PXP_CTRL) & BM_PXP_CTRL_ENABLE) + ; + + for (i = 0; i < REGS1_NUMS; i++) + regs1[i] = + __raw_readl(PXP_BASE_ADDR + HW_PXP_CTRL + REG_OFFSET * i); + + for (i = 0; i < REGS2_NUMS; i++) + regs2[i] = + __raw_readl(PXP_BASE_ADDR + HW_PXP_S0COLORKEYLOW + + REG_OFFSET * i); + + for (i = 0; i < REGS3_NUMS; i++) + regs3[i] = + __raw_readl(PXP_BASE_ADDR + HW_PXP_OLn(0) + REG_OFFSET * i); + + __raw_writel(BM_PXP_CTRL_SFTRST, PXP_BASE_ADDR + HW_PXP_CTRL); + + return 0; +} + +static int pxp_resume(struct platform_device *pdev) +{ + int i; + + /* Pull PxP out of reset */ + __raw_writel(0, PXP_BASE_ADDR + HW_PXP_CTRL); + + for (i = 0; i < REGS1_NUMS; i++) + __raw_writel(regs1[i], + PXP_BASE_ADDR + HW_PXP_CTRL + REG_OFFSET * i); + + for (i = 0; i < REGS2_NUMS; i++) + __raw_writel(regs2[i], + PXP_BASE_ADDR + HW_PXP_S0COLORKEYLOW + + REG_OFFSET * i); + + for (i = 0; i < REGS3_NUMS; i++) + __raw_writel(regs3[i], + PXP_BASE_ADDR + HW_PXP_OLn(0) + REG_OFFSET * i); + + return 0; +} +#else +#define pxp_suspend NULL +#define pxp_resume NULL +#endif + +static struct platform_driver pxp_driver = { + .driver = { + .name = PXP_DRIVER_NAME, + }, + .probe = pxp_probe, + .remove = __exit_p(pxp_remove), + .suspend = pxp_suspend, + .resume = pxp_resume, +}; + +static int __devinit pxp_init(void) +{ + return platform_driver_register(&pxp_driver); +} + +static void __exit pxp_exit(void) +{ + platform_driver_unregister(&pxp_driver); +} + +module_init(pxp_init); +module_exit(pxp_exit); + +MODULE_DESCRIPTION("STMP37xx PxP driver"); +MODULE_AUTHOR("Matt Porter "); +MODULE_LICENSE("GPL"); diff --git a/drivers/media/video/mxs_pxp.h b/drivers/media/video/mxs_pxp.h new file mode 100644 index 000000000000..6538388fa4cd --- /dev/null +++ b/drivers/media/video/mxs_pxp.h @@ -0,0 +1,158 @@ +/* + * Freescale MXS PxP driver + * + * Author: Matt Porter + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. + * Copyright 2008-2009 Embedded Alley Solutions, Inc All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#ifdef CONFIG_ARCH_MX23 +#define BF_PXP_CTRL_OUTBUF_FORMAT(v) BF_PXP_CTRL_OUTPUT_RGB_FORMAT(v) + +#define BV_PXP_CTRL_OUTBUF_FORMAT__ARGB8888 \ + BV_PXP_CTRL_OUTPUT_RGB_FORMAT__ARGB8888 +#define BV_PXP_CTRL_OUTBUF_FORMAT__RGB888 \ + BV_PXP_CTRL_OUTPUT_RGB_FORMAT__RGB888 +#define BV_PXP_CTRL_OUTBUF_FORMAT__RGB888P \ + BV_PXP_CTRL_OUTPUT_RGB_FORMAT__RGB888P +#define BV_PXP_CTRL_OUTBUF_FORMAT__ARGB1555 \ + BV_PXP_CTRL_OUTPUT_RGB_FORMAT__ARGB1555 +#define BV_PXP_CTRL_OUTBUF_FORMAT__RGB565 \ + BV_PXP_CTRL_OUTPUT_RGB_FORMAT__RGB565 +#define BV_PXP_CTRL_OUTBUF_FORMAT__RGB555 \ + BV_PXP_CTRL_OUTPUT_RGB_FORMAT__RGB555 + +#define BF_PXP_OUTSIZE_WIDTH(v) BF_PXP_RGBSIZE_WIDTH(v) +#define BF_PXP_OUTSIZE_HEIGHT(v) BF_PXP_RGBSIZE_HEIGHT(v) + +/* The maximum down scaling factor is 1/2 */ +#define PXP_DOWNSCALE_THRESHOLD 0x2000 +#else +/* The maximum down scaling factor is 1/4 */ +#define PXP_DOWNSCALE_THRESHOLD 0x4000 +#endif + +struct pxp_overlay_registers { + u32 ol; + u32 olsize; + u32 olparam; + u32 olparam2; +}; + +/* Registers feed for PXP_NEXT */ +struct pxp_registers { + u32 ctrl; + u32 outbuf; + u32 outbuf2; + u32 outsize; + u32 s0buf; + u32 s0ubuf; + u32 s0vbuf; + u32 s0param; + u32 s0background; + u32 s0crop; + u32 s0scale; + u32 s0offset; + u32 s0colorkeylow; + u32 s0colorkeyhigh; + u32 olcolorkeylow; + u32 olcolorkeyhigh; + + struct pxp_overlay_registers ol0; + struct pxp_overlay_registers ol1; + struct pxp_overlay_registers ol2; + struct pxp_overlay_registers ol3; + struct pxp_overlay_registers ol4; + struct pxp_overlay_registers ol5; + struct pxp_overlay_registers ol6; + struct pxp_overlay_registers ol7; +}; + +struct pxp_buffer { + /* Must be first! */ + struct videobuf_buffer vb; + struct list_head queue; +}; + +struct pxps { + struct platform_device *pdev; + struct resource *res; + int irq; + void __iomem *regs; + + struct work_struct work; + struct workqueue_struct *workqueue; + spinlock_t lock; + struct mutex mutex; + int users; + + struct video_device *vdev; + + struct videobuf_queue s0_vbq; + struct videobuf_buffer *active; + struct list_head outq; + struct list_head nextq; + + int output; + u32 *outb; + dma_addr_t outb_phys; + + /* Current S0 configuration */ + struct pxp_data_format *s0_fmt; + u32 s0_width; + u32 s0_height; + u32 s0_bgcolor; + u32 s0_chromakey; + + struct v4l2_framebuffer fb; + struct v4l2_rect drect; + struct v4l2_rect srect; + + /* Transformation support */ + int scaling; + int hflip; + int vflip; + int rotate; + int yuv; + + /* Output overlay support */ + int overlay_state; + int global_alpha_state; + u8 global_alpha; + int local_alpha_state; + int s1_chromakey_state; + u32 s1_chromakey; + + /* PXP_NEXT */ + u32 regs_phys; + struct pxp_registers *regs_virt; + wait_queue_head_t done; + int next_queue_ended; +}; + +struct pxp_data_format { + char *name; + unsigned int bpp; + u32 fourcc; + enum v4l2_colorspace colorspace; + u32 ctrl_s0_fmt; +}; + +extern int mxsfb_get_info(struct fb_var_screeninfo *var, + struct fb_fix_screeninfo *fix); +extern void mxsfb_cfg_pxp(int enable, dma_addr_t pxp_phys); diff --git a/drivers/media/video/pxp.c b/drivers/media/video/pxp.c new file mode 100644 index 000000000000..5ef30c4a8f82 --- /dev/null +++ b/drivers/media/video/pxp.c @@ -0,0 +1,1409 @@ +/* + * Freescale STMP378X PxP driver + * + * Author: Matt Porter + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. + * Copyright 2008-2009 Embedded Alley Solutions, Inc All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include + +#include "pxp.h" + +#define PXP_DRIVER_NAME "stmp3xxx-pxp" +#define PXP_DRIVER_MAJOR 1 +#define PXP_DRIVER_MINOR 0 + +#define PXP_DEF_BUFS 2 +#define PXP_MIN_PIX 8 + +#define V4L2_OUTPUT_TYPE_INTERNAL 4 + +#define PXP_WAITCON ((__raw_readl(HW_PXP_NEXT_ADDR) & BM_PXP_NEXT_ENABLED) \ + != BM_PXP_NEXT_ENABLED) + +#define REG_OFFSET 0x10 +#define REGS1_NUMS 16 +#define REGS2_NUMS 5 +#define REGS3_NUMS 32 +static u32 regs1[REGS1_NUMS]; +static u32 regs2[REGS2_NUMS]; +static u32 regs3[REGS3_NUMS]; + +static struct pxp_data_format pxp_s0_formats[] = { + { + .name = "24-bit RGB", + .bpp = 4, + .fourcc = V4L2_PIX_FMT_RGB24, + .colorspace = V4L2_COLORSPACE_SRGB, + .ctrl_s0_fmt = BV_PXP_CTRL_S0_FORMAT__RGB888, + }, { + .name = "16-bit RGB 5:6:5", + .bpp = 2, + .fourcc = V4L2_PIX_FMT_RGB565, + .colorspace = V4L2_COLORSPACE_SRGB, + .ctrl_s0_fmt = BV_PXP_CTRL_S0_FORMAT__RGB565, + }, { + .name = "16-bit RGB 5:5:5", + .bpp = 2, + .fourcc = V4L2_PIX_FMT_RGB555, + .colorspace = V4L2_COLORSPACE_SRGB, + .ctrl_s0_fmt = BV_PXP_CTRL_S0_FORMAT__RGB555, + }, { + .name = "YUV 4:2:0 Planar", + .bpp = 2, + .fourcc = V4L2_PIX_FMT_YUV420, + .colorspace = V4L2_COLORSPACE_JPEG, + .ctrl_s0_fmt = BV_PXP_CTRL_S0_FORMAT__YUV420, + }, { + .name = "YUV 4:2:2 Planar", + .bpp = 2, + .fourcc = V4L2_PIX_FMT_YUV422P, + .colorspace = V4L2_COLORSPACE_JPEG, + .ctrl_s0_fmt = BV_PXP_CTRL_S0_FORMAT__YUV422, + }, +}; + +struct v4l2_queryctrl pxp_controls[] = { + { + .id = V4L2_CID_HFLIP, + .type = V4L2_CTRL_TYPE_BOOLEAN, + .name = "Horizontal Flip", + .minimum = 0, + .maximum = 1, + .step = 1, + .default_value = 0, + .flags = 0, + }, { + .id = V4L2_CID_VFLIP, + .type = V4L2_CTRL_TYPE_BOOLEAN, + .name = "Vertical Flip", + .minimum = 0, + .maximum = 1, + .step = 1, + .default_value = 0, + .flags = 0, + }, { + .id = V4L2_CID_PRIVATE_BASE, + .type = V4L2_CTRL_TYPE_INTEGER, + .name = "Rotation", + .minimum = 0, + .maximum = 270, + .step = 90, + .default_value = 0, + .flags = 0, + }, { + .id = V4L2_CID_PRIVATE_BASE + 1, + .name = "Background Color", + .minimum = 0, + .maximum = 0xFFFFFF, + .step = 1, + .default_value = 0, + .flags = 0, + .type = V4L2_CTRL_TYPE_INTEGER, + }, { + .id = V4L2_CID_PRIVATE_BASE + 2, + .name = "Set S0 Chromakey", + .minimum = -1, + .maximum = 0xFFFFFF, + .step = 1, + .default_value = -1, + .flags = 0, + .type = V4L2_CTRL_TYPE_INTEGER, + }, { + .id = V4L2_CID_PRIVATE_BASE + 3, + .name = "YUV Colorspace", + .minimum = 0, + .maximum = 1, + .step = 1, + .default_value = 0, + .flags = 0, + .type = V4L2_CTRL_TYPE_BOOLEAN, + }, +}; + +static void pxp_set_ctrl(struct pxps *pxp) +{ + u32 ctrl; + + ctrl = BF(pxp->s0_fmt->ctrl_s0_fmt, PXP_CTRL_S0_FORMAT); + ctrl |= + BF(BV_PXP_CTRL_OUTPUT_RGB_FORMAT__RGB888, PXP_CTRL_OUTPUT_RGB_FORMAT); + ctrl |= BM_PXP_CTRL_CROP; + + if (pxp->scaling) + ctrl |= BM_PXP_CTRL_SCALE; + if (pxp->vflip) + ctrl |= BM_PXP_CTRL_VFLIP; + if (pxp->hflip) + ctrl |= BM_PXP_CTRL_HFLIP; + if (pxp->rotate) + ctrl |= BF(pxp->rotate/90, PXP_CTRL_ROTATE); + + ctrl |= BM_PXP_CTRL_IRQ_ENABLE; + if (pxp->active) + ctrl |= BM_PXP_CTRL_ENABLE; + + __raw_writel(ctrl, HW_PXP_CTRL_ADDR); + pxp->regs_virt->ctrl = ctrl; +} + +static void pxp_set_rgbbuf(struct pxps *pxp) +{ + pxp->regs_virt->rgbbuf = pxp->outb_phys; + /* Always equal to the FB size */ + pxp->regs_virt->rgbsize = BF(pxp->fb.fmt.width, PXP_RGBSIZE_WIDTH) | + BF(pxp->fb.fmt.height, PXP_RGBSIZE_HEIGHT); +} + +static void pxp_set_s0colorkey(struct pxps *pxp) +{ + /* Low and high are set equal. V4L does not allow a chromakey range */ + if (pxp->s0_chromakey == -1) { + /* disable color key */ + pxp->regs_virt->s0colorkeylow = 0xFFFFFF; + pxp->regs_virt->s0colorkeyhigh = 0; + } else { + pxp->regs_virt->s0colorkeylow = pxp->s0_chromakey; + pxp->regs_virt->s0colorkeyhigh = pxp->s0_chromakey; + } +} + +static void pxp_set_s1colorkey(struct pxps *pxp) +{ + /* Low and high are set equal. V4L does not allow a chromakey range */ + if (pxp->s1_chromakey_state != 0 && pxp->s1_chromakey != -1) { + pxp->regs_virt->olcolorkeylow = pxp->s1_chromakey; + pxp->regs_virt->olcolorkeyhigh = pxp->s1_chromakey; + } else { + /* disable color key */ + pxp->regs_virt->olcolorkeylow = 0xFFFFFF; + pxp->regs_virt->olcolorkeyhigh = 0; + } +} + +static void pxp_set_oln(struct pxps *pxp) +{ + pxp->regs_virt->ol0.ol = (u32)pxp->fb.base; + pxp->regs_virt->ol0.olsize = + BF(pxp->fb.fmt.width >> 3, PXP_OLnSIZE_WIDTH) | + BF(pxp->fb.fmt.height >> 3, PXP_OLnSIZE_HEIGHT); +} + +static void pxp_set_olparam(struct pxps *pxp) +{ + u32 olparam; + struct v4l2_pix_format *fmt = &pxp->fb.fmt; + + olparam = BF(pxp->global_alpha, PXP_OLnPARAM_ALPHA); + if (fmt->pixelformat == V4L2_PIX_FMT_RGB24) + olparam |= + BF(BV_PXP_OLnPARAM_FORMAT__RGB888, PXP_OLnPARAM_FORMAT); + else + olparam |= + BF(BV_PXP_OLnPARAM_FORMAT__RGB565, PXP_OLnPARAM_FORMAT); + if (pxp->global_alpha_state) + olparam |= BF(BV_PXP_OLnPARAM_ALPHA_CNTL__Override, + PXP_OLnPARAM_ALPHA_CNTL); + if (pxp->s1_chromakey_state) + olparam |= BM_PXP_OLnPARAM_ENABLE_COLORKEY; + if (pxp->overlay_state) + olparam |= BM_PXP_OLnPARAM_ENABLE; + + pxp->regs_virt->ol0.olparam = olparam; +} + +static void pxp_set_s0param(struct pxps *pxp) +{ + u32 s0param; + + s0param = BF(pxp->drect.left >> 3, PXP_S0PARAM_XBASE); + s0param |= BF(pxp->drect.top >> 3, PXP_S0PARAM_YBASE); + s0param |= BF(pxp->s0_width >> 3, PXP_S0PARAM_WIDTH); + s0param |= BF(pxp->s0_height >> 3, PXP_S0PARAM_HEIGHT); + pxp->regs_virt->s0param = s0param; +} + +static void pxp_set_s0crop(struct pxps *pxp) +{ + u32 s0crop; + + s0crop = BF(pxp->srect.left >> 3, PXP_S0CROP_XBASE); + s0crop |= BF(pxp->srect.top >> 3, PXP_S0CROP_YBASE); + s0crop |= BF(pxp->drect.width >> 3, PXP_S0CROP_WIDTH); + s0crop |= BF(pxp->drect.height >> 3, PXP_S0CROP_HEIGHT); + pxp->regs_virt->s0crop = s0crop; +} + +static int pxp_set_scaling(struct pxps *pxp) +{ + int ret = 0; + u32 xscale, yscale, s0scale; + + if ((pxp->s0_fmt->fourcc != V4L2_PIX_FMT_YUV420) && + (pxp->s0_fmt->fourcc != V4L2_PIX_FMT_YUV422P)) { + pxp->scaling = 0; + ret = -EINVAL; + goto out; + } + + if ((pxp->srect.width == pxp->drect.width) && + (pxp->srect.height == pxp->drect.height)) { + pxp->scaling = 0; + goto out; + } + + pxp->scaling = 1; + xscale = pxp->srect.width * 0x1000 / pxp->drect.width; + yscale = pxp->srect.height * 0x1000 / pxp->drect.height; + s0scale = BF(yscale, PXP_S0SCALE_YSCALE) | + BF(xscale, PXP_S0SCALE_XSCALE); + pxp->regs_virt->s0scale = s0scale; + +out: + pxp_set_ctrl(pxp); + + return ret; +} + +static int pxp_set_fbinfo(struct pxps *pxp) +{ + struct fb_var_screeninfo var; + struct fb_fix_screeninfo fix; + struct v4l2_framebuffer *fb = &pxp->fb; + int err; + + err = stmp3xxxfb_get_info(&var, &fix); + + fb->fmt.width = var.xres; + fb->fmt.height = var.yres; + if (var.bits_per_pixel == 16) + fb->fmt.pixelformat = V4L2_PIX_FMT_RGB565; + else + fb->fmt.pixelformat = V4L2_PIX_FMT_RGB24; + fb->base = (void *)fix.smem_start; + return err; +} + +static void pxp_set_s0bg(struct pxps *pxp) +{ + pxp->regs_virt->s0background = pxp->s0_bgcolor; +} + +static void pxp_set_csc(struct pxps *pxp) +{ + if (pxp->yuv) { + /* YUV colorspace */ + __raw_writel(0x04030000, HW_PXP_CSCCOEFF0_ADDR); + __raw_writel(0x01230208, HW_PXP_CSCCOEFF1_ADDR); + __raw_writel(0x076b079c, HW_PXP_CSCCOEFF2_ADDR); + } else { + /* YCrCb colorspace */ + __raw_writel(0x84ab01f0, HW_PXP_CSCCOEFF0_ADDR); + __raw_writel(0x01230204, HW_PXP_CSCCOEFF1_ADDR); + __raw_writel(0x0730079c, HW_PXP_CSCCOEFF2_ADDR); + } +} + +static int pxp_set_cstate(struct pxps *pxp, struct v4l2_control *vc) +{ + + if (vc->id == V4L2_CID_HFLIP) + pxp->hflip = vc->value; + else if (vc->id == V4L2_CID_VFLIP) + pxp->vflip = vc->value; + else if (vc->id == V4L2_CID_PRIVATE_BASE) { + if (vc->value % 90) + return -ERANGE; + pxp->rotate = vc->value; + } else if (vc->id == V4L2_CID_PRIVATE_BASE + 1) { + pxp->s0_bgcolor = vc->value; + pxp_set_s0bg(pxp); + } else if (vc->id == V4L2_CID_PRIVATE_BASE + 2) { + pxp->s0_chromakey = vc->value; + pxp_set_s0colorkey(pxp); + } else if (vc->id == V4L2_CID_PRIVATE_BASE + 3) { + pxp->yuv = vc->value; + pxp_set_csc(pxp); + } + + pxp_set_ctrl(pxp); + + return 0; +} + +static int pxp_get_cstate(struct pxps *pxp, struct v4l2_control *vc) +{ + if (vc->id == V4L2_CID_HFLIP) + vc->value = pxp->hflip; + else if (vc->id == V4L2_CID_VFLIP) + vc->value = pxp->vflip; + else if (vc->id == V4L2_CID_PRIVATE_BASE) + vc->value = pxp->rotate; + else if (vc->id == V4L2_CID_PRIVATE_BASE + 1) + vc->value = pxp->s0_bgcolor; + else if (vc->id == V4L2_CID_PRIVATE_BASE + 2) + vc->value = pxp->s0_chromakey; + else if (vc->id == V4L2_CID_PRIVATE_BASE + 3) + vc->value = pxp->yuv; + + return 0; +} + +static int pxp_enumoutput(struct file *file, void *fh, + struct v4l2_output *o) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + + if ((o->index < 0) || (o->index > 1)) + return -EINVAL; + + memset(o, 0, sizeof(struct v4l2_output)); + if (o->index == 0) { + strcpy(o->name, "PxP Display Output"); + pxp->output = 0; + } else { + strcpy(o->name, "PxP Virtual Output"); + pxp->output = 1; + } + o->type = V4L2_OUTPUT_TYPE_INTERNAL; + o->std = 0; + o->reserved[0] = pxp->outb_phys; + + return 0; +} + +static int pxp_g_output(struct file *file, void *fh, + unsigned int *i) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + + *i = pxp->output; + + return 0; +} + +static int pxp_s_output(struct file *file, void *fh, + unsigned int i) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + struct v4l2_pix_format *fmt = &pxp->fb.fmt; + int bpp; + + if ((i < 0) || (i > 1)) + return -EINVAL; + + if (pxp->outb) + goto out; + + /* Output buffer is same format as fbdev */ + if (fmt->pixelformat == V4L2_PIX_FMT_RGB24) + bpp = 4; + else + bpp = 2; + + pxp->outb = kmalloc(fmt->width * fmt->height * bpp, GFP_KERNEL); + pxp->outb_phys = virt_to_phys(pxp->outb); + dma_map_single(NULL, pxp->outb, + fmt->width * fmt->height * bpp, DMA_TO_DEVICE); + +out: + pxp_set_rgbbuf(pxp); + + return 0; +} + +static int pxp_enum_fmt_video_output(struct file *file, void *fh, + struct v4l2_fmtdesc *fmt) +{ + enum v4l2_buf_type type = fmt->type; + int index = fmt->index; + + if ((fmt->index < 0) || (fmt->index >= ARRAY_SIZE(pxp_s0_formats))) + return -EINVAL; + + memset(fmt, 0, sizeof(struct v4l2_fmtdesc)); + fmt->index = index; + fmt->type = type; + fmt->pixelformat = pxp_s0_formats[index].fourcc; + strcpy(fmt->description, pxp_s0_formats[index].name); + + return 0; +} + +static int pxp_g_fmt_video_output(struct file *file, void *fh, + struct v4l2_format *f) +{ + struct v4l2_pix_format *pf = &f->fmt.pix; + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + struct pxp_data_format *fmt = pxp->s0_fmt; + + pf->width = pxp->s0_width; + pf->height = pxp->s0_height; + pf->pixelformat = fmt->fourcc; + pf->field = V4L2_FIELD_NONE; + pf->bytesperline = fmt->bpp * pf->width; + pf->sizeimage = pf->bytesperline * pf->height; + pf->colorspace = fmt->colorspace; + pf->priv = 0; + + return 0; +} + +static struct pxp_data_format *pxp_get_format(struct v4l2_format *f) +{ + struct pxp_data_format *fmt; + int i; + + for (i = 0; i < ARRAY_SIZE(pxp_s0_formats); i++) { + fmt = &pxp_s0_formats[i]; + if (fmt->fourcc == f->fmt.pix.pixelformat) + break; + } + + if (i == ARRAY_SIZE(pxp_s0_formats)) + return NULL; + + return &pxp_s0_formats[i]; +} + +static int pxp_try_fmt_video_output(struct file *file, void *fh, + struct v4l2_format *f) +{ + int w = f->fmt.pix.width; + int h = f->fmt.pix.height; + struct pxp_data_format *fmt = pxp_get_format(f); + + if (!fmt) + return -EINVAL; + + w = min(w, 2040); + w = max(w, 8); + h = min(h, 2040); + h = max(h, 8); + f->fmt.pix.field = V4L2_FIELD_NONE; + f->fmt.pix.width = w; + f->fmt.pix.height = h; + f->fmt.pix.pixelformat = fmt->fourcc; + + return 0; +} + +static int pxp_s_fmt_video_output(struct file *file, void *fh, + struct v4l2_format *f) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + struct v4l2_pix_format *pf = &f->fmt.pix; + int ret = pxp_try_fmt_video_output(file, fh, f); + + if (ret == 0) { + pxp->s0_fmt = pxp_get_format(f); + pxp->s0_width = pf->width; + pxp->s0_height = pf->height; + pxp_set_ctrl(pxp); + pxp_set_s0param(pxp); + } + + return ret; +} + +static int pxp_g_fmt_output_overlay(struct file *file, void *fh, + struct v4l2_format *f) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + struct v4l2_window *wf = &f->fmt.win; + + memset(wf, 0, sizeof(struct v4l2_window)); + wf->chromakey = pxp->s1_chromakey; + wf->global_alpha = pxp->global_alpha; + wf->field = V4L2_FIELD_NONE; + wf->clips = NULL; + wf->clipcount = 0; + wf->bitmap = NULL; + wf->w.left = pxp->srect.left; + wf->w.top = pxp->srect.top; + wf->w.width = pxp->srect.width; + wf->w.height = pxp->srect.height; + + return 0; +} + +static int pxp_try_fmt_output_overlay(struct file *file, void *fh, + struct v4l2_format *f) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + struct v4l2_window *wf = &f->fmt.win; + struct v4l2_rect srect; + u32 s1_chromakey = wf->chromakey; + u8 global_alpha = wf->global_alpha; + + memcpy(&srect, &(wf->w), sizeof(struct v4l2_rect)); + + pxp_g_fmt_output_overlay(file, fh, f); + + wf->chromakey = s1_chromakey; + wf->global_alpha = global_alpha; + + /* Constrain parameters to the input buffer */ + wf->w.left = srect.left; + wf->w.top = srect.top; + wf->w.width = min(srect.width, ((__s32)pxp->s0_width - wf->w.left)); + wf->w.height = min(srect.height, ((__s32)pxp->s0_height - wf->w.top)); + + return 0; +} + +static int pxp_s_fmt_output_overlay(struct file *file, void *fh, + struct v4l2_format *f) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + struct v4l2_window *wf = &f->fmt.win; + int ret = pxp_try_fmt_output_overlay(file, fh, f); + + if (ret == 0) { + pxp->srect.left = wf->w.left; + pxp->srect.top = wf->w.top; + pxp->srect.width = wf->w.width; + pxp->srect.height = wf->w.height; + pxp->global_alpha = wf->global_alpha; + pxp->s1_chromakey = wf->chromakey; + pxp_set_s0param(pxp); + pxp_set_s0crop(pxp); + pxp_set_scaling(pxp); + pxp_set_olparam(pxp); + pxp_set_s1colorkey(pxp); + } + + return ret; +} + +static int pxp_reqbufs(struct file *file, void *priv, + struct v4l2_requestbuffers *r) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + + return videobuf_reqbufs(&pxp->s0_vbq, r); +} + +static int pxp_querybuf(struct file *file, void *priv, + struct v4l2_buffer *b) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + + return videobuf_querybuf(&pxp->s0_vbq, b); +} + +static int pxp_qbuf(struct file *file, void *priv, + struct v4l2_buffer *b) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + + return videobuf_qbuf(&pxp->s0_vbq, b); +} + +static int pxp_dqbuf(struct file *file, void *priv, + struct v4l2_buffer *b) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + + return videobuf_dqbuf(&pxp->s0_vbq, b, file->f_flags & O_NONBLOCK); +} + +static int pxp_streamon(struct file *file, void *priv, + enum v4l2_buf_type t) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + int ret = 0; + + if ((t != V4L2_BUF_TYPE_VIDEO_OUTPUT)) + return -EINVAL; + + ret = videobuf_streamon(&pxp->s0_vbq); + + if (!ret && (pxp->output == 0)) + stmp3xxxfb_cfg_pxp(1, pxp->outb_phys); + + return ret; +} + +static int pxp_streamoff(struct file *file, void *priv, + enum v4l2_buf_type t) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + int ret = 0; + + if ((t != V4L2_BUF_TYPE_VIDEO_OUTPUT)) + return -EINVAL; + + ret = videobuf_streamoff(&pxp->s0_vbq); + + if (!ret) + stmp3xxxfb_cfg_pxp(0, 0); + + return ret; +} + +static int pxp_buf_setup(struct videobuf_queue *q, + unsigned int *count, unsigned *size) +{ + struct pxps *pxp = q->priv_data; + + *size = pxp->s0_width * pxp->s0_height * pxp->s0_fmt->bpp; + + if (0 == *count) + *count = PXP_DEF_BUFS; + + return 0; +} + +static void pxp_buf_free(struct videobuf_queue *q, struct videobuf_buffer *vb) +{ + if (in_interrupt()) + BUG(); + + videobuf_dma_contig_free(q, vb); + + vb->state = VIDEOBUF_NEEDS_INIT; +} + +static int pxp_buf_prepare(struct videobuf_queue *q, + struct videobuf_buffer *vb, + enum v4l2_field field) +{ + struct pxps *pxp = q->priv_data; + int ret = 0; + + vb->width = pxp->s0_width; + vb->height = pxp->s0_height; + vb->size = vb->width * vb->height * pxp->s0_fmt->bpp; + vb->field = V4L2_FIELD_NONE; + vb->state = VIDEOBUF_NEEDS_INIT; + + ret = videobuf_iolock(q, vb, NULL); + if (ret) + goto fail; + vb->state = VIDEOBUF_PREPARED; + + return 0; + +fail: + pxp_buf_free(q, vb); + return ret; +} + +static void pxp_buf_next(struct pxps *pxp) +{ + dma_addr_t Y, U, V; + + if (pxp->active) { + pxp->active->state = VIDEOBUF_ACTIVE; + Y = videobuf_to_dma_contig(pxp->active); + pxp->regs_virt->s0buf = Y; + if ((pxp->s0_fmt->fourcc == V4L2_PIX_FMT_YUV420) || + (pxp->s0_fmt->fourcc == V4L2_PIX_FMT_YUV422P)) { + int s = 1; /* default to YUV 4:2:2 */ + if (pxp->s0_fmt->fourcc == V4L2_PIX_FMT_YUV420) + s = 2; + U = Y + (pxp->s0_width * pxp->s0_height); + V = U + ((pxp->s0_width * pxp->s0_height) >> s); + pxp->regs_virt->s0ubuf = U; + pxp->regs_virt->s0vbuf = V; + } + pxp->regs_virt->ctrl = + __raw_readl(HW_PXP_CTRL_ADDR) | BM_PXP_CTRL_ENABLE; + } + + __raw_writel(pxp->regs_phys, HW_PXP_NEXT_ADDR); +} + +static void pxp_next_handle(struct work_struct *w) +{ + struct pxps *pxp = container_of(w, struct pxps, work); + struct pxp_buffer *buf, *next; + unsigned long flags; + + if (pxp->next_queue_ended == 1) + return; + + spin_lock_irqsave(&pxp->lock, flags); + + while (!list_empty(&pxp->nextq)) { + spin_unlock_irqrestore(&pxp->lock, flags); + + if (!wait_event_interruptible_timeout(pxp->done, PXP_WAITCON, + 5 * HZ) || signal_pending(current)) { + spin_lock_irqsave(&pxp->lock, flags); + list_for_each_entry_safe(buf, next, &pxp->nextq, queue) + list_del(&buf->queue); + spin_unlock_irqrestore(&pxp->lock, flags); + pxp->next_queue_ended = 1; + return; + } + + spin_lock_irqsave(&pxp->lock, flags); + buf = list_entry(pxp->nextq.next, + struct pxp_buffer, + queue); + list_del_init(&buf->queue); + pxp->active = &buf->vb; + pxp->active->state = VIDEOBUF_QUEUED; + pxp_buf_next(pxp); + } + + spin_unlock_irqrestore(&pxp->lock, flags); +} + +static void pxp_buf_queue(struct videobuf_queue *q, + struct videobuf_buffer *vb) +{ + struct pxps *pxp = q->priv_data; + struct pxp_buffer *buf; + unsigned long flags; + + spin_lock_irqsave(&pxp->lock, flags); + + if (list_empty(&pxp->outq)) { + list_add_tail(&vb->queue, &pxp->outq); + vb->state = VIDEOBUF_QUEUED; + + pxp->active = vb; + pxp_buf_next(pxp); + } else { + list_add_tail(&vb->queue, &pxp->outq); + + buf = container_of(vb, struct pxp_buffer, vb); + list_add_tail(&buf->queue, &pxp->nextq); + queue_work(pxp->workqueue, &pxp->work); + } + + spin_unlock_irqrestore(&pxp->lock, flags); +} + +static void pxp_buf_release(struct videobuf_queue *q, + struct videobuf_buffer *vb) +{ + pxp_buf_free(q, vb); +} + +static struct videobuf_queue_ops pxp_vbq_ops = { + .buf_setup = pxp_buf_setup, + .buf_prepare = pxp_buf_prepare, + .buf_queue = pxp_buf_queue, + .buf_release = pxp_buf_release, +}; + +static int pxp_querycap(struct file *file, void *fh, + struct v4l2_capability *cap) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + + memset(cap, 0, sizeof(*cap)); + strcpy(cap->driver, "pxp"); + strcpy(cap->card, "pxp"); + strlcpy(cap->bus_info, dev_name(&pxp->pdev->dev), sizeof(cap->bus_info)); + + cap->version = (PXP_DRIVER_MAJOR << 8) + PXP_DRIVER_MINOR; + + cap->capabilities = V4L2_CAP_VIDEO_OUTPUT | + V4L2_CAP_VIDEO_OUTPUT_OVERLAY | + V4L2_CAP_STREAMING; + + return 0; +} + +static int pxp_g_fbuf(struct file *file, void *priv, + struct v4l2_framebuffer *fb) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + + memset(fb, 0, sizeof(*fb)); + + fb->capability = V4L2_FBUF_CAP_EXTERNOVERLAY | + V4L2_FBUF_CAP_CHROMAKEY | + V4L2_FBUF_CAP_LOCAL_ALPHA | + V4L2_FBUF_CAP_GLOBAL_ALPHA; + + if (pxp->global_alpha_state) + fb->flags |= V4L2_FBUF_FLAG_GLOBAL_ALPHA; + if (pxp->local_alpha_state) + fb->flags |= V4L2_FBUF_FLAG_LOCAL_ALPHA; + if (pxp->s1_chromakey_state) + fb->flags |= V4L2_FBUF_FLAG_CHROMAKEY; + + return 0; +} + +static int pxp_s_fbuf(struct file *file, void *priv, + struct v4l2_framebuffer *fb) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + + pxp->overlay_state = + (fb->flags & V4L2_FBUF_FLAG_OVERLAY) != 0; + pxp->global_alpha_state = + (fb->flags & V4L2_FBUF_FLAG_GLOBAL_ALPHA) != 0; + pxp->local_alpha_state = + (fb->flags & V4L2_FBUF_FLAG_LOCAL_ALPHA) != 0; + /* Global alpha overrides local alpha if both are requested */ + if (pxp->global_alpha_state && pxp->local_alpha_state) + pxp->local_alpha_state = 0; + pxp->s1_chromakey_state = + (fb->flags & V4L2_FBUF_FLAG_CHROMAKEY) != 0; + + pxp_set_olparam(pxp); + pxp_set_s0crop(pxp); + pxp_set_scaling(pxp); + + return 0; +} + +static int pxp_g_crop(struct file *file, void *fh, + struct v4l2_crop *c) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + + if (c->type != V4L2_BUF_TYPE_VIDEO_OUTPUT_OVERLAY) + return -EINVAL; + + c->c.left = pxp->drect.left; + c->c.top = pxp->drect.top; + c->c.width = pxp->drect.width; + c->c.height = pxp->drect.height; + + return 0; +} + +static int pxp_s_crop(struct file *file, void *fh, + struct v4l2_crop *c) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + int l = c->c.left; + int t = c->c.top; + int w = c->c.width; + int h = c->c.height; + int fbw = pxp->fb.fmt.width; + int fbh = pxp->fb.fmt.height; + + if (c->type != V4L2_BUF_TYPE_VIDEO_OUTPUT_OVERLAY) + return -EINVAL; + + /* Constrain parameters to FB limits */ + w = min(w, fbw); + w = max(w, PXP_MIN_PIX); + h = min(h, fbh); + h = max(h, PXP_MIN_PIX); + if ((l + w) > fbw) + l = 0; + if ((t + h) > fbh) + t = 0; + + /* Round up values to PxP pixel block */ + l = roundup(l, PXP_MIN_PIX); + t = roundup(t, PXP_MIN_PIX); + w = roundup(w, PXP_MIN_PIX); + h = roundup(h, PXP_MIN_PIX); + + pxp->drect.left = l; + pxp->drect.top = t; + pxp->drect.width = w; + pxp->drect.height = h; + + pxp_set_s0param(pxp); + pxp_set_s0crop(pxp); + pxp_set_scaling(pxp); + + return 0; +} + +static int pxp_queryctrl(struct file *file, void *priv, + struct v4l2_queryctrl *qc) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(pxp_controls); i++) + if (qc->id && qc->id == pxp_controls[i].id) { + memcpy(qc, &(pxp_controls[i]), sizeof(*qc)); + return 0; + } + + return -EINVAL; +} + +static int pxp_g_ctrl(struct file *file, void *priv, + struct v4l2_control *vc) +{ + int i; + + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + + for (i = 0; i < ARRAY_SIZE(pxp_controls); i++) + if (vc->id == pxp_controls[i].id) + return pxp_get_cstate(pxp, vc); + + return -EINVAL; +} + +static int pxp_s_ctrl(struct file *file, void *priv, + struct v4l2_control *vc) +{ + int i; + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + + for (i = 0; i < ARRAY_SIZE(pxp_controls); i++) + if (vc->id == pxp_controls[i].id) { + if (vc->value < pxp_controls[i].minimum || + vc->value > pxp_controls[i].maximum) + return -ERANGE; + return pxp_set_cstate(pxp, vc); + } + + return -EINVAL; +} + +void pxp_release(struct video_device *vfd) +{ + struct pxps *pxp = video_get_drvdata(vfd); + + spin_lock(&pxp->lock); + video_device_release(vfd); + spin_unlock(&pxp->lock); +} + +static int pxp_hw_init(struct pxps *pxp) +{ + struct fb_var_screeninfo var; + struct fb_fix_screeninfo fix; + int err; + + err = stmp3xxxfb_get_info(&var, &fix); + if (err) + return err; + + /* Pull PxP out of reset */ + __raw_writel(0, HW_PXP_CTRL_ADDR); + + /* Config defaults */ + pxp->active = NULL; + + pxp->s0_fmt = &pxp_s0_formats[0]; + pxp->drect.left = pxp->srect.left = 0; + pxp->drect.top = pxp->srect.top = 0; + pxp->drect.width = pxp->srect.width = pxp->s0_width = var.xres; + pxp->drect.height = pxp->srect.height = pxp->s0_height = var.yres; + pxp->s0_bgcolor = 0; + + pxp->output = 0; + err = pxp_set_fbinfo(pxp); + if (err) + return err; + + pxp->scaling = 0; + pxp->hflip = 0; + pxp->vflip = 0; + pxp->rotate = 0; + pxp->yuv = 0; + + pxp->overlay_state = 0; + pxp->global_alpha_state = 0; + pxp->global_alpha = 0; + pxp->local_alpha_state = 0; + pxp->s1_chromakey_state = 0; + pxp->s1_chromakey = -1; + pxp->s0_chromakey = -1; + + /* Write default h/w config */ + pxp_set_ctrl(pxp); + pxp_set_s0param(pxp); + pxp_set_s0crop(pxp); + pxp_set_oln(pxp); + pxp_set_olparam(pxp); + pxp_set_s0colorkey(pxp); + pxp_set_s1colorkey(pxp); + pxp_set_csc(pxp); + + return 0; +} + +static int pxp_open(struct file *file) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + int ret = 0; + + mutex_lock(&pxp->mutex); + pxp->users++; + + if (pxp->users > 1) { + pxp->users--; + ret = -EBUSY; + goto out; + } +out: + mutex_unlock(&pxp->mutex); + if (ret) + return ret; + + pxp->next_queue_ended = 0; + pxp->workqueue = create_singlethread_workqueue("pxp"); + + videobuf_queue_dma_contig_init(&pxp->s0_vbq, + &pxp_vbq_ops, + &pxp->pdev->dev, + &pxp->lock, + V4L2_BUF_TYPE_VIDEO_OUTPUT, + V4L2_FIELD_NONE, + sizeof(struct pxp_buffer), + pxp); + + return 0; +} + +static int pxp_close(struct file *file) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + + if (pxp->workqueue) + destroy_workqueue(pxp->workqueue); + + videobuf_stop(&pxp->s0_vbq); + videobuf_mmap_free(&pxp->s0_vbq); + pxp->active = NULL; + + mutex_lock(&pxp->mutex); + pxp->users--; + mutex_unlock(&pxp->mutex); + + return 0; +} + +static int pxp_mmap(struct file *file, struct vm_area_struct *vma) +{ + struct pxps *pxp = video_get_drvdata(video_devdata(file)); + int ret; + + ret = videobuf_mmap_mapper(&pxp->s0_vbq, vma); + + return ret; +} + +static const struct v4l2_file_operations pxp_fops = { + .owner = THIS_MODULE, + .open = pxp_open, + .release = pxp_close, + .ioctl = video_ioctl2, + .mmap = pxp_mmap, +}; + +static const struct v4l2_ioctl_ops pxp_ioctl_ops = { + .vidioc_querycap = pxp_querycap, + + .vidioc_reqbufs = pxp_reqbufs, + .vidioc_querybuf = pxp_querybuf, + .vidioc_qbuf = pxp_qbuf, + .vidioc_dqbuf = pxp_dqbuf, + + .vidioc_streamon = pxp_streamon, + .vidioc_streamoff = pxp_streamoff, + + .vidioc_enum_output = pxp_enumoutput, + .vidioc_g_output = pxp_g_output, + .vidioc_s_output = pxp_s_output, + + .vidioc_enum_fmt_vid_out = pxp_enum_fmt_video_output, + .vidioc_try_fmt_vid_out = pxp_try_fmt_video_output, + .vidioc_g_fmt_vid_out = pxp_g_fmt_video_output, + .vidioc_s_fmt_vid_out = pxp_s_fmt_video_output, + + .vidioc_try_fmt_vid_out_overlay = pxp_try_fmt_output_overlay, + .vidioc_g_fmt_vid_out_overlay = pxp_g_fmt_output_overlay, + .vidioc_s_fmt_vid_out_overlay = pxp_s_fmt_output_overlay, + + .vidioc_g_fbuf = pxp_g_fbuf, + .vidioc_s_fbuf = pxp_s_fbuf, + + .vidioc_g_crop = pxp_g_crop, + .vidioc_s_crop = pxp_s_crop, + + .vidioc_queryctrl = pxp_queryctrl, + .vidioc_g_ctrl = pxp_g_ctrl, + .vidioc_s_ctrl = pxp_s_ctrl, +}; + +static const struct video_device pxp_template = { + .name = "PxP", + .vfl_type = V4L2_CAP_VIDEO_OUTPUT | + V4L2_CAP_VIDEO_OVERLAY | + V4L2_CAP_STREAMING, + .fops = &pxp_fops, + .release = pxp_release, + .minor = -1, + .ioctl_ops = &pxp_ioctl_ops, +}; + +static irqreturn_t pxp_irq(int irq, void *dev_id) +{ + struct pxps *pxp = (struct pxps *)dev_id; + struct videobuf_buffer *vb; + unsigned long flags; + + spin_lock_irqsave(&pxp->lock, flags); + + __raw_writel(BM_PXP_STAT_IRQ, HW_PXP_STAT_CLR_ADDR); + + if (list_empty(&pxp->outq)) { + pr_warning("irq: outq empty!!!\n"); + goto out; + } + + vb = list_entry(pxp->outq.next, + struct videobuf_buffer, + queue); + list_del_init(&vb->queue); + + vb->state = VIDEOBUF_DONE; + do_gettimeofday(&vb->ts); + vb->field_count++; + + wake_up(&vb->done); + wake_up(&pxp->done); +out: + spin_unlock_irqrestore(&pxp->lock, flags); + + return IRQ_HANDLED; +} + +static int pxp_notifier_callback(struct notifier_block *self, + unsigned long event, void *data) +{ + struct pxps *pxp = container_of(self, struct pxps, nb); + + switch (event) { + case STMP3XXX_LCDIF_PANEL_INIT: + pxp_set_fbinfo(pxp); + break; + default: + break; + } + return 0; +} + +static int pxp_probe(struct platform_device *pdev) +{ + struct pxps *pxp; + struct resource *res; + int irq; + int err = 0; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + irq = platform_get_irq(pdev, 0); + if (!res || irq < 0) { + err = -ENODEV; + goto exit; + } + + pxp = kzalloc(sizeof(*pxp), GFP_KERNEL); + if (!pxp) { + dev_err(&pdev->dev, "failed to allocate control object\n"); + err = -ENOMEM; + goto exit; + } + + dev_set_drvdata(&pdev->dev, pxp); + pxp->res = res; + pxp->irq = irq; + + pxp->regs_virt = dma_alloc_coherent(NULL, + PAGE_ALIGN(sizeof(struct pxp_registers)), + &pxp->regs_phys, GFP_KERNEL); + if (pxp->regs_virt == NULL) { + dev_err(&pdev->dev, "failed to allocate pxp_register object\n"); + err = -ENOMEM; + goto exit; + } + + init_waitqueue_head(&pxp->done); + + INIT_WORK(&pxp->work, pxp_next_handle); + INIT_LIST_HEAD(&pxp->outq); + INIT_LIST_HEAD(&pxp->nextq); + spin_lock_init(&pxp->lock); + mutex_init(&pxp->mutex); + + if (!request_mem_region(res->start, res->end - res->start + 1, + PXP_DRIVER_NAME)) { + err = -EBUSY; + goto freepxp; + } + + pxp->regs = (void __iomem *)res->start; /* it is already ioremapped */ + pxp->pdev = pdev; + + err = request_irq(pxp->irq, pxp_irq, 0, PXP_DRIVER_NAME, pxp); + + if (err) { + dev_err(&pdev->dev, "interrupt register failed\n"); + goto release; + } + + pxp->vdev = video_device_alloc(); + if (!pxp->vdev) { + dev_err(&pdev->dev, "video_device_alloc() failed\n"); + err = -ENOMEM; + goto freeirq; + } + + memcpy(pxp->vdev, &pxp_template, sizeof(pxp_template)); + video_set_drvdata(pxp->vdev, pxp); + + err = video_register_device(pxp->vdev, VFL_TYPE_GRABBER, 0); + if (err) { + dev_err(&pdev->dev, "failed to register video device\n"); + goto freevdev; + } + + err = pxp_hw_init(pxp); + if (err) { + dev_err(&pdev->dev, "failed to initialize hardware\n"); + goto freevdev; + } + + pxp->nb.notifier_call = pxp_notifier_callback, + stmp3xxx_lcdif_register_client(&pxp->nb); + dev_info(&pdev->dev, "initialized\n"); + +exit: + return err; + +freevdev: + video_device_release(pxp->vdev); + +freeirq: + free_irq(pxp->irq, pxp); + +release: + release_mem_region(res->start, res->end - res->start + 1); + +freepxp: + kfree(pxp); + + return err; +} + +static int __devexit pxp_remove(struct platform_device *pdev) +{ + struct pxps *pxp = platform_get_drvdata(pdev); + + stmp3xxx_lcdif_unregister_client(&pxp->nb); + video_unregister_device(pxp->vdev); + video_device_release(pxp->vdev); + + if (pxp->regs_virt) + dma_free_coherent(0, PAGE_ALIGN(sizeof(struct pxp_registers)), + pxp->regs_virt, pxp->regs_phys); + kfree(pxp->outb); + kfree(pxp); + + return 0; +} + +#ifdef CONFIG_PM +static int pxp_suspend(struct platform_device *pdev, pm_message_t state) +{ + int i; + + while (__raw_readl(HW_PXP_CTRL_ADDR) & BM_PXP_CTRL_ENABLE) + ; + + for (i = 0; i < REGS1_NUMS; i++) + regs1[i] = __raw_readl(HW_PXP_CTRL_ADDR + REG_OFFSET * i); + + for (i = 0; i < REGS2_NUMS; i++) + regs2[i] = __raw_readl(HW_PXP_PAGETABLE_ADDR + REG_OFFSET * i); + + for (i = 0; i < REGS3_NUMS; i++) + regs3[i] = __raw_readl(HW_PXP_OLn_ADDR(0) + REG_OFFSET * i); + + __raw_writel(BM_PXP_CTRL_SFTRST, HW_PXP_CTRL_ADDR); + + return 0; +} + +static int pxp_resume(struct platform_device *pdev) +{ + int i; + + /* Pull PxP out of reset */ + __raw_writel(0, HW_PXP_CTRL_ADDR); + + for (i = 0; i < REGS1_NUMS; i++) + __raw_writel(regs1[i], HW_PXP_CTRL_ADDR + REG_OFFSET * i); + + for (i = 0; i < REGS2_NUMS; i++) + __raw_writel(regs2[i], HW_PXP_PAGETABLE_ADDR + REG_OFFSET * i); + + for (i = 0; i < REGS3_NUMS; i++) + __raw_writel(regs3[i], HW_PXP_OLn_ADDR(0) + REG_OFFSET * i); + + return 0; +} +#else +#define pxp_suspend NULL +#define pxp_resume NULL +#endif + +static struct platform_driver pxp_driver = { + .driver = { + .name = PXP_DRIVER_NAME, + }, + .probe = pxp_probe, + .remove = __exit_p(pxp_remove), + .suspend = pxp_suspend, + .resume = pxp_resume, +}; + + +static int __devinit pxp_init(void) +{ + return platform_driver_register(&pxp_driver); +} + +static void __exit pxp_exit(void) +{ + platform_driver_unregister(&pxp_driver); +} + +module_init(pxp_init); +module_exit(pxp_exit); + +MODULE_DESCRIPTION("STMP37xx PxP driver"); +MODULE_AUTHOR("Matt Porter "); +MODULE_LICENSE("GPL"); diff --git a/drivers/media/video/pxp.h b/drivers/media/video/pxp.h new file mode 100644 index 000000000000..11b41dcc6ade --- /dev/null +++ b/drivers/media/video/pxp.h @@ -0,0 +1,130 @@ +/* + * Freescale STMP378X PxP driver + * + * Author: Matt Porter + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. + * Copyright 2008-2009 Embedded Alley Solutions, Inc All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +struct pxp_overlay_registers { + u32 ol; + u32 olsize; + u32 olparam; + u32 olparam2; +}; + +/* Registers feed for PXP_NEXT */ +struct pxp_registers { + u32 ctrl; + u32 rgbbuf; + u32 rgbbuf2; + u32 rgbsize; + u32 s0buf; + u32 s0ubuf; + u32 s0vbuf; + u32 s0param; + u32 s0background; + u32 s0crop; + u32 s0scale; + u32 s0offset; + u32 s0colorkeylow; + u32 s0colorkeyhigh; + u32 olcolorkeylow; + u32 olcolorkeyhigh; + + struct pxp_overlay_registers ol0; + struct pxp_overlay_registers ol1; + struct pxp_overlay_registers ol2; + struct pxp_overlay_registers ol3; + struct pxp_overlay_registers ol4; + struct pxp_overlay_registers ol5; + struct pxp_overlay_registers ol6; + struct pxp_overlay_registers ol7; +}; + +struct pxp_buffer { + /* Must be first! */ + struct videobuf_buffer vb; + struct list_head queue; +}; + +struct pxps { + struct platform_device *pdev; + struct resource *res; + int irq; + void __iomem *regs; + + struct work_struct work; + struct workqueue_struct *workqueue; + spinlock_t lock; + struct mutex mutex; + int users; + + struct video_device *vdev; + + struct videobuf_queue s0_vbq; + struct videobuf_buffer *active; + struct list_head outq; + struct list_head nextq; + + int output; + u32 *outb; + dma_addr_t outb_phys; + + /* Current S0 configuration */ + struct pxp_data_format *s0_fmt; + u32 s0_width; + u32 s0_height; + u32 s0_bgcolor; + u32 s0_chromakey; + + struct v4l2_framebuffer fb; + struct v4l2_rect drect; + struct v4l2_rect srect; + + /* Transformation support */ + int scaling; + int hflip; + int vflip; + int rotate; + int yuv; + + /* Output overlay support */ + int overlay_state; + int global_alpha_state; + u8 global_alpha; + int local_alpha_state; + int s1_chromakey_state; + u32 s1_chromakey; + + /* PXP_NEXT */ + u32 regs_phys; + struct pxp_registers *regs_virt; + wait_queue_head_t done; + int next_queue_ended; + + /* notifier for PXP when fb changed */ + struct notifier_block nb; +}; + +struct pxp_data_format { + char *name; + unsigned int bpp; + u32 fourcc; + enum v4l2_colorspace colorspace; + u32 ctrl_s0_fmt; +}; + +extern int stmp3xxxfb_get_info(struct fb_var_screeninfo *var, + struct fb_fix_screeninfo *fix); +extern void stmp3xxxfb_cfg_pxp(int enable, dma_addr_t pxp_phys); diff --git a/drivers/misc/Kconfig b/drivers/misc/Kconfig index 26386a92f5aa..51f64671bfd9 100644 --- a/drivers/misc/Kconfig +++ b/drivers/misc/Kconfig @@ -353,6 +353,11 @@ config VMWARE_BALLOON To compile this driver as a module, choose M here: the module will be called vmware_balloon. +config MXS_PERSISTENT + tristate "MX23/MX28 persistent bit" + depends on ARCH_MXS + default y + source "drivers/misc/c2port/Kconfig" source "drivers/misc/eeprom/Kconfig" source "drivers/misc/cb710/Kconfig" diff --git a/drivers/misc/Makefile b/drivers/misc/Makefile index 6ed06a19474a..9e5c604344a8 100644 --- a/drivers/misc/Makefile +++ b/drivers/misc/Makefile @@ -28,6 +28,7 @@ obj-$(CONFIG_DS1682) += ds1682.o obj-$(CONFIG_TI_DAC7512) += ti_dac7512.o obj-$(CONFIG_C2PORT) += c2port/ obj-$(CONFIG_IWMC3200TOP) += iwmc3200top/ +obj-$(CONFIG_MXS_PERSISTENT) += mxs-persistent.o obj-y += eeprom/ obj-y += cb710/ obj-$(CONFIG_VMWARE_BALLOON) += vmware_balloon.o diff --git a/drivers/misc/mxs-persistent.c b/drivers/misc/mxs-persistent.c new file mode 100644 index 000000000000..6acb006489d0 --- /dev/null +++ b/drivers/misc/mxs-persistent.c @@ -0,0 +1,271 @@ +/* + * Freescale STMP378X Persistent bits manipulation driver + * + * Author: Pantelis Antoniou + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. + * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +struct mxs_persistent_data { + struct device *dev; + struct mxs_platform_persistent_data *pdata; + int count; + struct attribute_group attr_group; + unsigned int base; + /* attribute ** follow */ + /* device_attribute follow */ +}; + +#define pd_attribute_ptr(x) \ + ((struct attribute **)((x) + 1)) +#define pd_device_attribute_ptr(x) \ + ((struct device_attribute *)(pd_attribute_ptr(x) + (x)->count + 1)) + +static inline u32 persistent_reg_read(struct mxs_persistent_data *pdata, + int reg) +{ + u32 msk; + + /* wait for stable value */ + msk = BF_RTC_STAT_STALE_REGS((0x1 << reg)); + while (__raw_readl(pdata->base + HW_RTC_STAT) & msk) + cpu_relax(); + + return __raw_readl(pdata->base + 0x60 + (reg * 0x10)); +} + +static inline void persistent_reg_wait_settle(struct mxs_persistent_data *pdata + , int reg) +{ + u32 msk; + + /* wait until the change is propagated */ + msk = BF_RTC_STAT_NEW_REGS((0x1 << reg)); + while (__raw_readl(pdata->base + HW_RTC_STAT) & msk) + cpu_relax(); +} + +static inline void persistent_reg_write(struct mxs_persistent_data *pdata, + u32 val, int reg) +{ + __raw_writel(val, pdata->base + 0x60 + (reg * 0x10)); + persistent_reg_wait_settle(pdata, reg); +} + +static inline void persistent_reg_set(struct mxs_persistent_data *pdata, + u32 val, int reg) +{ + __raw_writel(val, pdata->base + 0x60 + (reg * 0x10) + 0x4); + persistent_reg_wait_settle(pdata, reg); +} + +static inline void persistent_reg_clr(struct mxs_persistent_data *pdata, + u32 val, int reg) +{ + __raw_writel(val, pdata->base + 0x60 + (reg * 0x10) + 0x8); + persistent_reg_wait_settle(pdata, reg); +} + +static inline void persistent_reg_tog(struct mxs_persistent_data *pdata, + u32 val, int reg) +{ + __raw_writel(val, pdata->base + 0x60 + (reg * 0x10) + 0xc); + persistent_reg_wait_settle(pdata, reg); +} + +static ssize_t +persistent_show(struct device *dev, struct device_attribute *attr, char *buf) +{ + struct platform_device *pdev = to_platform_device(dev); + struct mxs_persistent_data *pd = platform_get_drvdata(pdev); + struct device_attribute *devattr = pd_device_attribute_ptr(pd); + const struct mxs_persistent_bit_config *pb; + int idx; + u32 val; + + idx = attr - devattr; + if ((unsigned int)idx >= pd->count) + return -EINVAL; + + pb = &pd->pdata->bit_config_tab[idx]; + + /* read value and shift */ + val = persistent_reg_read(pd, pb->reg); + val >>= pb->start; + val &= (1 << pb->width) - 1; + + return sprintf(buf, "%u\n", val); +} + +static ssize_t +persistent_store(struct device *dev, struct device_attribute *attr, + const char *buf, size_t count) +{ + struct platform_device *pdev = to_platform_device(dev); + struct mxs_persistent_data *pd = platform_get_drvdata(pdev); + struct device_attribute *devattr = pd_device_attribute_ptr(pd); + const struct mxs_persistent_bit_config *pb; + int idx, r; + unsigned long val, msk; + + idx = attr - devattr; + if ((unsigned int)idx >= pd->count) + return -EINVAL; + + pb = &pd->pdata->bit_config_tab[idx]; + + /* get value to write */ + r = strict_strtoul(buf, 10, &val); + if (r != 0) + return r; + + /* verify it fits */ + if ((unsigned int)val > (1 << pb->width) - 1) + return -EINVAL; + + /* lockless update, first clear the area */ + msk = ((1 << pb->width) - 1) << pb->start; + persistent_reg_clr(pd, msk, pb->reg); + + /* shift into position */ + val <<= pb->start; + persistent_reg_set(pd, val, pb->reg); + + return count; +} + + +static int __devinit mxs_persistent_probe(struct platform_device *pdev) +{ + struct mxs_persistent_data *pd; + struct mxs_platform_persistent_data *pdata; + struct resource *res; + const struct mxs_persistent_bit_config *pb; + struct attribute **attr; + struct device_attribute *devattr; + int i, cnt, size; + int err; + + pdata = pdev->dev.platform_data; + if (pdata == NULL) + return -ENODEV; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (res == NULL) + return -ENODEV; + + cnt = pdata->bit_config_cnt; + size = sizeof(*pd) + + (cnt + 1) * sizeof(struct atrribute *) + + cnt * sizeof(struct device_attribute); + pd = kzalloc(size, GFP_KERNEL); + if (pd == NULL) + return -ENOMEM; + pd->dev = &pdev->dev; + pd->pdata = pdata; + pd->base = (unsigned int)IO_ADDRESS(res->start); + + platform_set_drvdata(pdev, pd); + pd->count = cnt; + attr = pd_attribute_ptr(pd); + devattr = pd_device_attribute_ptr(pd); + + /* build the attributes structures */ + pd->attr_group.attrs = attr; + pb = pdata->bit_config_tab; + for (i = 0; i < cnt; i++) { + devattr[i].attr.name = pb[i].name; + devattr[i].attr.mode = S_IWUSR | S_IRUGO; + devattr[i].show = persistent_show; + devattr[i].store = persistent_store; + attr[i] = &devattr[i].attr; + } + + err = sysfs_create_group(&pdev->dev.kobj, &pd->attr_group); + if (err != 0) { + platform_set_drvdata(pdev, NULL); + kfree(pd); + return err; + } + + return 0; +} + +static int __devexit mxs_persistent_remove(struct platform_device *pdev) +{ + struct mxs_persistent_data *pd; + + pd = platform_get_drvdata(pdev); + sysfs_remove_group(&pdev->dev.kobj, &pd->attr_group); + platform_set_drvdata(pdev, NULL); + kfree(pd); + + return 0; +} + +#ifdef CONFIG_PM +static int +mxs_persistent_suspend(struct platform_device *pdev, pm_message_t state) +{ + return 0; +} + +static int mxs_persistent_resume(struct platform_device *pdev) +{ + return 0; +} +#else +#define mxs_persistent_suspend NULL +#define mxs_persistent_resume NULL +#endif + +static struct platform_driver mxs_persistent_driver = { + .probe = mxs_persistent_probe, + .remove = __exit_p(mxs_persistent_remove), + .suspend = mxs_persistent_suspend, + .resume = mxs_persistent_resume, + .driver = { + .name = "mxs-persistent", + .owner = THIS_MODULE, + }, +}; + +static int __init mxs_persistent_init(void) +{ + return platform_driver_register(&mxs_persistent_driver); +} + +static void __exit mxs_persistent_exit(void) +{ + platform_driver_unregister(&mxs_persistent_driver); +} + +MODULE_AUTHOR("Pantelis Antoniou "); +MODULE_DESCRIPTION("Persistent bits user-access driver"); +MODULE_LICENSE("GPL"); + +module_init(mxs_persistent_init); +module_exit(mxs_persistent_exit); diff --git a/drivers/mmc/card/Kconfig b/drivers/mmc/card/Kconfig index 3f2a912659af..10ba9a035a58 100644 --- a/drivers/mmc/card/Kconfig +++ b/drivers/mmc/card/Kconfig @@ -50,3 +50,15 @@ config MMC_TEST This driver is only of interest to those developing or testing a host driver. Most people should say N here. + +config SDIO_UNIFI_FS + tristate "UniFi SDIO glue for Freescale MMC/SDIO" + depends on (MMC_MXC || MMC_IMX_ESDHCI) + depends on (MACH_MX31_3DS || MACH_MX35_3DS || MACH_MX37_3DS || MACH_MX51_3DS) + help + This provides an interface between the CSR UniFi WiFi + driver and the Freescale MMC/SDIO interface. + If you have a MXC platform with a UniFi WiFi chip, + say M here. + + If unsure, say N. diff --git a/drivers/mmc/card/Makefile b/drivers/mmc/card/Makefile index 0d407514f67d..bbcf742d0ea1 100644 --- a/drivers/mmc/card/Makefile +++ b/drivers/mmc/card/Makefile @@ -12,3 +12,4 @@ obj-$(CONFIG_MMC_TEST) += mmc_test.o obj-$(CONFIG_SDIO_UART) += sdio_uart.o +obj-$(CONFIG_SDIO_UNIFI_FS) += unifi_fs/ diff --git a/drivers/mmc/card/unifi_fs/Makefile b/drivers/mmc/card/unifi_fs/Makefile new file mode 100644 index 000000000000..381d4a2d1fd5 --- /dev/null +++ b/drivers/mmc/card/unifi_fs/Makefile @@ -0,0 +1,2 @@ +obj-$(CONFIG_SDIO_UNIFI_FS) = unifi_fs.o +unifi_fs-objs = fs_lx.o diff --git a/drivers/mmc/card/unifi_fs/fs_lx.c b/drivers/mmc/card/unifi_fs/fs_lx.c new file mode 100644 index 000000000000..d449e6c13258 --- /dev/null +++ b/drivers/mmc/card/unifi_fs/fs_lx.c @@ -0,0 +1,683 @@ +/* + * fs_lx.c - Freescale SDIO glue module for UniFi. + * + * Copyright (C) 2008 Cambridge Silicon Radio Ltd. + * + * Important: + * This module does not support more than one device driver instances. + * + */ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#include +#include +#include + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +#include +#include + +#include "fs_sdio_api.h" + +struct regulator_unifi { + struct regulator *reg_gpo1; + struct regulator *reg_gpo2; + struct regulator *reg_1v5_ana_bb; + struct regulator *reg_vdd_vpa; + struct regulator *reg_1v5_dd; +}; + +static struct sdio_driver sdio_unifi_driver; + +static int fs_sdio_probe(struct sdio_func *func, + const struct sdio_device_id *id); +static void fs_sdio_remove(struct sdio_func *func); +static void fs_sdio_irq(struct sdio_func *func); +static int fs_sdio_suspend(struct device *dev, pm_message_t state); +static int fs_sdio_resume(struct device *dev); + +/* Globals to store the context to this module and the device driver */ +static struct sdio_dev *available_sdio_dev; +static struct fs_driver *available_driver; +struct mxc_unifi_platform_data *plat_data; + +extern void mxc_mmc_force_detect(int id); + +enum sdio_cmd_direction { + CMD_READ, + CMD_WRITE, +}; + +static int fsl_io_rw_direct(struct mmc_card *card, int write, unsigned fn, + unsigned addr, u8 in, u8 *out) +{ + struct mmc_command cmd; + int err; + + BUG_ON(!card); + BUG_ON(fn > 7); + + memset(&cmd, 0, sizeof(struct mmc_command)); + + cmd.opcode = SD_IO_RW_DIRECT; + cmd.arg = write ? 0x80000000 : 0x00000000; + cmd.arg |= fn << 28; + cmd.arg |= (write && out) ? 0x08000000 : 0x00000000; + cmd.arg |= addr << 9; + cmd.arg |= in; + cmd.flags = MMC_RSP_SPI_R5 | MMC_RSP_R5 | MMC_CMD_AC; + + err = mmc_wait_for_cmd(card->host, &cmd, 0); + if (err) + return err; + + if (mmc_host_is_spi(card->host)) { + /* host driver already reported errors */ + } else { + if (cmd.resp[0] & R5_ERROR) + return -EIO; + if (cmd.resp[0] & R5_FUNCTION_NUMBER) + return -EINVAL; + if (cmd.resp[0] & R5_OUT_OF_RANGE) + return -ERANGE; + } + + if (out) { + if (mmc_host_is_spi(card->host)) + *out = (cmd.resp[0] >> 8) & 0xFF; + else + *out = cmd.resp[0] & 0xFF; + } + + return 0; +} + + +int fs_sdio_readb(struct sdio_dev *fdev, int funcnum, unsigned long addr, + unsigned char *pdata) +{ + int err; + char val; + + sdio_claim_host(fdev->func); + if (funcnum == 0) + val = sdio_f0_readb(fdev->func, (unsigned int)addr, &err); + else + val = sdio_readb(fdev->func, (unsigned int)addr, &err); + sdio_release_host(fdev->func); + if (!err) + *pdata = val; + else + printk(KERN_ERR "fs_lx: readb error,fun=%d,addr=%d,data=%d," + "err=%d\n", funcnum, (int)addr, *pdata, err); + + return err; +} +EXPORT_SYMBOL(fs_sdio_readb); + +int fs_sdio_writeb(struct sdio_dev *fdev, int funcnum, unsigned long addr, + unsigned char data) +{ + int err; + + sdio_claim_host(fdev->func); + if (funcnum == 0) + err = fsl_io_rw_direct(fdev->func->card, 1, 0, addr, + data, NULL); + else + sdio_writeb(fdev->func, data, (unsigned int)addr, &err); + sdio_release_host(fdev->func); + + if (err) + printk(KERN_ERR "fs_lx: writeb error,fun=%d,addr=%d,data=%d," + "err=%d\n", funcnum, (int)addr, data, err); + return err; +} +EXPORT_SYMBOL(fs_sdio_writeb); + +int fs_sdio_block_rw(struct sdio_dev *fdev, int funcnum, unsigned long addr, + unsigned char *pdata, unsigned int count, int direction) +{ + int err; + + sdio_claim_host(fdev->func); + if (direction == CMD_READ) + err = sdio_memcpy_fromio(fdev->func, pdata, addr, count); + else + err = sdio_memcpy_toio(fdev->func, addr, pdata, count); + sdio_release_host(fdev->func); + + return err; +} +EXPORT_SYMBOL(fs_sdio_block_rw); + +int fs_sdio_enable_interrupt(struct sdio_dev *fdev, int enable) +{ + struct mmc_host *host = fdev->func->card->host; + unsigned long flags; + + spin_lock_irqsave(&fdev->lock, flags); + if (enable) { + if (!fdev->int_enabled) { + fdev->int_enabled = 1; + host->ops->enable_sdio_irq(host, 1); + } + } else { + if (fdev->int_enabled) { + host->ops->enable_sdio_irq(host, 0); + fdev->int_enabled = 0; + } + } + spin_unlock_irqrestore(&fdev->lock, flags); + + return 0; +} +EXPORT_SYMBOL(fs_sdio_enable_interrupt); + +int fs_sdio_disable(struct sdio_dev *fdev) +{ + int err; + sdio_claim_host(fdev->func); + err = sdio_disable_func(fdev->func); + sdio_release_host(fdev->func); + if (err) + printk(KERN_ERR "fs_lx:fs_sdio_disable error,err=%d\n", err); + return err; +} +EXPORT_SYMBOL(fs_sdio_disable); + +int fs_sdio_enable(struct sdio_dev *fdev) +{ + int err = 0; + + sdio_claim_host(fdev->func); + err = sdio_disable_func(fdev->func); + err = sdio_enable_func(fdev->func); + sdio_release_host(fdev->func); + if (err) + printk(KERN_ERR "fs_lx:fs_sdio_enable error,err=%d\n", err); + return err; +} +EXPORT_SYMBOL(fs_sdio_enable); + +int fs_sdio_set_max_clock_speed(struct sdio_dev *fdev, int max_khz) +{ + struct mmc_card *card = fdev->func->card; + + /* Respect the host controller's min-max. */ + max_khz *= 1000; + if (max_khz < card->host->f_min) + max_khz = card->host->f_min; + if (max_khz > card->host->f_max) + max_khz = card->host->f_max; + + card->host->ios.clock = max_khz; + card->host->ops->set_ios(card->host, &card->host->ios); + + return max_khz / 1000; +} +EXPORT_SYMBOL(fs_sdio_set_max_clock_speed); + +int fs_sdio_set_block_size(struct sdio_dev *fdev, int blksz) +{ + return 0; +} +EXPORT_SYMBOL(fs_sdio_set_block_size); + +/* + * --------------------------------------------------------------------------- + * + * Turn on the power of WIFI card + * + * --------------------------------------------------------------------------- + */ +static void fs_unifi_power_on(void) +{ + struct regulator_unifi *reg_unifi; + unsigned int tmp; + + reg_unifi = plat_data->priv; + + if (reg_unifi->reg_gpo1) + regulator_enable(reg_unifi->reg_gpo1); + if (reg_unifi->reg_gpo2) + regulator_enable(reg_unifi->reg_gpo2); + + if (plat_data->enable) + plat_data->enable(1); + + if (reg_unifi->reg_1v5_ana_bb) { + regulator_set_voltage(reg_unifi->reg_1v5_ana_bb, + 1500000, 1500000); + regulator_enable(reg_unifi->reg_1v5_ana_bb); + } + if (reg_unifi->reg_vdd_vpa) { + tmp = regulator_get_voltage(reg_unifi->reg_vdd_vpa); + if (tmp < 3000000 || tmp > 3600000) + regulator_set_voltage(reg_unifi->reg_vdd_vpa, + 3000000, 3000000); + regulator_enable(reg_unifi->reg_vdd_vpa); + } + /* WL_1V5DD should come on last, 10ms after other supplies */ + msleep(10); + if (reg_unifi->reg_1v5_dd) { + regulator_set_voltage(reg_unifi->reg_1v5_dd, + 1500000, 1500000); + regulator_enable(reg_unifi->reg_1v5_dd); + } + msleep(10); +} + +/* + * --------------------------------------------------------------------------- + * + * Turn off the power of WIFI card + * + * --------------------------------------------------------------------------- + */ +static void fs_unifi_power_off(void) +{ + struct regulator_unifi *reg_unifi; + + reg_unifi = plat_data->priv; + if (reg_unifi->reg_1v5_dd) + regulator_disable(reg_unifi->reg_1v5_dd); + if (reg_unifi->reg_vdd_vpa) + regulator_disable(reg_unifi->reg_vdd_vpa); + + if (reg_unifi->reg_1v5_ana_bb) + regulator_disable(reg_unifi->reg_1v5_ana_bb); + + if (plat_data->enable) + plat_data->enable(0); + + if (reg_unifi->reg_gpo2) + regulator_disable(reg_unifi->reg_gpo2); + + if (reg_unifi->reg_gpo1) + regulator_disable(reg_unifi->reg_gpo1); +} + +/* This should be made conditional on being slot 2 too - so we can + * use a plug in card in slot 1 + */ +int fs_sdio_hard_reset(struct sdio_dev *fdev) +{ + return 0; +} +EXPORT_SYMBOL(fs_sdio_hard_reset); + +static const struct sdio_device_id fs_sdio_ids[] = { + {SDIO_DEVICE(0x032a, 0x0001)}, + { /* end: all zeroes */ }, +}; + +static struct sdio_driver sdio_unifi_driver = { + .name = "fs_unifi", + .probe = fs_sdio_probe, + .remove = fs_sdio_remove, + .id_table = fs_sdio_ids, + .drv = { + .suspend = fs_sdio_suspend, + .resume = fs_sdio_resume, + } +}; + +int fs_sdio_register_driver(struct fs_driver *driver) +{ + int ret, retry; + + /* Switch us on, sdio device may exist if power is on by default. */ + plat_data->hardreset(0); + if (available_sdio_dev) + mxc_mmc_force_detect(plat_data->host_id); + /* Wait for card removed */ + for (retry = 0; retry < 100; retry++) { + if (!available_sdio_dev) + break; + msleep(100); + } + if (retry == 100) + printk(KERN_ERR "fs_sdio_register_driver: sdio device exists, " + "timeout for card removed"); + fs_unifi_power_on(); + plat_data->hardreset(1); + msleep(500); + mxc_mmc_force_detect(plat_data->host_id); + for (retry = 0; retry < 100; retry++) { + if (available_sdio_dev) + break; + msleep(50); + } + if (retry == 100) + printk(KERN_ERR "fs_sdio_register_driver: Timeout waiting" + " for card added\n"); + /* Store the context to the device driver to the global */ + available_driver = driver; + + /* + * If available_sdio_dev is not NULL, probe has been called, + * so pass the probe to the registered driver + */ + if (available_sdio_dev) { + /* Store the context to the new device driver */ + available_sdio_dev->driver = driver; + + printk(KERN_INFO "fs_sdio_register_driver: Glue exists, add " + "device driver and register IRQ\n"); + driver->probe(available_sdio_dev); + + /* Register the IRQ handler to the SDIO IRQ. */ + sdio_claim_host(available_sdio_dev->func); + ret = sdio_claim_irq(available_sdio_dev->func, fs_sdio_irq); + sdio_release_host(available_sdio_dev->func); + if (ret) + return ret; + } + + return 0; +} +EXPORT_SYMBOL(fs_sdio_register_driver); + +void fs_sdio_unregister_driver(struct fs_driver *driver) +{ + /* + * If available_sdio_dev is not NULL, probe has been called, + * so pass the remove to the registered driver to clean up. + */ + if (available_sdio_dev) { + struct mmc_host *host = available_sdio_dev->func->card->host; + + printk(KERN_INFO "fs_sdio_unregister_driver: Glue exists, " + "unregister IRQ and remove device driver\n"); + + /* Unregister the IRQ handler first. */ + sdio_claim_host(available_sdio_dev->func); + sdio_release_irq(available_sdio_dev->func); + sdio_release_host(available_sdio_dev->func); + + driver->remove(available_sdio_dev); + + if (!available_sdio_dev->int_enabled) { + available_sdio_dev->int_enabled = 1; + host->ops->enable_sdio_irq(host, 1); + } + + /* Invalidate the context to the device driver */ + available_sdio_dev->driver = NULL; + } + + /* invalidate the context to the device driver to the global */ + available_driver = NULL; + /* Power down the UniFi */ + fs_unifi_power_off(); + +} +EXPORT_SYMBOL(fs_sdio_unregister_driver); + +static void fs_sdio_irq(struct sdio_func *func) +{ + struct sdio_dev *fdev = (struct sdio_dev *)sdio_get_drvdata(func); + if (fdev->driver) { + if (fdev->driver->card_int_handler) + fdev->driver->card_int_handler(fdev); + } +} + +#ifdef CONFIG_PM +static int fs_sdio_suspend(struct device *dev, pm_message_t state) +{ + struct sdio_dev *fdev = available_sdio_dev; + + /* Pass event to the registered driver. */ + if (fdev->driver) + if (fdev->driver->suspend) + fdev->driver->suspend(fdev, state); + + return 0; +} + +static int fs_sdio_resume(struct device *dev) +{ + struct sdio_dev *fdev = available_sdio_dev; + + /* Pass event to the registered driver. */ + if (fdev->driver) + if (fdev->driver->resume) + fdev->driver->resume(fdev); + + return 0; +} +#else +#define fs_sdio_suspend NULL +#define fs_sdio_resume NULL +#endif + +static int fs_sdio_probe(struct sdio_func *func, + const struct sdio_device_id *id) +{ + struct sdio_dev *fdev; + + /* Allocate our private context */ + fdev = kmalloc(sizeof(struct sdio_dev), GFP_KERNEL); + if (!fdev) + return -ENOMEM; + available_sdio_dev = fdev; + memset(fdev, 0, sizeof(struct sdio_dev)); + fdev->func = func; + fdev->vendor_id = id->vendor; + fdev->device_id = id->device; + fdev->max_blocksize = func->max_blksize; + fdev->int_enabled = 1; + spin_lock_init(&fdev->lock); + + /* Store our context in the MMC driver */ + printk(KERN_INFO "fs_sdio_probe: Add glue driver\n"); + sdio_set_drvdata(func, fdev); + + return 0; +} + +static void fs_sdio_remove(struct sdio_func *func) +{ + struct sdio_dev *fdev = (struct sdio_dev *)sdio_get_drvdata(func); + struct mmc_host *host = func->card->host; + + /* If there is a registered device driver, pass on the remove */ + if (fdev->driver) { + printk(KERN_INFO "fs_sdio_remove: Free IRQ and remove device " + "driver\n"); + /* Unregister the IRQ handler first. */ + sdio_claim_host(fdev->func); + sdio_release_irq(func); + sdio_release_host(fdev->func); + + fdev->driver->remove(fdev); + + if (!fdev->int_enabled) { + fdev->int_enabled = 1; + host->ops->enable_sdio_irq(host, 1); + } + } + + /* Unregister the card context from the MMC driver. */ + sdio_set_drvdata(func, NULL); + + /* Invalidate the global to our context. */ + available_sdio_dev = NULL; + kfree(fdev); +} + +static int fs_unifi_init(void) +{ + struct regulator_unifi *reg_unifi; + struct regulator *reg; + int err = 0; + + plat_data = get_unifi_plat_data(); + + if (!plat_data) + return -ENOENT; + + reg_unifi = kzalloc(sizeof(struct regulator_unifi), GFP_KERNEL); + if (!reg_unifi) + return -ENOMEM; + + if (plat_data->reg_gpo1) { + reg = regulator_get(NULL, plat_data->reg_gpo1); + if (!IS_ERR(reg)) + reg_unifi->reg_gpo1 = reg; + else { + err = -EINVAL; + goto err_reg_gpo1; + } + } + + if (plat_data->reg_gpo2) { + reg = regulator_get(NULL, plat_data->reg_gpo2); + if (!IS_ERR(reg)) + reg_unifi->reg_gpo2 = reg; + else { + err = -EINVAL; + goto err_reg_gpo2; + } + } + + if (plat_data->reg_1v5_ana_bb) { + reg = regulator_get(NULL, plat_data->reg_1v5_ana_bb); + if (!IS_ERR(reg)) + reg_unifi->reg_1v5_ana_bb = reg; + else { + err = -EINVAL; + goto err_reg_1v5_ana_bb; + } + } + + if (plat_data->reg_vdd_vpa) { + reg = regulator_get(NULL, plat_data->reg_vdd_vpa); + if (!IS_ERR(reg)) + reg_unifi->reg_vdd_vpa = reg; + else { + err = -EINVAL; + goto err_reg_vdd_vpa; + } + } + + if (plat_data->reg_1v5_dd) { + reg = regulator_get(NULL, plat_data->reg_1v5_dd); + if (!IS_ERR(reg)) + reg_unifi->reg_1v5_dd = reg; + else { + err = -EINVAL; + goto err_reg_1v5_dd; + } + } + plat_data->priv = reg_unifi; + return 0; + +err_reg_1v5_dd: + if (reg_unifi->reg_vdd_vpa) + regulator_put(reg_unifi->reg_vdd_vpa); +err_reg_vdd_vpa: + if (reg_unifi->reg_1v5_ana_bb) + regulator_put(reg_unifi->reg_1v5_ana_bb); +err_reg_1v5_ana_bb: + if (reg_unifi->reg_gpo2) + regulator_put(reg_unifi->reg_gpo2); +err_reg_gpo2: + if (reg_unifi->reg_gpo1) + regulator_put(reg_unifi->reg_gpo1); +err_reg_gpo1: + kfree(reg_unifi); + return err; +} + +int fs_unifi_remove(void) +{ + struct regulator_unifi *reg_unifi; + + reg_unifi = plat_data->priv; + plat_data->priv = NULL; + + if (reg_unifi->reg_1v5_dd) + regulator_put(reg_unifi->reg_1v5_dd); + if (reg_unifi->reg_vdd_vpa) + regulator_put(reg_unifi->reg_vdd_vpa); + + if (reg_unifi->reg_1v5_ana_bb) + regulator_put(reg_unifi->reg_1v5_ana_bb); + + if (reg_unifi->reg_gpo2) + regulator_put(reg_unifi->reg_gpo2); + + if (reg_unifi->reg_gpo1) + regulator_put(reg_unifi->reg_gpo1); + + kfree(reg_unifi); + return 0; +} + +/* Module init and exit, register and unregister to the SDIO/MMC driver */ +static int __init fs_sdio_init(void) +{ + int err; + + printk(KERN_INFO "Freescale: Register to MMC/SDIO driver\n"); + /* Sleep a bit - otherwise if the mmc subsystem has just started, it + * will allow us to register, then immediatly remove us! + */ + msleep(10); + err = fs_unifi_init(); + if (err) { + printk(KERN_ERR "Error: fs_unifi_init failed!\n"); + return err; + } + err = sdio_register_driver(&sdio_unifi_driver); + if (err) { + printk(KERN_ERR "Error: register sdio_unifi_driver failed!\n"); + fs_unifi_remove(); + } + return err; +} + +module_init(fs_sdio_init); + +static void __exit fs_sdio_exit(void) +{ + printk(KERN_INFO "Freescale: Unregister from MMC/SDIO driver\n"); + sdio_unregister_driver(&sdio_unifi_driver); + fs_unifi_remove(); +} + +module_exit(fs_sdio_exit); + +MODULE_DESCRIPTION("Freescale SDIO glue driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/mmc/card/unifi_fs/fs_sdio_api.h b/drivers/mmc/card/unifi_fs/fs_sdio_api.h new file mode 100644 index 000000000000..d23531509d62 --- /dev/null +++ b/drivers/mmc/card/unifi_fs/fs_sdio_api.h @@ -0,0 +1,68 @@ +/* + *fs_sdio_api.h - Freescale SDIO glue module API for UniFi. + * + * Copyright (C) 2008 Cambridge Silicon Radio Ltd. + * + */ +/* + * Copyright 2008-2010 Freescale Semiconductor + */ +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#ifndef _FS_SDIO_API_H +#define _FS_SDIO_API_H + +struct sdio_dev; + +struct fs_driver { + const char *name; + int (*probe)(struct sdio_dev *fdev); + void (*remove)(struct sdio_dev *fdev); + void (*card_int_handler)(struct sdio_dev *fdev); + void (*suspend)(struct sdio_dev *fdev, pm_message_t state); + void (*resume)(struct sdio_dev *fdev); +}; + +int fs_sdio_readb(struct sdio_dev *fdev, int funcnum, + unsigned long addr, unsigned char *pdata); +int fs_sdio_writeb(struct sdio_dev *fdev, int funcnum, + unsigned long addr, unsigned char data); +int fs_sdio_block_rw(struct sdio_dev *fdev, int funcnum, + unsigned long addr, unsigned char *pdata, + unsigned int count, int direction); + +int fs_sdio_register_driver(struct fs_driver *driver); +void fs_sdio_unregister_driver(struct fs_driver *driver); +int fs_sdio_set_block_size(struct sdio_dev *fdev, int blksz); +int fs_sdio_set_max_clock_speed(struct sdio_dev *fdev, int max_khz); +int fs_sdio_enable_interrupt(struct sdio_dev *fdev, int enable); +int fs_sdio_enable(struct sdio_dev *fdev); +int fs_sdio_hard_reset(struct sdio_dev *fdev); + +struct sdio_dev { + /**< Device driver for this module. */ + struct fs_driver *driver; + + struct sdio_func *func; + + /**< Data private to the device driver. */ + void *drv_data; + + int int_enabled; + spinlock_t lock; + + uint16_t vendor_id; /**< Vendor ID of the card. */ + uint16_t device_id; /**< Device ID of the card. */ + + /**< Maximum block size supported. */ + int max_blocksize; +}; + + +#endif /* #ifndef _FS_SDIO_API_H */ diff --git a/drivers/mmc/host/Kconfig b/drivers/mmc/host/Kconfig index f06d06e7fdfa..951f1fd2661f 100644 --- a/drivers/mmc/host/Kconfig +++ b/drivers/mmc/host/Kconfig @@ -313,6 +313,59 @@ config MMC_SPI If unsure, or if your system has no SPI master driver, say N. +config MMC_MXC + tristate "Freescale MXC Multimedia Card Interface support" + depends on ARCH_MXC && MMC + help + This selects the Freescale MXC Multimedia card Interface. + If you have a MXC platform with a Multimedia Card slot, + say Y or M here. + +config MMC_IMX_ESDHCI + tristate "Freescale i.MX Secure Digital Host Controller Interface support" + depends on ARCH_MXC && MMC + help + This selects the Freescale i.MX Multimedia card Interface. + If you have a i.MX platform with a Multimedia Card slot, + say Y or M here. + + If unsure, say N. + +config MMC_IMX_ESDHCI_SELECT2 + bool "Enable second ESDHCI port" + depends on MMC_IMX_ESDHCI && ARCH_MX25 + default n + help + Enable the second ESDHC port + +config MMC_IMX_ESDHCI_PIO_MODE + bool "Freescale i.MX Secure Digital Host Controller Interface PIO mode" + depends on MMC_IMX_ESDHC != n + default n + help + This set the Freescale i.MX Multimedia card Interface to PIO mode. + If you have a i.MX platform with a Multimedia Card slot, + and want test it with PIO mode. + say Y here. + + If unsure, say N. + +config MMC_STMP3XXX + tristate "STMP37xx/378x MMC support" + depends on MMC && ARCH_STMP3XXX + help + Select Y if you would like to access STMP37xx/378x MMC support. + + If unsure, say N. + +config MMC_MXS + tristate "MXS MMC support" + depends on MMC && (ARCH_MX28 || ARCH_MX23) + help + Select Y if you would like to access MXS MMC support. + + If unsure, say N. + config MMC_S3C tristate "Samsung S3C SD/MMC Card Interface support" depends on ARCH_S3C2410 @@ -371,6 +424,7 @@ config MMC_SDRICOH_CS help Say Y here if your Notebook reports a Ricoh Bay1Controller PCMCIA card whenever you insert a MMC or SD card into the card slot. + say Y or M here. To compile this driver as a module, choose M here: the module will be called sdricoh_cs. diff --git a/drivers/mmc/host/Makefile b/drivers/mmc/host/Makefile index e30c2ee48894..70643ebe0e57 100644 --- a/drivers/mmc/host/Makefile +++ b/drivers/mmc/host/Makefile @@ -9,12 +9,14 @@ endif obj-$(CONFIG_MMC_ARMMMCI) += mmci.o obj-$(CONFIG_MMC_PXA) += pxamci.o obj-$(CONFIG_MMC_IMX) += imxmmc.o -obj-$(CONFIG_MMC_MXC) += mxcmmc.o +obj-$(CONFIG_MMC_MXC) += mxc_mmc.o obj-$(CONFIG_MMC_SDHCI) += sdhci.o obj-$(CONFIG_MMC_SDHCI_PCI) += sdhci-pci.o obj-$(CONFIG_MMC_SDHCI_PLTFM) += sdhci-pltfm.o obj-$(CONFIG_MMC_SDHCI_S3C) += sdhci-s3c.o obj-$(CONFIG_MMC_SDHCI_SPEAR) += sdhci-spear.o +obj-$(CONFIG_MMC_IMX_ESDHCI) += mx_sdhci.o +obj-$(CONFIG_MMC_MXS) += mxs-mmc.o obj-$(CONFIG_MMC_WBSD) += wbsd.o obj-$(CONFIG_MMC_AU1X) += au1xmmc.o obj-$(CONFIG_MMC_OMAP) += omap.o diff --git a/drivers/mmc/host/mx_sdhci.c b/drivers/mmc/host/mx_sdhci.c new file mode 100644 index 000000000000..b5e4f1895fc7 --- /dev/null +++ b/drivers/mmc/host/mx_sdhci.c @@ -0,0 +1,2296 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mx_sdhci.c + * + * @brief Driver for the Freescale Semiconductor MXC eSDHC modules. + * + * This driver code is based on sdhci.c, by Pierre Ossman "); + * This driver supports Enhanced Secure Digital Host Controller + * modules eSDHC of MXC. eSDHC is also referred as enhanced MMC/SD + * controller. + * + * @ingroup MMC_SD + */ + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "mx_sdhci.h" + +#define DRIVER_NAME "mxsdhci" + +#define DBG(f, x...) \ + pr_debug(DRIVER_NAME " [%s()]: " f, __func__, ## x) + +static unsigned int debug_quirks; +static int last_op_dir; + +/* + * Different quirks to handle when the hardware deviates from a strict + * interpretation of the SDHCI specification. + */ + +/* Controller doesn't honor resets unless we touch the clock register */ +#define SDHCI_QUIRK_CLOCK_BEFORE_RESET (1<<0) +/* Controller has bad caps bits, but really supports DMA */ +#define SDHCI_QUIRK_FORCE_DMA (1<<1) +/* Controller doesn't like to be reset when there is no card inserted. */ +#define SDHCI_QUIRK_NO_CARD_NO_RESET (1<<2) +/* Controller doesn't like clearing the power reg before a change */ +#define SDHCI_QUIRK_SINGLE_POWER_WRITE (1<<3) +/* Controller has flaky internal state so reset it on each ios change */ +#define SDHCI_QUIRK_RESET_CMD_DATA_ON_IOS (1<<4) +/* Controller has an unusable DMA engine */ +#define SDHCI_QUIRK_BROKEN_DMA (1<<5) +/* Controller can only DMA from 32-bit aligned addresses */ +#define SDHCI_QUIRK_32BIT_DMA_ADDR (1<<6) +/* Controller can only DMA chunk sizes that are a multiple of 32 bits */ +#define SDHCI_QUIRK_32BIT_DMA_SIZE (1<<7) +/* Controller needs to be reset after each request to stay stable */ +#define SDHCI_QUIRK_RESET_AFTER_REQUEST (1<<8) +/* Controller needs voltage and power writes to happen separately */ +#define SDHCI_QUIRK_NO_SIMULT_VDD_AND_POWER (1<<9) +/* Controller has an off-by-one issue with timeout value */ +#define SDHCI_QUIRK_INCR_TIMEOUT_CONTROL (1<<10) +/* Controller only support the PIO */ +#define SDHCI_QUIRK_ONLY_PIO (1<<16) +/* Controller support the External DMA */ +#define SDHCI_QUIRK_EXTERNAL_DMA_MODE (1<<17) +/* Controller support the Internal Simple DMA */ +#define SDHCI_QUIRK_INTERNAL_SIMPLE_DMA (1<<18) +/* Controller support the Internal Advanced DMA */ +#define SDHCI_QUIRK_INTERNAL_ADVANCED_DMA (1<<19) + +/* + * defines the mxc flags refer to the special hw pre-conditons and behavior + */ +static unsigned int mxc_quirks; +#ifdef CONFIG_MMC_IMX_ESDHCI_PIO_MODE +static unsigned int debug_quirks = SDHCI_QUIRK_ONLY_PIO; +#else +static unsigned int debug_quirks; +#endif +static unsigned int mxc_wml_value = 512; +static unsigned int *adma_des_table; + +#ifndef MXC_SDHCI_NUM +#define MXC_SDHCI_NUM 4 +#endif + +static struct sdhci_chip *mxc_fix_chips[MXC_SDHCI_NUM]; + +static void sdhci_prepare_data(struct sdhci_host *, struct mmc_data *); +static void sdhci_finish_data(struct sdhci_host *); + +static void sdhci_send_command(struct sdhci_host *, struct mmc_command *); +static void sdhci_finish_command(struct sdhci_host *); + +/* Used to active the SD bus */ +extern void gpio_sdhc_active(int module); +extern void gpio_sdhc_inactive(int module); +static void sdhci_dma_irq(void *devid, int error, unsigned int cnt); + +void mxc_mmc_force_detect(int id) +{ + struct sdhci_host *host; + if ((id < 0) || (id >= MXC_SDHCI_NUM)) + return; + if (!mxc_fix_chips[id]) + return; + host = mxc_fix_chips[id]->hosts[0]; + if (host->detect_irq) + return; + + schedule_work(&host->cd_wq); + return; +} + +EXPORT_SYMBOL(mxc_mmc_force_detect); + +static void sdhci_dumpregs(struct sdhci_host *host) +{ + printk(KERN_INFO DRIVER_NAME + ": ============== REGISTER DUMP ==============\n"); + + printk(KERN_INFO DRIVER_NAME ": Sys addr: 0x%08x | Version: 0x%08x\n", + readl(host->ioaddr + SDHCI_DMA_ADDRESS), + readl(host->ioaddr + SDHCI_HOST_VERSION)); + printk(KERN_INFO DRIVER_NAME ": Blk size: 0x%08x | Blk cnt: 0x%08x\n", + (readl(host->ioaddr + SDHCI_BLOCK_SIZE) & 0xFFFF), + (readl(host->ioaddr + SDHCI_BLOCK_COUNT) >> 16)); + printk(KERN_INFO DRIVER_NAME ": Argument: 0x%08x | Trn mode: 0x%08x\n", + readl(host->ioaddr + SDHCI_ARGUMENT), + readl(host->ioaddr + SDHCI_TRANSFER_MODE)); + printk(KERN_INFO DRIVER_NAME ": Present: 0x%08x | Host ctl: 0x%08x\n", + readl(host->ioaddr + SDHCI_PRESENT_STATE), + readl(host->ioaddr + SDHCI_HOST_CONTROL)); + printk(KERN_INFO DRIVER_NAME ": Clock: 0x%08x\n", + readl(host->ioaddr + SDHCI_CLOCK_CONTROL)); + printk(KERN_INFO DRIVER_NAME ": Int stat: 0x%08x\n", + readl(host->ioaddr + SDHCI_INT_STATUS)); + printk(KERN_INFO DRIVER_NAME ": Int enab: 0x%08x | Sig enab: 0x%08x\n", + readl(host->ioaddr + SDHCI_INT_ENABLE), + readl(host->ioaddr + SDHCI_SIGNAL_ENABLE)); + printk(KERN_INFO DRIVER_NAME ": Caps: 0x%08x\n", + readl(host->ioaddr + SDHCI_CAPABILITIES)); + + printk(KERN_INFO DRIVER_NAME + ": ===========================================\n"); +} + +/*****************************************************************************\ + * * + * Low level functions * + * * +\*****************************************************************************/ + +static void sdhci_reset(struct sdhci_host *host, u8 mask) +{ + unsigned long tmp; + unsigned long mask_u32; + unsigned long reg_save = 0; + + if (host->chip->quirks & SDHCI_QUIRK_NO_CARD_NO_RESET) { + if (!(readl(host->ioaddr + SDHCI_PRESENT_STATE) & + SDHCI_CARD_PRESENT)) + return; + } + + if (mask & SDHCI_RESET_ALL) + host->clock = 0; + else if (host->flags & SDHCI_CD_PRESENT) + reg_save = readl(host->ioaddr + SDHCI_HOST_CONTROL); + + tmp = readl(host->ioaddr + SDHCI_CLOCK_CONTROL) | (mask << 24); + mask_u32 = readl(host->ioaddr + SDHCI_SIGNAL_ENABLE); + writel(tmp, host->ioaddr + SDHCI_CLOCK_CONTROL); + + /* Wait max 100 ms */ + tmp = 5000; + + /* hw clears the bit when it's done */ + while ((readl(host->ioaddr + SDHCI_CLOCK_CONTROL) >> 24) & mask) { + if (tmp == 0) { + printk(KERN_ERR "%s: Reset 0x%x never completed.\n", + mmc_hostname(host->mmc), (int)mask); + sdhci_dumpregs(host); + return; + } + tmp--; + udelay(20); + } + /* + * The INT_EN SIG_EN regs have been modified after reset. + * re-configure them ag. + */ + if (!(mask & SDHCI_RESET_ALL) && (host->flags & SDHCI_CD_PRESENT)) + writel(reg_save, host->ioaddr + SDHCI_HOST_CONTROL); + if (host->flags & SDHCI_USE_DMA) + mask_u32 &= ~(SDHCI_INT_DATA_AVAIL | SDHCI_INT_SPACE_AVAIL); + if (mxc_wml_value == 512) + writel(SDHCI_WML_128_WORDS, host->ioaddr + SDHCI_WML); + else + writel(SDHCI_WML_16_WORDS, host->ioaddr + SDHCI_WML); + writel(mask_u32 | SDHCI_INT_CARD_INT, host->ioaddr + SDHCI_INT_ENABLE); + writel(mask_u32, host->ioaddr + SDHCI_SIGNAL_ENABLE); + last_op_dir = 0; +} + +static void sdhci_init(struct sdhci_host *host) +{ + u32 intmask; + + sdhci_reset(host, SDHCI_RESET_ALL); + + intmask = SDHCI_INT_ADMA_ERROR | SDHCI_INT_ACMD12ERR | + SDHCI_INT_DATA_END_BIT | SDHCI_INT_DATA_CRC | + SDHCI_INT_DATA_TIMEOUT | SDHCI_INT_INDEX | + SDHCI_INT_END_BIT | SDHCI_INT_CRC | SDHCI_INT_TIMEOUT | + SDHCI_INT_DATA_AVAIL | SDHCI_INT_SPACE_AVAIL | + SDHCI_INT_DMA_END | SDHCI_INT_DATA_END | SDHCI_INT_RESPONSE; + + if (host->flags & SDHCI_USE_DMA) + intmask &= ~(SDHCI_INT_DATA_AVAIL | SDHCI_INT_SPACE_AVAIL); + /* Configure the WML rege */ + if (mxc_wml_value == 512) + writel(SDHCI_WML_128_WORDS, host->ioaddr + SDHCI_WML); + else + writel(SDHCI_WML_16_WORDS, host->ioaddr + SDHCI_WML); + writel(intmask | SDHCI_INT_CARD_INT, host->ioaddr + SDHCI_INT_ENABLE); + writel(intmask, host->ioaddr + SDHCI_SIGNAL_ENABLE); +} + +static void sdhci_activate_led(struct sdhci_host *host) +{ + u32 ctrl; + + ctrl = readl(host->ioaddr + SDHCI_HOST_CONTROL); + ctrl |= SDHCI_CTRL_LED; + writel(ctrl, host->ioaddr + SDHCI_HOST_CONTROL); +} + +static void sdhci_deactivate_led(struct sdhci_host *host) +{ + u32 ctrl; + + ctrl = readl(host->ioaddr + SDHCI_HOST_CONTROL); + ctrl &= ~SDHCI_CTRL_LED; + writel(ctrl, host->ioaddr + SDHCI_HOST_CONTROL); +} + +/*****************************************************************************\ + * * + * Core functions * + * * +\*****************************************************************************/ + +static inline char *sdhci_sg_to_buffer(struct sdhci_host *host) +{ + return sg_virt(host->cur_sg); +} + +static inline int sdhci_next_sg(struct sdhci_host *host) +{ + /* + * Skip to next SG entry. + */ + host->cur_sg++; + host->num_sg--; + + /* + * Any entries left? + */ + if (host->num_sg > 0) { + host->offset = 0; + host->remain = host->cur_sg->length; + } + + return host->num_sg; +} + +static void sdhci_read_block_pio(struct sdhci_host *host) +{ + int blksize, chunk_remain; + u32 data; + char *buffer; + int size; + + DBG("PIO reading\n"); + + blksize = host->data->blksz; + chunk_remain = 0; + data = 0; + + buffer = sdhci_sg_to_buffer(host) + host->offset; + + while (blksize) { + if (chunk_remain == 0) { + data = readl(host->ioaddr + SDHCI_BUFFER); + chunk_remain = min(blksize, 4); + } + + size = min(host->remain, chunk_remain); + + chunk_remain -= size; + blksize -= size; + host->offset += size; + host->remain -= size; + + while (size) { + *buffer = data & 0xFF; + buffer++; + data >>= 8; + size--; + } + + if (host->remain == 0) { + if (sdhci_next_sg(host) == 0) { + BUG_ON(blksize != 0); + return; + } + buffer = sdhci_sg_to_buffer(host); + } + } +} + +static void sdhci_write_block_pio(struct sdhci_host *host) +{ + int blksize, chunk_remain; + u32 data; + char *buffer; + int bytes, size; + + DBG("PIO writing\n"); + + blksize = host->data->blksz; + chunk_remain = 4; + data = 0; + + bytes = 0; + buffer = sdhci_sg_to_buffer(host) + host->offset; + + while (blksize) { + size = min(host->remain, chunk_remain); + + chunk_remain -= size; + blksize -= size; + host->offset += size; + host->remain -= size; + + while (size) { + data >>= 8; + data |= (u32) *buffer << 24; + buffer++; + size--; + } + + if (chunk_remain == 0) { + writel(data, host->ioaddr + SDHCI_BUFFER); + chunk_remain = min(blksize, 4); + } + + if (host->remain == 0) { + if (sdhci_next_sg(host) == 0) { + BUG_ON(blksize != 0); + return; + } + buffer = sdhci_sg_to_buffer(host); + } + } +} + +static void sdhci_transfer_pio(struct sdhci_host *host) +{ + u32 mask; + + BUG_ON(!host->data); + + if (host->num_sg == 0) + return; + + if (host->data->flags & MMC_DATA_READ) + mask = SDHCI_DATA_AVAILABLE; + else + mask = SDHCI_SPACE_AVAILABLE; + + while (readl(host->ioaddr + SDHCI_PRESENT_STATE) & mask) { + if (host->data->flags & MMC_DATA_READ) + sdhci_read_block_pio(host); + else + sdhci_write_block_pio(host); + + if (host->num_sg == 0) + break; + } + + DBG("PIO transfer complete.\n"); +} + +static void sdhci_prepare_data(struct sdhci_host *host, struct mmc_data *data) +{ + u32 count; + unsigned target_timeout, current_timeout; + + WARN_ON(host->data); + + if (data == NULL) + return; + + /* Sanity checks */ + BUG_ON(data->blksz * data->blocks > 524288); + BUG_ON(data->blksz > host->mmc->max_blk_size); + BUG_ON(data->blocks > 65535); + + host->data = data; + host->data_early = 0; + if (host->data->flags & MMC_DATA_READ) + writel(readl(host->ioaddr + SDHCI_CLOCK_CONTROL) | + SDHCI_CLOCK_HLK_EN, host->ioaddr + SDHCI_CLOCK_CONTROL); + + /* timeout in us */ + target_timeout = data->timeout_ns / 1000 + + data->timeout_clks / host->clock; + + /* + * Figure out needed cycles. + * We do this in steps in order to fit inside a 32 bit int. + * The first step is the minimum timeout, which will have a + * minimum resolution of 6 bits: + * (1) 2^13*1000 > 2^22, + * (2) host->timeout_clk < 2^16 + * => + * (1) / (2) > 2^6 + */ + count = 0; + current_timeout = (1 << 13) * 1000 / host->timeout_clk; + while (current_timeout < target_timeout) { + count++; + current_timeout <<= 1; + if (count >= 0xF) + break; + } + + /* + * Compensate for an off-by-one error in the CaFe hardware; otherwise, + * a too-small count gives us interrupt timeouts. + */ + if ((host->chip->quirks & SDHCI_QUIRK_INCR_TIMEOUT_CONTROL)) + count++; + + if (count >= 0xF) { + DBG(KERN_WARNING "%s: Too large timeout requested!\n", + mmc_hostname(host->mmc)); + count = 0xE; + } + + /* Set the max time-out value to level up the compatibility */ + count = 0xE; + + count = + (count << 16) | (readl(host->ioaddr + SDHCI_CLOCK_CONTROL) & + 0xFFF0FFFF); + writel(count, host->ioaddr + SDHCI_CLOCK_CONTROL); + + if (host->flags & SDHCI_USE_DMA) + host->flags |= SDHCI_REQ_USE_DMA; + + if (unlikely((host->flags & SDHCI_REQ_USE_DMA) && + (host->chip->quirks & SDHCI_QUIRK_32BIT_DMA_SIZE) && + ((data->blksz * data->blocks) & 0x3))) { + DBG("Reverting to PIO because of transfer size (%d)\n", + data->blksz * data->blocks); + host->flags &= ~SDHCI_REQ_USE_DMA; + } + + /* + * The assumption here being that alignment is the same after + * translation to device address space. + */ + if (unlikely((host->flags & SDHCI_REQ_USE_DMA) && + (host->chip->quirks & SDHCI_QUIRK_32BIT_DMA_ADDR) && + (data->sg->offset & 0x3))) { + DBG("Reverting to PIO because of bad alignment\n"); + host->flags &= ~SDHCI_REQ_USE_DMA; + } + + if (cpu_is_mx25() && (data->blksz * data->blocks < 0x10)) { + host->flags &= ~SDHCI_REQ_USE_DMA; + DBG("Reverting to PIO in small data transfer.\n"); + writel(readl(host->ioaddr + SDHCI_INT_ENABLE) + | SDHCI_INT_DATA_AVAIL + | SDHCI_INT_SPACE_AVAIL, + host->ioaddr + SDHCI_INT_ENABLE); + writel(readl(host->ioaddr + SDHCI_SIGNAL_ENABLE) + | SDHCI_INT_DATA_AVAIL + | SDHCI_INT_SPACE_AVAIL, + host->ioaddr + SDHCI_SIGNAL_ENABLE); + } else if (cpu_is_mx25() && (host->flags & SDHCI_USE_DMA)) { + host->flags |= SDHCI_REQ_USE_DMA; + DBG("Reverting to DMA in large data transfer.\n"); + writel(readl(host->ioaddr + SDHCI_INT_ENABLE) + & ~(SDHCI_INT_DATA_AVAIL + | SDHCI_INT_SPACE_AVAIL), + host->ioaddr + SDHCI_INT_ENABLE); + writel(readl(host->ioaddr + SDHCI_SIGNAL_ENABLE) + & ~(SDHCI_INT_DATA_AVAIL + | SDHCI_INT_SPACE_AVAIL), + host->ioaddr + SDHCI_SIGNAL_ENABLE); + } + + if (host->flags & SDHCI_REQ_USE_DMA) { + int i; + struct scatterlist *tsg; + + host->dma_size = data->blocks * data->blksz; + count = + dma_map_sg(mmc_dev(host->mmc), data->sg, data->sg_len, + (data-> + flags & MMC_DATA_READ) ? DMA_FROM_DEVICE : + DMA_TO_DEVICE); + BUG_ON(count != data->sg_len); + DBG("Configure the sg DMA, %s, len is 0x%x, count is %d\n", + (data->flags & MMC_DATA_READ) + ? "DMA_FROM_DEIVCE" : "DMA_TO_DEVICE", host->dma_size, + count); + + /* Make sure the ADMA mode is selected. */ + i = readl(host->ioaddr + SDHCI_HOST_CONTROL); + i |= SDHCI_CTRL_ADMA; + writel(i, host->ioaddr + SDHCI_HOST_CONTROL); + + tsg = data->sg; + /* ADMA mode is used, create the descriptor table */ + for (i = 0; i < count; i++) { + if (tsg->dma_address & 0xFFF) { + DBG(KERN_ERR "ADMA addr isn't 4K aligned.\n"); + DBG(KERN_ERR "0x%x\n", tsg->dma_address); + DBG(KERN_ERR "Changed to Single DMA mode.\n"); + goto Single_DMA; + } + adma_des_table[2 * i] = tsg->length << 12; + adma_des_table[2 * i] |= FSL_ADMA_DES_ATTR_SET; + adma_des_table[2 * i] |= FSL_ADMA_DES_ATTR_VALID; + adma_des_table[2 * i + 1] = tsg->dma_address; + adma_des_table[2 * i + 1] |= FSL_ADMA_DES_ATTR_TRAN; + adma_des_table[2 * i + 1] |= FSL_ADMA_DES_ATTR_VALID; + if (count == (i + 1)) + adma_des_table[2 * i + 1] |= + FSL_ADMA_DES_ATTR_END; + tsg++; + } + + /* Write the physical address to ADMA address reg */ + writel(virt_to_phys(adma_des_table), + host->ioaddr + SDHCI_ADMA_ADDRESS); + Single_DMA: + /* Rollback to the Single DMA mode */ + i = readl(host->ioaddr + SDHCI_HOST_CONTROL); + i &= ~SDHCI_CTRL_ADMA; + writel(i, host->ioaddr + SDHCI_HOST_CONTROL); + /* Single DMA mode is used */ + writel(sg_dma_address(data->sg), + host->ioaddr + SDHCI_DMA_ADDRESS); + } else if ((host->flags & SDHCI_USE_EXTERNAL_DMA) && + (data->blocks * data->blksz >= mxc_wml_value)) { + host->dma_size = data->blocks * data->blksz; + DBG("Configure the External DMA, %s, len is 0x%x\n", + (data->flags & MMC_DATA_READ) + ? "DMA_FROM_DEIVCE" : "DMA_TO_DEVICE", host->dma_size); + + if (data->blksz & 0x3) { + printk(KERN_ERR + "mxc_mci: block size not multiple of 4 bytes\n"); + } + + if (data->flags & MMC_DATA_READ) + host->dma_dir = DMA_FROM_DEVICE; + else + host->dma_dir = DMA_TO_DEVICE; + + host->dma_len = dma_map_sg(mmc_dev(host->mmc), data->sg, + data->sg_len, host->dma_dir); + + if (data->flags & MMC_DATA_READ) { + mxc_dma_sg_config(host->dma, data->sg, data->sg_len, + host->dma_size, MXC_DMA_MODE_READ); + } else { + mxc_dma_sg_config(host->dma, data->sg, data->sg_len, + host->dma_size, MXC_DMA_MODE_WRITE); + } + } else { + host->cur_sg = data->sg; + host->num_sg = data->sg_len; + + host->offset = 0; + host->remain = host->cur_sg->length; + } + + /* We do not handle DMA boundaries, so set it to max (512 KiB) */ + writel((data->blocks << 16) | SDHCI_MAKE_BLKSZ(0, data->blksz), + host->ioaddr + SDHCI_BLOCK_SIZE); +} + +static void sdhci_finish_data(struct sdhci_host *host) +{ + struct mmc_data *data; + u16 blocks; + + BUG_ON(!host->data); + + data = host->data; + host->data = NULL; + + if (host->flags & SDHCI_REQ_USE_DMA) { + dma_unmap_sg(&(host->chip->pdev)->dev, data->sg, data->sg_len, + (data->flags & MMC_DATA_READ) ? DMA_FROM_DEVICE : + DMA_TO_DEVICE); + } + if ((host->flags & SDHCI_USE_EXTERNAL_DMA) && + (host->dma_size >= mxc_wml_value) && (data != NULL)) { + dma_unmap_sg(mmc_dev(host->mmc), data->sg, + host->dma_len, host->dma_dir); + host->dma_size = 0; + } + + /* + * Controller doesn't count down when in single block mode. + */ + if (data->blocks == 1) + blocks = (data->error == 0) ? 0 : 1; + else + blocks = readl(host->ioaddr + SDHCI_BLOCK_COUNT) >> 16; + data->bytes_xfered = data->blksz * data->blocks; + + tasklet_schedule(&host->finish_tasklet); +} + +static void sdhci_send_command(struct sdhci_host *host, struct mmc_command *cmd) +{ + int flags, tmp; + u32 mask; + u32 mode = 0; + unsigned long timeout; + + DBG("sdhci_send_command 0x%x is starting...\n", cmd->opcode); + WARN_ON(host->cmd); + + /* Wait max 10 ms */ + timeout = 500; + + mask = SDHCI_CMD_INHIBIT; + if ((cmd->data != NULL) || (cmd->flags & MMC_RSP_BUSY)) + mask |= SDHCI_DATA_INHIBIT; + + /* We shouldn't wait for data inihibit for stop commands, even + though they might use busy signaling */ + if (host->mrq->data && (cmd == host->mrq->data->stop)) + mask &= ~SDHCI_DATA_INHIBIT; + + while (readl(host->ioaddr + SDHCI_PRESENT_STATE) & mask) { + if (timeout == 0) { + printk(KERN_ERR "%s: Controller never released " + "inhibit bit(s).\n", mmc_hostname(host->mmc)); + sdhci_dumpregs(host); + cmd->error = -EIO; + tasklet_schedule(&host->finish_tasklet); + return; + } + timeout--; + udelay(20); + } + + mod_timer(&host->timer, jiffies + 10 * HZ); + + host->cmd = cmd; + + sdhci_prepare_data(host, cmd->data); + + writel(cmd->arg, host->ioaddr + SDHCI_ARGUMENT); + + /* Set up the transfer mode */ + if (cmd->data != NULL) { + mode = SDHCI_TRNS_BLK_CNT_EN | SDHCI_TRNS_DPSEL; + if (cmd->data->blocks > 1) { + mode |= SDHCI_TRNS_MULTI | SDHCI_TRNS_ACMD12; + if (cmd->opcode == 0x35) { + tmp = readl(host->ioaddr + SDHCI_INT_ENABLE); + tmp &= ~SDHCI_INT_ACMD12ERR; + writel(tmp, host->ioaddr + SDHCI_INT_ENABLE); + } else { + tmp = readl(host->ioaddr + SDHCI_INT_ENABLE); + tmp |= SDHCI_INT_ACMD12ERR; + writel(tmp, host->ioaddr + SDHCI_INT_ENABLE); + } + } + if (cmd->data->flags & MMC_DATA_READ) + mode |= SDHCI_TRNS_READ; + else + mode &= ~SDHCI_TRNS_READ; + if (host->flags & SDHCI_REQ_USE_DMA) + mode |= SDHCI_TRNS_DMA; + if (host->flags & SDHCI_USE_EXTERNAL_DMA) + DBG("Prepare data completely in %s transfer mode.\n", + "EXTTERNAL DMA"); + } + + if ((cmd->flags & MMC_RSP_136) && (cmd->flags & MMC_RSP_BUSY)) { + printk(KERN_ERR "%s: Unsupported response type!\n", + mmc_hostname(host->mmc)); + cmd->error = -EINVAL; + tasklet_schedule(&host->finish_tasklet); + return; + } + + if (!(cmd->flags & MMC_RSP_PRESENT)) + flags = SDHCI_CMD_RESP_NONE; + else if (cmd->flags & MMC_RSP_136) + flags = SDHCI_CMD_RESP_LONG; + else if (cmd->flags & MMC_RSP_BUSY) + flags = SDHCI_CMD_RESP_SHORT_BUSY; + else + flags = SDHCI_CMD_RESP_SHORT; + + if (cmd->flags & MMC_RSP_CRC) + flags |= SDHCI_CMD_CRC; + if (cmd->flags & MMC_RSP_OPCODE) + flags |= SDHCI_CMD_INDEX; + if (cmd->data) + flags |= SDHCI_CMD_DATA; + + mode |= SDHCI_MAKE_CMD(cmd->opcode, flags); + if (host->mmc->ios.bus_width & MMC_BUS_WIDTH_DDR) { + /* Eanble the DDR mode */ + mode |= SDHCI_TRNS_DDR_EN; + } else + mode &= ~SDHCI_TRNS_DDR_EN; + DBG("Complete sending cmd, transfer mode would be 0x%x.\n", mode); + writel(mode, host->ioaddr + SDHCI_TRANSFER_MODE); +} + +static void sdhci_finish_command(struct sdhci_host *host) +{ + int i; + + BUG_ON(host->cmd == NULL); + + if (host->cmd->flags & MMC_RSP_PRESENT) { + if (host->cmd->flags & MMC_RSP_136) { + /* CRC is stripped so we need to do some shifting. */ + for (i = 0; i < 4; i++) { + host->cmd->resp[i] = readl(host->ioaddr + + SDHCI_RESPONSE + (3 - + i) + * 4) << 8; + if (i != 3) + host->cmd->resp[i] |= + readb(host->ioaddr + + SDHCI_RESPONSE + (3 - i) * 4 - + 1); + } + } else { + host->cmd->resp[0] = + readl(host->ioaddr + SDHCI_RESPONSE); + } + } + + host->cmd->error = 0; + + if (host->data && host->data_early) + sdhci_finish_data(host); + + if (!host->cmd->data) + tasklet_schedule(&host->finish_tasklet); + + host->cmd = NULL; +} + +static void sdhci_set_clock(struct sdhci_host *host, unsigned int clock) +{ + /*This variable holds the value of clock divider, prescaler */ + int div = 0, prescaler = 0; + int clk_rate = 0; + u32 clk; + unsigned long timeout; + struct mmc_ios ios = host->mmc->ios; + + if (clock == 0) { + goto out; + } else { + if (!host->plat_data->clk_flg) { + clk_enable(host->clk); + host->plat_data->clk_flg = 1; + } + } + if (clock == host->clock && !(ios.bus_width & MMC_BUS_WIDTH_DDR)) + return; + + clk_rate = clk_get_rate(host->clk); + clk = readl(host->ioaddr + SDHCI_CLOCK_CONTROL) & ~SDHCI_CLOCK_MASK; + if (cpu_is_mx53() || cpu_is_mx50()) + writel(clk | SDHCI_CLOCK_SDCLKFS1, + host->ioaddr + SDHCI_CLOCK_CONTROL); + else + writel(clk, host->ioaddr + SDHCI_CLOCK_CONTROL); + + if (clock == host->min_clk) + prescaler = 16; + else if (cpu_is_mx53() || cpu_is_mx50()) + prescaler = 1; + else + prescaler = 0; + while (prescaler <= 0x80) { + for (div = 0; div <= 0xF; div++) { + int x; + if (prescaler != 0) + x = (clk_rate / (div + 1)) / (prescaler * 2); + else + x = clk_rate / (div + 1); + + DBG("x=%d, clock=%d %d\n", x, clock, div); + if (x <= clock) + break; + } + if (div < 0x10) + break; + if (prescaler == 0) + prescaler = 1; + else + prescaler <<= 1; + } + DBG("prescaler = 0x%x, divider = 0x%x\n", prescaler, div); + clk |= (prescaler << 8) | (div << 4); + + /* Configure the DLL when DDR mode is enabled */ + if (ios.bus_width & MMC_BUS_WIDTH_DDR) { + /* Make sure that the PER, HLK, IPG are all enabled */ + writel(readl(host->ioaddr + SDHCI_CLOCK_CONTROL) + | SDHCI_CLOCK_IPG_EN + | SDHCI_CLOCK_HLK_EN + | SDHCI_CLOCK_PER_EN, + host->ioaddr + SDHCI_CLOCK_CONTROL); + + /* Enable the DLL and delay chain */ + writel(readl(host->ioaddr + SDHCI_DLL_CONTROL) + | DLL_CTRL_ENABLE, + host->ioaddr + SDHCI_DLL_CONTROL); + + timeout = 1000000; + while (timeout > 0) { + timeout--; + if (readl(host->ioaddr + SDHCI_DLL_STATUS) + & DLL_STS_REF_LOCK) + break; + else if (timeout == 0) + printk(KERN_ERR "DLL REF LOCK Timeout!\n"); + }; + DBG("dll stat: 0x%x\n", readl(host->ioaddr + SDHCI_DLL_STATUS)); + + writel(readl(host->ioaddr + SDHCI_DLL_CONTROL) + | DLL_CTRL_SLV_UP_INT | DLL_CTRL_REF_UP_INT + | DLL_CTRL_SLV_DLY_TAR, + host->ioaddr + SDHCI_DLL_CONTROL); + + timeout = 1000000; + while (timeout > 0) { + timeout--; + if (readl(host->ioaddr + SDHCI_DLL_STATUS) + & DLL_STS_SLV_LOCK) + break; + else if (timeout == 0) + printk(KERN_ERR "DLL SLV LOCK Timeout!\n"); + }; + + writel(readl(host->ioaddr + SDHCI_DLL_CONTROL) + | DLL_CTRL_SLV_FORCE_UPD, + host->ioaddr + SDHCI_DLL_CONTROL); + + writel(readl(host->ioaddr + SDHCI_DLL_CONTROL) + & (~DLL_CTRL_SLV_FORCE_UPD), + host->ioaddr + SDHCI_DLL_CONTROL); + + timeout = 1000000; + while (timeout > 0) { + timeout--; + if (readl(host->ioaddr + SDHCI_DLL_STATUS) + & DLL_STS_REF_LOCK) + break; + else if (timeout == 0) + printk(KERN_ERR "DLL REF LOCK Timeout!\n"); + }; + timeout = 1000000; + while (timeout > 0) { + timeout--; + if (readl(host->ioaddr + SDHCI_DLL_STATUS) + & DLL_STS_SLV_LOCK) + break; + else if (timeout == 0) + printk(KERN_ERR "DLL SLV LOCK Timeout!\n"); + }; + DBG("dll stat: 0x%x\n", readl(host->ioaddr + SDHCI_DLL_STATUS)); + + /* Let the PER, HLK, IPG to be auto-gate */ + writel(readl(host->ioaddr + SDHCI_CLOCK_CONTROL) + & ~(SDHCI_CLOCK_IPG_EN | SDHCI_CLOCK_HLK_EN + | SDHCI_CLOCK_PER_EN), + host->ioaddr + SDHCI_CLOCK_CONTROL); + + } else if (readl(host->ioaddr + SDHCI_DLL_STATUS) & DLL_STS_SLV_LOCK) { + /* reset DLL CTRL */ + writel(readl(host->ioaddr + SDHCI_DLL_CONTROL) | DLL_CTRL_RESET, + host->ioaddr + SDHCI_DLL_CONTROL); + } + + /* Configure the clock control register */ + clk |= + (readl(host->ioaddr + SDHCI_CLOCK_CONTROL) & (~SDHCI_CLOCK_MASK)); + if (host->plat_data->vendor_ver < ESDHC_VENDOR_V22) + writel(clk, host->ioaddr + SDHCI_CLOCK_CONTROL); + else + writel(clk | SDHCI_CLOCK_SD_EN, + host->ioaddr + SDHCI_CLOCK_CONTROL); + + /* Wait max 10 ms */ + timeout = 500; + while (timeout > 0) { + timeout--; + udelay(20); + } + + out: + if (prescaler != 0) + host->clock = (clk_rate / (div + 1)) / (prescaler * 2); + else + host->clock = clk_rate / (div + 1); +} + +static void sdhci_set_power(struct sdhci_host *host, unsigned short power) +{ + int voltage = 0; + + /* There is no PWR CTL REG */ + if (host->power == power) + return; + + if (host->regulator_mmc) { + if (power == (unsigned short)-1) { + regulator_disable(host->regulator_mmc); + DBG("mmc power off\n"); + } else { + if (power == 7) + voltage = 1800000; + else if (power >= 8) + voltage = 2000000 + (power - 8) * 100000; + regulator_set_voltage(host->regulator_mmc, + voltage, voltage); + + if (regulator_enable(host->regulator_mmc) == 0) { + DBG("mmc power on\n"); + msleep(1); + } + } + } + + host->power = power; +} + +/*****************************************************************************\ + * * + * MMC callbacks * + * * +\*****************************************************************************/ + +static void sdhci_request(struct mmc_host *mmc, struct mmc_request *mrq) +{ + struct sdhci_host *host; + unsigned long flags; + + host = mmc_priv(mmc); + + /* Enable the clock */ + if (!host->plat_data->clk_flg) { + clk_enable(host->clk); + host->plat_data->clk_flg = 1; + } + + spin_lock_irqsave(&host->lock, flags); + + WARN_ON(host->mrq != NULL); + + sdhci_activate_led(host); + if (cpu_is_mx35_rev(CHIP_REV_2_0) < 0) { + if (mrq->cmd && mrq->data) { + if (mrq->data->flags & MMC_DATA_READ) + last_op_dir = 1; + else { + if (last_op_dir) + sdhci_reset(host, + SDHCI_RESET_CMD | + SDHCI_RESET_DATA); + } + } + } + + if (host->flags & SDHCI_USE_EXTERNAL_DMA) + spin_unlock_irqrestore(&host->lock, flags); + + host->mrq = mrq; + if (!(host->flags & SDHCI_CD_PRESENT)) { + host->mrq->cmd->error = -ENOMEDIUM; + tasklet_schedule(&host->finish_tasklet); + } else + sdhci_send_command(host, mrq->cmd); + + if (!(host->flags & SDHCI_USE_EXTERNAL_DMA)) + spin_unlock_irqrestore(&host->lock, flags); + + mmiowb(); +} + +static void sdhci_set_ios(struct mmc_host *mmc, struct mmc_ios *ios) +{ + struct sdhci_host *host; + unsigned long flags; + u32 tmp; + mxc_dma_device_t dev_id = 0; + + DBG("%s: clock %u, bus %u, power %u, vdd %u\n", DRIVER_NAME, + ios->clock, ios->bus_width, ios->power_mode, ios->vdd); + + host = mmc_priv(mmc); + + /* Configure the External DMA mode */ + if (host->flags & SDHCI_USE_EXTERNAL_DMA) { + host->dma_dir = DMA_NONE; + if (mmc->ios.bus_width != host->mode) { + mxc_dma_free(host->dma); + if (mmc->ios.bus_width == MMC_BUS_WIDTH_4) { + if (host->id == 0) + dev_id = MXC_DMA_MMC1_WIDTH_4; + else + dev_id = MXC_DMA_MMC2_WIDTH_4; + } else { + if (host->id == 0) + dev_id = MXC_DMA_MMC1_WIDTH_1; + else + dev_id = MXC_DMA_MMC2_WIDTH_1; + } + host->dma = mxc_dma_request(dev_id, "MXC MMC"); + if (host->dma < 0) + DBG("Cannot allocate MMC DMA channel\n"); + mxc_dma_callback_set(host->dma, sdhci_dma_irq, + (void *)host); + /* Configure the WML rege */ + if (mxc_wml_value == 512) + writel(SDHCI_WML_128_WORDS, + host->ioaddr + SDHCI_WML); + else + writel(SDHCI_WML_16_WORDS, + host->ioaddr + SDHCI_WML); + } + } + + host->mode = mmc->ios.bus_width; + + spin_lock_irqsave(&host->lock, flags); + + /* + * Reset the chip on each power off. + * Should clear out any weird states. + */ + if (ios->power_mode == MMC_POWER_OFF) { + writel(0, host->ioaddr + SDHCI_SIGNAL_ENABLE); + sdhci_init(host); + } + + sdhci_set_clock(host, ios->clock); + + if (ios->power_mode == MMC_POWER_OFF) + sdhci_set_power(host, -1); + else { + sdhci_set_power(host, ios->vdd); + if (!readl(host->ioaddr + SDHCI_SIGNAL_ENABLE)) { + tmp = readl(host->ioaddr + SDHCI_INT_ENABLE); + if (host->sdio_enable) + writel(tmp, host->ioaddr + SDHCI_SIGNAL_ENABLE); + else + writel(tmp & ~SDHCI_INT_CARD_INT, + host->ioaddr + SDHCI_SIGNAL_ENABLE); + } + } + + tmp = readl(host->ioaddr + SDHCI_HOST_CONTROL); + + if ((ios->bus_width & ~MMC_BUS_WIDTH_DDR) == MMC_BUS_WIDTH_4) { + tmp &= ~SDHCI_CTRL_8BITBUS; + tmp |= SDHCI_CTRL_4BITBUS; + } else if ((ios->bus_width & ~MMC_BUS_WIDTH_DDR) == MMC_BUS_WIDTH_8) { + tmp &= ~SDHCI_CTRL_4BITBUS; + tmp |= SDHCI_CTRL_8BITBUS; + } else if (ios->bus_width == MMC_BUS_WIDTH_1) { + tmp &= ~SDHCI_CTRL_4BITBUS; + tmp &= ~SDHCI_CTRL_8BITBUS; + } + + if (host->flags & SDHCI_USE_DMA) + tmp |= SDHCI_CTRL_ADMA; + + writel(tmp, host->ioaddr + SDHCI_HOST_CONTROL); + + /* + * Some (ENE) controllers go apeshit on some ios operation, + * signalling timeout and CRC errors even on CMD0. Resetting + * it on each ios seems to solve the problem. + */ + if (host->chip->quirks & SDHCI_QUIRK_RESET_CMD_DATA_ON_IOS) + sdhci_reset(host, SDHCI_RESET_CMD | SDHCI_RESET_DATA); + + mmiowb(); + spin_unlock_irqrestore(&host->lock, flags); +} + +static int sdhci_get_ro(struct mmc_host *mmc) +{ + struct sdhci_host *host; + + host = mmc_priv(mmc); + + if (host->plat_data->wp_status) + return host->plat_data->wp_status(mmc->parent); + else + return 0; +} + +static void sdhci_enable_sdio_irq(struct mmc_host *mmc, int enable) +{ + struct sdhci_host *host; + unsigned long flags; + u32 ier, prot, clk, present; + + host = mmc_priv(mmc); + + spin_lock_irqsave(&host->lock, flags); + + if (enable) { + if (host->sdio_enable++) + goto exit_unlock; + } else { + if (--(host->sdio_enable)) + goto exit_unlock; + } + /* Enable the clock */ + if (!host->plat_data->clk_flg) { + clk_enable(host->clk); + host->plat_data->clk_flg = 1; + } + ier = readl(host->ioaddr + SDHCI_SIGNAL_ENABLE); + prot = readl(host->ioaddr + SDHCI_HOST_CONTROL); + clk = readl(host->ioaddr + SDHCI_CLOCK_CONTROL); + + if (enable) { + ier |= SDHCI_INT_CARD_INT; + prot |= SDHCI_CTRL_D3CD; + clk |= SDHCI_CLOCK_PER_EN | SDHCI_CLOCK_IPG_EN; + present = readl(host->ioaddr + SDHCI_PRESENT_STATE); + if ((present & SDHCI_CARD_INT_MASK) != SDHCI_CARD_INT_ID) + writel(SDHCI_INT_CARD_INT, + host->ioaddr + SDHCI_INT_STATUS); + } else { + ier &= ~SDHCI_INT_CARD_INT; + prot &= ~SDHCI_CTRL_D3CD; + clk &= ~(SDHCI_CLOCK_PER_EN | SDHCI_CLOCK_IPG_EN); + } + + writel(prot, host->ioaddr + SDHCI_HOST_CONTROL); + writel(ier, host->ioaddr + SDHCI_SIGNAL_ENABLE); + writel(clk, host->ioaddr + SDHCI_CLOCK_CONTROL); + + mmiowb(); + exit_unlock: + spin_unlock_irqrestore(&host->lock, flags); +} + +static const struct mmc_host_ops sdhci_ops = { + .request = sdhci_request, + .set_ios = sdhci_set_ios, + .get_ro = sdhci_get_ro, + .enable_sdio_irq = sdhci_enable_sdio_irq, +}; + +/*****************************************************************************\ + * * + * Tasklets * + * * +\*****************************************************************************/ + +static void sdhci_tasklet_card(unsigned long param) +{ + struct sdhci_host *host; + unsigned long flags; + unsigned int cd_status = 0; + + host = (struct sdhci_host *)param; + + if (host->flags & SDHCI_CD_PRESENT) + host->flags &= ~SDHCI_CD_PRESENT; + else + host->flags |= SDHCI_CD_PRESENT; + /* Detect there is a card in slot or not */ + DBG("cd_status=%d %s\n", cd_status, + (host->flags & SDHCI_CD_PRESENT) ? "inserted" : "removed"); + + spin_lock_irqsave(&host->lock, flags); + + if (!(host->flags & SDHCI_CD_PRESENT)) { + if (host->mrq) { + printk(KERN_ERR "%s: Card removed during transfer!\n", + mmc_hostname(host->mmc)); + printk(KERN_ERR "%s: Resetting controller.\n", + mmc_hostname(host->mmc)); + + sdhci_reset(host, SDHCI_RESET_CMD); + sdhci_reset(host, SDHCI_RESET_DATA); + + host->mrq->cmd->error = -ENOMEDIUM; + tasklet_schedule(&host->finish_tasklet); + } + } + + spin_unlock_irqrestore(&host->lock, flags); + + mmc_detect_change(host->mmc, msecs_to_jiffies(200)); +} + +static void sdhci_tasklet_finish(unsigned long param) +{ + struct sdhci_host *host; + unsigned long flags; + int req_done; + struct mmc_request *mrq; + + host = (struct sdhci_host *)param; + + spin_lock_irqsave(&host->lock, flags); + + del_timer(&host->timer); + + mrq = host->mrq; + + /* + * The controller needs a reset of internal state machines + * upon error conditions. + */ + if (mrq->cmd->error || + (mrq->data && (mrq->data->error || + (mrq->data->stop && mrq->data->stop->error))) || + (host->chip->quirks & SDHCI_QUIRK_RESET_AFTER_REQUEST)) { + + /* Some controllers need this kick or reset won't work here */ + if (host->chip->quirks & SDHCI_QUIRK_CLOCK_BEFORE_RESET) { + unsigned int clock; + + /* This is to force an update */ + clock = host->clock; + host->clock = 0; + sdhci_set_clock(host, clock); + } + + /* Spec says we should do both at the same time, but Ricoh + controllers do not like that. */ + sdhci_reset(host, SDHCI_RESET_CMD); + sdhci_reset(host, SDHCI_RESET_DATA); + } + + host->mrq = NULL; + host->cmd = NULL; + host->data = NULL; + + sdhci_deactivate_led(host); + + mmiowb(); + spin_unlock_irqrestore(&host->lock, flags); + + /* Stop the clock when the req is done */ + req_done = !(readl(host->ioaddr + SDHCI_PRESENT_STATE) & + (SDHCI_DATA_ACTIVE | SDHCI_DOING_WRITE | SDHCI_DOING_READ)); + /* Do not disable the eSDHC clk on MX35 3DS board, + * since SYSTEM can't boot up after the reset key + * is pressed when the SD/MMC boot mode is used. + * The root cause is that the ROM code don't ensure + * the SD/MMC clk is running when boot system. + * */ + if (!machine_is_mx35_3ds() && req_done && host->plat_data->clk_flg && + !(host->mmc && host->mmc->card && mmc_card_sdio(host->mmc->card))) { + clk_disable(host->clk); + host->plat_data->clk_flg = 0; + } + mmc_request_done(host->mmc, mrq); +} + +static void sdhci_timeout_timer(unsigned long data) +{ + struct sdhci_host *host; + unsigned long tmp, flags; + + host = (struct sdhci_host *)data; + + spin_lock_irqsave(&host->lock, flags); + + if (host->mrq) { + printk(KERN_ERR "%s: Timeout waiting for hardware " + "interrupt.\n", mmc_hostname(host->mmc)); + sdhci_dumpregs(host); + + if (host->data) { + host->data->error = -ETIMEDOUT; + sdhci_finish_data(host); + } else { + if (host->cmd) + host->cmd->error = -ETIMEDOUT; + else + host->mrq->cmd->error = -ETIMEDOUT; + + tasklet_schedule(&host->finish_tasklet); + } + + if (!readl(host->ioaddr + SDHCI_SIGNAL_ENABLE)) { + printk(KERN_ERR "%s, ERROR SIG_INT is 0.\n", __func__); + tmp = readl(host->ioaddr + SDHCI_INT_ENABLE); + if (host->sdio_enable) + writel(tmp, host->ioaddr + SDHCI_SIGNAL_ENABLE); + else + writel(tmp & ~SDHCI_INT_CARD_INT, + host->ioaddr + SDHCI_SIGNAL_ENABLE); + if (!host->plat_data->status(host->mmc->parent)) + schedule_work(&host->cd_wq); + } + } + + mmiowb(); + spin_unlock_irqrestore(&host->lock, flags); +} + +static void sdhci_cd_timer(unsigned long data) +{ + struct sdhci_host *host; + + host = (struct sdhci_host *)data; + host->flags |= SDHCI_CD_TIMEOUT; + schedule_work(&host->cd_wq); +} + +/*****************************************************************************\ + * * + * Interrupt handling * + * * +\*****************************************************************************/ + +static void sdhci_cmd_irq(struct sdhci_host *host, u32 intmask) +{ + BUG_ON(intmask == 0); + + if (!host->cmd) { + printk(KERN_ERR "%s: Got command interrupt 0x%08x even " + "though no command operation was in progress.\n", + mmc_hostname(host->mmc), (unsigned)intmask); + sdhci_dumpregs(host); + return; + } + + if (intmask & SDHCI_INT_TIMEOUT) + host->cmd->error = -ETIMEDOUT; + else if (intmask & (SDHCI_INT_CRC | SDHCI_INT_END_BIT | + SDHCI_INT_INDEX)) + host->cmd->error = -EILSEQ; + + if (intmask & SDHCI_INT_ACMD12ERR) { + int tmp = 0; + tmp = readl(host->ioaddr + SDHCI_ACMD12_ERR); + if (tmp & (SDHCI_ACMD12_ERR_CE | SDHCI_ACMD12_ERR_IE | + SDHCI_ACMD12_ERR_EBE)) + host->cmd->error = -EILSEQ; + else if (tmp & SDHCI_ACMD12_ERR_TOE) + host->cmd->error = -ETIMEDOUT; + } + + if (host->cmd->error) + tasklet_schedule(&host->finish_tasklet); + else if (intmask & SDHCI_INT_RESPONSE) + sdhci_finish_command(host); +} + +static void sdhci_data_irq(struct sdhci_host *host, u32 intmask) +{ + u32 intsave = 0; + + BUG_ON(intmask == 0); + + if (!host->data) { + /* + * A data end interrupt is sent together with the response + * for the stop command. + */ + if (intmask & SDHCI_INT_DATA_END) + return; + + printk(KERN_ERR "%s: Got data interrupt 0x%08x even " + "though no data operation was in progress.\n", + mmc_hostname(host->mmc), (unsigned)intmask); + sdhci_dumpregs(host); + sdhci_reset(host, SDHCI_RESET_CMD); + sdhci_reset(host, SDHCI_RESET_DATA); + return; + } + + /* Mask the INT */ + intsave = readl(host->ioaddr + SDHCI_INT_ENABLE); + writel(intsave & (~(intmask & SDHCI_INT_DATA_RE_MASK)), + host->ioaddr + SDHCI_INT_ENABLE); + + if (intmask & SDHCI_INT_DATA_TIMEOUT) + host->data->error = -ETIMEDOUT; + else if (intmask & (SDHCI_INT_DATA_CRC | SDHCI_INT_DATA_END_BIT)) + host->data->error = -EILSEQ; + + if (host->data->error) + sdhci_finish_data(host); + else { + if ((host->flags & SDHCI_USE_EXTERNAL_DMA) && + (host->dma_size >= mxc_wml_value)) { + /* Use DMA if transfer size is greater than fifo size */ + if (intmask & (SDHCI_INT_DATA_AVAIL | + SDHCI_INT_SPACE_AVAIL)) { + intsave &= ~SDHCI_INT_DATA_RE_MASK; + if (mxc_dma_enable(host->dma) < 0) { + printk(KERN_ERR "ENABLE SDMA ERR.\n"); + intsave |= SDHCI_INT_DATA_RE_MASK; + } + } + } else { + if (intmask & (SDHCI_INT_DATA_AVAIL | + SDHCI_INT_SPACE_AVAIL)) + sdhci_transfer_pio(host); + } + + /* + * We currently don't do anything fancy with DMA + * boundaries, but as we can't disable the feature + * we need to at least restart the transfer. + */ + if ((intmask & SDHCI_INT_DMA_END) && + (!(intmask & SDHCI_INT_DATA_END))) + writel(readl(host->ioaddr + SDHCI_DMA_ADDRESS), + host->ioaddr + SDHCI_DMA_ADDRESS); + + if (intmask & SDHCI_INT_DATA_END) { + if (host->data->flags & MMC_DATA_READ) + writel(readl(host->ioaddr + SDHCI_CLOCK_CONTROL) + & ~SDHCI_CLOCK_HLK_EN, + host->ioaddr + SDHCI_CLOCK_CONTROL); + if (host->cmd) { + /* + * Data managed to finish before the + * command completed. Make sure we do + * things in the proper order. + */ + host->data_early = 1; + } else { + + if (host->plat_data->vendor_ver + < ESDHC_VENDOR_V22) { + /* + * There are the DATA END INT when + * writing is not complete. Double + * check on it. TO2 has been fixed it. + */ + intmask = readl(host->ioaddr + + SDHCI_PRESENT_STATE); + if (intmask & SDHCI_DATA_ACTIVE) + goto data_irq_out; + } + sdhci_finish_data(host); + } + } + } + data_irq_out: + /* Enable the INT */ + writel(intsave, host->ioaddr + SDHCI_INT_ENABLE); +} + +/*! +* This function is called by DMA Interrupt Service Routine to indicate +* requested DMA transfer is completed. +* +* @param devid pointer to device specific structure +* @param error any DMA error +* @param cnt amount of data that was transferred +*/ +static void sdhci_dma_irq(void *devid, int error, unsigned int cnt) +{ + u32 intsave = 0; + int ret; + struct sdhci_host *host = devid; + + DBG("%s: error: %d Transferred bytes:%d\n", DRIVER_NAME, error, cnt); + if (host->flags & SDHCI_USE_EXTERNAL_DMA) { + /* + * Stop the DMA transfer here, the data_irq would be called + * to process the others + */ + ret = mxc_dma_disable(host->dma); + if (ret < 0) + printk(KERN_ERR "Disable dma channel err %d\n", ret); + + if (error) { + DBG("Error in DMA transfer\n"); + return; + } + intsave = readl(host->ioaddr + SDHCI_INT_ENABLE); + intsave |= SDHCI_INT_DATA_RE_MASK; + writel(intsave, host->ioaddr + SDHCI_INT_ENABLE); + } +} + +/* woke queue handler func */ +static void esdhc_cd_callback(struct work_struct *work) +{ + unsigned long flags; + unsigned int cd_status = 0; + struct sdhci_host *host = container_of(work, struct sdhci_host, cd_wq); + + do { + if (host->detect_irq == 0) + break; + cd_status = host->plat_data->status(host->mmc->parent); + if (cd_status) + set_irq_type(host->detect_irq, IRQF_TRIGGER_FALLING); + else + set_irq_type(host->detect_irq, IRQF_TRIGGER_RISING); + } while (cd_status != host->plat_data->status(host->mmc->parent)); + + cd_status = host->plat_data->status(host->mmc->parent); + + DBG("cd_status=%d %s\n", cd_status, cd_status ? "removed" : "inserted"); + /* If there is no card, call the card detection func + * immediately. */ + if (!cd_status) { + /* If there is a card in the slot, the timer is start + * to work. Then the card detection would be carried + * after the timer is timeout. + * */ + if (host->flags & SDHCI_CD_TIMEOUT) + host->flags &= ~SDHCI_CD_TIMEOUT; + else { + mod_timer(&host->cd_timer, jiffies + HZ / 4); + return; + } + } + + cd_status = host->plat_data->status(host->mmc->parent); + if (cd_status) + host->flags &= ~SDHCI_CD_PRESENT; + else + host->flags |= SDHCI_CD_PRESENT; + /* Detect there is a card in slot or not */ + DBG("cd_status=%d %s\n", cd_status, + (host->flags & SDHCI_CD_PRESENT) ? "inserted" : "removed"); + + spin_lock_irqsave(&host->lock, flags); + + if (!(host->flags & SDHCI_CD_PRESENT)) { + printk(KERN_INFO + "%s: Card removed and resetting controller.\n", + mmc_hostname(host->mmc)); + if (host->mrq) { + struct mmc_data *data; + data = host->data; + host->data = NULL; + + printk(KERN_ERR + "%s: Card removed during transfer!\n", + mmc_hostname(host->mmc)); + printk(KERN_ERR + "%s: Resetting controller.\n", + mmc_hostname(host->mmc)); + + if ((host->flags & SDHCI_USE_EXTERNAL_DMA) && + (data != NULL)) { + dma_unmap_sg(mmc_dev(host->mmc), data->sg, + host->dma_len, host->dma_dir); + host->dma_size = 0; + } + sdhci_reset(host, SDHCI_RESET_CMD); + sdhci_reset(host, SDHCI_RESET_DATA); + + host->mrq->cmd->error = -ENOMEDIUM; + tasklet_schedule(&host->finish_tasklet); + } + + if (host->init_flag > 0) + /* The initialization of sdhc controller has been + * done in the resume func */ + host->init_flag--; + else + sdhci_init(host); + } + + spin_unlock_irqrestore(&host->lock, flags); + + if (host->flags & SDHCI_CD_PRESENT) { + del_timer(&host->cd_timer); + mmc_detect_change(host->mmc, msecs_to_jiffies(100)); + } else + mmc_detect_change(host->mmc, 0); +} + +/*! +* Card detection interrupt service routine registered to handle +* the SDHC interrupts. This interrupt routine handles card +* insertion and card removal interrupts. +* +* @param irq the interrupt number +* @param devid driver private data +* +* @return The function returns \b IRQ_RETVAL(1) +*/ +static irqreturn_t sdhci_cd_irq(int irq, void *dev_id) +{ + struct sdhci_host *host = dev_id; + + schedule_work(&host->cd_wq); + + return IRQ_HANDLED; +} + +static irqreturn_t sdhci_irq(int irq, void *dev_id) +{ + irqreturn_t result; + struct sdhci_host *host = dev_id; + u32 intmask; + int cardint = 0; + + spin_lock(&host->lock); + + intmask = readl(host->ioaddr + SDHCI_INT_STATUS); + + if (!intmask || intmask == 0xffffffff) { + result = IRQ_NONE; + goto out; + } + + DBG("*** %s got interrupt: 0x%08x\n", mmc_hostname(host->mmc), intmask); + + if (intmask & (SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE)) { + writel(intmask & + (SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE), + host->ioaddr + SDHCI_INT_STATUS); + tasklet_schedule(&host->card_tasklet); + } + + intmask &= ~(SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE); + + if (intmask & SDHCI_INT_CMD_MASK) { + writel(intmask & SDHCI_INT_CMD_MASK, + host->ioaddr + SDHCI_INT_STATUS); + sdhci_cmd_irq(host, intmask & SDHCI_INT_CMD_MASK); + } + + if (intmask & SDHCI_INT_DATA_MASK) { + writel(intmask & SDHCI_INT_DATA_MASK, + host->ioaddr + SDHCI_INT_STATUS); + if (cpu_is_mx35_rev(CHIP_REV_2_0) < 0) { + if (! + (readl(host->ioaddr + SDHCI_TRANSFER_MODE) & + SDHCI_TRNS_READ)) + intmask &= ~SDHCI_INT_DATA_END_BIT; + } + if (intmask & SDHCI_INT_DATA_MASK) + sdhci_data_irq(host, intmask & SDHCI_INT_DATA_MASK); + } + + intmask &= ~(SDHCI_INT_CMD_MASK | SDHCI_INT_DATA_MASK); + + intmask &= ~SDHCI_INT_ERROR; + + if (intmask & SDHCI_INT_BUS_POWER) { + printk(KERN_ERR "%s: Card is consuming too much power!\n", + mmc_hostname(host->mmc)); + writel(SDHCI_INT_BUS_POWER, host->ioaddr + SDHCI_INT_STATUS); + } + + intmask &= ~SDHCI_INT_BUS_POWER; + + if (intmask & SDHCI_INT_CARD_INT) + cardint = readl(host->ioaddr + SDHCI_SIGNAL_ENABLE) & + SDHCI_INT_CARD_INT; + + intmask &= ~SDHCI_INT_CARD_INT; + + if (intmask) { + printk(KERN_ERR "%s: Unexpected interrupt 0x%08x.\n", + mmc_hostname(host->mmc), intmask); + sdhci_dumpregs(host); + + writel(intmask, host->ioaddr + SDHCI_INT_STATUS); + } + + result = IRQ_HANDLED; + + mmiowb(); + out: + spin_unlock(&host->lock); + + /* + * We have to delay this as it calls back into the driver. + */ + if (cardint) + mmc_signal_sdio_irq(host->mmc); + + return result; +} + +/*****************************************************************************\ + * * + * Suspend/resume * + * * +\*****************************************************************************/ + +#ifdef CONFIG_PM + +static int sdhci_suspend(struct platform_device *pdev, pm_message_t state) +{ + struct sdhci_chip *chip; + int i, ret; + + chip = dev_get_drvdata(&pdev->dev); + if (!chip) + return 0; + + DBG("Suspending...\n"); + + for (i = 0; i < chip->num_slots; i++) { + if (!chip->hosts[i]) + continue; + ret = mmc_suspend_host(chip->hosts[i]->mmc); + if (ret) { + for (i--; i >= 0; i--) + mmc_resume_host(chip->hosts[i]->mmc); + return ret; + } + } + + for (i = 0; i < chip->num_slots; i++) { + if (!chip->hosts[i]) + continue; + free_irq(chip->hosts[i]->irq, chip->hosts[i]); + } + + return 0; +} + +static int sdhci_resume(struct platform_device *pdev) +{ + struct sdhci_chip *chip; + int i, ret; + + chip = dev_get_drvdata(&pdev->dev); + if (!chip) + return 0; + + DBG("Resuming...\n"); + + for (i = 0; i < chip->num_slots; i++) { + if (!chip->hosts[i]) + continue; + ret = request_irq(chip->hosts[i]->irq, sdhci_irq, + IRQF_SHARED, + mmc_hostname(chip->hosts[i]->mmc), + chip->hosts[i]); + if (ret) + return ret; + sdhci_init(chip->hosts[i]); + chip->hosts[i]->init_flag = 2; + mmiowb(); + ret = mmc_resume_host(chip->hosts[i]->mmc); + if (ret) + return ret; + } + + return 0; +} + +#else /* CONFIG_PM */ + +#define sdhci_suspend NULL +#define sdhci_resume NULL + +#endif /* CONFIG_PM */ + +/*****************************************************************************\ + * * + * Device probing/removal * + * * +\*****************************************************************************/ + +static int __devinit sdhci_probe_slot(struct platform_device + *pdev, int slot) +{ + struct mxc_mmc_platform_data *mmc_plat = pdev->dev.platform_data; + int ret = 0; + unsigned int version, caps; + struct sdhci_chip *chip; + struct mmc_host *mmc; + struct sdhci_host *host; + mxc_dma_device_t dev_id = 0; + + if (!mmc_plat) + return -EINVAL; + + chip = dev_get_drvdata(&pdev->dev); + BUG_ON(!chip); + + mmc = mmc_alloc_host(sizeof(struct sdhci_host), &pdev->dev); + if (!mmc) + return -ENOMEM; + + host = mmc_priv(mmc); + host->mmc = mmc; + host->id = pdev->id; + host->dma = -1; + host->plat_data = mmc_plat; + if (!host->plat_data) { + ret = -EINVAL; + goto out0; + } + + host->chip = chip; + chip->hosts[slot] = host; + + /* Get pwr supply for eSDHC */ + if (NULL != mmc_plat->power_mmc) { + host->regulator_mmc = + regulator_get(&pdev->dev, mmc_plat->power_mmc); + if (IS_ERR(host->regulator_mmc)) { + ret = PTR_ERR(host->regulator_mmc); + goto out1; + } + if (regulator_enable(host->regulator_mmc) == 0) { + DBG("mmc power on\n"); + msleep(1); + } + } + + /* Active the eSDHC bus */ + gpio_sdhc_active(pdev->id); + + /* Get the SDHC clock from clock system APIs */ + host->clk = clk_get(&pdev->dev, mmc_plat->clock_mmc); + if (NULL == host->clk) + printk(KERN_ERR "MXC MMC can't get clock.\n"); + DBG("SDHC:%d clock:%lu\n", pdev->id, clk_get_rate(host->clk)); + + host->res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!host->res) { + ret = -ENOMEM; + goto out2; + } + host->irq = platform_get_irq(pdev, 0); + if (!host->irq) { + ret = -ENOMEM; + goto out2; + } + host->detect_irq = platform_get_irq(pdev, 1); + if (!host->detect_irq) { + if (mmc_plat->card_inserted_state) + host->flags |= SDHCI_CD_PRESENT; + else + host->flags &= ~SDHCI_CD_PRESENT; + if ((pdev->id >= 0) && (pdev->id < MXC_SDHCI_NUM)) + mxc_fix_chips[pdev->id] = chip; + goto no_detect_irq; + } + + do { + ret = host->plat_data->status(host->mmc->parent); + if (ret) + set_irq_type(host->detect_irq, IRQF_TRIGGER_FALLING); + else + set_irq_type(host->detect_irq, IRQF_TRIGGER_RISING); + } while (ret != host->plat_data->status(host->mmc->parent)); + + ret = host->plat_data->status(host->mmc->parent); + if (ret) + host->flags &= ~SDHCI_CD_PRESENT; + else + host->flags |= SDHCI_CD_PRESENT; + + no_detect_irq: + DBG("slot %d at 0x%x, irq %d \n", slot, host->res->start, host->irq); + if (!request_mem_region(host->res->start, + host->res->end - + host->res->start + 1, pdev->name)) { + printk(KERN_ERR "request_mem_region failed\n"); + ret = -ENOMEM; + goto out2; + } + host->ioaddr = (void *)ioremap(host->res->start, host->res->end - + host->res->start + 1); + if (!host->ioaddr) { + ret = -ENOMEM; + goto out3; + } + + sdhci_reset(host, SDHCI_RESET_ALL); + + version = readl(host->ioaddr + SDHCI_HOST_VERSION); + host->plat_data->vendor_ver = (version & SDHCI_VENDOR_VER_MASK) >> + SDHCI_VENDOR_VER_SHIFT; + version = (version & SDHCI_SPEC_VER_MASK) >> SDHCI_SPEC_VER_SHIFT; + if (version != 1) { + printk(KERN_ERR "%s: Unknown controller version (%d). " + "You may experience problems.\n", mmc_hostname(mmc), + version); + } + + caps = readl(host->ioaddr + SDHCI_CAPABILITIES); + + if (chip->quirks & SDHCI_QUIRK_FORCE_DMA) + host->flags |= SDHCI_USE_DMA; + else if (!(caps & SDHCI_CAN_DO_DMA)) + DBG("Controller doesn't have DMA capability\n"); + else if (chip-> + quirks & (SDHCI_QUIRK_INTERNAL_ADVANCED_DMA | + SDHCI_QUIRK_INTERNAL_SIMPLE_DMA)) + host->flags |= SDHCI_USE_DMA; + else if (chip->quirks & (SDHCI_QUIRK_EXTERNAL_DMA_MODE)) + host->flags |= SDHCI_USE_EXTERNAL_DMA; + else + host->flags &= ~SDHCI_USE_DMA; + + /* + * These definitions of eSDHC are not compatible with the SD Host + * Controller Spec v2.0 + */ + host->min_clk = mmc_plat->min_clk; + host->max_clk = mmc_plat->max_clk; + host->timeout_clk = 1024 * 1000; /* Just set the value temply. */ + + /* + * Set host parameters. + */ + mmc->ops = &sdhci_ops; + mmc->f_min = host->min_clk; + mmc->f_max = host->max_clk; + mmc->caps = MMC_CAP_SDIO_IRQ; + mmc->caps |= mmc_plat->caps; + + if (caps & SDHCI_CAN_DO_HISPD) + mmc->caps |= MMC_CAP_SD_HIGHSPEED | MMC_CAP_MMC_HIGHSPEED; + + mmc->ocr_avail = mmc_plat->ocr_mask; + if (caps & SDHCI_CAN_VDD_330) + mmc->ocr_avail |= MMC_VDD_32_33 | MMC_VDD_33_34; + if (caps & SDHCI_CAN_VDD_300) + mmc->ocr_avail |= MMC_VDD_29_30 | MMC_VDD_30_31; + if (caps & SDHCI_CAN_VDD_180) + mmc->ocr_avail |= MMC_VDD_165_195; + + if (mmc->ocr_avail == 0) { + printk(KERN_ERR "%s: Hardware doesn't report any " + "support voltages.\n", mmc_hostname(mmc)); + ret = -ENODEV; + goto out3; + } + + spin_lock_init(&host->lock); + + /* + * Maximum number of segments. Hardware cannot do scatter lists. + */ + if (host->flags & SDHCI_USE_DMA) + mmc->max_hw_segs = 1; + else + mmc->max_hw_segs = 16; + mmc->max_phys_segs = 16; + + /* + * Maximum number of sectors in one transfer. Limited by DMA boundary + * size (512KiB). + */ + if (host->flags & SDHCI_USE_EXTERNAL_DMA) + mmc->max_req_size = 32 * 1024; + else + mmc->max_req_size = 524288; + + /* + * Maximum segment size. Could be one segment with the maximum number + * of bytes. + */ + mmc->max_seg_size = mmc->max_req_size; + + /* + * Maximum block size. This varies from controller to controller and + * is specified in the capabilities register. + */ + mmc->max_blk_size = + (caps & SDHCI_MAX_BLOCK_MASK) >> SDHCI_MAX_BLOCK_SHIFT; + if (mmc->max_blk_size > 3) { + printk(KERN_WARNING "%s: Invalid maximum block size, " + "assuming 512 bytes\n", mmc_hostname(mmc)); + mmc->max_blk_size = 512; + } else + mmc->max_blk_size = 512 << mmc->max_blk_size; + + /* + * Maximum block count. + */ + mmc->max_blk_count = 65535; + + /* + * Apply a continous physical memory used for storing the ADMA + * descriptor table. + */ + if (host->flags & SDHCI_USE_DMA) { + adma_des_table = kcalloc((2 * (mmc->max_phys_segs) + 1), + sizeof(unsigned int), GFP_DMA); + if (adma_des_table == NULL) { + printk(KERN_ERR "Cannot allocate ADMA memory\n"); + ret = -ENOMEM; + goto out3; + } + } + + /* + * Init tasklets. + */ + tasklet_init(&host->card_tasklet, + sdhci_tasklet_card, (unsigned long)host); + tasklet_init(&host->finish_tasklet, + sdhci_tasklet_finish, (unsigned long)host); + + /* initialize the work queue */ + INIT_WORK(&host->cd_wq, esdhc_cd_callback); + + setup_timer(&host->timer, sdhci_timeout_timer, (unsigned long)host); + setup_timer(&host->cd_timer, sdhci_cd_timer, (unsigned long)host); + + if (host->detect_irq) { + ret = request_irq(host->detect_irq, sdhci_cd_irq, 0, + pdev->name, host); + if (ret) + goto out4; + } + + ret = request_irq(host->irq, sdhci_irq, IRQF_SHARED, pdev->name, host); + if (ret) + goto out5; + + sdhci_init(host); + + if (host->flags & SDHCI_USE_EXTERNAL_DMA) { + /* Apply the 1-bit SDMA channel. */ + if (host->id == 0) + dev_id = MXC_DMA_MMC1_WIDTH_1; + else + dev_id = MXC_DMA_MMC2_WIDTH_1; + host->dma = mxc_dma_request(dev_id, "MXC MMC"); + if (host->dma < 0) { + DBG("Cannot allocate MMC DMA channel\n"); + goto out6; + } + mxc_dma_callback_set(host->dma, sdhci_dma_irq, (void *)host); + } +#ifdef CONFIG_MMC_DEBUG + sdhci_dumpregs(host); +#endif + + mmiowb(); + + if (mmc_add_host(mmc) < 0) + goto out6; + if (host->flags & SDHCI_USE_EXTERNAL_DMA) + printk(KERN_INFO "%s: SDHCI detect irq %d irq %d %s\n", + mmc_hostname(mmc), host->detect_irq, host->irq, + "EXTERNAL DMA"); + else + printk(KERN_INFO "%s: SDHCI detect irq %d irq %d %s\n", + mmc_hostname(mmc), host->detect_irq, host->irq, + (host->flags & SDHCI_USE_DMA) ? "INTERNAL DMA" : "PIO"); + + return 0; + + out6: + free_irq(host->irq, host); + out5: + if (host->detect_irq) + free_irq(host->detect_irq, host); + else { + if ((pdev->id >= 0) && (pdev->id < MXC_SDHCI_NUM)) + mxc_fix_chips[pdev->id] = chip; + } + out4: + del_timer_sync(&host->timer); + del_timer_sync(&host->cd_timer); + tasklet_kill(&host->card_tasklet); + tasklet_kill(&host->finish_tasklet); + out3: + if (host->flags & SDHCI_USE_DMA) + kfree(adma_des_table); + release_mem_region(host->res->start, + host->res->end - host->res->start + 1); + out2: + clk_disable(host->clk); + host->plat_data->clk_flg = 0; + clk_put(host->clk); + out1: + gpio_sdhc_inactive(pdev->id); + out0: + mmc_free_host(mmc); + return ret; +} + +static void sdhci_remove_slot(struct platform_device *pdev, int slot) +{ + struct sdhci_chip *chip; + struct mmc_host *mmc; + struct sdhci_host *host; + + chip = dev_get_drvdata(&pdev->dev); + host = chip->hosts[slot]; + mmc = host->mmc; + + chip->hosts[slot] = NULL; + + mmc_remove_host(mmc); + + sdhci_reset(host, SDHCI_RESET_ALL); + + if (host->detect_irq) + free_irq(host->detect_irq, host); + else { + if ((pdev->id >= 0) && (pdev->id < MXC_SDHCI_NUM)) + mxc_fix_chips[pdev->id] = NULL; + } + free_irq(host->irq, host); + if (chip->quirks & SDHCI_QUIRK_EXTERNAL_DMA_MODE) { + host->flags &= ~SDHCI_USE_EXTERNAL_DMA; + mxc_dma_free(host->dma); + } + + del_timer_sync(&host->timer); + + tasklet_kill(&host->card_tasklet); + tasklet_kill(&host->finish_tasklet); + + if (host->flags & SDHCI_USE_DMA) + kfree(adma_des_table); + release_mem_region(host->res->start, + host->res->end - host->res->start + 1); + clk_disable(host->clk); + host->plat_data->clk_flg = 0; + clk_put(host->clk); + mmc_free_host(mmc); + gpio_sdhc_inactive(pdev->id); +} + +static int sdhci_probe(struct platform_device *pdev) +{ + int ret = 0, i; + u8 slots = 1; + struct sdhci_chip *chip; + + printk(KERN_INFO DRIVER_NAME ": MXC SDHCI Controller Driver. \n"); + BUG_ON(pdev == NULL); + + chip = kzalloc(sizeof(struct sdhci_chip) + + sizeof(struct sdhci_host *) * slots, GFP_KERNEL); + if (!chip) { + ret = -ENOMEM; + goto err; + } + + /* Distinguish different platform */ + if (machine_is_mx37_3ds()) { + mxc_quirks = SDHCI_QUIRK_EXTERNAL_DMA_MODE; + } else { + mxc_quirks = SDHCI_QUIRK_INTERNAL_ADVANCED_DMA | + SDHCI_QUIRK_INTERNAL_SIMPLE_DMA; + } + chip->pdev = pdev; + chip->quirks = mxc_quirks; + + if (debug_quirks) + chip->quirks = debug_quirks; + + chip->num_slots = slots; + dev_set_drvdata(&pdev->dev, chip); + + for (i = 0; i < slots; i++) { + ret = sdhci_probe_slot(pdev, i); + if (ret) { + for (i--; i >= 0; i--) + sdhci_remove_slot(pdev, i); + goto free; + } + } + + return 0; + + free: + dev_set_drvdata(&pdev->dev, NULL); + kfree(chip); + + err: + return ret; +} + +static int sdhci_remove(struct platform_device *pdev) +{ + int i; + struct sdhci_chip *chip; + + chip = dev_get_drvdata(&pdev->dev); + + if (chip) { + for (i = 0; i < chip->num_slots; i++) + sdhci_remove_slot(pdev, i); + + dev_set_drvdata(&pdev->dev, NULL); + + kfree(chip); + } + + return 0; +} + +static struct platform_driver sdhci_driver = { + .driver = { + .name = DRIVER_NAME, + }, + .probe = sdhci_probe, + .remove = sdhci_remove, + .suspend = sdhci_suspend, + .resume = sdhci_resume, +}; + +/*****************************************************************************\ + * * + * Driver init/exit * + * * +\*****************************************************************************/ + +static int __init sdhci_drv_init(void) +{ + printk(KERN_INFO DRIVER_NAME + ": MXC Secure Digital Host Controller Interface driver\n"); + return platform_driver_register(&sdhci_driver); +} + +static void __exit sdhci_drv_exit(void) +{ + DBG("Exiting\n"); + + platform_driver_unregister(&sdhci_driver); +} + +module_init(sdhci_drv_init); +module_exit(sdhci_drv_exit); + +module_param(debug_quirks, uint, 0444); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MXC Secure Digital Host Controller Interface driver"); +MODULE_LICENSE("GPL"); + +MODULE_PARM_DESC(debug_quirks, "Force certain quirks."); diff --git a/drivers/mmc/host/mx_sdhci.h b/drivers/mmc/host/mx_sdhci.h new file mode 100644 index 000000000000..314d8d6e4487 --- /dev/null +++ b/drivers/mmc/host/mx_sdhci.h @@ -0,0 +1,295 @@ +/* + * linux/drivers/mmc/host/mx_sdhci.h - Secure Digital Host + * Controller Interface driver + * + * Copyright (C) 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or (at + * your option) any later version. + */ + +/* + * Controller registers + */ + +#define SDHCI_DMA_ADDRESS 0x00 + +#define SDHCI_BLOCK_SIZE 0x04 +#define SDHCI_MAKE_BLKSZ(dma, blksz) (((dma & 0x7) << 13) | (blksz & 0x1FFF)) + +#define SDHCI_BLOCK_COUNT 0x04 + +#define SDHCI_ARGUMENT 0x08 + +#define SDHCI_TRANSFER_MODE 0x0C +#define SDHCI_TRNS_DMA 0x00000001 +#define SDHCI_TRNS_BLK_CNT_EN 0x00000002 +#define SDHCI_TRNS_ACMD12 0x00000004 +#define SDHCI_TRNS_DDR_EN 0x00000008 +#define SDHCI_TRNS_READ 0x00000010 +#define SDHCI_TRNS_MULTI 0x00000020 +#define SDHCI_TRNS_DPSEL 0x00200000 +#define SDHCI_TRNS_MASK 0xFFFF0000 + +#define SDHCI_COMMAND 0x0E +#define SDHCI_CMD_RESP_MASK 0x03 +#define SDHCI_CMD_CRC 0x08 +#define SDHCI_CMD_INDEX 0x10 +#define SDHCI_CMD_DATA 0x20 + +#define SDHCI_CMD_RESP_NONE 0x00 +#define SDHCI_CMD_RESP_LONG 0x01 +#define SDHCI_CMD_RESP_SHORT 0x02 +#define SDHCI_CMD_RESP_SHORT_BUSY 0x03 + +#define SDHCI_MAKE_CMD(c, f) ((((c & 0xff) << 8) | (f & 0xff)) << 16) + +#define SDHCI_RESPONSE 0x10 + +#define SDHCI_BUFFER 0x20 + +#define SDHCI_PRESENT_STATE 0x24 +#define SDHCI_CMD_INHIBIT 0x00000001 +#define SDHCI_DATA_INHIBIT 0x00000002 +#define SDHCI_DATA_ACTIVE 0x00000004 +#define SDHCI_DOING_WRITE 0x00000100 +#define SDHCI_DOING_READ 0x00000200 +#define SDHCI_SPACE_AVAILABLE 0x00000400 +#define SDHCI_DATA_AVAILABLE 0x00000800 +#define SDHCI_CARD_PRESENT 0x00010000 +#define SDHCI_WRITE_PROTECT 0x00080000 +#define SDHCI_DAT0_IDLE 0x01000000 +#define SDHCI_CARD_INT_MASK 0x0E000000 +#define SDHCI_CARD_INT_ID 0x0C000000 + +#define SDHCI_HOST_CONTROL 0x28 +#define SDHCI_CTRL_LED 0x00000001 +#define SDHCI_CTRL_4BITBUS 0x00000002 +#define SDHCI_CTRL_8BITBUS 0x00000004 +#define SDHCI_CTRL_HISPD 0x00000004 +#define SDHCI_CTRL_DMA_MASK 0x18 +#define SDHCI_CTRL_SDMA 0x00 +#define SDHCI_CTRL_ADMA1 0x08 +#define SDHCI_CTRL_ADMA32 0x10 +#define SDHCI_CTRL_ADMA64 0x18 +#define SDHCI_CTRL_D3CD 0x00000008 +#define SDHCI_CTRL_ADMA 0x00000100 +/* wake up control */ +#define SDHCI_CTRL_WECINS 0x04000000 + +#define SDHCI_POWER_CONTROL 0x29 +#define SDHCI_POWER_ON 0x01 +#define SDHCI_POWER_180 0x0A +#define SDHCI_POWER_300 0x0C +#define SDHCI_POWER_330 0x0E + +#define SDHCI_BLOCK_GAP_CONTROL 0x2A + +#define SDHCI_WAKE_UP_CONTROL 0x2B + +#define SDHCI_CLOCK_CONTROL 0x2C +#define SDHCI_DIVIDER_SHIFT 8 +#define SDHCI_CLOCK_SD_EN 0x00000008 +#define SDHCI_CLOCK_PER_EN 0x00000004 +#define SDHCI_CLOCK_HLK_EN 0x00000002 +#define SDHCI_CLOCK_IPG_EN 0x00000001 +#define SDHCI_CLOCK_SDCLKFS1 0x00000100 +#define SDHCI_CLOCK_MASK 0x0000FFFF + +#define SDHCI_TIMEOUT_CONTROL 0x2E + +#define SDHCI_SOFTWARE_RESET 0x2F +#define SDHCI_RESET_ALL 0x01 +#define SDHCI_RESET_CMD 0x02 +#define SDHCI_RESET_DATA 0x04 + +#define SDHCI_INT_STATUS 0x30 +#define SDHCI_INT_ENABLE 0x34 +#define SDHCI_SIGNAL_ENABLE 0x38 +#define SDHCI_INT_RESPONSE 0x00000001 +#define SDHCI_INT_DATA_END 0x00000002 +#define SDHCI_INT_DMA_END 0x00000008 +#define SDHCI_INT_SPACE_AVAIL 0x00000010 +#define SDHCI_INT_DATA_AVAIL 0x00000020 +#define SDHCI_INT_CARD_INSERT 0x00000040 +#define SDHCI_INT_CARD_REMOVE 0x00000080 +#define SDHCI_INT_CARD_INT 0x00000100 +#define SDHCI_INT_ERROR 0x00008000 +#define SDHCI_INT_TIMEOUT 0x00010000 +#define SDHCI_INT_CRC 0x00020000 +#define SDHCI_INT_END_BIT 0x00040000 +#define SDHCI_INT_INDEX 0x00080000 +#define SDHCI_INT_DATA_TIMEOUT 0x00100000 +#define SDHCI_INT_DATA_CRC 0x00200000 +#define SDHCI_INT_DATA_END_BIT 0x00400000 +#define SDHCI_INT_BUS_POWER 0x00800000 +#define SDHCI_INT_ACMD12ERR 0x01000000 +#define SDHCI_INT_ADMA_ERROR 0x10000000 + +#define SDHCI_INT_NORMAL_MASK 0x00007FFF +#define SDHCI_INT_ERROR_MASK 0xFFFF8000 + +#define SDHCI_INT_CMD_MASK (SDHCI_INT_RESPONSE | SDHCI_INT_TIMEOUT | \ + SDHCI_INT_CRC | SDHCI_INT_END_BIT | SDHCI_INT_INDEX | \ + SDHCI_INT_ACMD12ERR) +#define SDHCI_INT_DATA_MASK (SDHCI_INT_DATA_END | SDHCI_INT_DMA_END | \ + SDHCI_INT_DATA_AVAIL | SDHCI_INT_SPACE_AVAIL | \ + SDHCI_INT_DATA_TIMEOUT | SDHCI_INT_DATA_CRC | \ + SDHCI_INT_DATA_END_BIT | SDHCI_INT_ADMA_ERROR) +#define SDHCI_INT_DATA_RE_MASK (SDHCI_INT_DMA_END | \ + SDHCI_INT_DATA_AVAIL | SDHCI_INT_SPACE_AVAIL) + +#define SDHCI_ACMD12_ERR 0x3C +#define SDHCI_ACMD12_ERR_NE 0x00000001 +#define SDHCI_ACMD12_ERR_TOE 0x00000002 +#define SDHCI_ACMD12_ERR_EBE 0x00000004 +#define SDHCI_ACMD12_ERR_CE 0x00000008 +#define SDHCI_ACMD12_ERR_IE 0x00000010 +#define SDHCI_ACMD12_ERR_CNIBE 0x00000080 + +/* 3E-3F reserved */ + +#define SDHCI_CAPABILITIES 0x40 +#define SDHCI_TIMEOUT_CLK_MASK 0x0000003F +#define SDHCI_TIMEOUT_CLK_SHIFT 0 +#define SDHCI_TIMEOUT_CLK_UNIT 0x00000080 +#define SDHCI_CLOCK_BASE_MASK 0x00003F00 +#define SDHCI_CLOCK_BASE_SHIFT 8 +#define SDHCI_MAX_BLOCK_MASK 0x00030000 +#define SDHCI_MAX_BLOCK_SHIFT 16 +#define SDHCI_CAN_DO_ADMA2 0x00080000 +#define SDHCI_CAN_DO_ADMA1 0x00100000 +#define SDHCI_CAN_DO_HISPD 0x00200000 +#define SDHCI_CAN_DO_DMA 0x00400000 +#define SDHCI_CAN_VDD_330 0x01000000 +#define SDHCI_CAN_VDD_300 0x02000000 +#define SDHCI_CAN_VDD_180 0x04000000 +#define SDHCI_CAN_64BIT 0x10000000 + +/* 44-47 reserved for more caps */ +#define SDHCI_WML 0x44 +#define SDHCI_WML_4_WORDS 0x00040004 +#define SDHCI_WML_16_WORDS 0x00100010 +#define SDHCI_WML_64_WORDS 0x00400040 +#define SDHCI_WML_128_WORDS 0x00800080 + +#define SDHCI_MAX_CURRENT 0x48 + +/* 4C-4F reserved for more max current */ + +#define SDHCI_SET_ACMD12_ERROR 0x50 +#define SDHCI_SET_INT_ERROR 0x52 + +#define SDHCI_ADMA_ERROR 0x54 + +/* 55-57 reserved */ + +#define SDHCI_ADMA_ADDRESS 0x58 + +/* 60-FB reserved */ +#define SDHCI_DLL_CONTROL 0x60 +#define DLL_CTRL_ENABLE 0x00000001 +#define DLL_CTRL_RESET 0x00000002 +#define DLL_CTRL_SLV_FORCE_UPD 0x00000004 +#define DLL_CTRL_SLV_DLY_TAR 0x00000000 +#define DLL_CTRL_SLV_UP_INT 0x00200000 +#define DLL_CTRL_REF_UP_INT 0x20000000 + +#define SDHCI_DLL_STATUS 0x64 +#define DLL_STS_SLV_LOCK 0x00000001 +#define DLL_STS_REF_LOCK 0x00000002 + +/* ADMA Addr Descriptor Attribute Filed */ +enum { + FSL_ADMA_DES_ATTR_VALID = 0x01, + FSL_ADMA_DES_ATTR_END = 0x02, + FSL_ADMA_DES_ATTR_INT = 0x04, + FSL_ADMA_DES_ATTR_SET = 0x10, + FSL_ADMA_DES_ATTR_TRAN = 0x20, + FSL_ADMA_DES_ATTR_LINK = 0x30, +}; + +#define SDHCI_HOST_VERSION 0xFC +#define SDHCI_VENDOR_VER_MASK 0xFF00 +#define SDHCI_VENDOR_VER_SHIFT 8 +#define SDHCI_SPEC_VER_MASK 0x00FF +#define SDHCI_SPEC_VER_SHIFT 0 +#define SDHCI_SPEC_100 0 +#define SDHCI_SPEC_200 1 +#define ESDHC_VENDOR_V22 0x12 + +struct sdhci_chip; + +struct sdhci_host { + struct sdhci_chip *chip; + struct mmc_host *mmc; /* MMC structure */ + +#ifdef CONFIG_LEDS_CLASS + struct led_classdev led; /* LED control */ +#endif + + spinlock_t lock; /* Mutex */ + + int init_flag; /* Host has been initialized */ + int flags; /* Host attributes */ +#define SDHCI_USE_DMA (1<<0) /* Host is DMA capable */ +#define SDHCI_REQ_USE_DMA (1<<1) /* Use DMA for this req. */ +#define SDHCI_USE_EXTERNAL_DMA (1<<2) /* Use the External DMA */ +#define SDHCI_CD_PRESENT (1<<8) /* CD present */ +#define SDHCI_WP_ENABLED (1<<9) /* Write protect */ +#define SDHCI_CD_TIMEOUT (1<<10) /* cd timer is expired */ + + unsigned int max_clk; /* Max possible freq (MHz) */ + unsigned int min_clk; /* Min possible freq (MHz) */ + unsigned int timeout_clk; /* Timeout freq (KHz) */ + + unsigned int clock; /* Current clock (MHz) */ + unsigned short power; /* Current voltage */ + struct regulator *regulator_mmc; /*! Regulator */ + + struct mmc_request *mrq; /* Current request */ + struct mmc_command *cmd; /* Current command */ + struct mmc_data *data; /* Current data request */ + unsigned int data_early:1; /* Data finished before cmd */ + + unsigned int id; /* Id for SD/MMC block */ + int mode; /* SD/MMC mode */ + int dma; /* DMA channel number. */ + unsigned int dma_size; /* Number of Bytes in DMA */ + unsigned int dma_len; /* Length of the s-g list */ + unsigned int dma_dir; /* DMA transfer direction */ + + struct scatterlist *cur_sg; /* We're working on this */ + int num_sg; /* Entries left */ + int offset; /* Offset into current sg */ + int remain; /* Bytes left in current */ + + struct resource *res; /* IO map memory */ + int irq; /* Device IRQ */ + int detect_irq; /* Card Detect IRQ number. */ + int sdio_enable; /* sdio interrupt enable number. */ + struct clk *clk; /* Clock id */ + int bar; /* PCI BAR index */ + unsigned long addr; /* Bus address */ + void __iomem *ioaddr; /* Mapped address */ + + struct tasklet_struct card_tasklet; /* Tasklet structures */ + struct tasklet_struct finish_tasklet; + struct work_struct cd_wq; /* card detection work queue */ + /* Platform specific data */ + struct mxc_mmc_platform_data *plat_data; + + struct timer_list timer; /* Timer for timeouts */ + struct timer_list cd_timer; /* Timer for cd */ +}; + +struct sdhci_chip { + struct platform_device *pdev; + + unsigned long quirks; + + int num_slots; /* Slots on controller */ + struct sdhci_host *hosts[0]; /* Pointers to hosts */ +}; diff --git a/drivers/mmc/host/mxc_mmc.c b/drivers/mmc/host/mxc_mmc.c new file mode 100644 index 000000000000..bc803b141990 --- /dev/null +++ b/drivers/mmc/host/mxc_mmc.c @@ -0,0 +1,1534 @@ +/* + * linux/drivers/mmc/host/mxc_mmc.c - Freescale MXC/i.MX MMC driver + * + * based on imxmmc.c + * Copyright (C) 2004 Sascha Hauer, Pengutronix + * + * derived from pxamci.c by Russell King + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + */ + +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mxc_mmc.c + * + * @brief Driver for the Freescale Semiconductor MXC SDHC modules. + * + * This driver code is based on imxmmc.c, by Sascha Hauer, + * Pengutronix . This driver supports both Secure Digital + * Host Controller modules (SDHC1 and SDHC2) of MXC. SDHC is also referred as + * MMC/SD controller. This code is not tested for SD cards. + * + * @ingroup MMC_SD + */ + +/* + * Include Files + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "mxc_mmc.h" + +#define RSP_TYPE(x) ((x) & ~(MMC_RSP_BUSY|MMC_RSP_OPCODE)) + +/* + * This define is used to test the driver without using DMA + */ +#define MXC_MMC_DMA_ENABLE + +/*! + * Maxumum length of s/g list, only length of 1 is currently supported + */ +#define NR_SG 1 + +#ifdef CONFIG_MMC_DEBUG +static void dump_cmd(struct mmc_command *cmd) +{ + printk(KERN_INFO "%s: CMD: opcode: %d ", DRIVER_NAME, cmd->opcode); + printk(KERN_INFO "arg: 0x%08x ", cmd->arg); + printk(KERN_INFO "flags: 0x%08x\n", cmd->flags); +} + +static void dump_status(const char *func, int sts) +{ + unsigned int bitset; + printk(KERN_INFO "%s:status: ", func); + while (sts) { + /* Find the next bit set */ + bitset = sts & ~(sts - 1); + switch (bitset) { + case STATUS_CARD_INSERTION: + printk(KERN_INFO "CARD_INSERTION|"); + break; + case STATUS_CARD_REMOVAL: + printk(KERN_INFO "CARD_REMOVAL |"); + break; + case STATUS_YBUF_EMPTY: + printk(KERN_INFO "YBUF_EMPTY |"); + break; + case STATUS_XBUF_EMPTY: + printk(KERN_INFO "XBUF_EMPTY |"); + break; + case STATUS_YBUF_FULL: + printk(KERN_INFO "YBUF_FULL |"); + break; + case STATUS_XBUF_FULL: + printk(KERN_INFO "XBUF_FULL |"); + break; + case STATUS_BUF_UND_RUN: + printk(KERN_INFO "BUF_UND_RUN |"); + break; + case STATUS_BUF_OVFL: + printk(KERN_INFO "BUF_OVFL |"); + break; + case STATUS_READ_OP_DONE: + printk(KERN_INFO "READ_OP_DONE |"); + break; + case STATUS_WR_CRC_ERROR_CODE_MASK: + printk(KERN_INFO "WR_CRC_ERROR_CODE |"); + break; + case STATUS_READ_CRC_ERR: + printk(KERN_INFO "READ_CRC_ERR |"); + break; + case STATUS_WRITE_CRC_ERR: + printk(KERN_INFO "WRITE_CRC_ERR |"); + break; + case STATUS_SDIO_INT_ACTIVE: + printk(KERN_INFO "SDIO_INT_ACTIVE |"); + break; + case STATUS_END_CMD_RESP: + printk(KERN_INFO "END_CMD_RESP |"); + break; + case STATUS_WRITE_OP_DONE: + printk(KERN_INFO "WRITE_OP_DONE |"); + break; + case STATUS_CARD_BUS_CLK_RUN: + printk(KERN_INFO "CARD_BUS_CLK_RUN |"); + break; + case STATUS_BUF_READ_RDY: + printk(KERN_INFO "BUF_READ_RDY |"); + break; + case STATUS_BUF_WRITE_RDY: + printk(KERN_INFO "BUF_WRITE_RDY |"); + break; + case STATUS_RESP_CRC_ERR: + printk(KERN_INFO "RESP_CRC_ERR |"); + break; + case STATUS_TIME_OUT_RESP: + printk(KERN_INFO "TIME_OUT_RESP |"); + break; + case STATUS_TIME_OUT_READ: + printk(KERN_INFO "TIME_OUT_READ |"); + break; + default: + printk(KERN_INFO "Invalid Status Register value0x%x\n", + bitset); + break; + } + sts &= ~bitset; + } + printk(KERN_INFO "\n"); +} +#endif + +/*! + * This structure is a way for the low level driver to define their own + * \b mmc_host structure. This structure includes the core \b mmc_host + * structure that is provided by Linux MMC/SD Bus protocol driver as an + * element and has other elements that are specifically required by this + * low-level driver. + */ +struct mxcmci_host { + /*! + * The mmc structure holds all the information about the device + * structure, current SDHC io bus settings, the current OCR setting, + * devices attached to this host, and so on. + */ + struct mmc_host *mmc; + + /*! + * This variable is used for locking the host data structure from + * multiple access. + */ + spinlock_t lock; + + /*! + * Resource structure, which will maintain base addresses and IRQs. + */ + struct resource *res; + + /*! + * Base address of SDHC, used in readl and writel. + */ + void *base; + + /*! + * SDHC IRQ number. + */ + int irq; + + /*! + * Card Detect IRQ number. + */ + int detect_irq; + + /*! + * Clock id to hold ipg_perclk. + */ + struct clk *clk; + /*! + * MMC mode. + */ + int mode; + + /*! + * DMA channel number. + */ + int dma; + + /*! + * Pointer to hold MMC/SD request. + */ + struct mmc_request *req; + + /*! + * Pointer to hold MMC/SD command. + */ + struct mmc_command *cmd; + + /*! + * Pointer to hold MMC/SD data. + */ + struct mmc_data *data; + + /*! + * Holds the number of bytes to transfer using DMA. + */ + unsigned int dma_size; + + /*! + * Value to store in Command and Data Control Register + * - currently unused + */ + unsigned int cmdat; + + /*! + * Regulator + */ + struct regulator *regulator_mmc; + + /*! + * Current vdd settting + */ + int current_vdd; + + /*! + * Power mode - currently unused + */ + unsigned int power_mode; + + /*! + * DMA address for scatter-gather transfers + */ + dma_addr_t sg_dma; + + /*! + * Length of the scatter-gather list + */ + unsigned int dma_len; + + /*! + * Holds the direction of data transfer. + */ + unsigned int dma_dir; + + /*! + * Id for MMC block. + */ + unsigned int id; + + /*! + * Note whether this driver has been suspended. + */ + unsigned int mxc_mmc_suspend_flag; + + /*! + * sdio_irq enable/disable ref count + */ + int sdio_irq_cnt; + + /*! + * Platform specific data + */ + struct mxc_mmc_platform_data *plat_data; +}; + +extern void gpio_sdhc_active(int module); +extern void gpio_sdhc_inactive(int module); + +#ifdef MXC_MMC_DMA_ENABLE +static void mxcmci_dma_irq(void *devid, int error, unsigned int cnt); +#endif +static int mxcmci_data_done(struct mxcmci_host *host, unsigned int stat); + +/* Wait count to start the clock */ +#define CMD_WAIT_CNT 100 + +#define MAX_HOST 10 +static struct mmc_host *hosts[MAX_HOST]; + +void mxc_mmc_force_detect(int id) +{ + if (id < MAX_HOST) + mmc_detect_change(hosts[id], msecs_to_jiffies(100)); +} + +EXPORT_SYMBOL(mxc_mmc_force_detect); + +/*! + This function sets the SDHC register to stop the clock and waits for the + * clock stop indication. + */ +static void mxcmci_stop_clock(struct mxcmci_host *host, bool wait) +{ + int wait_cnt = 0; + while (1) { + __raw_writel(STR_STP_CLK_STOP_CLK, + host->base + MMC_STR_STP_CLK); + + if (!wait) + break; + + wait_cnt = CMD_WAIT_CNT; + while (wait_cnt--) { + if (!(__raw_readl(host->base + MMC_STATUS) & + STATUS_CARD_BUS_CLK_RUN)) + break; + } + + if (!(__raw_readl(host->base + MMC_STATUS) & + STATUS_CARD_BUS_CLK_RUN)) + break; + } +} + +/*! + * This function sets the SDHC register to start the clock and waits for the + * clock start indication. When the clock starts SDHC module starts processing + * the command in CMD Register with arguments in ARG Register. + * + * @param host Pointer to MMC/SD host structure + * @param wait Boolean value to indicate whether to wait for the clock to start or come out instantly + */ +static void mxcmci_start_clock(struct mxcmci_host *host, bool wait) +{ + int wait_cnt; + +#ifdef CONFIG_MMC_DEBUG + dump_status(__FUNCTION__, __raw_readl(host->base + MMC_STATUS)); +#endif + + while (1) { + __raw_writel(STR_STP_CLK_START_CLK, + host->base + MMC_STR_STP_CLK); + if (!wait) + break; + + wait_cnt = CMD_WAIT_CNT; + while (wait_cnt--) { + if (__raw_readl(host->base + MMC_STATUS) & + STATUS_CARD_BUS_CLK_RUN) { + break; + } + } + + if (__raw_readl(host->base + MMC_STATUS) & + STATUS_CARD_BUS_CLK_RUN) { + break; + } + } +#ifdef CONFIG_MMC_DEBUG + dump_status(__FUNCTION__, __raw_readl(host->base + MMC_STATUS)); +#endif + pr_debug("%s:CLK_RATE: 0x%08x\n", DRIVER_NAME, + __raw_readl(host->base + MMC_CLK_RATE)); +} + +/*! + * This function resets the SDHC host. + * + * @param host Pointer to MMC/SD host structure + */ +static void mxcmci_softreset(struct mxcmci_host *host) +{ + /* reset sequence */ + __raw_writel(0x8, host->base + MMC_STR_STP_CLK); + __raw_writel(0x9, host->base + MMC_STR_STP_CLK); + __raw_writel(0x1, host->base + MMC_STR_STP_CLK); + __raw_writel(0x1, host->base + MMC_STR_STP_CLK); + __raw_writel(0x1, host->base + MMC_STR_STP_CLK); + __raw_writel(0x1, host->base + MMC_STR_STP_CLK); + __raw_writel(0x1, host->base + MMC_STR_STP_CLK); + __raw_writel(0x1, host->base + MMC_STR_STP_CLK); + __raw_writel(0x1, host->base + MMC_STR_STP_CLK); + __raw_writel(0x1, host->base + MMC_STR_STP_CLK); + __raw_writel(0x3f, host->base + MMC_CLK_RATE); + + __raw_writel(0xff, host->base + MMC_RES_TO); + __raw_writel(512, host->base + MMC_BLK_LEN); + __raw_writel(1, host->base + MMC_NOB); +} + +/*! + * This function is called to setup SDHC register for data transfer. + * The function allocates DMA buffers, configures the DMA channel. + * Start the DMA channel to transfer data. When DMA is not enabled this + * function set ups only Number of Block and Block Length registers. + * + * @param host Pointer to MMC/SD host structure + * @param data Pointer to MMC/SD data structure + */ +static void mxcmci_setup_data(struct mxcmci_host *host, struct mmc_data *data) +{ + unsigned int nob = data->blocks; + + if (data->flags & MMC_DATA_STREAM) { + nob = 0xffff; + } + + host->data = data; + + __raw_writel(nob, host->base + MMC_NOB); + __raw_writel(data->blksz, host->base + MMC_BLK_LEN); + + host->dma_size = data->blocks * data->blksz; + pr_debug("%s:Request bytes to transfer:%d\n", DRIVER_NAME, + host->dma_size); + +#ifdef MXC_MMC_DMA_ENABLE + if (host->dma_size <= (16 << host->mmc->ios.bus_width)) { + return; + } + + if (data->blksz & 0x3) { + printk(KERN_ERR + "mxc_mci: block size not multiple of 4 bytes\n"); + } + + if (data->flags & MMC_DATA_READ) { + host->dma_dir = DMA_FROM_DEVICE; + } else { + host->dma_dir = DMA_TO_DEVICE; + } + host->dma_len = dma_map_sg(mmc_dev(host->mmc), data->sg, data->sg_len, + host->dma_dir); + + if (data->flags & MMC_DATA_READ) { + mxc_dma_sg_config(host->dma, data->sg, data->sg_len, + host->dma_size, MXC_DMA_MODE_READ); + } else { + mxc_dma_sg_config(host->dma, data->sg, data->sg_len, + host->dma_size, MXC_DMA_MODE_WRITE); + } +#endif +} + +/*! + * This function is called by \b mxcmci_request() function to setup the SDHC + * register to issue command. This function disables the card insertion and + * removal detection interrupt. + * + * @param host Pointer to MMC/SD host structure + * @param cmd Pointer to MMC/SD command structure + * @param cmdat Value to store in Command and Data Control Register + */ +static void mxcmci_start_cmd(struct mxcmci_host *host, struct mmc_command *cmd, + unsigned int cmdat) +{ + WARN_ON(host->cmd != NULL); + host->cmd = cmd; + + switch (RSP_TYPE(mmc_resp_type(cmd))) { + case RSP_TYPE(MMC_RSP_R1): /* r1, r1b, r6 */ + cmdat |= CMD_DAT_CONT_RESPONSE_FORMAT_R1; + break; + case RSP_TYPE(MMC_RSP_R3): + cmdat |= CMD_DAT_CONT_RESPONSE_FORMAT_R3; + break; + case RSP_TYPE(MMC_RSP_R2): + cmdat |= CMD_DAT_CONT_RESPONSE_FORMAT_R2; + break; + default: + /* No Response required */ + break; + } + + if (cmd->opcode == MMC_GO_IDLE_STATE) { + cmdat |= CMD_DAT_CONT_INIT; /* This command needs init */ + } + + if (host->mmc->ios.bus_width == MMC_BUS_WIDTH_4) { + cmdat |= CMD_DAT_CONT_BUS_WIDTH_4; + } + + __raw_writel(cmd->opcode, host->base + MMC_CMD); + __raw_writel(cmd->arg, host->base + MMC_ARG); + + __raw_writel(cmdat, host->base + MMC_CMD_DAT_CONT); + + if (!(__raw_readl(host->base + MMC_STATUS) & STATUS_CARD_BUS_CLK_RUN)) + mxcmci_start_clock(host, true); +} + +/*! + * This function is called to complete the command request. + * This function enables insertion or removal interrupt. + * + * @param host Pointer to MMC/SD host structure + * @param req Pointer to MMC/SD command request structure + */ +static void mxcmci_finish_request(struct mxcmci_host *host, + struct mmc_request *req) +{ + + host->req = NULL; + host->cmd = NULL; + host->data = NULL; + + mmc_request_done(host->mmc, req); +} + +/*! + * This function is called when the requested command is completed. + * This function reads the response from the card and data if the command is for + * data transfer. This function checks for CRC error in response FIFO or + * data FIFO. + * + * @param host Pointer to MMC/SD host structure + * @param stat Content of SDHC Status Register + * + * @return This function returns 0 if there is no pending command, otherwise 1 + * always. + */ +static int mxcmci_cmd_done(struct mxcmci_host *host, unsigned int stat) +{ + struct mmc_command *cmd = host->cmd; + struct mmc_data *data = host->data; + int i; + u32 a, b, c; + u32 temp_data; + unsigned int status; + unsigned long *buf; + u8 *buf8; + int no_of_bytes; + int no_of_words; + + if (!cmd) { + /* There is no command for completion */ + return 0; + } + + /* As this function finishes the command, initialize cmd to NULL */ + host->cmd = NULL; + + /* check for Time out errors */ + if (stat & STATUS_TIME_OUT_RESP) { + __raw_writel(STATUS_TIME_OUT_RESP, host->base + MMC_STATUS); + pr_debug("%s: CMD %d TIMEOUT\n", DRIVER_NAME, cmd->opcode); + cmd->error = -ETIMEDOUT; + /* + * Reinitialized the controller to clear the unknown + * error state. + */ + mxcmci_softreset(host); + __raw_writel(READ_TO_VALUE, host->base + MMC_READ_TO); + __raw_writel(INT_CNTR_END_CMD_RES, host->base + MMC_INT_CNTR); + } else if (stat & STATUS_RESP_CRC_ERR && cmd->flags & MMC_RSP_CRC) { + __raw_writel(STATUS_RESP_CRC_ERR, host->base + MMC_STATUS); + printk(KERN_ERR "%s: cmd %d CRC error\n", DRIVER_NAME, + cmd->opcode); + cmd->error = -EILSEQ; + /* + * Reinitialized the controller to clear the unknown + * error state. + */ + mxcmci_softreset(host); + __raw_writel(READ_TO_VALUE, host->base + MMC_READ_TO); + __raw_writel(INT_CNTR_END_CMD_RES, host->base + MMC_INT_CNTR); + } + + /* Read response from the card */ + switch (RSP_TYPE(mmc_resp_type(cmd))) { + case RSP_TYPE(MMC_RSP_R1): /* r1, r1b, r6 */ + a = __raw_readl(host->base + MMC_RES_FIFO) & 0xffff; + b = __raw_readl(host->base + MMC_RES_FIFO) & 0xffff; + c = __raw_readl(host->base + MMC_RES_FIFO) & 0xffff; + cmd->resp[0] = a << 24 | b << 8 | c >> 8; + break; + case RSP_TYPE(MMC_RSP_R3): /* r3, r4 */ + a = __raw_readl(host->base + MMC_RES_FIFO) & 0xffff; + b = __raw_readl(host->base + MMC_RES_FIFO) & 0xffff; + c = __raw_readl(host->base + MMC_RES_FIFO) & 0xffff; + cmd->resp[0] = a << 24 | b << 8 | c >> 8; + break; + case RSP_TYPE(MMC_RSP_R2): + for (i = 0; i < 4; i++) { + a = __raw_readl(host->base + MMC_RES_FIFO) & 0xffff; + b = __raw_readl(host->base + MMC_RES_FIFO) & 0xffff; + cmd->resp[i] = a << 16 | b; + } + break; + default: + break; + } + + pr_debug("%s: 0x%08x, 0x%08x, 0x%08x, 0x%08x\n", DRIVER_NAME, + cmd->resp[0], cmd->resp[1], cmd->resp[2], cmd->resp[3]); + + if (!host->data || cmd->error) { + /* complete the command */ + mxcmci_finish_request(host, host->req); + return 1; + } + + /* The command has a data transfer */ +#ifdef MXC_MMC_DMA_ENABLE + /* Use DMA if transfer size is greater than fifo size */ + if (host->dma_size > (16 << host->mmc->ios.bus_width)) { + mxc_dma_enable(host->dma); + return 1; + } +#endif + /* Use PIO tranfer of data */ + buf = (unsigned long *)sg_virt(data->sg); + buf8 = (u8 *) buf; + + /* calculate the number of bytes requested for transfer */ + no_of_bytes = data->blocks * data->blksz; + no_of_words = (no_of_bytes + 3) / 4; + pr_debug("no_of_words=%d\n", no_of_words); + + if (data->flags & MMC_DATA_READ) { + for (i = 0; i < no_of_words; i++) { + /* wait for buffers to be ready for read */ + while (!(__raw_readl(host->base + MMC_STATUS) & + (STATUS_BUF_READ_RDY | STATUS_READ_OP_DONE))) + ; + + pr_debug("status is 0x%x\n", + __raw_readl(host->base + MMC_STATUS)); + /* read 32 bit data */ + temp_data = __raw_readl(host->base + MMC_BUFFER_ACCESS); + if (SD_APP_SEND_SCR == cmd->opcode) { + pr_debug("CMD51 read out 0x%x\n", temp_data); + if (temp_data == 0xFFFFFFFF) + temp_data = 0; + } + if (no_of_bytes >= 4) { + *buf++ = temp_data; + no_of_bytes -= 4; + } else { + do { + *buf8++ = temp_data; + temp_data = temp_data >> 8; + } while (--no_of_bytes); + } + } + + /* wait for read operation completion bit */ + while (!(__raw_readl(host->base + MMC_STATUS) & + STATUS_READ_OP_DONE)) + ; + + /* check for time out and CRC errors */ + status = __raw_readl(host->base + MMC_STATUS); + if (status & STATUS_TIME_OUT_READ) { + printk(KERN_ERR "%s: Read time out occurred\n", + DRIVER_NAME); + data->error = -ETIMEDOUT; + __raw_writel(STATUS_TIME_OUT_READ, + host->base + MMC_STATUS); + /* + * Reinitialized the controller to clear the unknown + * error state. + */ + mxcmci_softreset(host); + __raw_writel(READ_TO_VALUE, host->base + MMC_READ_TO); + __raw_writel(INT_CNTR_END_CMD_RES, + host->base + MMC_INT_CNTR); + } else if (status & STATUS_READ_CRC_ERR) { + printk(KERN_ERR "%s: Read CRC error occurred\n", + DRIVER_NAME); + if (SD_APP_SEND_SCR != cmd->opcode) + data->error = -EILSEQ; + __raw_writel(STATUS_READ_CRC_ERR, + host->base + MMC_STATUS); + /* + * Reinitialized the controller to clear the unknown + * error state. + */ + mxcmci_softreset(host); + __raw_writel(READ_TO_VALUE, host->base + MMC_READ_TO); + __raw_writel(INT_CNTR_END_CMD_RES, + host->base + MMC_INT_CNTR); + } + __raw_writel(STATUS_READ_OP_DONE, host->base + MMC_STATUS); + + pr_debug("%s: Read %u words\n", DRIVER_NAME, i); + } else { + for (i = 0; i < no_of_words; i++) { + + /* wait for buffers to be ready for write */ + while (!(__raw_readl(host->base + MMC_STATUS) & + STATUS_BUF_WRITE_RDY)) + ; + + /* write 32 bit data */ + __raw_writel(*buf++, host->base + MMC_BUFFER_ACCESS); + if (__raw_readl(host->base + MMC_STATUS) & + STATUS_WRITE_OP_DONE) { + break; + } + } + + /* wait for write operation completion bit */ + while (!(__raw_readl(host->base + MMC_STATUS) & + STATUS_WRITE_OP_DONE)) + ; + + /* check for CRC errors */ + status = __raw_readl(host->base + MMC_STATUS); + if (status & STATUS_WRITE_CRC_ERR) { + printk(KERN_ERR "%s: Write CRC error occurred\n", + DRIVER_NAME); + data->error = -EILSEQ; + __raw_writel(STATUS_WRITE_CRC_ERR, + host->base + MMC_STATUS); + } + __raw_writel(STATUS_WRITE_OP_DONE, host->base + MMC_STATUS); + pr_debug("%s: Written %u words\n", DRIVER_NAME, i); + } + + /* complete the data transfer request */ + mxcmci_data_done(host, status); + + return 1; +} + +/*! + * This function is called when the data transfer is completed either by DMA + * or by core. This function is called to clean up the DMA buffer and to send + * STOP transmission command for commands to transfer data. This function + * completes request issued by the MMC/SD core driver. + * + * @param host pointer to MMC/SD host structure. + * @param stat content of SDHC Status Register + * + * @return This function returns 0 if no data transfer otherwise return 1 + * always. + */ +static int mxcmci_data_done(struct mxcmci_host *host, unsigned int stat) +{ + struct mmc_data *data = host->data; + + if (!data) { + return 0; + } +#ifdef MXC_MMC_DMA_ENABLE + if (host->dma_size > (16 << host->mmc->ios.bus_width)) { + dma_unmap_sg(mmc_dev(host->mmc), data->sg, host->dma_len, + host->dma_dir); + } +#endif + if (__raw_readl(host->base + MMC_STATUS) & STATUS_ERR_MASK) { + printk(KERN_ERR "%s: request failed. status: 0x%08x\n", + DRIVER_NAME, __raw_readl(host->base + MMC_STATUS)); + } + + host->data = NULL; + data->bytes_xfered = host->dma_size; + + if (host->req->stop && !(data->error)) { + mxcmci_stop_clock(host, true); + mxcmci_start_cmd(host, host->req->stop, 0); + } else { + mxcmci_finish_request(host, host->req); + } + + return 1; +} + +/*! + * GPIO interrupt service routine registered to handle the SDHC interrupts. + * This interrupt routine handles card insertion and card removal interrupts. + * + * @param irq the interrupt number + * @param devid driver private data + * @param regs holds a snapshot of the processor's context before the + * processor entered the interrupt code + * + * @return The function returns \b IRQ_RETVAL(1) + */ +static irqreturn_t mxcmci_gpio_irq(int irq, void *devid) +{ + struct mxcmci_host *host = devid; + int card_gpio_status = host->plat_data->status(host->mmc->parent); + + pr_debug("%s: MMC%d status=%d %s\n", DRIVER_NAME, host->id, + card_gpio_status, card_gpio_status ? "removed" : "inserted"); + + if (card_gpio_status == host->plat_data->card_inserted_state) { + /* + * Reinitialized the controller to clear the unknown + * error state when a card is inserted. + */ + mxcmci_softreset(host); + __raw_writel(READ_TO_VALUE, host->base + MMC_READ_TO); + __raw_writel(INT_CNTR_END_CMD_RES, host->base + MMC_INT_CNTR); + + mmc_detect_change(host->mmc, msecs_to_jiffies(100)); + } else { + mxcmci_cmd_done(host, STATUS_TIME_OUT_RESP); + mmc_detect_change(host->mmc, msecs_to_jiffies(50)); + } + + do { + card_gpio_status = host->plat_data->status(host->mmc->parent); + if (card_gpio_status) { + set_irq_type(host->detect_irq, IRQF_TRIGGER_FALLING); + } else { + set_irq_type(host->detect_irq, IRQF_TRIGGER_RISING); + } + } while (card_gpio_status != + host->plat_data->status(host->mmc->parent)); + + return IRQ_HANDLED; +} + +/*! + * Interrupt service routine registered to handle the SDHC interrupts. + * This interrupt routine handles end of command, card insertion and + * card removal interrupts. If the interrupt is card insertion or removal then + * inform the MMC/SD core driver to detect the change in physical connections. + * If the command is END_CMD_RESP read the Response FIFO. If DMA is not enabled + * and data transfer is associated with the command then read or write the data + * from or to the BUFFER_ACCESS FIFO. + * + * @param irq the interrupt number + * @param devid driver private data + * @param regs holds a snapshot of the processor's context before the + * processor entered the interrupt code + * + * @return The function returns \b IRQ_RETVAL(1) if interrupt was handled, + * returns \b IRQ_RETVAL(0) if the interrupt was not handled. + */ +static irqreturn_t mxcmci_irq(int irq, void *devid) +{ + struct mxcmci_host *host = devid; + struct mmc_data *data = host->data; + unsigned int status = 0; + u32 intctrl; + + if (host->mxc_mmc_suspend_flag == 1) { + clk_enable(host->clk); + } + + status = __raw_readl(host->base + MMC_STATUS); + pr_debug("MXC MMC IRQ status is 0x%x.\n", status); +#ifdef CONFIG_MMC_DEBUG + dump_status(__FUNCTION__, status); +#endif + if (status & STATUS_END_CMD_RESP) { + __raw_writel(STATUS_END_CMD_RESP, host->base + MMC_STATUS); + mxcmci_cmd_done(host, status); + } +#ifdef MXC_MMC_DMA_ENABLE + /* + * If read length < fifo length, STATUS_END_CMD_RESP and + * STATUS_READ_OP_DONE may come together. In this case, it's using PIO + * mode, we ignore STATUS_READ_OP_DONE. + */ + if ((status & (STATUS_WRITE_OP_DONE | STATUS_READ_OP_DONE)) && + !(status & STATUS_END_CMD_RESP)) { + pr_debug(KERN_INFO "MXC MMC IO OP DONE INT.\n"); + intctrl = __raw_readl(host->base + MMC_INT_CNTR); + __raw_writel((~(INT_CNTR_WRITE_OP_DONE | INT_CNTR_READ_OP_DONE) + & intctrl), host->base + MMC_INT_CNTR); + + pr_debug("%s:READ/WRITE OPERATION DONE\n", DRIVER_NAME); + /* check for time out and CRC errors */ + status = __raw_readl(host->base + MMC_STATUS); + if (status & STATUS_READ_OP_DONE) { + if (status & STATUS_TIME_OUT_READ) { + pr_debug("%s: Read time out occurred\n", + DRIVER_NAME); + data->error = -ETIMEDOUT; + __raw_writel(STATUS_TIME_OUT_READ, + host->base + MMC_STATUS); + } else if (status & STATUS_READ_CRC_ERR) { + pr_debug("%s: Read CRC error occurred\n", + DRIVER_NAME); + data->error = -EILSEQ; + __raw_writel(STATUS_READ_CRC_ERR, + host->base + MMC_STATUS); + } + __raw_writel(STATUS_READ_OP_DONE, + host->base + MMC_STATUS); + } + + /* check for CRC errors */ + if (status & STATUS_WRITE_OP_DONE) { + if (status & STATUS_WRITE_CRC_ERR) { + printk(KERN_ERR + "%s: Write CRC error occurred\n", + DRIVER_NAME); + data->error = -EILSEQ; + __raw_writel(STATUS_WRITE_CRC_ERR, + host->base + MMC_STATUS); + } + __raw_writel(STATUS_WRITE_OP_DONE, + host->base + MMC_STATUS); + } + + mxcmci_data_done(host, status); + } +#endif + status = __raw_readl(host->base + MMC_STATUS); + intctrl = __raw_readl(host->base + MMC_INT_CNTR); + if ((status & STATUS_SDIO_INT_ACTIVE) + && (intctrl & INT_CNTR_SDIO_IRQ_EN)) { + __raw_writel(STATUS_SDIO_INT_ACTIVE, host->base + MMC_STATUS); + + /*Here we do not handle the sdio interrupt to client driver + if the host is in suspend state */ + if (host->mxc_mmc_suspend_flag == 0) { + mmc_signal_sdio_irq(host->mmc); + } + } + return IRQ_HANDLED; +} + +/*! + * This function is called by MMC/SD Bus Protocol driver to issue a MMC + * and SD commands to the SDHC. + * + * @param mmc Pointer to MMC/SD host structure + * @param req Pointer to MMC/SD command request structure + */ +static void mxcmci_request(struct mmc_host *mmc, struct mmc_request *req) +{ + struct mxcmci_host *host = mmc_priv(mmc); + /* Holds the value of Command and Data Control Register */ + unsigned long cmdat; + + WARN_ON(host->req != NULL); + + host->req = req; +#ifdef CONFIG_MMC_DEBUG + dump_cmd(req->cmd); + dump_status(__FUNCTION__, __raw_readl(host->base + MMC_STATUS)); +#endif + + cmdat = 0; + if (req->data) { + mxcmci_setup_data(host, req->data); + + cmdat |= CMD_DAT_CONT_DATA_ENABLE; + + if (req->data->flags & MMC_DATA_WRITE) { + cmdat |= CMD_DAT_CONT_WRITE; + } + if (req->data->flags & MMC_DATA_STREAM) { + printk(KERN_ERR + "MXC MMC does not support stream mode\n"); + } + } + mxcmci_start_cmd(host, req->cmd, cmdat); +} + +/*! + * This function is called by MMC/SD Bus Protocol driver to change the clock + * speed of MMC or SD card + * + * @param mmc Pointer to MMC/SD host structure + * @param ios Pointer to MMC/SD I/O type structure + */ +static void mxcmci_set_ios(struct mmc_host *mmc, struct mmc_ios *ios) +{ + struct mxcmci_host *host = mmc_priv(mmc); + /*This variable holds the value of clock prescaler */ + int prescaler; + int clk_rate = clk_get_rate(host->clk); + int voltage = 0; +#ifdef MXC_MMC_DMA_ENABLE + mxc_dma_device_t dev_id = 0; +#endif + + pr_debug("%s: clock %u, bus %lu, power %u, vdd %u\n", DRIVER_NAME, + ios->clock, 1UL << ios->bus_width, ios->power_mode, ios->vdd); + + host->dma_dir = DMA_NONE; + +#ifdef MXC_MMC_DMA_ENABLE + if (mmc->ios.bus_width != host->mode) { + mxc_dma_free(host->dma); + if (mmc->ios.bus_width == MMC_BUS_WIDTH_4) { + if (host->id == 0) { + dev_id = MXC_DMA_MMC1_WIDTH_4; + } else { + dev_id = MXC_DMA_MMC2_WIDTH_4; + } + } else { + if (host->id == 0) { + dev_id = MXC_DMA_MMC1_WIDTH_1; + } else { + dev_id = MXC_DMA_MMC2_WIDTH_1; + } + } + host->dma = mxc_dma_request(dev_id, "MXC MMC"); + if (host->dma < 0) { + printk(KERN_ERR "Cannot allocate MMC DMA channel\n"); + } + host->mode = mmc->ios.bus_width; + mxc_dma_callback_set(host->dma, mxcmci_dma_irq, (void *)host); + } +#endif + + if ((ios->vdd != host->current_vdd) && host->regulator_mmc) { + if (ios->vdd == 7) + voltage = 1800000; + else if (ios->vdd >= 8) + voltage = 2000000 + (ios->vdd - 8) * 100000; + regulator_set_voltage(host->regulator_mmc, voltage, voltage); + } + host->current_vdd = ios->vdd; + + if (ios->power_mode != host->power_mode && host->regulator_mmc) { + if (ios->power_mode == MMC_POWER_UP) { + if (regulator_enable(host->regulator_mmc) == 0) { + pr_debug("mmc power on\n"); + msleep(1); + } + } else if (ios->power_mode == MMC_POWER_OFF) { + regulator_disable(host->regulator_mmc); + pr_debug("mmc power off\n"); + } + } + host->power_mode = ios->power_mode; + + /* + * Vary divider first, then prescaler. + **/ + if (ios->clock) { + unsigned int clk_dev = 0; + + /* + * when prescaler = 16, CLK_20M = CLK_DIV / 2 + */ + if (ios->clock == mmc->f_min) + prescaler = 16; + else + prescaler = 0; + + /* clk_dev =1, CLK_DIV = ipg_perclk/2 */ + while (prescaler <= 0x800) { + for (clk_dev = 1; clk_dev <= 0xF; clk_dev++) { + int x; + if (prescaler != 0) { + x = (clk_rate / (clk_dev + 1)) / + (prescaler * 2); + } else { + x = clk_rate / (clk_dev + 1); + } + + pr_debug("x=%d, clock=%d %d\n", x, ios->clock, + clk_dev); + if (x <= ios->clock) { + break; + } + } + if (clk_dev < 0x10) { + break; + } + if (prescaler == 0) + prescaler = 1; + else + prescaler <<= 1; + } + + pr_debug("prescaler = 0x%x, divider = 0x%x\n", prescaler, + clk_dev); + mxcmci_stop_clock(host, true); + __raw_writel((prescaler << 4) | clk_dev, + host->base + MMC_CLK_RATE); + mxcmci_start_clock(host, false); + } else { + mxcmci_stop_clock(host, true); + } +} + +static void mxcmci_enable_sdio_irq(struct mmc_host *mmc, int enable) +{ + struct mxcmci_host *host = mmc_priv(mmc); + u32 intctrl; + unsigned long flags; + + spin_lock_irqsave(&host->lock, flags); + + if (enable) + host->sdio_irq_cnt++; + else + host->sdio_irq_cnt--; + + if (host->sdio_irq_cnt == 1 || host->sdio_irq_cnt == 0) { + intctrl = __raw_readl(host->base + MMC_INT_CNTR); + intctrl &= ~INT_CNTR_SDIO_IRQ_EN; + if (host->sdio_irq_cnt) + intctrl |= INT_CNTR_SDIO_IRQ_EN; + __raw_writel(intctrl, host->base + MMC_INT_CNTR); + } + + spin_unlock_irqrestore(&host->lock, flags); +} + +static int mxcmci_get_ro(struct mmc_host *mmc) +{ + struct mxcmci_host *host = mmc_priv(mmc); + + if (host->plat_data->wp_status) + return host->plat_data->wp_status(mmc->parent); + else + return 0; +} + +/*! + * MMC/SD host operations structure. + * These functions are registered with MMC/SD Bus protocol driver. + */ +static struct mmc_host_ops mxcmci_ops = { + .request = mxcmci_request, + .set_ios = mxcmci_set_ios, + .get_ro = mxcmci_get_ro, + .enable_sdio_irq = mxcmci_enable_sdio_irq, +}; + +#ifdef MXC_MMC_DMA_ENABLE +/*! + * This function is called by DMA Interrupt Service Routine to indicate + * requested DMA transfer is completed. + * + * @param devid pointer to device specific structure + * @param error any DMA error + * @param cnt amount of data that was transferred + */ +static void mxcmci_dma_irq(void *devid, int error, unsigned int cnt) +{ + struct mxcmci_host *host = devid; + u32 status; + ulong nob, blk_size, i, blk_len; + + mxc_dma_disable(host->dma); + + if (error) { + printk(KERN_ERR "Error in DMA transfer\n"); + status = __raw_readl(host->base + MMC_STATUS); +#ifdef CONFIG_MMC_DEBUG + dump_status(__FUNCTION__, status); +#endif + mxcmci_data_done(host, status); + return; + } + pr_debug("%s: Transfered bytes:%d\n", DRIVER_NAME, cnt); + nob = __raw_readl(host->base + MMC_REM_NOB); + blk_size = __raw_readl(host->base + MMC_REM_BLK_SIZE); + blk_len = __raw_readl(host->base + MMC_BLK_LEN); + pr_debug("%s: REM_NOB:%lu REM_BLK_SIZE:%lu\n", DRIVER_NAME, nob, + blk_size); + i = 0; + + /* Enable the WRITE OP Done INT */ + status = __raw_readl(host->base + MMC_INT_CNTR); + __raw_writel((INT_CNTR_READ_OP_DONE | INT_CNTR_WRITE_OP_DONE | status), + host->base + MMC_INT_CNTR); +} +#endif + +/*! + * This function is called during the driver binding process. Based on the SDHC + * module that is being probed this function adds the appropriate SDHC module + * structure in the core driver. + * + * @param pdev the device structure used to store device specific + * information that is used by the suspend, resume and remove + * functions. + * + * @return The function returns 0 on successful registration and initialization + * of SDHC module. Otherwise returns specific error code. + */ +static int mxcmci_probe(struct platform_device *pdev) +{ + struct mxc_mmc_platform_data *mmc_plat = pdev->dev.platform_data; + struct mmc_host *mmc; + struct mxcmci_host *host = NULL; + int card_gpio_status; + int ret = -ENODEV; + + if (!mmc_plat) { + return -EINVAL; + } + + mmc = mmc_alloc_host(sizeof(struct mxcmci_host), &pdev->dev); + if (!mmc) { + return -ENOMEM; + } + host = mmc_priv(mmc); + platform_set_drvdata(pdev, mmc); + + mmc->ops = &mxcmci_ops; + mmc->ocr_avail = mmc_plat->ocr_mask; + + /* Hack to work with LP1070 */ + if (mmc->ocr_avail && ~(MMC_VDD_31_32 - 1) == 0) + mmc->ocr_avail |= MMC_VDD_31_32; + + mmc->max_phys_segs = NR_SG; + mmc->caps = MMC_CAP_4_BIT_DATA | MMC_CAP_SDIO_IRQ; + + mmc->f_min = mmc_plat->min_clk; + mmc->f_max = mmc_plat->max_clk; + mmc->max_req_size = 32 * 1024; + mmc->max_seg_size = mmc->max_req_size; + mmc->max_blk_count = 32; + + spin_lock_init(&host->lock); + host->mmc = mmc; + host->dma = -1; + host->dma_dir = DMA_NONE; + host->id = pdev->id; + host->mxc_mmc_suspend_flag = 0; + host->mode = -1; + host->plat_data = mmc_plat; + if (!host->plat_data) { + ret = -EINVAL; + goto out0; + } + + /* Get pwr supply for SDHC */ + if (NULL != mmc_plat->power_mmc) { + host->regulator_mmc = + regulator_get(&pdev->dev, mmc_plat->power_mmc); + if (IS_ERR(host->regulator_mmc)) { + ret = PTR_ERR(host->regulator_mmc); + goto out1; + } + if (!regulator_is_enabled(host->regulator_mmc)) { + if (regulator_enable(host->regulator_mmc) == 0) { + pr_debug("mmc power on\n"); + msleep(1); + } + } + } + + gpio_sdhc_active(pdev->id); + + host->clk = clk_get(&pdev->dev, "sdhc_clk"); + pr_debug("SDHC:%d clock:%lu\n", pdev->id, clk_get_rate(host->clk)); + clk_enable(host->clk); + + host->res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!host->res) { + ret = -ENOMEM; + goto out2; + } + + if (!request_mem_region(host->res->start, + host->res->end - + host->res->start + 1, pdev->name)) { + printk(KERN_ERR "request_mem_region failed\n"); + ret = -ENOMEM; + goto out2; + } + host->base = (void *)IO_ADDRESS(host->res->start); + if (!host->base) { + ret = -ENOMEM; + goto out3; + } + + host->irq = platform_get_irq(pdev, 0); + if (!host->irq) { + ret = -ENOMEM; + goto out3; + } + + if (!host->plat_data->card_fixed) { + host->detect_irq = platform_get_irq(pdev, 1); + if (!host->detect_irq) + goto out3; + + do { + card_gpio_status = + host->plat_data->status(host->mmc->parent); + if (card_gpio_status) + set_irq_type(host->detect_irq, + IRQF_TRIGGER_FALLING); + else + set_irq_type(host->detect_irq, + IRQF_TRIGGER_RISING); + + } while (card_gpio_status != + host->plat_data->status(host->mmc->parent)); + + ret = request_irq(host->detect_irq, mxcmci_gpio_irq, 0, + pdev->name, host); + if (ret) + goto out3; + } + + mxcmci_softreset(host); + + if (__raw_readl(host->base + MMC_REV_NO) != SDHC_REV_NO) { + printk(KERN_ERR "%s: wrong rev.no. 0x%08x. aborting.\n", + pdev->name, MMC_REV_NO); + goto out3; + } + __raw_writel(READ_TO_VALUE, host->base + MMC_READ_TO); + + __raw_writel(INT_CNTR_END_CMD_RES, host->base + MMC_INT_CNTR); + + ret = request_irq(host->irq, mxcmci_irq, 0, pdev->name, host); + if (ret) { + goto out4; + } + + ret = mmc_add_host(mmc); + if (ret < 0) + goto out5; + + printk(KERN_INFO "%s-%d found\n", pdev->name, pdev->id); + if (host->id < MAX_HOST) + hosts[host->id] = host->mmc; + + return 0; + + out5: + free_irq(host->irq, host); + out4: + free_irq(host->detect_irq, host); + out3: + release_mem_region(pdev->resource[0].start, + pdev->resource[0].end - pdev->resource[0].start + 1); + out2: + clk_disable(host->clk); + regulator_disable(host->regulator_mmc); + regulator_put(host->regulator_mmc); + out1: + gpio_sdhc_inactive(pdev->id); + out0: + mmc_free_host(mmc); + platform_set_drvdata(pdev, NULL); + return ret; +} + +/*! + * Dissociates the driver from the SDHC device. Removes the appropriate SDHC + * module structure from the core driver. + * + * @param pdev the device structure used to give information on which SDHC + * to remove + * + * @return The function always returns 0. + */ +static int mxcmci_remove(struct platform_device *pdev) +{ + struct mmc_host *mmc = platform_get_drvdata(pdev); + + if (mmc) { + struct mxcmci_host *host = mmc_priv(mmc); + + hosts[host->id] = NULL; + mmc_remove_host(mmc); + free_irq(host->irq, host); + free_irq(host->detect_irq, host); +#ifdef MXC_MMC_DMA_ENABLE + mxc_dma_free(host->dma); +#endif + release_mem_region(host->res->start, + host->res->end - host->res->start + 1); + mmc_free_host(mmc); + if (NULL != host->regulator_mmc) + regulator_put(host->regulator_mmc); + gpio_sdhc_inactive(pdev->id); + } + platform_set_drvdata(pdev, NULL); + return 0; +} + +#ifdef CONFIG_PM + +/*! + * This function is called to put the SDHC in a low power state. Refer to the + * document driver-model/driver.txt in the kernel source tree for more + * information. + * + * @param pdev the device structure used to give information on which SDHC + * to suspend + * @param state the power state the device is entering + * + * @return The function always returns 0. + */ +static int mxcmci_suspend(struct platform_device *pdev, pm_message_t state) +{ + struct mmc_host *mmc = platform_get_drvdata(pdev); + struct mxcmci_host *host = mmc_priv(mmc); + int ret = 0; + + if (mmc) { + host->mxc_mmc_suspend_flag = 1; + ret = mmc_suspend_host(mmc, state); + } + + clk_disable(host->clk); + /* + * The CD INT should be disabled in the suspend + * and enabled in resumed. + * Otherwise, the system would be halt when wake + * up with the situation that there is a card + * insertion during the system is in suspend mode. + */ + disable_irq(host->detect_irq); + + gpio_sdhc_inactive(pdev->id); + + if (host->regulator_mmc) + regulator_disable(host->regulator_mmc); + + return ret; +} + +/*! + * This function is called to bring the SDHC back from a low power state. Refer + * to the document driver-model/driver.txt in the kernel source tree for more + * information. + * + * @param pdev the device structure used to give information on which SDHC + * to resume + * + * @return The function always returns 0. + */ +static int mxcmci_resume(struct platform_device *pdev) +{ + struct mmc_host *mmc = platform_get_drvdata(pdev); + struct mxcmci_host *host = mmc_priv(mmc); + int ret = 0; + + /* + * Note that a card insertion interrupt will cause this + * driver to resume automatically. In that case we won't + * actually have to do any work here. Return success. + */ + if (!host->mxc_mmc_suspend_flag) { + return 0; + } + + /* enable pwr supply for SDHC */ + if (host->regulator_mmc && !regulator_is_enabled(host->regulator_mmc)) { + regulator_enable(host->regulator_mmc); + msleep(1); + } + + gpio_sdhc_active(pdev->id); + + clk_enable(host->clk); + + if (mmc) { + ret = mmc_resume_host(mmc); + host->mxc_mmc_suspend_flag = 0; + } + + enable_irq(host->detect_irq); + + return ret; +} +#else +#define mxcmci_suspend NULL +#define mxcmci_resume NULL +#endif /* CONFIG_PM */ + +/*! + * This structure contains pointers to the power management callback functions. + */ +static struct platform_driver mxcmci_driver = { + .driver = { + .name = "mxcmci", + }, + .probe = mxcmci_probe, + .remove = mxcmci_remove, + .suspend = mxcmci_suspend, + .resume = mxcmci_resume, +}; + +/*! + * This function is used to initialize the MMC/SD driver module. The function + * registers the power management callback functions with the kernel and also + * registers the MMC/SD callback functions with the core MMC/SD driver. + * + * @return The function returns 0 on success and a non-zero value on failure. + */ +static int __init mxcmci_init(void) +{ + printk(KERN_INFO "MXC MMC/SD driver\n"); + return platform_driver_register(&mxcmci_driver); +} + +/*! + * This function is used to cleanup all resources before the driver exits. + */ +static void __exit mxcmci_exit(void) +{ + platform_driver_unregister(&mxcmci_driver); +} + +module_init(mxcmci_init); +module_exit(mxcmci_exit); + +MODULE_DESCRIPTION("MXC Multimedia Card Interface Driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/mmc/host/mxc_mmc.h b/drivers/mmc/host/mxc_mmc.h new file mode 100644 index 000000000000..d86cc8f7c726 --- /dev/null +++ b/drivers/mmc/host/mxc_mmc.h @@ -0,0 +1,124 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#ifndef __MXC_MMC_REG_H__ +#define __MXC_MMC_REG_H__ + +/*! + * @defgroup MMC_SD MMC/SD Driver + */ + +/*! + * @file mxc_mmc.h + * + * @brief Driver for the Freescale Semiconductor MXC SDHC modules. + * + * This file defines offsets and bits of SDHC registers. SDHC is also referred as + * MMC/SD controller + * + * @ingroup MMC_SD + */ + +/*! + * Number of SDHC modules + */ + +#define SDHC_MMC_WML 16 +#define SDHC_SD_WML 64 +#define DRIVER_NAME "MXCMMC" +#define SDHC_MEM_SIZE 16384 +#define SDHC_REV_NO 0x400 +#define READ_TO_VALUE 0x2db4 + +/* Address offsets of the SDHC registers */ +#define MMC_STR_STP_CLK 0x00 /* Clock Control Reg */ +#define MMC_STATUS 0x04 /* Status Reg */ +#define MMC_CLK_RATE 0x08 /* Clock Rate Reg */ +#define MMC_CMD_DAT_CONT 0x0C /* Command and Data Control Reg */ +#define MMC_RES_TO 0x10 /* Response Time-out Reg */ +#define MMC_READ_TO 0x14 /* Read Time-out Reg */ +#define MMC_BLK_LEN 0x18 /* Block Length Reg */ +#define MMC_NOB 0x1C /* Number of Blocks Reg */ +#define MMC_REV_NO 0x20 /* Revision Number Reg */ +#define MMC_INT_CNTR 0x24 /* Interrupt Control Reg */ +#define MMC_CMD 0x28 /* Command Number Reg */ +#define MMC_ARG 0x2C /* Command Argument Reg */ +#define MMC_RES_FIFO 0x34 /* Command Response Reg */ +#define MMC_BUFFER_ACCESS 0x38 /* Data Buffer Access Reg */ +#define MMC_REM_NOB 0x40 /* Remaining NOB Reg */ +#define MMC_REM_BLK_SIZE 0x44 /* Remaining Block Size Reg */ + +/* Bit definitions for STR_STP_CLK */ +#define STR_STP_CLK_RESET (1<<3) +#define STR_STP_CLK_START_CLK (1<<1) +#define STR_STP_CLK_STOP_CLK (1<<0) + +/* Bit definitions for STATUS */ +#define STATUS_CARD_INSERTION (1<<31) +#define STATUS_CARD_REMOVAL (1<<30) +#define STATUS_YBUF_EMPTY (1<<29) +#define STATUS_XBUF_EMPTY (1<<28) +#define STATUS_YBUF_FULL (1<<27) +#define STATUS_XBUF_FULL (1<<26) +#define STATUS_BUF_UND_RUN (1<<25) +#define STATUS_BUF_OVFL (1<<24) +#define STATUS_SDIO_INT_ACTIVE (1<<14) +#define STATUS_END_CMD_RESP (1<<13) +#define STATUS_WRITE_OP_DONE (1<<12) +#define STATUS_READ_OP_DONE (1<<11) +#define STATUS_WR_CRC_ERROR_CODE_MASK (3<<9) +#define STATUS_CARD_BUS_CLK_RUN (1<<8) +#define STATUS_BUF_READ_RDY (1<<7) +#define STATUS_BUF_WRITE_RDY (1<<6) +#define STATUS_RESP_CRC_ERR (1<<5) +#define STATUS_READ_CRC_ERR (1<<3) +#define STATUS_WRITE_CRC_ERR (1<<2) +#define STATUS_TIME_OUT_RESP (1<<1) +#define STATUS_TIME_OUT_READ (1<<0) +#define STATUS_ERR_MASK 0x3f + +/* Clock rate definitions */ +#define CLK_RATE_PRESCALER(x) ((x) & 0xF) +#define CLK_RATE_CLK_DIVIDER(x) (((x) & 0xF) << 4) + +/* Bit definitions for CMD_DAT_CONT */ +#define CMD_DAT_CONT_CMD_RESP_LONG_OFF (1<<12) +#define CMD_DAT_CONT_STOP_READWAIT (1<<11) +#define CMD_DAT_CONT_START_READWAIT (1<<10) +#define CMD_DAT_CONT_BUS_WIDTH_1 (0<<8) +#define CMD_DAT_CONT_BUS_WIDTH_4 (2<<8) +#define CMD_DAT_CONT_INIT (1<<7) +#define CMD_DAT_CONT_WRITE (1<<4) +#define CMD_DAT_CONT_DATA_ENABLE (1<<3) +#define CMD_DAT_CONT_RESPONSE_FORMAT_R1 (1) +#define CMD_DAT_CONT_RESPONSE_FORMAT_R2 (2) +#define CMD_DAT_CONT_RESPONSE_FORMAT_R3 (3) +#define CMD_DAT_CONT_RESPONSE_FORMAT_R4 (4) +#define CMD_DAT_CONT_RESPONSE_FORMAT_R5 (5) +#define CMD_DAT_CONT_RESPONSE_FORMAT_R6 (6) + +/* Bit definitions for INT_CNTR */ +#define INT_CNTR_SDIO_INT_WKP_EN (1<<18) +#define INT_CNTR_CARD_INSERTION_WKP_EN (1<<17) +#define INT_CNTR_CARD_REMOVAL_WKP_EN (1<<16) +#define INT_CNTR_CARD_INSERTION_EN (1<<15) +#define INT_CNTR_CARD_REMOVAL_EN (1<<14) +#define INT_CNTR_SDIO_IRQ_EN (1<<13) +#define INT_CNTR_DAT0_EN (1<<12) +#define INT_CNTR_BUF_READ_EN (1<<4) +#define INT_CNTR_BUF_WRITE_EN (1<<3) +#define INT_CNTR_END_CMD_RES (1<<2) +#define INT_CNTR_WRITE_OP_DONE (1<<1) +#define INT_CNTR_READ_OP_DONE (1<<0) + +#endif /* __MXC_MMC_REG_H__ */ diff --git a/drivers/mmc/host/mxs-mmc.c b/drivers/mmc/host/mxs-mmc.c new file mode 100644 index 000000000000..5e5c90430a42 --- /dev/null +++ b/drivers/mmc/host/mxs-mmc.c @@ -0,0 +1,1318 @@ +/* + * Portions copyright (C) 2003 Russell King, PXA MMCI Driver + * Portions copyright (C) 2004-2005 Pierre Ossman, W83L51xD SD/MMC driver + * + * Copyright 2008 Embedded Alley Solutions, Inc. + * Copyright 2009-2010 Freescale Semiconductor, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#define DRIVER_NAME "mxs-mmc" + +/* + * Card detect polling timeout + */ +#define MXS_MMC_DETECT_TIMEOUT (HZ/2) + +/* Max value supported for XFER_COUNT */ +#define SSP_BUFFER_SIZE (65535) + +#ifndef BF +#define BF(value, field) (((value) << BP_##field) & BM_##field) +#endif + +#ifndef HW_SSP_XFER_SIZE +#define HW_SSP_XFER_SIZE (0xFFFFFFFF) +#endif +#ifndef HW_SSP_BLOCK_SIZE +#define HW_SSP_BLOCK_SIZE (0xFFFFFFFF) +#endif + +#ifndef BP_SSP_XFER_SIZE_XFER_COUNT +#define BP_SSP_XFER_SIZE_XFER_COUNT BP_SSP_CTRL0_XFER_COUNT +#endif +#ifndef BM_SSP_XFER_SIZE_XFER_COUNT +#define BM_SSP_XFER_SIZE_XFER_COUNT BM_SSP_CTRL0_XFER_COUNT +#endif +#ifndef BF_SSP_XFER_SIZE_XFER_COUNT +#define BF_SSP_XFER_SIZE_XFER_COUNT(v) \ + (((v) << 0) & BM_SSP_CTRL0_XFER_COUNT) +#endif + +#ifndef BP_SSP_BLOCK_SIZE_BLOCK_COUNT +#define BP_SSP_BLOCK_SIZE_BLOCK_COUNT 8 +#endif +#ifndef BM_SSP_BLOCK_SIZE_BLOCK_COUNT +#define BM_SSP_BLOCK_SIZE_BLOCK_COUNT 0x0000FF00 +#endif +#ifndef BF_SSP_BLOCK_SIZE_BLOCK_COUNT +#define BF_SSP_BLOCK_SIZE_BLOCK_COUNT(v) \ + (((v) << 8) & BM_SSP_BLOCK_SIZE_BLOCK_COUNT) +#endif +#ifndef BP_SSP_BLOCK_SIZE_BLOCK_SIZE +#define BP_SSP_BLOCK_SIZE_BLOCK_SIZE 16 +#endif +#ifndef BM_SSP_BLOCK_SIZE_BLOCK_SIZE +#define BM_SSP_BLOCK_SIZE_BLOCK_SIZE 0x000F0000 +#endif +#ifndef BF_SSP_BLOCK_SIZE_BLOCK_SIZE +#define BF_SSP_BLOCK_SIZE_BLOCK_SIZE(v) \ + (((v) << 16) & BM_SSP_BLOCK_SIZE_BLOCK_SIZE) +#endif +#ifndef BM_SSP_CMD0_DBL_DATA_RATE_EN +#define BM_SSP_CMD0_DBL_DATA_RATE_EN 0x02000000 +#endif + +struct mxs_mmc_host { + struct device *dev; + struct mmc_host *mmc; + + struct clk *clk; + unsigned int clkrt; + + struct mmc_request *mrq; + struct mmc_command *cmd; + struct mmc_data *data; + + /* data bus width 0:1bit, 1:4bit, 2:8bit */ + unsigned char bus_width; + + /* Whether SD card is present */ + unsigned present:1; + + /* Polling timer */ + struct timer_list timer; + + /* SSP interface which MMC/SD card slot is attached to */ + void __iomem *ssp_base; + + /* DMA channel used for this host */ + unsigned int dmach; + + /* IRQs */ + int dmairq, errirq; + + /* DMA descriptor to transfer data over SSP interface */ + struct mxs_dma_desc *dma_desc; + + /* DMA buffer */ + dma_addr_t dma_buf_phys; + char *dma_buf; + + struct completion dma_done; + /* status on last interrupt */ + u32 status; + int read_uA, write_uA; + struct regulator *regulator; /*! Regulator */ + + spinlock_t lock; + int sdio_irq_en; +}; + +/* Return read only state of card */ +static int mxs_mmc_get_ro(struct mmc_host *mmc) +{ + struct mxs_mmc_host *host = mmc_priv(mmc); + struct mxs_mmc_platform_data *mmc_data = host->dev->platform_data; + + if (mmc_data && mmc_data->get_wp) + return mmc_data->get_wp(); + + return 0; +} + +/* Detect if card is plugged */ +static inline int mxs_mmc_is_plugged(struct mxs_mmc_host *host) +{ + u32 status = __raw_readl(host->ssp_base + HW_SSP_STATUS); + return !(status & BM_SSP_STATUS_CARD_DETECT); +} + +static void mxs_mmc_reset(struct mxs_mmc_host *host); +/* Card detection polling function */ +static void mxs_mmc_detect_poll(unsigned long arg) +{ + struct mxs_mmc_host *host = (struct mxs_mmc_host *)arg; + int card_status; + + card_status = mxs_mmc_is_plugged(host); + if (card_status != host->present) { + /* Reset MMC block */ + mxs_mmc_reset(host); + host->present = card_status; + mmc_detect_change(host->mmc, 0); + } + + mod_timer(&host->timer, jiffies + MXS_MMC_DETECT_TIMEOUT); +} + +#define MXS_MMC_IRQ_BITS (BM_SSP_CTRL1_SDIO_IRQ | \ + BM_SSP_CTRL1_RESP_ERR_IRQ | \ + BM_SSP_CTRL1_RESP_TIMEOUT_IRQ | \ + BM_SSP_CTRL1_DATA_TIMEOUT_IRQ | \ + BM_SSP_CTRL1_DATA_CRC_IRQ | \ + BM_SSP_CTRL1_FIFO_UNDERRUN_IRQ | \ + BM_SSP_CTRL1_RECV_TIMEOUT_IRQ | \ + BM_SSP_CTRL1_FIFO_OVERRUN_IRQ) + +#define MXS_MMC_ERR_BITS (BM_SSP_CTRL1_RESP_ERR_IRQ | \ + BM_SSP_CTRL1_RESP_TIMEOUT_IRQ | \ + BM_SSP_CTRL1_DATA_TIMEOUT_IRQ | \ + BM_SSP_CTRL1_DATA_CRC_IRQ | \ + BM_SSP_CTRL1_RECV_TIMEOUT_IRQ) + +/* SSP DMA interrupt handler */ +static irqreturn_t mmc_irq_handler(int irq, void *dev_id) +{ + struct mxs_mmc_host *host = dev_id; + u32 c1; + + c1 = __raw_readl(host->ssp_base + HW_SSP_CTRL1); + __raw_writel(c1 & MXS_MMC_IRQ_BITS, + host->ssp_base + HW_SSP_CTRL1_CLR); + if (irq == host->dmairq) { + dev_dbg(host->dev, "dma irq 0x%x and stop DMA.\n", irq); + mxs_dma_ack_irq(host->dmach); + /* STOP the dma transfer here. */ + mxs_dma_cooked(host->dmach, NULL); + } + + if ((irq == host->dmairq) || (c1 & MXS_MMC_ERR_BITS)) + if (host->cmd) { + host->status = + __raw_readl(host->ssp_base + HW_SSP_STATUS); + complete(&host->dma_done); + } + + if ((c1 & BM_SSP_CTRL1_SDIO_IRQ) && (c1 & BM_SSP_CTRL1_SDIO_IRQ_EN)) + mmc_signal_sdio_irq(host->mmc); + + return IRQ_HANDLED; +} + +/* + * Check for MMC command errors + * Returns error code or zerro if no errors + */ +static inline int mxs_mmc_cmd_error(u32 status) +{ + int err = 0; + + if (status & BM_SSP_STATUS_TIMEOUT) + err = -ETIMEDOUT; + else if (status & BM_SSP_STATUS_RESP_TIMEOUT) + err = -ETIMEDOUT; + else if (status & BM_SSP_STATUS_RESP_CRC_ERR) + err = -EILSEQ; + else if (status & BM_SSP_STATUS_RESP_ERR) + err = -EIO; + + return err; +} + +/* Send the BC command to the device */ +static void mxs_mmc_bc(struct mxs_mmc_host *host) +{ + struct mmc_command *cmd = host->cmd; + struct mxs_dma_desc *dma_desc = host->dma_desc; + unsigned long flags; + + dma_desc->cmd.cmd.bits.command = NO_DMA_XFER; + dma_desc->cmd.cmd.bits.irq = 1; + dma_desc->cmd.cmd.bits.dec_sem = 1; + dma_desc->cmd.cmd.bits.wait4end = 1; + dma_desc->cmd.cmd.bits.pio_words = 3; + dma_desc->cmd.cmd.bits.bytes = 0; + + dma_desc->cmd.pio_words[0] = BM_SSP_CTRL0_ENABLE | + BM_SSP_CTRL0_IGNORE_CRC; + dma_desc->cmd.pio_words[1] = BF(cmd->opcode, SSP_CMD0_CMD) | + BM_SSP_CMD0_APPEND_8CYC; + dma_desc->cmd.pio_words[2] = BF(cmd->arg, SSP_CMD1_CMD_ARG); + + if (host->sdio_irq_en) { + dma_desc->cmd.pio_words[0] |= BM_SSP_CTRL0_SDIO_IRQ_CHECK; + dma_desc->cmd.pio_words[1] |= BM_SSP_CMD0_CONT_CLKING_EN \ + | BM_SSP_CMD0_SLOW_CLKING_EN; + } + + init_completion(&host->dma_done); + mxs_dma_reset(host->dmach); + if (mxs_dma_desc_append(host->dmach, host->dma_desc) < 0) + dev_err(host->dev, "mmc_dma_desc_append failed\n"); + dev_dbg(host->dev, "%s start DMA.\n", __func__); + if (mxs_dma_enable(host->dmach) < 0) + dev_err(host->dev, "mmc_dma_enable failed\n"); + + wait_for_completion(&host->dma_done); + + cmd->error = mxs_mmc_cmd_error(host->status); + + if (cmd->error) { + dev_dbg(host->dev, "Command error 0x%x\n", cmd->error); + mxs_dma_reset(host->dmach); + } + mxs_dma_disable(host->dmach); +} + +/* Send the ac command to the device */ +static void mxs_mmc_ac(struct mxs_mmc_host *host) +{ + struct mmc_command *cmd = host->cmd; + struct mxs_dma_desc *dma_desc = host->dma_desc; + u32 ignore_crc, resp, long_resp; + u32 ssp_ctrl0; + u32 ssp_cmd0; + u32 ssp_cmd1; + unsigned long flags; + + ignore_crc = (mmc_resp_type(cmd) & MMC_RSP_CRC) ? + 0 : BM_SSP_CTRL0_IGNORE_CRC; + resp = (mmc_resp_type(cmd) & MMC_RSP_PRESENT) ? + BM_SSP_CTRL0_GET_RESP : 0; + long_resp = (mmc_resp_type(cmd) & MMC_RSP_136) ? + BM_SSP_CTRL0_LONG_RESP : 0; + + dma_desc->cmd.cmd.bits.command = NO_DMA_XFER; + dma_desc->cmd.cmd.bits.irq = 1; + dma_desc->cmd.cmd.bits.dec_sem = 1; + dma_desc->cmd.cmd.bits.wait4end = 1; + dma_desc->cmd.cmd.bits.pio_words = 3; + dma_desc->cmd.cmd.bits.bytes = 0; + + ssp_ctrl0 = BM_SSP_CTRL0_ENABLE | ignore_crc | long_resp | resp; + ssp_cmd0 = BF(cmd->opcode, SSP_CMD0_CMD); + ssp_cmd1 = BF(cmd->arg, SSP_CMD1_CMD_ARG); + + if (host->sdio_irq_en) { + ssp_ctrl0 |= BM_SSP_CTRL0_SDIO_IRQ_CHECK; + ssp_cmd0 |= BM_SSP_CMD0_CONT_CLKING_EN \ + | BM_SSP_CMD0_SLOW_CLKING_EN; + } + + dma_desc->cmd.pio_words[0] = ssp_ctrl0; + dma_desc->cmd.pio_words[1] = ssp_cmd0; + dma_desc->cmd.pio_words[2] = ssp_cmd1; + + mxs_dma_reset(host->dmach); + init_completion(&host->dma_done); + if (mxs_dma_desc_append(host->dmach, host->dma_desc) < 0) + dev_err(host->dev, "mmc_dma_desc_append failed\n"); + dev_dbg(host->dev, "%s start DMA.\n", __func__); + if (mxs_dma_enable(host->dmach) < 0) + dev_err(host->dev, "mmc_dma_enable failed\n"); + wait_for_completion(&host->dma_done); + + switch (mmc_resp_type(cmd)) { + case MMC_RSP_NONE: + while (__raw_readl(host->ssp_base + HW_SSP_CTRL0) + & BM_SSP_CTRL0_RUN) + continue; + break; + case MMC_RSP_R1: + case MMC_RSP_R1B: + case MMC_RSP_R3: + cmd->resp[0] = + __raw_readl(host->ssp_base + HW_SSP_SDRESP0); + break; + case MMC_RSP_R2: + cmd->resp[3] = + __raw_readl(host->ssp_base + HW_SSP_SDRESP0); + cmd->resp[2] = + __raw_readl(host->ssp_base + HW_SSP_SDRESP1); + cmd->resp[1] = + __raw_readl(host->ssp_base + HW_SSP_SDRESP2); + cmd->resp[0] = + __raw_readl(host->ssp_base + HW_SSP_SDRESP3); + break; + default: + dev_warn(host->dev, "Unsupported response type 0x%x\n", + mmc_resp_type(cmd)); + BUG(); + break; + } + + cmd->error = mxs_mmc_cmd_error(host->status); + + if (cmd->error) { + dev_dbg(host->dev, "Command error 0x%x\n", cmd->error); + mxs_dma_reset(host->dmach); + } + mxs_dma_disable(host->dmach); +} + +/* Copy data between sg list and dma buffer */ +static unsigned int mxs_sg_dma_copy(struct mxs_mmc_host *host, + unsigned int size, int to_dma) +{ + struct mmc_data *data = host->cmd->data; + unsigned int copy_size, bytes_copied = 0; + struct scatterlist *sg; + char *dmabuf = host->dma_buf; + char *sgbuf; + int len, i; + + sg = data->sg; + len = data->sg_len; + + /* + * Just loop through all entries. Size might not + * be the entire list though so make sure that + * we do not transfer too much. + */ + for (i = 0; i < len; i++) { + sgbuf = kmap_atomic(sg_page(&sg[i]), KM_BIO_SRC_IRQ) + + sg[i].offset; + copy_size = size < sg[i].length ? size : sg[i].length; + if (to_dma) + memcpy(dmabuf, sgbuf, copy_size); + else + memcpy(sgbuf, dmabuf, copy_size); + kunmap_atomic(sgbuf, KM_BIO_SRC_IRQ); + + dmabuf += sg[i].length; + + bytes_copied += copy_size; + size -= copy_size; + + if (size == 0) + break; + } + + return bytes_copied; +} + +/* Convert ns to tick count according to the current sclk speed */ +static unsigned short mxs_ns_to_ssp_ticks(unsigned clock_rate, unsigned ns) +{ + const unsigned int ssp_timeout_mul = 4096; + /* + * Calculate ticks in ms since ns are large numbers + * and might overflow + */ + const unsigned int clock_per_ms = clock_rate / 1000; + const unsigned int ms = ns / 1000; + const unsigned int ticks = ms * clock_per_ms; + const unsigned int ssp_ticks = ticks / ssp_timeout_mul; + + BUG_ON(ssp_ticks == 0); + return ssp_ticks; +} + +static void __init_reg(struct device *dev, struct regulator **pp_reg) +{ +#if 0 + /* Up to now, there is not pwr ctrl. Just keep it for future usage. */ + struct regulator *reg = *pp_reg; + + if (!reg) { + reg = regulator_get(NULL, "mmc_ssp-1"); + if (reg && !IS_ERR(reg)) + regulator_set_mode(reg, REGULATOR_MODE_NORMAL); + else + reg = NULL; + *pp_reg = reg; + } +#endif +} + +/* Send adtc command to the card */ +static void mxs_mmc_adtc(struct mxs_mmc_host *host) +{ + struct mmc_command *cmd = host->cmd; + struct mxs_dma_desc *dma_desc = host->dma_desc; + int ignore_crc, resp, long_resp; + int is_reading = 0; + unsigned int copy_size; + unsigned int ssp_ver_major; + + u32 ssp_ctrl0; + u32 ssp_cmd0; + u32 ssp_cmd1; + u32 timeout; + u32 val; + + u32 data_size = cmd->data->blksz * cmd->data->blocks; + u32 log2_block_size; + unsigned long flags; + + ignore_crc = mmc_resp_type(cmd) & MMC_RSP_CRC ? 0 : 1; + resp = mmc_resp_type(cmd) & MMC_RSP_PRESENT ? 1 : 0; + long_resp = mmc_resp_type(cmd) & MMC_RSP_136 ? 1 : 0; + + dev_dbg(host->dev, "ADTC command:\n" + "response: %d, ignore crc: %d\n" + "data list: %u, blocksz: %u, blocks: %u, timeout: %uns %uclks, " + "flags: 0x%x\n", resp, ignore_crc, cmd->data->sg_len, + cmd->data->blksz, cmd->data->blocks, cmd->data->timeout_ns, + cmd->data->timeout_clks, cmd->data->flags); + + if (cmd->data->flags & MMC_DATA_WRITE) { + dev_dbg(host->dev, "Data Write\n"); + copy_size = mxs_sg_dma_copy(host, data_size, 1); + BUG_ON(copy_size < data_size); + is_reading = 0; + if (!host->regulator) + __init_reg(host->dev, &host->regulator); + if (host->regulator) + regulator_set_current_limit(host->regulator, + host->write_uA, + host->write_uA); + } else if (cmd->data->flags & MMC_DATA_READ) { + dev_dbg(host->dev, "Data Read\n"); + is_reading = 1; + if (!host->regulator) + __init_reg(host->dev, &host->regulator); + if (host->regulator) + regulator_set_current_limit(host->regulator, + host->read_uA, + host->read_uA); + } else { + dev_warn(host->dev, "Unsuspported data mode, 0x%x\n", + cmd->data->flags); + BUG(); + } + + BUG_ON(cmd->data->flags & MMC_DATA_STREAM); + /* BUG_ON((data_size % 8) > 0); */ + + /* when is_reading is set, DMA controller performs WRITE operation. */ + dma_desc->cmd.cmd.bits.command = is_reading ? DMA_WRITE : DMA_READ; + dma_desc->cmd.cmd.bits.irq = 1; + dma_desc->cmd.cmd.bits.dec_sem = 1; + dma_desc->cmd.cmd.bits.wait4end = 1; + dma_desc->cmd.cmd.bits.pio_words = 3; + dma_desc->cmd.cmd.bits.bytes = data_size; + + ssp_ver_major = __raw_readl(host->ssp_base + HW_SSP_VERSION) >> 24; + dev_dbg(host->dev, "ssp ver major is 0x%x\n", ssp_ver_major); + if (ssp_ver_major > 3) { + __raw_writel(data_size, host->ssp_base + HW_SSP_XFER_SIZE); + ssp_ctrl0 = (ignore_crc ? BM_SSP_CTRL0_IGNORE_CRC : 0) | + (resp ? BM_SSP_CTRL0_GET_RESP : 0) | + (long_resp ? BM_SSP_CTRL0_LONG_RESP : 0) | + (is_reading ? BM_SSP_CTRL0_READ : 0) | + BM_SSP_CTRL0_DATA_XFER | BM_SSP_CTRL0_WAIT_FOR_IRQ | + BM_SSP_CTRL0_ENABLE; + if (host->bus_width == 2) + ssp_ctrl0 |= BF(BV_SSP_CTRL0_BUS_WIDTH__EIGHT_BIT, + SSP_CTRL0_BUS_WIDTH); + else if (host->bus_width == 1) + ssp_ctrl0 |= BF(BV_SSP_CTRL0_BUS_WIDTH__FOUR_BIT, + SSP_CTRL0_BUS_WIDTH); + else + ssp_ctrl0 |= BF(BV_SSP_CTRL0_BUS_WIDTH__ONE_BIT, + SSP_CTRL0_BUS_WIDTH); + } else + ssp_ctrl0 = (ignore_crc ? BM_SSP_CTRL0_IGNORE_CRC : 0) | + (resp ? BM_SSP_CTRL0_GET_RESP : 0) | + (long_resp ? BM_SSP_CTRL0_LONG_RESP : 0) | + (is_reading ? BM_SSP_CTRL0_READ : 0) | + BM_SSP_CTRL0_DATA_XFER | BM_SSP_CTRL0_WAIT_FOR_IRQ | + BM_SSP_CTRL0_ENABLE | + BF(data_size, SSP_XFER_SIZE_XFER_COUNT) | + BF(host->bus_width ? + BV_SSP_CTRL0_BUS_WIDTH__FOUR_BIT : + BV_SSP_CTRL0_BUS_WIDTH__ONE_BIT, + SSP_CTRL0_BUS_WIDTH); + + /* + * We need to set the hardware register to the logarithm to base 2 of + * the block size. + */ + log2_block_size = ilog2(cmd->data->blksz); + dev_dbg(host->dev, "%s blksz is 0x%x.\n", __func__, log2_block_size); + + if (ssp_ver_major > 3) { + /* Configure the CMD0 */ + ssp_cmd0 = BF(cmd->opcode, SSP_CMD0_CMD); + + /* Configure the BLOCK SIZE and BLOCK COUNT */ + if ((1<data->blksz) { + BUG_ON(cmd->data->blocks > 1); + __raw_writel(0, host->ssp_base + HW_SSP_BLOCK_SIZE); + } else{ + val = BF(log2_block_size, SSP_BLOCK_SIZE_BLOCK_SIZE) | + BF(cmd->data->blocks - 1, SSP_BLOCK_SIZE_BLOCK_COUNT); + __raw_writel(val, host->ssp_base + HW_SSP_BLOCK_SIZE); + if (host->mmc->ios.bus_width & MMC_BUS_WIDTH_DDR) + /* Enable the DDR mode */ + ssp_cmd0 |= BM_SSP_CMD0_DBL_DATA_RATE_EN; + else + ssp_cmd0 &= ~BM_SSP_CMD0_DBL_DATA_RATE_EN; + + } + } else { + if ((1<data->blksz) { + BUG_ON(cmd->data->blocks > 1); + ssp_cmd0 = + BF(0, SSP_BLOCK_SIZE_BLOCK_SIZE) | + BF(cmd->opcode, SSP_CMD0_CMD) | + BF(0, SSP_BLOCK_SIZE_BLOCK_COUNT); + } else + ssp_cmd0 = + BF(log2_block_size, SSP_BLOCK_SIZE_BLOCK_SIZE) | + BF(cmd->opcode, SSP_CMD0_CMD) | + BF(cmd->data->blocks - 1, SSP_BLOCK_SIZE_BLOCK_COUNT); + } + if (host->sdio_irq_en) { + ssp_ctrl0 |= BM_SSP_CTRL0_SDIO_IRQ_CHECK; + ssp_cmd0 |= BM_SSP_CMD0_CONT_CLKING_EN \ + | BM_SSP_CMD0_SLOW_CLKING_EN; + } + if ((cmd->opcode == 12) || (cmd->opcode == 53)) + ssp_cmd0 |= BM_SSP_CMD0_APPEND_8CYC; + + ssp_cmd1 = BF(cmd->arg, SSP_CMD1_CMD_ARG); + + dma_desc->cmd.pio_words[0] = ssp_ctrl0; + dma_desc->cmd.pio_words[1] = ssp_cmd0; + dma_desc->cmd.pio_words[2] = ssp_cmd1; + + /* Set the timeout count */ + timeout = mxs_ns_to_ssp_ticks(host->clkrt, cmd->data->timeout_ns); + val = __raw_readl(host->ssp_base + HW_SSP_TIMING); + val &= ~(BM_SSP_TIMING_TIMEOUT); + val |= BF(timeout, SSP_TIMING_TIMEOUT); + __raw_writel(val, host->ssp_base + HW_SSP_TIMING); + + init_completion(&host->dma_done); + mxs_dma_reset(host->dmach); + if (mxs_dma_desc_append(host->dmach, host->dma_desc) < 0) + dev_err(host->dev, "mmc_dma_desc_append failed\n"); + dev_dbg(host->dev, "%s start DMA.\n", __func__); + if (mxs_dma_enable(host->dmach) < 0) + dev_err(host->dev, "mmc_dma_enable failed\n"); + wait_for_completion(&host->dma_done); + if (host->regulator) + regulator_set_current_limit(host->regulator, 0, 0); + + switch (mmc_resp_type(cmd)) { + case MMC_RSP_NONE: + break; + case MMC_RSP_R1: + case MMC_RSP_R3: + cmd->resp[0] = + __raw_readl(host->ssp_base + HW_SSP_SDRESP0); + break; + case MMC_RSP_R2: + cmd->resp[3] = + __raw_readl(host->ssp_base + HW_SSP_SDRESP0); + cmd->resp[2] = + __raw_readl(host->ssp_base + HW_SSP_SDRESP1); + cmd->resp[1] = + __raw_readl(host->ssp_base + HW_SSP_SDRESP2); + cmd->resp[0] = + __raw_readl(host->ssp_base + HW_SSP_SDRESP3); + break; + default: + dev_warn(host->dev, "Unsupported response type 0x%x\n", + mmc_resp_type(cmd)); + BUG(); + break; + } + + cmd->error = mxs_mmc_cmd_error(host->status); + + if (cmd->error) { + dev_dbg(host->dev, "Command error 0x%x\n", cmd->error); + mxs_dma_reset(host->dmach); + } else { + if (is_reading) { + cmd->data->bytes_xfered = + mxs_sg_dma_copy(host, data_size, 0); + } else + cmd->data->bytes_xfered = data_size; + + dev_dbg(host->dev, "Transferred %u bytes\n", + cmd->data->bytes_xfered); + } + mxs_dma_disable(host->dmach); +} + +/* Begin sedning a command to the card */ +static void mxs_mmc_start_cmd(struct mxs_mmc_host *host, + struct mmc_command *cmd) +{ + dev_dbg(host->dev, "MMC command:\n" + "type: 0x%x opcode: %u, arg: %u, flags 0x%x retries: %u\n", + mmc_cmd_type(cmd), cmd->opcode, cmd->arg, cmd->flags, + cmd->retries); + + host->cmd = cmd; + + switch (mmc_cmd_type(cmd)) { + case MMC_CMD_BC: + mxs_mmc_bc(host); + break; + case MMC_CMD_BCR: + mxs_mmc_ac(host); + break; + case MMC_CMD_AC: + mxs_mmc_ac(host); + break; + case MMC_CMD_ADTC: + mxs_mmc_adtc(host); + break; + default: + dev_warn(host->dev, "Unknown MMC command\n"); + BUG(); + break; + } + + dev_dbg(host->dev, "response: %u %u %u %u errors: %u\n", + cmd->resp[0], cmd->resp[1], cmd->resp[2], cmd->resp[3], + cmd->error); +} + +/* Handle MMC request */ +static void mxs_mmc_request(struct mmc_host *mmc, struct mmc_request *mrq) +{ + struct mxs_mmc_host *host = mmc_priv(mmc); + + dev_dbg(host->dev, "MMC request\n"); + BUG_ON(host->mrq != NULL); + host->mrq = mrq; + + mxs_mmc_start_cmd(host, mrq->cmd); + + if (mrq->data && mrq->data->stop) { + dev_dbg(host->dev, "Stop opcode is %u\n", + mrq->data->stop->opcode); + mxs_mmc_start_cmd(host, mrq->data->stop); + } + + host->mrq = NULL; + mmc_request_done(mmc, mrq); +} + +/* + * Change divisors to reflect the rate of 'hz'. Note that we should not + * play with clock rate, because the same source is used to clock both + * SSP ports. + */ +static void +mxs_set_sclk_speed(struct mxs_mmc_host *host, unsigned int hz) +{ + unsigned long ssp, bus_clk = 0; + u32 div1, div2; + u32 val; + struct mxs_mmc_platform_data *mmc_data = host->dev->platform_data; + + if (mmc_data && mmc_data->setclock) { + /* using SSP1, no timeout, clock rate 1 */ + __raw_writel(BF(0xFFFF, SSP_TIMING_TIMEOUT) | + BF(2, SSP_TIMING_CLOCK_DIVIDE) | + BF(0, SSP_TIMING_CLOCK_RATE), + host->ssp_base + HW_SSP_TIMING); + + /* + if the SSP is buggy and platform provides callback... + well, let it be. + */ + host->clkrt = mmc_data->setclock(hz); + dev_dbg(host->dev, "Setting clock rate to %d Hz" + "(requested %d)\n", + host->clkrt, hz); + dev_dbg(host->dev, "source %ldk\n", + clk_get_rate(host->clk)); + + return; + } + + /* + ...but the RightIdea(tm) is to set divisors to match + the requested clock. + */ + ssp = clk_get_rate(host->clk); + + for (div1 = 2; div1 < 254; div1 += 2) { + div2 = ssp / hz / div1; + if (div2 < 0x100) + break; + } + if (div1 >= 254) { + dev_err(host->dev, "Cannot set clock to %dHz\n", hz); + return; + } + + if (div2 == 0) + bus_clk = ssp / div1; + else + bus_clk = ssp / div1 / div2; + + dev_dbg(host->dev, "Setting clock rate to %ld Hz [%x+%x] " + "(requested %d), source %ldk\n", + bus_clk, div1, div2, hz, ssp); + + val = __raw_readl(host->ssp_base + HW_SSP_TIMING); + val &= ~(BM_SSP_TIMING_CLOCK_DIVIDE | BM_SSP_TIMING_CLOCK_RATE); + val |= BF(div1, SSP_TIMING_CLOCK_DIVIDE) | + BF(div2 - 1, SSP_TIMING_CLOCK_RATE); + __raw_writel(val, host->ssp_base + HW_SSP_TIMING); + + host->clkrt = bus_clk; +} + +/* Configure card */ +static void mxs_mmc_set_ios(struct mmc_host *mmc, struct mmc_ios *ios) +{ + struct mxs_mmc_host *host = mmc_priv(mmc); + struct mxs_mmc_platform_data *mmc_data; + + dev_dbg(host->dev, "MMC set ios:\n" + "Clock %u, vdd %u, bus_mode %u, chip_select %u, " + "power mode %u, bus_width %u\n", ios->clock, ios->vdd, + ios->bus_mode, ios->chip_select, ios->power_mode, + ios->bus_width); + + mmc_data = host->dev->platform_data; + + if (mmc_data->cmd_pullup) { + if (ios->bus_mode == MMC_BUSMODE_PUSHPULL) + mmc_data->cmd_pullup(0); + else + mmc_data->cmd_pullup(1); + } else + dev_warn(host->dev, + "Platform does not support CMD pin pullup control\n"); + + if ((ios->bus_width & ~MMC_BUS_WIDTH_DDR) == MMC_BUS_WIDTH_8) + host->bus_width = 2; + else if ((ios->bus_width & ~MMC_BUS_WIDTH_DDR) == MMC_BUS_WIDTH_4) + host->bus_width = 1; + else + host->bus_width = 0; + dev_dbg(host->dev, "MMC bus_width %u\n", host->bus_width); + + if (ios->clock > 0) + mxs_set_sclk_speed(host, ios->clock); +} + +static void mxs_mmc_enable_sdio_irq(struct mmc_host *mmc, int enable) +{ + unsigned long flags; + struct mxs_mmc_host *host = mmc_priv(mmc); + + spin_lock_irqsave(&host->lock, flags); + + if (enable) { + if (host->sdio_irq_en) + goto exit; + host->sdio_irq_en = 1; + __raw_writel(BM_SSP_CTRL0_SDIO_IRQ_CHECK, host->ssp_base + \ + HW_SSP_CTRL0_SET); + __raw_writel(BM_SSP_CTRL1_SDIO_IRQ_EN, host->ssp_base + \ + HW_SSP_CTRL1_SET); + + if (__raw_readl(host->ssp_base + \ + HW_SSP_STATUS) & BM_SSP_STATUS_SDIO_IRQ) + mmc_signal_sdio_irq(host->mmc); + + } else { + if (host->sdio_irq_en == 0) + goto exit; + host->sdio_irq_en = 0; + __raw_writel(BM_SSP_CTRL0_SDIO_IRQ_CHECK, \ + host->ssp_base + HW_SSP_CTRL0_CLR); + __raw_writel(BM_SSP_CTRL1_SDIO_IRQ_EN, \ + host->ssp_base + HW_SSP_CTRL1_CLR); + } + +exit: + spin_unlock_irqrestore(&host->lock, flags); + return; +} + +static const struct mmc_host_ops mxs_mmc_ops = { + .request = mxs_mmc_request, + .get_ro = mxs_mmc_get_ro, + .set_ios = mxs_mmc_set_ios, + .enable_sdio_irq = mxs_mmc_enable_sdio_irq, +}; + +/* + * MXS MMC/SD driver initialization + */ + +/* Reset ssp peripheral to default values */ +static void mxs_mmc_reset(struct mxs_mmc_host *host) +{ + u32 ssp_ctrl0; + u32 ssp_ctrl1; + + mxs_reset_block(host->ssp_base, 0); + + /* Configure SSP Control Register 0 */ + ssp_ctrl0 = + BM_SSP_CTRL0_IGNORE_CRC | + BF(BV_SSP_CTRL0_BUS_WIDTH__ONE_BIT, SSP_CTRL0_BUS_WIDTH); + + /* Configure SSP Control Register 1 */ + ssp_ctrl1 = + BM_SSP_CTRL1_DMA_ENABLE | + BM_SSP_CTRL1_RECV_TIMEOUT_IRQ_EN | + BM_SSP_CTRL1_DATA_CRC_IRQ_EN | + BM_SSP_CTRL1_DATA_TIMEOUT_IRQ_EN | + BM_SSP_CTRL1_RESP_TIMEOUT_IRQ_EN | + BM_SSP_CTRL1_RESP_ERR_IRQ_EN | + BF(BV_SSP_CTRL1_WORD_LENGTH__EIGHT_BITS, SSP_CTRL1_WORD_LENGTH) | + BF(BV_SSP_CTRL1_SSP_MODE__SD_MMC, SSP_CTRL1_SSP_MODE); + + __raw_writel(BF(0xFFFF, SSP_TIMING_TIMEOUT) | + BF(2, SSP_TIMING_CLOCK_DIVIDE) | + BF(0, SSP_TIMING_CLOCK_RATE), + host->ssp_base + HW_SSP_TIMING); + + if (host->sdio_irq_en) { + ssp_ctrl1 |= BM_SSP_CTRL1_SDIO_IRQ_EN; + ssp_ctrl0 |= BM_SSP_CTRL0_SDIO_IRQ_CHECK; + } + + /* Write the SSP Control Register 0 and 1 values out to the interface */ + __raw_writel(ssp_ctrl0, host->ssp_base + HW_SSP_CTRL0); + __raw_writel(ssp_ctrl1, host->ssp_base + HW_SSP_CTRL1); +} + +static void mxs_mmc_irq_release(struct mxs_mmc_host *host) +{ + free_irq(host->dmairq, host); + free_irq(host->errirq, host); +} + +static int __init mxs_mmc_irq_init(struct mxs_mmc_host *host) +{ + int ret; + + ret = request_irq(host->dmairq, mmc_irq_handler, 0, + DRIVER_NAME " dma", host); + if (ret) { + dev_err(host->dev, "Unable to set up DMA irq handler\n"); + goto out0; + } + + ret = request_irq(host->errirq, mmc_irq_handler, IRQF_SHARED, + DRIVER_NAME " error", host); + if (ret) { + dev_err(host->dev, "Unable to set up SSP error irq handler\n"); + goto out1; + } + return 0; + +out1: + free_irq(host->dmairq, host); +out0: + return ret; +} + +/* Allocate and initialise the DMA chains */ +static int mxs_mmc_dma_init(struct mxs_mmc_host *host, int reset) +{ + int ret = 0; + + if (!reset) { + /* Allocate DMA channel */ + ret = mxs_dma_request(host->dmach, + host->dev, "MXS MMC/SD"); + if (ret) { + dev_err(host->dev, "Unable to request DMA channel\n"); + return ret; + } + + host->dma_buf = dma_alloc_coherent(host->dev, SSP_BUFFER_SIZE, + &host->dma_buf_phys, + GFP_DMA); + if (host->dma_buf == NULL) { + dev_err(host->dev, "Unable to allocate DMA memory\n"); + ret = -ENOMEM; + goto out_mem; + } + + host->dma_desc = mxs_dma_alloc_desc(); + if (host->dma_desc == NULL) { + dev_err(host->dev, + "Unable to allocate DMA descriptor\n"); + ret = -ENOMEM; + goto out_cmd; + } + + host->dma_desc->cmd.next = (u32) host->dma_desc->address; + host->dma_desc->cmd.address = (u32) host->dma_buf_phys; + host->dma_desc->buffer = host->dma_buf; + } + + /* Reset DMA channel */ + mxs_dma_reset(host->dmach); + + /* Enable DMA interrupt */ + mxs_dma_ack_irq(host->dmach); + mxs_dma_enable_irq(host->dmach, 1); + + return 0; + +out_cmd: + dma_free_coherent(host->dev, SSP_BUFFER_SIZE, host->dma_buf, + host->dma_buf_phys); +out_mem: + mxs_dma_release(host->dmach, host->dev); + + return ret; +} + +static void mxs_mmc_dma_release(struct mxs_mmc_host *host) +{ + mxs_dma_reset(host->dmach); + + mxs_dma_enable_irq(host->dmach, 0); + mxs_dma_disable(host->dmach); + mxs_dma_get_cooked(host->dmach, NULL); + + dma_free_coherent(host->dev, SSP_BUFFER_SIZE, host->dma_buf, + host->dma_buf_phys); + + mxs_dma_free_desc(host->dma_desc); + mxs_dma_release(host->dmach, host->dev); +} + +/* Probe peripheral for connected cards */ +static int __init mxs_mmc_probe(struct platform_device *pdev) +{ + struct device *dev = &pdev->dev; + struct mxs_mmc_platform_data *mmc_data; + struct mxs_mmc_host *host; + struct mmc_host *mmc; + struct resource *r; + int err = 0; + unsigned int ssp_ver_major; + + mmc_data = dev->platform_data; + if (mmc_data == NULL) { + err = -EINVAL; + dev_err(dev, "Missing platform data\n"); + goto out; + } + + /* Allocate main MMC host structure */ + mmc = mmc_alloc_host(sizeof(struct mxs_mmc_host), dev); + if (!mmc) { + dev_err(dev, "Unable to allocate MMC host\n"); + err = -ENOMEM; + goto out; + } + host = mmc_priv(mmc); + + host->read_uA = mmc_data->read_uA; + host->write_uA = mmc_data->write_uA; + if (mmc_data->power_mmc != NULL) + host->regulator = regulator_get(NULL, mmc_data->power_mmc); + if (host->regulator && !IS_ERR(host->regulator)) + regulator_set_mode(host->regulator, REGULATOR_MODE_NORMAL); + else + host->regulator = NULL; + + /* get resources: */ + + /* + * 1. io memory + */ + r = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!r) { + dev_err(&pdev->dev, "failed to get IORESOURCE_MEM\n"); + err = -ENXIO; + goto out_res; + } + host->ssp_base = IO_ADDRESS(r->start); + + /* + * 2. DMA channel + */ + r = platform_get_resource(pdev, IORESOURCE_DMA, 0); + if (!r) { + dev_err(&pdev->dev, "failed to get IORESOURCE_DMA\n"); + err = -ENXIO; + goto out_res; + } + host->dmach = r->start; + + /* + * 3. two IRQs + */ + host->dmairq = platform_get_irq(pdev, 0); + if (host->dmairq < 0) { + dev_err(&pdev->dev, "failed to get IORESOURCE_IRQ/0\n"); + err = host->dmairq; + goto out_res; + } + + host->errirq = platform_get_irq(pdev, 1); + if (host->errirq < 0) { + dev_err(&pdev->dev, "failed to get IORESOURCE_IRQ/1\n"); + err = host->errirq; + goto out_res; + } + + /* Set up MMC pins */ + if (mmc_data->hw_init) { + err = mmc_data->hw_init(); + if (err) { + dev_err(dev, "MMC HW configuration failed\n"); + goto out_res; + } + } + + host->mmc = mmc; + host->dev = dev; + + host->sdio_irq_en = 0; + + /* Set minimal clock rate */ + host->clk = clk_get(dev, mmc_data->clock_mmc); + if (IS_ERR(host->clk)) { + err = PTR_ERR(host->clk); + dev_err(dev, "Clocks initialization failed\n"); + goto out_clk; + } + + clk_enable(host->clk); + mxs_set_sclk_speed(host, mmc_data->min_clk); + + /* Reset MMC block */ + mxs_mmc_reset(host); + + /* Enable DMA */ + err = mxs_mmc_dma_init(host, 0); + if (err) { + dev_err(dev, "DMA init failed\n"); + goto out_dma; + } + + /* Set up interrupt handlers */ + err = mxs_mmc_irq_init(host); + if (err) { + dev_err(dev, "IRQ initialization failed\n"); + goto out_irq; + } + + /* Get current card status for further cnanges tracking */ + host->present = mxs_mmc_is_plugged(host); + + /* Add a card detection polling timer */ + init_timer(&host->timer); + host->timer.function = mxs_mmc_detect_poll; + host->timer.data = (unsigned long)host; + host->timer.expires = jiffies + MXS_MMC_DETECT_TIMEOUT; + add_timer(&host->timer); + + mmc->ops = &mxs_mmc_ops; + mmc->f_min = mmc_data->min_clk; + mmc->f_max = mmc_data->max_clk; + mmc->caps = mmc_data->caps; + mmc->caps |= MMC_CAP_SD_HIGHSPEED | MMC_CAP_MMC_HIGHSPEED; + mmc->caps |= MMC_CAP_SDIO_IRQ; + + /* Maximum block count requests. */ + mmc->max_blk_size = 512; + ssp_ver_major = __raw_readl(host->ssp_base + HW_SSP_VERSION) >> 24; + dev_dbg(host->dev, "ssp ver major is 0x%x\n", ssp_ver_major); + if (ssp_ver_major > 3) { + mmc->max_blk_count = SSP_BUFFER_SIZE / 512; + mmc->max_hw_segs = SSP_BUFFER_SIZE / 512; + mmc->max_phys_segs = SSP_BUFFER_SIZE / 512; + mmc->max_req_size = SSP_BUFFER_SIZE; + mmc->max_seg_size = SSP_BUFFER_SIZE; + } else { + mmc->max_blk_count = SSP_BUFFER_SIZE / 512 - 1; + mmc->max_hw_segs = SSP_BUFFER_SIZE / 512 - 1; + mmc->max_phys_segs = SSP_BUFFER_SIZE / 512 - 1; + mmc->max_req_size = SSP_BUFFER_SIZE - 512; + mmc->max_seg_size = SSP_BUFFER_SIZE - 512; + } + + mmc->ocr_avail = MMC_VDD_32_33 | MMC_VDD_33_34; + + platform_set_drvdata(pdev, mmc); + + spin_lock_init(&host->lock); + + err = mmc_add_host(mmc); + if (err) { + dev_err(dev, "Oh God. mmc_add_host failed\n"); + goto out_all; + } + + dev_info(&pdev->dev, "%s: MXS SSP MMC DMAIRQ %d ERRIRQ %d \n", + mmc_hostname(mmc), host->dmairq, host->errirq); + + return err; + +out_all: + +out_irq: + mxs_mmc_dma_release(host); +out_dma: + clk_disable(host->clk); +out_clk: + if (mmc_data->hw_release) + mmc_data->hw_release(); +out_res: + mmc_free_host(mmc); +out: + return err; +} + +static int __exit mxs_mmc_remove(struct platform_device *pdev) +{ + struct mxs_mmc_host *host; + struct mxs_mmc_platform_data *mmc_data; + struct mmc_host *mmc; + + dev_info(&pdev->dev, "Removing\n"); + + mmc_data = pdev->dev.platform_data; + mmc = platform_get_drvdata(pdev); + platform_set_drvdata(pdev, NULL); + + host = mmc_priv(mmc); + mmc_remove_host(mmc); + + /* Disable SSP clock */ + clk_disable(host->clk); + clk_put(host->clk); + + /* Release IRQs */ + mxs_mmc_irq_release(host); + + /* Delete card detection timer */ + del_timer(&host->timer); + + /* Release DMA */ + mxs_mmc_dma_release(host); + if (host->regulator) + regulator_put(host->regulator); + + mmc_free_host(mmc); + + if (mmc_data->hw_release) + mmc_data->hw_release(); + + return 0; +} + +#ifdef CONFIG_PM +static int mxs_mmc_suspend(struct platform_device *pdev, + pm_message_t state) +{ + struct mxs_mmc_host *host; + struct mxs_mmc_platform_data *mmc_data; + struct mmc_host *mmc; + int ret = 0; + + dev_dbg(&pdev->dev, "Suspending\n"); + + mmc_data = pdev->dev.platform_data; + mmc = platform_get_drvdata(pdev); + host = mmc_priv(mmc); + + ret = mmc_suspend_host(mmc, state); + if (!ret) { + if (mmc_data && mmc_data->hw_release) + mmc_data->hw_release(); + clk_disable(host->clk); + } + return ret; +} + +static int mxs_mmc_resume(struct platform_device *pdev) +{ + struct mxs_mmc_host *host; + struct mxs_mmc_platform_data *mmc_data; + struct mmc_host *mmc; + + dev_dbg(&pdev->dev, "Resuming\n"); + + mmc_data = pdev->dev.platform_data; + mmc = platform_get_drvdata(pdev); + host = mmc_priv(mmc); + + clk_enable(host->clk); + + if (mmc_data->hw_init) + mmc_data->hw_init(); + mxs_mmc_reset(host); + mxs_mmc_dma_init(host, 1); + + return mmc_resume_host(mmc); +} +#else +#define mxs_mmc_suspend NULL +#define mxs_mmc_resume NULL +#endif /* CONFIG_PM */ + +static struct platform_driver mxs_mmc_driver = { + .probe = mxs_mmc_probe, + .remove = __exit_p(mxs_mmc_remove), + .suspend = mxs_mmc_suspend, + .resume = mxs_mmc_resume, + .driver = { + .name = DRIVER_NAME, + .owner = THIS_MODULE, + }, +}; + +static int __init mxs_mmc_init(void) +{ + int ret = 0; + + printk(KERN_INFO DRIVER_NAME + ": MXS SSP Controller MMC Interface driver\n"); + ret = platform_driver_register(&mxs_mmc_driver); + if (ret < 0) + return ret; + + return ret; +} + +static void __exit mxs_mmc_exit(void) +{ + platform_driver_unregister(&mxs_mmc_driver); +} + +module_init(mxs_mmc_init); +module_exit(mxs_mmc_exit); + +MODULE_DESCRIPTION("FREESCALE MXS MMC peripheral"); +MODULE_LICENSE("GPL"); diff --git a/drivers/mtd/devices/Kconfig b/drivers/mtd/devices/Kconfig index 35081ce77fbd..5079ad7553f0 100644 --- a/drivers/mtd/devices/Kconfig +++ b/drivers/mtd/devices/Kconfig @@ -78,6 +78,14 @@ config MTD_DATAFLASH_OTP other key product data. The second half is programmed with a unique-to-each-chip bit pattern at the factory. +config MTD_MXC_DATAFLASH + tristate "Support for AT DataFlash via FSL SPI interface" + depends on SPI_MASTER && EXPERIMENTAL + help + This enables access to AT DataFlash chips, using FSL SPI. + Sometimes DataFlash chips are packaged inside MMC-format + cards; at this writing, the MMC stack won't handle those. + config MTD_M25P80 tristate "Support most SPI Flash chips (AT26DF, M25P, W25X, ...)" depends on SPI_MASTER && EXPERIMENTAL diff --git a/drivers/mtd/devices/Makefile b/drivers/mtd/devices/Makefile index f3226b1d38fc..93a8fefbefdf 100644 --- a/drivers/mtd/devices/Makefile +++ b/drivers/mtd/devices/Makefile @@ -17,3 +17,4 @@ obj-$(CONFIG_MTD_BLOCK2MTD) += block2mtd.o obj-$(CONFIG_MTD_DATAFLASH) += mtd_dataflash.o obj-$(CONFIG_MTD_M25P80) += m25p80.o obj-$(CONFIG_MTD_SST25L) += sst25l.o +obj-$(CONFIG_MTD_MXC_DATAFLASH) += mxc_dataflash.o diff --git a/drivers/mtd/devices/mxc_dataflash.c b/drivers/mtd/devices/mxc_dataflash.c new file mode 100644 index 000000000000..0ed701d6778c --- /dev/null +++ b/drivers/mtd/devices/mxc_dataflash.c @@ -0,0 +1,1037 @@ +/* + * Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + * (c) 2005 MontaVista Software, Inc. + * + * This code is based on mtd_dataflash.c by adding FSL spi access. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +/* + * DataFlash is a kind of SPI flash. Most AT45 chips have two buffers in + * each chip, which may be used for double buffered I/O; but this driver + * doesn't (yet) use these for any kind of i/o overlap or prefetching. + * + * Sometimes DataFlash is packaged in MMC-format cards, although the + * MMC stack can't (yet?) distinguish between MMC and DataFlash + * protocols during enumeration. + */ + +/* reads can bypass the buffers */ +#define OP_READ_CONTINUOUS 0xE8 +#define OP_READ_PAGE 0xD2 + +/* group B requests can run even while status reports "busy" */ +#define OP_READ_STATUS 0xD7 /* group B */ + +/* move data between host and buffer */ +#define OP_READ_BUFFER1 0xD4 /* group B */ +#define OP_READ_BUFFER2 0xD6 /* group B */ +#define OP_WRITE_BUFFER1 0x84 /* group B */ +#define OP_WRITE_BUFFER2 0x87 /* group B */ + +/* erasing flash */ +#define OP_ERASE_PAGE 0x81 +#define OP_ERASE_BLOCK 0x50 + +/* move data between buffer and flash */ +#define OP_TRANSFER_BUF1 0x53 +#define OP_TRANSFER_BUF2 0x55 +#define OP_MREAD_BUFFER1 0xD4 +#define OP_MREAD_BUFFER2 0xD6 +#define OP_MWERASE_BUFFER1 0x83 +#define OP_MWERASE_BUFFER2 0x86 +#define OP_MWRITE_BUFFER1 0x88 /* sector must be pre-erased */ +#define OP_MWRITE_BUFFER2 0x89 /* sector must be pre-erased */ + +/* write to buffer, then write-erase to flash */ +#define OP_PROGRAM_VIA_BUF1 0x82 +#define OP_PROGRAM_VIA_BUF2 0x85 + +/* compare buffer to flash */ +#define OP_COMPARE_BUF1 0x60 +#define OP_COMPARE_BUF2 0x61 + +/* read flash to buffer, then write-erase to flash */ +#define OP_REWRITE_VIA_BUF1 0x58 +#define OP_REWRITE_VIA_BUF2 0x59 + +/* newer chips report JEDEC manufacturer and device IDs; chip + * serial number and OTP bits; and per-sector writeprotect. + */ +#define OP_READ_ID 0x9F +#define OP_READ_SECURITY 0x77 +#define OP_WRITE_SECURITY_REVC 0x9A +#define OP_WRITE_SECURITY 0x9B /* revision D */ + +#define SPI_FIFOSIZE 24 /* Bust size in bytes */ +#define CMD_SIZE 4 +#define DUMY_SIZE 4 + +struct dataflash { + uint8_t command[4]; + char name[24]; + + unsigned partitioned:1; + + unsigned short page_offset; /* offset in flash address */ + unsigned int page_size; /* of bytes per page */ + + struct mutex lock; + struct spi_device *spi; + + struct mtd_info mtd; +}; + +#ifdef CONFIG_MTD_PARTITIONS +#define mtd_has_partitions() (1) +#else +#define mtd_has_partitions() (0) +#endif + +/* ......................................................................... */ + +/* + * This function initializes the SPI device parameters. + */ +static inline int spi_nor_setup(struct spi_device *spi, u8 bst_len) +{ + spi->bits_per_word = bst_len << 3; + + return spi_setup(spi); +} + +/* + * This function perform spi read/write transfer. + */ +static int spi_read_write(struct spi_device *spi, u8 * buf, u32 len) +{ + struct spi_message m; + struct spi_transfer t; + + if (len > SPI_FIFOSIZE || len <= 0) + return -1; + + spi_nor_setup(spi, len); + + spi_message_init(&m); + memset(&t, 0, sizeof t); + + t.tx_buf = buf; + t.rx_buf = buf; + t.len = ((len - 1) >> 2) + 1; + + spi_message_add_tail(&t, &m); + + if (spi_sync(spi, &m) != 0 || m.status != 0) { + printk(KERN_ERR "%s: error\n", __func__); + return -1; + } + + DEBUG(MTD_DEBUG_LEVEL2, "%s: len: 0x%x success\n", __func__, len); + + return 0; + +} + +/* + * Return the status of the DataFlash device. + */ +static inline int dataflash_status(struct spi_device *spi) +{ + /* NOTE: at45db321c over 25 MHz wants to write + * a dummy byte after the opcode... + */ + ssize_t retval; + + u16 val = OP_READ_STATUS << 8; + + retval = spi_read_write(spi, (u8 *)&val, 2); + + if (retval < 0) + return retval; + + DEBUG(MTD_DEBUG_LEVEL2, "%s: status: 0x%x\n", __func__, val & 0xff); + + return val & 0xff; +} + +/* + * Poll the DataFlash device until it is READY. + * This usually takes 5-20 msec or so; more for sector erase. + */ +static int dataflash_waitready(struct spi_device *spi) +{ + int status; + + for (;;) { + status = dataflash_status(spi); + if (status < 0) { + DEBUG(MTD_DEBUG_LEVEL1, "%s: status %d?\n", + dev_name(&spi->dev), status); + status = 0; + } + + if (status & (1 << 7)) /* RDY/nBSY */ + return status; + + msleep(3); + } +} + +/* ......................................................................... */ + +/* + * Erase pages of flash. + */ +static int dataflash_erase(struct mtd_info *mtd, struct erase_info *instr) +{ + struct dataflash *priv = (struct dataflash *)mtd->priv; + struct spi_device *spi = priv->spi; + unsigned blocksize = priv->page_size << 3; + uint8_t *command; + uint32_t rem; + + DEBUG(MTD_DEBUG_LEVEL2, "%s: erase addr=0x%llx len 0x%llx\n", + dev_name(&spi->dev), (long long)instr->addr, + (long long)instr->len); + + /* Sanity checks */ + if (instr->addr + instr->len > mtd->size) + return -EINVAL; + div_u64_rem(instr->len, priv->page_size, &rem); + if (rem) + return -EINVAL; + div_u64_rem(instr->addr, priv->page_size, &rem); + if (rem) + return -EINVAL; + + command = priv->command; + + mutex_lock(&priv->lock); + while (instr->len > 0) { + unsigned int pageaddr; + int status; + int do_block; + + /* Calculate flash page address; use block erase (for speed) if + * we're at a block boundary and need to erase the whole block. + */ + pageaddr = div_u64(instr->addr, priv->page_size); + do_block = (pageaddr & 0x7) == 0 && instr->len >= blocksize; + pageaddr = pageaddr << priv->page_offset; + + command[3] = do_block ? OP_ERASE_BLOCK : OP_ERASE_PAGE; + command[2] = (uint8_t) (pageaddr >> 16); + command[1] = (uint8_t) (pageaddr >> 8); + command[0] = 0; + + DEBUG(MTD_DEBUG_LEVEL3, "ERASE %s: (%x) %x %x %x [%i]\n", + do_block ? "block" : "page", + command[0], command[1], command[2], command[3], pageaddr); + + status = spi_read_write(spi, command, 4); + (void)dataflash_waitready(spi); + + if (status < 0) { + printk(KERN_ERR "%s: erase %x, err %d\n", + dev_name(&spi->dev), pageaddr, status); + /* REVISIT: can retry instr->retries times; or + * giveup and instr->fail_addr = instr->addr; + */ + continue; + } + + if (do_block) { + instr->addr += blocksize; + instr->len -= blocksize; + } else { + instr->addr += priv->page_size; + instr->len -= priv->page_size; + } + } + mutex_unlock(&priv->lock); + + /* Inform MTD subsystem that erase is complete */ + instr->state = MTD_ERASE_DONE; + mtd_erase_callback(instr); + + return 0; +} + +/* + * Read from the DataFlash device. + * from : Start offset in flash device + * len : Amount to read + * retlen : About of data actually read + * buf : Buffer containing the data + */ +static int dataflash_read(struct mtd_info *mtd, loff_t from, size_t len, + size_t *retlen, u_char *buf) +{ + struct dataflash *priv = mtd->priv; + struct spi_device *spi = priv->spi; + u32 addr; + int rx_len = 0, count = 0, i = 0; + u_char txer[SPI_FIFOSIZE]; + u_char *s = txer; + u_char *d = buf; + int cmd_len = CMD_SIZE + DUMY_SIZE; + int status = 0; + + DEBUG(MTD_DEBUG_LEVEL2, "%s: read 0x%x..0x%x\n", + dev_name(&priv->spi->dev), (unsigned)from, (unsigned)(from + len)); + + *retlen = 0; + + /* Sanity checks */ + if (!len) + return 0; + + if (from + len > mtd->size) + return -EINVAL; + + /* Calculate flash page/byte address */ + addr = (((unsigned)from / priv->page_size) << priv->page_offset) + + ((unsigned)from % priv->page_size); + + mutex_unlock(&priv->lock); + + while (len > 0) { + + rx_len = len > (SPI_FIFOSIZE - cmd_len) ? + SPI_FIFOSIZE - cmd_len : len; + + txer[3] = OP_READ_CONTINUOUS; + txer[2] = (addr >> 16) & 0xff; + txer[1] = (addr >> 8) & 0xff; + txer[0] = addr & 0xff; + + status = spi_read_write(spi, txer, + roundup(rx_len, 4) + cmd_len); + if (status) { + mutex_unlock(&priv->lock); + return status; + } + + s = txer + cmd_len; + + for (i = rx_len; i >= 0; i -= 4, s += 4) { + if (i < 4) { + if (i == 1) { + *d = s[3]; + } else if (i == 2) { + *d++ = s[3]; + *d++ = s[2]; + } else if (i == 3) { + *d++ = s[3]; + *d++ = s[2]; + *d++ = s[1]; + } + + break; + } + + *d++ = s[3]; + *d++ = s[2]; + *d++ = s[1]; + *d++ = s[0]; + } + + /* updaate */ + len -= rx_len; + addr += rx_len; + count += rx_len; + + DEBUG(MTD_DEBUG_LEVEL2, + "%s: left:0x%x, from:0x%08x, to:0x%p, done: 0x%x\n", + __func__, len, (u32) addr, d, count); + } + + *retlen = count; + + DEBUG(MTD_DEBUG_LEVEL2, "%s: %d bytes read\n", __func__, count); + + mutex_unlock(&priv->lock); + + return status; +} + +/* + * Write to the DataFlash device. + * to : Start offset in flash device + * len : Amount to write + * retlen : Amount of data actually written + * buf : Buffer containing the data + */ +static int dataflash_write(struct mtd_info *mtd, loff_t to, size_t len, + size_t *retlen, const u_char *buf) +{ + struct dataflash *priv = mtd->priv; + struct spi_device *spi = priv->spi; + u32 pageaddr, addr, offset, writelen; + size_t remaining = len; + u_char *writebuf = (u_char *) buf; + int status = -EINVAL; + u_char txer[SPI_FIFOSIZE] = { 0 }; + uint8_t *command = priv->command; + u_char *d = txer; + u_char *s = (u_char *) buf; + int delta = 0, l = 0, i = 0, count = 0; + + DEBUG(MTD_DEBUG_LEVEL2, "%s: write 0x%x..0x%x\n", + dev_name(&spi->dev), (unsigned)to, (unsigned)(to + len)); + + *retlen = 0; + + /* Sanity checks */ + if (!len) + return 0; + + if ((to + len) > mtd->size) + return -EINVAL; + + pageaddr = ((unsigned)to / priv->page_size); + offset = ((unsigned)to % priv->page_size); + if (offset + len > priv->page_size) + writelen = priv->page_size - offset; + else + writelen = len; + + mutex_lock(&priv->lock); + + while (remaining > 0) { + DEBUG(MTD_DEBUG_LEVEL3, "write @ %i:%i len=%i\n", + pageaddr, offset, writelen); + + addr = pageaddr << priv->page_offset; + + /* (1) Maybe transfer partial page to Buffer1 */ + if (writelen != priv->page_size) { + command[3] = OP_TRANSFER_BUF1; + command[2] = (addr & 0x00FF0000) >> 16; + command[1] = (addr & 0x0000FF00) >> 8; + command[0] = 0; + + DEBUG(MTD_DEBUG_LEVEL3, "TRANSFER: (%x) %x %x %x\n", + command[3], command[2], command[1], command[0]); + + status = spi_read_write(spi, command, CMD_SIZE); + if (status) { + mutex_unlock(&priv->lock); + return status; + + } + + (void)dataflash_waitready(spi); + } + + count = writelen; + while (count) { + d = txer; + l = count > (SPI_FIFOSIZE - CMD_SIZE) ? + SPI_FIFOSIZE - CMD_SIZE : count; + + delta = l % 4; + if (delta) { + switch (delta) { + case 1: + d[0] = OP_WRITE_BUFFER1; + d[6] = (offset >> 8) & 0xff; + d[5] = offset & 0xff; + d[4] = *s++; + break; + case 2: + d[1] = OP_WRITE_BUFFER1; + d[7] = (offset >> 8) & 0xff; + d[6] = offset & 0xff; + d[5] = *s++; + d[4] = *s++; + break; + case 3: + d[2] = OP_WRITE_BUFFER1; + d[0] = (offset >> 8) & 0xff; + d[7] = offset & 0xff; + d[6] = *s++; + d[5] = *s++; + d[4] = *s++; + break; + default: + break; + } + + DEBUG(MTD_DEBUG_LEVEL3, + "WRITEBUF: (%x) %x %x %x\n", + txer[3], txer[2], txer[1], txer[0]); + + status = spi_read_write(spi, txer, + delta + CMD_SIZE); + if (status) { + mutex_unlock(&priv->lock); + return status; + } + + /* update */ + count -= delta; + offset += delta; + l -= delta; + } + + d[3] = OP_WRITE_BUFFER1; + d[1] = (offset >> 8) & 0xff; + d[0] = offset & 0xff; + + for (i = 0, d += 4; i < l / 4; i++, d += 4) { + d[3] = *s++; + d[2] = *s++; + d[1] = *s++; + d[0] = *s++; + } + + DEBUG(MTD_DEBUG_LEVEL3, "WRITEBUF: (%x) %x %x %x\n", + txer[3], txer[2], txer[1], txer[0]); + + status = spi_read_write(spi, txer, l + CMD_SIZE); + if (status) { + mutex_unlock(&priv->lock); + return status; + } + + /* update */ + count -= l; + offset += l; + } + + /* (2) Program full page via Buffer1 */ + command[3] = OP_MWERASE_BUFFER1; + command[2] = (addr >> 16) & 0xff; + command[1] = (addr >> 8) & 0xff; + + DEBUG(MTD_DEBUG_LEVEL3, "PROGRAM: (%x) %x %x %x\n", + command[3], command[2], command[1], command[0]); + + status = spi_read_write(spi, command, CMD_SIZE); + if (status) { + mutex_unlock(&priv->lock); + return status; + } + + (void)dataflash_waitready(spi); + + remaining -= writelen; + pageaddr++; + offset = 0; + writebuf += writelen; + *retlen += writelen; + + if (remaining > priv->page_size) + writelen = priv->page_size; + else + writelen = remaining; + } + mutex_unlock(&priv->lock); + + return status; +} + +/* ......................................................................... */ + +#ifdef CONFIG_MTD_DATAFLASH_OTP + +static int dataflash_get_otp_info(struct mtd_info *mtd, + struct otp_info *info, size_t len) +{ + /* Report both blocks as identical: bytes 0..64, locked. + * Unless the user block changed from all-ones, we can't + * tell whether it's still writable; so we assume it isn't. + */ + info->start = 0; + info->length = 64; + info->locked = 1; + return sizeof(*info); +} + +static ssize_t otp_read(struct spi_device *spi, unsigned base, + uint8_t *buf, loff_t off, size_t len) +{ + struct dataflash *priv = mtd->priv; + struct spi_device *spi = priv->spi; + int rx_len = 0, count = 0, i = 0; + u_char txer[SPI_FIFOSIZE]; + u_char *s = txer; + u_char *d = NULL; + int cmd_len = CMD_SIZE; + int status; + + if (off > 64) + return -EINVAL; + + if ((off + len) > 64) + len = 64 - off; + if (len == 0) + return len; + + /* to make simple, we read 64 out */ + l = base + 64; + + d = kzalloc(l, GFP_KERNEL); + if (!d) + return -ENOMEM; + + while (l > 0) { + + rx_len = l > (SPI_FIFOSIZE - cmd_len) ? + SPI_FIFOSIZE - cmd_len : l; + + txer[3] = OP_READ_SECURITY; + + status = spi_read_write(spi, txer, rx_len + cmd_len); + if (status) { + mutex_unlock(&priv->lock); + return status; + } + + s = txer + cmd_len; + for (i = rx_len; i >= 0; i -= 4, s += 4) { + + *d++ = s[3]; + *d++ = s[2]; + *d++ = s[1]; + *d++ = s[0]; + } + + /* updaate */ + l -= rx_len; + addr += rx_len; + count += rx_len; + + DEBUG(MTD_DEBUG_LEVEL2, + "%s: left:0x%x, from:0x%08x, to:0x%p, done: 0x%x\n", + __func__, len, (u32) addr, d, count); + } + + d -= count; + memcpy(buf, d + base + off, len); + + mutex_unlock(&priv->lock); + + return len; +} + +static int dataflash_read_fact_otp(struct mtd_info *mtd, + loff_t from, size_t len, size_t *retlen, + u_char *buf) +{ + struct dataflash *priv = (struct dataflash *)mtd->priv; + int status; + + /* 64 bytes, from 0..63 ... start at 64 on-chip */ + mutex_lock(&priv->lock); + status = otp_read(priv->spi, 64, buf, from, len); + mutex_unlock(&priv->lock); + + if (status < 0) + return status; + *retlen = status; + return 0; +} + +static int dataflash_read_user_otp(struct mtd_info *mtd, + loff_t from, size_t len, size_t *retlen, + u_char *buf) +{ + struct dataflash *priv = (struct dataflash *)mtd->priv; + int status; + + /* 64 bytes, from 0..63 ... start at 0 on-chip */ + mutex_lock(&priv->lock); + status = otp_read(priv->spi, 0, buf, from, len); + mutex_unlock(&priv->lock); + + if (status < 0) + return status; + *retlen = status; + return 0; +} + +static int dataflash_write_user_otp(struct mtd_info *mtd, + loff_t from, size_t len, size_t *retlen, + u_char *buf) +{ + printk(KERN_ERR "%s not support!!\n", __func__); + return 0; +} + +static char *otp_setup(struct mtd_info *device, char revision) +{ + device->get_fact_prot_info = dataflash_get_otp_info; + device->read_fact_prot_reg = dataflash_read_fact_otp; + device->get_user_prot_info = dataflash_get_otp_info; + device->read_user_prot_reg = dataflash_read_user_otp; + + /* rev c parts (at45db321c and at45db1281 only!) use a + * different write procedure; not (yet?) implemented. + */ + if (revision > 'c') + device->write_user_prot_reg = dataflash_write_user_otp; + + return ", OTP"; +} + +#else + +static char *otp_setup(struct mtd_info *device, char revision) +{ + return " (OTP)"; +} + +#endif + +/* ......................................................................... */ + +/* + * Register DataFlash device with MTD subsystem. + */ +static int __devinit +add_dataflash_otp(struct spi_device *spi, char *name, + int nr_pages, int pagesize, int pageoffset, char revision) +{ + struct dataflash *priv; + struct mtd_info *device; + struct flash_platform_data *pdata = spi->dev.platform_data; + char *otp_tag = ""; + + priv = kzalloc(sizeof *priv, GFP_KERNEL); + if (!priv) + return -ENOMEM; + + mutex_init(&priv->lock); + priv->spi = spi; + priv->page_size = pagesize; + priv->page_offset = pageoffset; + + /* name must be usable with cmdlinepart */ + sprintf(priv->name, "spi%d.%d-%s", + spi->master->bus_num, spi->chip_select, name); + + device = &priv->mtd; + device->name = (pdata && pdata->name) ? pdata->name : priv->name; + device->size = nr_pages * pagesize; + device->erasesize = pagesize; + device->writesize = pagesize; + device->owner = THIS_MODULE; + device->type = MTD_DATAFLASH; + device->flags = MTD_CAP_NORFLASH; + device->erase = dataflash_erase; + device->read = dataflash_read; + device->write = dataflash_write; + device->priv = priv; + + if (revision >= 'c') + otp_tag = otp_setup(device, revision); + + dev_info(&spi->dev, "%s (%llx KBytes) pagesize %d bytes%s\n", + name, DIV_ROUND_UP(device->size, 1024), pagesize, otp_tag); + dev_set_drvdata(&spi->dev, priv); + + if (mtd_has_partitions()) { + struct mtd_partition *parts; + int nr_parts = 0; + +#ifdef CONFIG_MTD_CMDLINE_PARTS + static const char *part_probes[] = { "cmdlinepart", NULL, }; + + nr_parts = parse_mtd_partitions(device, part_probes, &parts, 0); +#endif + + if (nr_parts <= 0 && pdata && pdata->parts) { + parts = pdata->parts; + nr_parts = pdata->nr_parts; + } + + if (nr_parts > 0) { + priv->partitioned = 1; + return add_mtd_partitions(device, parts, nr_parts); + } + } else if (pdata && pdata->nr_parts) + dev_warn(&spi->dev, "ignoring %d default partitions on %s\n", + pdata->nr_parts, device->name); + + return add_mtd_device(device) == 1 ? -ENODEV : 0; +} + +static inline int __devinit +add_dataflash(struct spi_device *spi, char *name, + int nr_pages, int pagesize, int pageoffset) +{ + return add_dataflash_otp(spi, name, nr_pages, pagesize, pageoffset, 0); +} + +struct flash_info { + char *name; + + /* JEDEC id has a high byte of zero plus three data bytes: + * the manufacturer id, then a two byte device id. + */ + uint32_t jedec_id; + + /* The size listed here is what works with OP_ERASE_PAGE. */ + unsigned nr_pages; + uint16_t pagesize; + uint16_t pageoffset; + + uint16_t flags; +#define SUP_POW2PS 0x0002 /* supports 2^N byte pages */ +#define IS_POW2PS 0x0001 /* uses 2^N byte pages */ +}; + +static struct flash_info __devinitdata dataflash_data[] = { + + /* + * NOTE: chips with SUP_POW2PS (rev D and up) need two entries, + * one with IS_POW2PS and the other without. The entry with the + * non-2^N byte page size can't name exact chip revisions without + * losing backwards compatibility for cmdlinepart. + * + * These newer chips also support 128-byte security registers (with + * 64 bytes one-time-programmable) and software write-protection. + */ + {"AT45DB011B", 0x1f2200, 512, 264, 9, SUP_POW2PS}, + {"at45db011d", 0x1f2200, 512, 256, 8, SUP_POW2PS | IS_POW2PS}, + + {"AT45DB021B", 0x1f2300, 1024, 264, 9, SUP_POW2PS}, + {"at45db021d", 0x1f2300, 1024, 256, 8, SUP_POW2PS | IS_POW2PS}, + + {"AT45DB041x", 0x1f2400, 2048, 264, 9, SUP_POW2PS}, + {"at45db041d", 0x1f2400, 2048, 256, 8, SUP_POW2PS | IS_POW2PS}, + + {"AT45DB081B", 0x1f2500, 4096, 264, 9, SUP_POW2PS}, + {"at45db081d", 0x1f2500, 4096, 256, 8, SUP_POW2PS | IS_POW2PS}, + + {"AT45DB161x", 0x1f2600, 4096, 528, 10, SUP_POW2PS}, + {"at45db161d", 0x1f2600, 4096, 512, 9, SUP_POW2PS | IS_POW2PS}, + + {"AT45DB321x", 0x1f2700, 8192, 528, 10, 0}, /* rev C */ + + {"AT45DB321x", 0x1f2701, 8192, 528, 10, SUP_POW2PS}, + {"at45db321d", 0x1f2701, 8192, 512, 9, SUP_POW2PS | IS_POW2PS}, + + {"AT45DB642x", 0x1f2800, 8192, 1056, 11, SUP_POW2PS}, + {"at45db642d", 0x1f2800, 8192, 1024, 10, SUP_POW2PS | IS_POW2PS}, +}; + +static struct flash_info *__devinit jedec_probe(struct spi_device *spi) +{ + int tmp; + u32 code = OP_READ_ID << 24; + u32 jedec; + struct flash_info *info; + int status; + + /* JEDEC also defines an optional "extended device information" + * string for after vendor-specific data, after the three bytes + * we use here. Supporting some chips might require using it. + * + * If the vendor ID isn't Atmel's (0x1f), assume this call failed. + * That's not an error; only rev C and newer chips handle it, and + * only Atmel sells these chips. + */ + + tmp = spi_read_write(spi, (u8 *)&code, 4); + if (tmp < 0) { + DEBUG(MTD_DEBUG_LEVEL0, "%s: error %d reading JEDEC ID\n", + dev_name(&spi->dev), tmp); + return NULL; + } + + jedec = code & 0xFFFFFF; + + for (tmp = 0, info = dataflash_data; + tmp < ARRAY_SIZE(dataflash_data); tmp++, info++) { + if (info->jedec_id == jedec) { + DEBUG(MTD_DEBUG_LEVEL1, "%s: OTP, sector protect%s\n", + dev_name(&spi->dev), (info->flags & SUP_POW2PS) + ? ", binary pagesize" : ""); + if (info->flags & SUP_POW2PS) { + status = dataflash_status(spi); + if (status < 0) { + DEBUG(MTD_DEBUG_LEVEL1, + "%s: status error %d\n", + dev_name(&spi->dev), status); + return ERR_PTR(status); + } + if (status & 0x1) { + if (info->flags & IS_POW2PS) + return info; + } else { + if (!(info->flags & IS_POW2PS)) + return info; + } + } + } + } + + /* + * Treat other chips as errors ... we won't know the right page + * size (it might be binary) even when we can tell which density + * class is involved (legacy chip id scheme). + */ + dev_warn(&spi->dev, "JEDEC id %06x not handled\n", jedec); + return ERR_PTR(-ENODEV); +} + +/* + * Detect and initialize DataFlash device, using JEDEC IDs on newer chips + * or else the ID code embedded in the status bits: + * + * Device Density ID code #Pages PageSize Offset + * AT45DB011B 1Mbit (128K) xx0011xx (0x0c) 512 264 9 + * AT45DB021B 2Mbit (256K) xx0101xx (0x14) 1024 264 9 + * AT45DB041B 4Mbit (512K) xx0111xx (0x1c) 2048 264 9 + * AT45DB081B 8Mbit (1M) xx1001xx (0x24) 4096 264 9 + * AT45DB0161B 16Mbit (2M) xx1011xx (0x2c) 4096 528 10 + * AT45DB0321B 32Mbit (4M) xx1101xx (0x34) 8192 528 10 + * AT45DB0642 64Mbit (8M) xx111xxx (0x3c) 8192 1056 11 + * AT45DB1282 128Mbit (16M) xx0100xx (0x10) 16384 1056 11 + */ +static int __devinit dataflash_probe(struct spi_device *spi) +{ + int status; + struct flash_info *info; + + /* + * Try to detect dataflash by JEDEC ID. + * If it succeeds we know we have either a C or D part. + * D will support power of 2 pagesize option. + * Both support the security register, though with different + * write procedures. + */ + info = jedec_probe(spi); + if (IS_ERR(info)) + return PTR_ERR(info); + if (info != NULL) + return add_dataflash_otp(spi, info->name, info->nr_pages, + info->pagesize, info->pageoffset, + (info->flags & SUP_POW2PS) ? 'd' : + 'c'); + + /* + * Older chips support only legacy commands, identifing + * capacity using bits in the status byte. + */ + status = dataflash_status(spi); + if (status <= 0 || status == 0xff) { + DEBUG(MTD_DEBUG_LEVEL1, "%s: status error %d\n", + dev_name(&spi->dev), status); + if (status == 0 || status == 0xff) + status = -ENODEV; + return status; + } + + /* if there's a device there, assume it's dataflash. + * board setup should have set spi->max_speed_max to + * match f(car) for continuous reads, mode 0 or 3. + */ + switch (status & 0x3c) { + case 0x0c: /* 0 0 1 1 x x */ + status = add_dataflash(spi, "AT45DB011B", 512, 264, 9); + break; + case 0x14: /* 0 1 0 1 x x */ + status = add_dataflash(spi, "AT45DB021B", 1024, 264, 9); + break; + case 0x1c: /* 0 1 1 1 x x */ + status = add_dataflash(spi, "AT45DB041x", 2048, 264, 9); + break; + case 0x24: /* 1 0 0 1 x x */ + status = add_dataflash(spi, "AT45DB081B", 4096, 264, 9); + break; + case 0x2c: /* 1 0 1 1 x x */ + status = add_dataflash(spi, "AT45DB161x", 4096, 528, 10); + break; + case 0x34: /* 1 1 0 1 x x */ + status = add_dataflash(spi, "AT45DB321x", 8192, 528, 10); + break; + case 0x38: /* 1 1 1 x x x */ + case 0x3c: + status = add_dataflash(spi, "AT45DB642x", 8192, 1056, 11); + break; + /* obsolete AT45DB1282 not (yet?) supported */ + default: + DEBUG(MTD_DEBUG_LEVEL1, "%s: unsupported device (%x)\n", + dev_name(&spi->dev), status & 0x3c); + status = -ENODEV; + } + + if (status < 0) + DEBUG(MTD_DEBUG_LEVEL1, "%s: add_dataflash --> %d\n", + dev_name(&spi->dev), status); + + return status; +} + +static int __devexit dataflash_remove(struct spi_device *spi) +{ + struct dataflash *flash = dev_get_drvdata(&spi->dev); + int status; + + DEBUG(MTD_DEBUG_LEVEL1, "%s: remove\n", dev_name(&spi->dev)); + + if (mtd_has_partitions() && flash->partitioned) + status = del_mtd_partitions(&flash->mtd); + else + status = del_mtd_device(&flash->mtd); + if (status == 0) + kfree(flash); + return status; +} + +static struct spi_driver dataflash_driver = { + .driver = { + .name = "mxc_dataflash", + .bus = &spi_bus_type, + .owner = THIS_MODULE, + }, + + .probe = dataflash_probe, + .remove = __devexit_p(dataflash_remove), + + /* FIXME: investigate suspend and resume... */ +}; + +static int __init dataflash_init(void) +{ + return spi_register_driver(&dataflash_driver); +} + +module_init(dataflash_init); + +static void __exit dataflash_exit(void) +{ + spi_unregister_driver(&dataflash_driver); +} + +module_exit(dataflash_exit); + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MTD DataFlash driver"); diff --git a/drivers/mtd/maps/Kconfig b/drivers/mtd/maps/Kconfig index f22bc9f05ddb..5362bc4a000d 100644 --- a/drivers/mtd/maps/Kconfig +++ b/drivers/mtd/maps/Kconfig @@ -551,4 +551,14 @@ config MTD_PISMO When built as a module, it will be called pismo.ko +config MTD_MXC + bool "Map driver for Freescale MXC boards" + depends on MTD && ARCH_MXC + default y + select MTD_CFI + select MTD_PARTITIONS + help + This enables access to the flash chips on Freescale MXC based + platforms. If you have such a board, say 'Y'. + endmenu diff --git a/drivers/mtd/maps/Makefile b/drivers/mtd/maps/Makefile index bb035cd54c72..556db2ec6253 100644 --- a/drivers/mtd/maps/Makefile +++ b/drivers/mtd/maps/Makefile @@ -59,3 +59,4 @@ obj-$(CONFIG_MTD_BFIN_ASYNC) += bfin-async-flash.o obj-$(CONFIG_MTD_RBTX4939) += rbtx4939-flash.o obj-$(CONFIG_MTD_VMU) += vmu-flash.o obj-$(CONFIG_MTD_GPIO_ADDR) += gpio-addr-flash.o +obj-$(CONFIG_MTD_MXC) += mxc_nor.o diff --git a/drivers/mtd/maps/mxc_nor.c b/drivers/mtd/maps/mxc_nor.c new file mode 100644 index 000000000000..d969f95a67a3 --- /dev/null +++ b/drivers/mtd/maps/mxc_nor.c @@ -0,0 +1,181 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + * (c) 2005 MontaVista Software, Inc. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define DVR_VER "2.0" + +#ifdef CONFIG_MTD_PARTITIONS +static const char *part_probes[] = { "RedBoot", "cmdlinepart", NULL }; +#endif + +struct mxcflash_info { + struct mtd_partition *parts; + struct mtd_info *mtd; + struct map_info map; +}; + +/*! + * @defgroup NOR_MTD NOR Flash MTD Driver + */ + +/*! + * @file mxc_nor.c + * + * @brief This file contains the MTD Mapping information on the MXC. + * + * @ingroup NOR_MTD + */ + +static int __devinit mxcflash_probe(struct platform_device *pdev) +{ + int err, nr_parts = 0; + struct mxcflash_info *info; + struct flash_platform_data *flash = pdev->dev.platform_data; + struct resource *res = pdev->resource; + unsigned long size = res->end - res->start + 1; + + info = kzalloc(sizeof(struct mxcflash_info), GFP_KERNEL); + if (!info) + return -ENOMEM; + + if (!request_mem_region(res->start, size, "flash")) { + err = -EBUSY; + goto out_free_info; + } + info->map.virt = ioremap(res->start, size); + if (!info->map.virt) { + err = -ENOMEM; + goto out_release_mem_region; + } + info->map.name = dev_name(&pdev->dev); + info->map.phys = res->start; + info->map.size = size; + info->map.bankwidth = flash->width; + + simple_map_init(&info->map); + info->mtd = do_map_probe(flash->map_name, &info->map); + if (!info->mtd) { + err = -EIO; + goto out_iounmap; + } + info->mtd->owner = THIS_MODULE; + +#ifdef CONFIG_MTD_PARTITIONS + nr_parts = + parse_mtd_partitions(info->mtd, part_probes, &info->parts, 0); + if (nr_parts > 0) { + add_mtd_partitions(info->mtd, info->parts, nr_parts); + } else if (flash->parts) { + add_mtd_partitions(info->mtd, flash->parts, flash->nr_parts); + } else +#endif + { + printk(KERN_NOTICE "MXC flash: no partition info " + "available, registering whole flash\n"); + add_mtd_device(info->mtd); + } + + platform_set_drvdata(pdev, info); + return 0; + + out_iounmap: + iounmap(info->map.virt); + out_release_mem_region: + release_mem_region(res->start, size); + out_free_info: + kfree(info); + + return err; +} + +static int __devexit mxcflash_remove(struct platform_device *pdev) +{ + + struct mxcflash_info *info = platform_get_drvdata(pdev); + struct flash_platform_data *flash = pdev->dev.platform_data; + + platform_set_drvdata(pdev, NULL); + + if (info) { + if (info->parts) { + del_mtd_partitions(info->mtd); + kfree(info->parts); + } else if (flash->parts) + del_mtd_partitions(info->mtd); + else + del_mtd_device(info->mtd); + + map_destroy(info->mtd); + release_mem_region(info->map.phys, info->map.size); + iounmap((void __iomem *)info->map.virt); + kfree(info); + } + return 0; +} + +static struct platform_driver mxcflash_driver = { + .driver = { + .name = "mxc_nor_flash", + }, + .probe = mxcflash_probe, + .remove = __devexit_p(mxcflash_remove), +}; + +/*! + * This is the module's entry function. It passes board specific + * config details into the MTD physmap driver which then does the + * real work for us. After this function runs, our job is done. + * + * @return 0 if successful; non-zero otherwise + */ +static int __init mxc_mtd_init(void) +{ + pr_info("MXC MTD nor Driver %s\n", DVR_VER); + if (platform_driver_register(&mxcflash_driver) != 0) { + printk(KERN_ERR "Driver register failed for mxcflash_driver\n"); + return -ENODEV; + } + return 0; +} + +/*! + * This function is the module's exit function. It's empty because the + * MTD physmap driver is doing the real work and our job was done after + * mxc_mtd_init() runs. + */ +static void __exit mxc_mtd_exit(void) +{ + platform_driver_unregister(&mxcflash_driver); +} + +module_init(mxc_mtd_init); +module_exit(mxc_mtd_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MTD map and partitions for Freescale MXC boards"); +MODULE_LICENSE("GPL"); diff --git a/drivers/mtd/nand/Kconfig b/drivers/mtd/nand/Kconfig index ffc3720929f1..12ee9059c948 100644 --- a/drivers/mtd/nand/Kconfig +++ b/drivers/mtd/nand/Kconfig @@ -432,6 +432,68 @@ config MTD_NAND_NANDSIM The simulator may simulate various NAND flash chips for the MTD nand layer. +config MTD_NAND_IMX_NFC + tristate "i.MX NAND Flash Controller driver" + depends on MTD_NAND && (ARCH_MX2 || ARCH_MX3 || ARCH_MX5) + help + Enables the i.MX NAND Flash controller driver. + +config MTD_NAND_MXC + tristate "MXC NAND support" + depends on MTD_NAND && ARCH_MXC_HAS_NFC_V1 + help + This enables the driver for the NAND flash controller on the + MXC processors. + +config MTD_NAND_MXC_V2 + tristate "MXC NAND Version 2 support" + depends on MTD_NAND && ARCH_MXC_HAS_NFC_V2 + help + This enables the driver for the version 2 of NAND flash controller + on the MXC processors. + +config MTD_NAND_MXC_V3 + tristate "MXC NAND Version 3 support" + depends on MTD_NAND && ARCH_MXC_HAS_NFC_V3 + help + This enables the driver for the version 3 of NAND flash controller + on the MXC processors. + +config MTD_NAND_MXC_SWECC + bool "Software ECC support " + depends on MTD_NAND_MXC || MTD_NAND_MXC_V2 || MTD_NAND_MXC_V3 + help + This enables the support for Software ECC handling. By + default MXC NAND controller Hardware ECC is supported. + + +config MTD_NAND_MXC_FORCE_CE + bool "NAND chip select operation support" + depends on MTD_NAND_MXC || MTD_NAND_MXC_V2|| MTD_NAND_MXC_V3 + help + This enables the NAND chip select by using CE control line. By + default CE operation is disabled. + +config MTD_NAND_MXC_ECC_CORRECTION_OPTION2 + bool "ECC correction in S/W" + depends on MTD_NAND_MXC + help + This enables the Option2 NFC ECC correction in software. By + default Option 1 is selected. Enable if you need option2 ECC correction. + +config MXC_NAND_LOW_LEVEL_ERASE + bool "Low level NAND erase" + depends on MTD_NAND_MXC || MTD_NAND_MXC_V2 || MTD_NAND_MXC_V3 + help + This enables the erase of whole NAND flash. By + default low level erase operation is disabled. + +config MTD_NAND_GPMI_NFC + tristate "GPMI NAND Flash Controller driver" + depends on MTD_NAND && (ARCH_MX23 || ARCH_MX28) + help + Enables NAND Flash support. + config MTD_NAND_PLATFORM tristate "Support for generic platform NAND driver" depends on MTD_NAND diff --git a/drivers/mtd/nand/Makefile b/drivers/mtd/nand/Makefile index e8ab884ba47b..87ab9180433c 100644 --- a/drivers/mtd/nand/Makefile +++ b/drivers/mtd/nand/Makefile @@ -38,7 +38,11 @@ obj-$(CONFIG_MTD_NAND_ORION) += orion_nand.o obj-$(CONFIG_MTD_NAND_FSL_ELBC) += fsl_elbc_nand.o obj-$(CONFIG_MTD_NAND_FSL_UPM) += fsl_upm.o obj-$(CONFIG_MTD_NAND_SH_FLCTL) += sh_flctl.o +obj-$(CONFIG_MTD_NAND_IMX_NFC) += imx_nfc.o obj-$(CONFIG_MTD_NAND_MXC) += mxc_nand.o +obj-$(CONFIG_MTD_NAND_MXC_V2) += mxc_nd2.o nand_device_info.o +obj-$(CONFIG_MTD_NAND_MXC_V3) += mxc_nd2.o nand_device_info.o +obj-$(CONFIG_MTD_NAND_GPMI_NFC) += gpmi-nfc/ nand_device_info.o obj-$(CONFIG_MTD_NAND_SOCRATES) += socrates_nand.o obj-$(CONFIG_MTD_NAND_TXX9NDFMC) += txx9ndfmc.o obj-$(CONFIG_MTD_NAND_NUC900) += nuc900_nand.o diff --git a/drivers/mtd/nand/gpmi-nfc/Makefile b/drivers/mtd/nand/gpmi-nfc/Makefile new file mode 100644 index 000000000000..e3d5660735b6 --- /dev/null +++ b/drivers/mtd/nand/gpmi-nfc/Makefile @@ -0,0 +1,10 @@ +obj-$(CONFIG_MTD_NAND_GPMI_NFC) += gpmi-nfc.o +gpmi-nfc-objs += gpmi-nfc-main.o +gpmi-nfc-objs += gpmi-nfc-event-reporting.o +gpmi-nfc-objs += gpmi-nfc-hal-common.o +gpmi-nfc-objs += gpmi-nfc-hal-v0.o +gpmi-nfc-objs += gpmi-nfc-hal-v1.o +gpmi-nfc-objs += gpmi-nfc-rom-common.o +gpmi-nfc-objs += gpmi-nfc-rom-v0.o +gpmi-nfc-objs += gpmi-nfc-rom-v1.o +gpmi-nfc-objs += gpmi-nfc-mil.o diff --git a/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-bch-regs-v0.h b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-bch-regs-v0.h new file mode 100644 index 000000000000..9af4feb29021 --- /dev/null +++ b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-bch-regs-v0.h @@ -0,0 +1,550 @@ +/* + * Freescale GPMI NFC NAND Flash Driver + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. + * Copyright 2008 Embedded Alley Solutions, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#ifndef __GPMI_NFC_BCH_REGS_H +#define __GPMI_NFC_BCH_REGS_H + +/*============================================================================*/ + +#define HW_BCH_CTRL (0x00000000) +#define HW_BCH_CTRL_SET (0x00000004) +#define HW_BCH_CTRL_CLR (0x00000008) +#define HW_BCH_CTRL_TOG (0x0000000c) + +#define BM_BCH_CTRL_SFTRST 0x80000000 +#define BV_BCH_CTRL_SFTRST__RUN 0x0 +#define BV_BCH_CTRL_SFTRST__RESET 0x1 +#define BM_BCH_CTRL_CLKGATE 0x40000000 +#define BV_BCH_CTRL_CLKGATE__RUN 0x0 +#define BV_BCH_CTRL_CLKGATE__NO_CLKS 0x1 +#define BP_BCH_CTRL_RSVD5 23 +#define BM_BCH_CTRL_RSVD5 0x3F800000 +#define BF_BCH_CTRL_RSVD5(v) (((v) << 23) & BM_BCH_CTRL_RSVD5) +#define BM_BCH_CTRL_DEBUGSYNDROME 0x00400000 +#define BP_BCH_CTRL_RSVD4 20 +#define BM_BCH_CTRL_RSVD4 0x00300000 +#define BF_BCH_CTRL_RSVD4(v) (((v) << 20) & BM_BCH_CTRL_RSVD4) +#define BP_BCH_CTRL_M2M_LAYOUT 18 +#define BM_BCH_CTRL_M2M_LAYOUT 0x000C0000 +#define BF_BCH_CTRL_M2M_LAYOUT(v) (((v) << 18) & BM_BCH_CTRL_M2M_LAYOUT) +#define BM_BCH_CTRL_M2M_ENCODE 0x00020000 +#define BM_BCH_CTRL_M2M_ENABLE 0x00010000 +#define BP_BCH_CTRL_RSVD3 11 +#define BM_BCH_CTRL_RSVD3 0x0000F800 +#define BF_BCH_CTRL_RSVD3(v) (((v) << 11) & BM_BCH_CTRL_RSVD3) +#define BM_BCH_CTRL_DEBUG_STALL_IRQ_EN 0x00000400 +#define BM_BCH_CTRL_RSVD2 0x00000200 +#define BM_BCH_CTRL_COMPLETE_IRQ_EN 0x00000100 +#define BP_BCH_CTRL_RSVD1 4 +#define BM_BCH_CTRL_RSVD1 0x000000F0 +#define BF_BCH_CTRL_RSVD1(v) (((v) << 4) & BM_BCH_CTRL_RSVD1) +#define BM_BCH_CTRL_BM_ERROR_IRQ 0x00000008 +#define BM_BCH_CTRL_DEBUG_STALL_IRQ 0x00000004 +#define BM_BCH_CTRL_RSVD0 0x00000002 +#define BM_BCH_CTRL_COMPLETE_IRQ 0x00000001 + +/*============================================================================*/ + +#define HW_BCH_STATUS0 (0x00000010) + +#define BP_BCH_STATUS0_HANDLE 20 +#define BM_BCH_STATUS0_HANDLE 0xFFF00000 +#define BF_BCH_STATUS0_HANDLE(v) \ + (((v) << 20) & BM_BCH_STATUS0_HANDLE) +#define BP_BCH_STATUS0_COMPLETED_CE 16 +#define BM_BCH_STATUS0_COMPLETED_CE 0x000F0000 +#define BF_BCH_STATUS0_COMPLETED_CE(v) \ + (((v) << 16) & BM_BCH_STATUS0_COMPLETED_CE) +#define BP_BCH_STATUS0_STATUS_BLK0 8 +#define BM_BCH_STATUS0_STATUS_BLK0 0x0000FF00 +#define BF_BCH_STATUS0_STATUS_BLK0(v) \ + (((v) << 8) & BM_BCH_STATUS0_STATUS_BLK0) +#define BV_BCH_STATUS0_STATUS_BLK0__ZERO 0x00 +#define BV_BCH_STATUS0_STATUS_BLK0__ERROR1 0x01 +#define BV_BCH_STATUS0_STATUS_BLK0__ERROR2 0x02 +#define BV_BCH_STATUS0_STATUS_BLK0__ERROR3 0x03 +#define BV_BCH_STATUS0_STATUS_BLK0__ERROR4 0x04 +#define BV_BCH_STATUS0_STATUS_BLK0__UNCORRECTABLE 0xFE +#define BV_BCH_STATUS0_STATUS_BLK0__ERASED 0xFF +#define BP_BCH_STATUS0_RSVD1 5 +#define BM_BCH_STATUS0_RSVD1 0x000000E0 +#define BF_BCH_STATUS0_RSVD1(v) \ + (((v) << 5) & BM_BCH_STATUS0_RSVD1) +#define BM_BCH_STATUS0_ALLONES 0x00000010 +#define BM_BCH_STATUS0_CORRECTED 0x00000008 +#define BM_BCH_STATUS0_UNCORRECTABLE 0x00000004 +#define BP_BCH_STATUS0_RSVD0 0 +#define BM_BCH_STATUS0_RSVD0 0x00000003 +#define BF_BCH_STATUS0_RSVD0(v) \ + (((v) << 0) & BM_BCH_STATUS0_RSVD0) + +/*============================================================================*/ + +#define HW_BCH_MODE (0x00000020) + +#define BP_BCH_MODE_RSVD 8 +#define BM_BCH_MODE_RSVD 0xFFFFFF00 +#define BF_BCH_MODE_RSVD(v) \ + (((v) << 8) & BM_BCH_MODE_RSVD) +#define BP_BCH_MODE_ERASE_THRESHOLD 0 +#define BM_BCH_MODE_ERASE_THRESHOLD 0x000000FF +#define BF_BCH_MODE_ERASE_THRESHOLD(v) \ + (((v) << 0) & BM_BCH_MODE_ERASE_THRESHOLD) + +/*============================================================================*/ + +#define HW_BCH_ENCODEPTR (0x00000030) + +#define BP_BCH_ENCODEPTR_ADDR 0 +#define BM_BCH_ENCODEPTR_ADDR 0xFFFFFFFF +#define BF_BCH_ENCODEPTR_ADDR(v) (v) + +/*============================================================================*/ + +#define HW_BCH_DATAPTR (0x00000040) + +#define BP_BCH_DATAPTR_ADDR 0 +#define BM_BCH_DATAPTR_ADDR 0xFFFFFFFF +#define BF_BCH_DATAPTR_ADDR(v) (v) + +/*============================================================================*/ + +#define HW_BCH_METAPTR (0x00000050) + +#define BP_BCH_METAPTR_ADDR 0 +#define BM_BCH_METAPTR_ADDR 0xFFFFFFFF +#define BF_BCH_METAPTR_ADDR(v) (v) + +/*============================================================================*/ + +#define HW_BCH_LAYOUTSELECT (0x00000070) + +#define BP_BCH_LAYOUTSELECT_CS15_SELECT 30 +#define BM_BCH_LAYOUTSELECT_CS15_SELECT 0xC0000000 +#define BF_BCH_LAYOUTSELECT_CS15_SELECT(v) \ + (((v) << 30) & BM_BCH_LAYOUTSELECT_CS15_SELECT) +#define BP_BCH_LAYOUTSELECT_CS14_SELECT 28 +#define BM_BCH_LAYOUTSELECT_CS14_SELECT 0x30000000 +#define BF_BCH_LAYOUTSELECT_CS14_SELECT(v) \ + (((v) << 28) & BM_BCH_LAYOUTSELECT_CS14_SELECT) +#define BP_BCH_LAYOUTSELECT_CS13_SELECT 26 +#define BM_BCH_LAYOUTSELECT_CS13_SELECT 0x0C000000 +#define BF_BCH_LAYOUTSELECT_CS13_SELECT(v) \ + (((v) << 26) & BM_BCH_LAYOUTSELECT_CS13_SELECT) +#define BP_BCH_LAYOUTSELECT_CS12_SELECT 24 +#define BM_BCH_LAYOUTSELECT_CS12_SELECT 0x03000000 +#define BF_BCH_LAYOUTSELECT_CS12_SELECT(v) \ + (((v) << 24) & BM_BCH_LAYOUTSELECT_CS12_SELECT) +#define BP_BCH_LAYOUTSELECT_CS11_SELECT 22 +#define BM_BCH_LAYOUTSELECT_CS11_SELECT 0x00C00000 +#define BF_BCH_LAYOUTSELECT_CS11_SELECT(v) \ + (((v) << 22) & BM_BCH_LAYOUTSELECT_CS11_SELECT) +#define BP_BCH_LAYOUTSELECT_CS10_SELECT 20 +#define BM_BCH_LAYOUTSELECT_CS10_SELECT 0x00300000 +#define BF_BCH_LAYOUTSELECT_CS10_SELECT(v) \ + (((v) << 20) & BM_BCH_LAYOUTSELECT_CS10_SELECT) +#define BP_BCH_LAYOUTSELECT_CS9_SELECT 18 +#define BM_BCH_LAYOUTSELECT_CS9_SELECT 0x000C0000 +#define BF_BCH_LAYOUTSELECT_CS9_SELECT(v) \ + (((v) << 18) & BM_BCH_LAYOUTSELECT_CS9_SELECT) +#define BP_BCH_LAYOUTSELECT_CS8_SELECT 16 +#define BM_BCH_LAYOUTSELECT_CS8_SELECT 0x00030000 +#define BF_BCH_LAYOUTSELECT_CS8_SELECT(v) \ + (((v) << 16) & BM_BCH_LAYOUTSELECT_CS8_SELECT) +#define BP_BCH_LAYOUTSELECT_CS7_SELECT 14 +#define BM_BCH_LAYOUTSELECT_CS7_SELECT 0x0000C000 +#define BF_BCH_LAYOUTSELECT_CS7_SELECT(v) \ + (((v) << 14) & BM_BCH_LAYOUTSELECT_CS7_SELECT) +#define BP_BCH_LAYOUTSELECT_CS6_SELECT 12 +#define BM_BCH_LAYOUTSELECT_CS6_SELECT 0x00003000 +#define BF_BCH_LAYOUTSELECT_CS6_SELECT(v) \ + (((v) << 12) & BM_BCH_LAYOUTSELECT_CS6_SELECT) +#define BP_BCH_LAYOUTSELECT_CS5_SELECT 10 +#define BM_BCH_LAYOUTSELECT_CS5_SELECT 0x00000C00 +#define BF_BCH_LAYOUTSELECT_CS5_SELECT(v) \ + (((v) << 10) & BM_BCH_LAYOUTSELECT_CS5_SELECT) +#define BP_BCH_LAYOUTSELECT_CS4_SELECT 8 +#define BM_BCH_LAYOUTSELECT_CS4_SELECT 0x00000300 +#define BF_BCH_LAYOUTSELECT_CS4_SELECT(v) \ + (((v) << 8) & BM_BCH_LAYOUTSELECT_CS4_SELECT) +#define BP_BCH_LAYOUTSELECT_CS3_SELECT 6 +#define BM_BCH_LAYOUTSELECT_CS3_SELECT 0x000000C0 +#define BF_BCH_LAYOUTSELECT_CS3_SELECT(v) \ + (((v) << 6) & BM_BCH_LAYOUTSELECT_CS3_SELECT) +#define BP_BCH_LAYOUTSELECT_CS2_SELECT 4 +#define BM_BCH_LAYOUTSELECT_CS2_SELECT 0x00000030 +#define BF_BCH_LAYOUTSELECT_CS2_SELECT(v) \ + (((v) << 4) & BM_BCH_LAYOUTSELECT_CS2_SELECT) +#define BP_BCH_LAYOUTSELECT_CS1_SELECT 2 +#define BM_BCH_LAYOUTSELECT_CS1_SELECT 0x0000000C +#define BF_BCH_LAYOUTSELECT_CS1_SELECT(v) \ + (((v) << 2) & BM_BCH_LAYOUTSELECT_CS1_SELECT) +#define BP_BCH_LAYOUTSELECT_CS0_SELECT 0 +#define BM_BCH_LAYOUTSELECT_CS0_SELECT 0x00000003 +#define BF_BCH_LAYOUTSELECT_CS0_SELECT(v) \ + (((v) << 0) & BM_BCH_LAYOUTSELECT_CS0_SELECT) + +/*============================================================================*/ + +#define HW_BCH_FLASH0LAYOUT0 (0x00000080) + +#define BP_BCH_FLASH0LAYOUT0_NBLOCKS 24 +#define BM_BCH_FLASH0LAYOUT0_NBLOCKS 0xFF000000 +#define BF_BCH_FLASH0LAYOUT0_NBLOCKS(v) \ + (((v) << 24) & BM_BCH_FLASH0LAYOUT0_NBLOCKS) +#define BP_BCH_FLASH0LAYOUT0_META_SIZE 16 +#define BM_BCH_FLASH0LAYOUT0_META_SIZE 0x00FF0000 +#define BF_BCH_FLASH0LAYOUT0_META_SIZE(v) \ + (((v) << 16) & BM_BCH_FLASH0LAYOUT0_META_SIZE) +#define BP_BCH_FLASH0LAYOUT0_ECC0 12 +#define BM_BCH_FLASH0LAYOUT0_ECC0 0x0000F000 +#define BF_BCH_FLASH0LAYOUT0_ECC0(v) \ + (((v) << 12) & BM_BCH_FLASH0LAYOUT0_ECC0) +#define BV_BCH_FLASH0LAYOUT0_ECC0__NONE 0x0 +#define BV_BCH_FLASH0LAYOUT0_ECC0__ECC2 0x1 +#define BV_BCH_FLASH0LAYOUT0_ECC0__ECC4 0x2 +#define BV_BCH_FLASH0LAYOUT0_ECC0__ECC6 0x3 +#define BV_BCH_FLASH0LAYOUT0_ECC0__ECC8 0x4 +#define BV_BCH_FLASH0LAYOUT0_ECC0__ECC10 0x5 +#define BV_BCH_FLASH0LAYOUT0_ECC0__ECC12 0x6 +#define BV_BCH_FLASH0LAYOUT0_ECC0__ECC14 0x7 +#define BV_BCH_FLASH0LAYOUT0_ECC0__ECC16 0x8 +#define BV_BCH_FLASH0LAYOUT0_ECC0__ECC18 0x9 +#define BV_BCH_FLASH0LAYOUT0_ECC0__ECC20 0xA +#define BP_BCH_FLASH0LAYOUT0_DATA0_SIZE 0 +#define BM_BCH_FLASH0LAYOUT0_DATA0_SIZE 0x00000FFF +#define BF_BCH_FLASH0LAYOUT0_DATA0_SIZE(v) \ + (((v) << 0) & BM_BCH_FLASH0LAYOUT0_DATA0_SIZE) + +/*============================================================================*/ + +#define HW_BCH_FLASH0LAYOUT1 (0x00000090) + +#define BP_BCH_FLASH0LAYOUT1_PAGE_SIZE 16 +#define BM_BCH_FLASH0LAYOUT1_PAGE_SIZE 0xFFFF0000 +#define BF_BCH_FLASH0LAYOUT1_PAGE_SIZE(v) \ + (((v) << 16) & BM_BCH_FLASH0LAYOUT1_PAGE_SIZE) +#define BP_BCH_FLASH0LAYOUT1_ECCN 12 +#define BM_BCH_FLASH0LAYOUT1_ECCN 0x0000F000 +#define BF_BCH_FLASH0LAYOUT1_ECCN(v) \ + (((v) << 12) & BM_BCH_FLASH0LAYOUT1_ECCN) +#define BV_BCH_FLASH0LAYOUT1_ECCN__NONE 0x0 +#define BV_BCH_FLASH0LAYOUT1_ECCN__ECC2 0x1 +#define BV_BCH_FLASH0LAYOUT1_ECCN__ECC4 0x2 +#define BV_BCH_FLASH0LAYOUT1_ECCN__ECC6 0x3 +#define BV_BCH_FLASH0LAYOUT1_ECCN__ECC8 0x4 +#define BV_BCH_FLASH0LAYOUT1_ECCN__ECC10 0x5 +#define BV_BCH_FLASH0LAYOUT1_ECCN__ECC12 0x6 +#define BV_BCH_FLASH0LAYOUT1_ECCN__ECC14 0x7 +#define BV_BCH_FLASH0LAYOUT1_ECCN__ECC16 0x8 +#define BV_BCH_FLASH0LAYOUT1_ECCN__ECC18 0x9 +#define BV_BCH_FLASH0LAYOUT1_ECCN__ECC20 0xA +#define BP_BCH_FLASH0LAYOUT1_DATAN_SIZE 0 +#define BM_BCH_FLASH0LAYOUT1_DATAN_SIZE 0x00000FFF +#define BF_BCH_FLASH0LAYOUT1_DATAN_SIZE(v) \ + (((v) << 0) & BM_BCH_FLASH0LAYOUT1_DATAN_SIZE) + +/*============================================================================*/ + +#define HW_BCH_FLASH1LAYOUT0 (0x000000a0) + +#define BP_BCH_FLASH1LAYOUT0_NBLOCKS 24 +#define BM_BCH_FLASH1LAYOUT0_NBLOCKS 0xFF000000 +#define BF_BCH_FLASH1LAYOUT0_NBLOCKS(v) \ + (((v) << 24) & BM_BCH_FLASH1LAYOUT0_NBLOCKS) +#define BP_BCH_FLASH1LAYOUT0_META_SIZE 16 +#define BM_BCH_FLASH1LAYOUT0_META_SIZE 0x00FF0000 +#define BF_BCH_FLASH1LAYOUT0_META_SIZE(v) \ + (((v) << 16) & BM_BCH_FLASH1LAYOUT0_META_SIZE) +#define BP_BCH_FLASH1LAYOUT0_ECC0 12 +#define BM_BCH_FLASH1LAYOUT0_ECC0 0x0000F000 +#define BF_BCH_FLASH1LAYOUT0_ECC0(v) \ + (((v) << 12) & BM_BCH_FLASH1LAYOUT0_ECC0) +#define BV_BCH_FLASH1LAYOUT0_ECC0__NONE 0x0 +#define BV_BCH_FLASH1LAYOUT0_ECC0__ECC2 0x1 +#define BV_BCH_FLASH1LAYOUT0_ECC0__ECC4 0x2 +#define BV_BCH_FLASH1LAYOUT0_ECC0__ECC6 0x3 +#define BV_BCH_FLASH1LAYOUT0_ECC0__ECC8 0x4 +#define BV_BCH_FLASH1LAYOUT0_ECC0__ECC10 0x5 +#define BV_BCH_FLASH1LAYOUT0_ECC0__ECC12 0x6 +#define BV_BCH_FLASH1LAYOUT0_ECC0__ECC14 0x7 +#define BV_BCH_FLASH1LAYOUT0_ECC0__ECC16 0x8 +#define BV_BCH_FLASH1LAYOUT0_ECC0__ECC18 0x9 +#define BV_BCH_FLASH1LAYOUT0_ECC0__ECC20 0xA +#define BP_BCH_FLASH1LAYOUT0_DATA0_SIZE 0 +#define BM_BCH_FLASH1LAYOUT0_DATA0_SIZE 0x00000FFF +#define BF_BCH_FLASH1LAYOUT0_DATA0_SIZE(v) \ + (((v) << 0) & BM_BCH_FLASH1LAYOUT0_DATA0_SIZE) + +/*============================================================================*/ + +#define HW_BCH_FLASH1LAYOUT1 (0x000000b0) + +#define BP_BCH_FLASH1LAYOUT1_PAGE_SIZE 16 +#define BM_BCH_FLASH1LAYOUT1_PAGE_SIZE 0xFFFF0000 +#define BF_BCH_FLASH1LAYOUT1_PAGE_SIZE(v) \ + (((v) << 16) & BM_BCH_FLASH1LAYOUT1_PAGE_SIZE) +#define BP_BCH_FLASH1LAYOUT1_ECCN 12 +#define BM_BCH_FLASH1LAYOUT1_ECCN 0x0000F000 +#define BF_BCH_FLASH1LAYOUT1_ECCN(v) \ + (((v) << 12) & BM_BCH_FLASH1LAYOUT1_ECCN) +#define BV_BCH_FLASH1LAYOUT1_ECCN__NONE 0x0 +#define BV_BCH_FLASH1LAYOUT1_ECCN__ECC2 0x1 +#define BV_BCH_FLASH1LAYOUT1_ECCN__ECC4 0x2 +#define BV_BCH_FLASH1LAYOUT1_ECCN__ECC6 0x3 +#define BV_BCH_FLASH1LAYOUT1_ECCN__ECC8 0x4 +#define BV_BCH_FLASH1LAYOUT1_ECCN__ECC10 0x5 +#define BV_BCH_FLASH1LAYOUT1_ECCN__ECC12 0x6 +#define BV_BCH_FLASH1LAYOUT1_ECCN__ECC14 0x7 +#define BV_BCH_FLASH1LAYOUT1_ECCN__ECC16 0x8 +#define BV_BCH_FLASH1LAYOUT1_ECCN__ECC18 0x9 +#define BV_BCH_FLASH1LAYOUT1_ECCN__ECC20 0xA +#define BP_BCH_FLASH1LAYOUT1_DATAN_SIZE 0 +#define BM_BCH_FLASH1LAYOUT1_DATAN_SIZE 0x00000FFF +#define BF_BCH_FLASH1LAYOUT1_DATAN_SIZE(v) \ + (((v) << 0) & BM_BCH_FLASH1LAYOUT1_DATAN_SIZE) + +/*============================================================================*/ + +#define HW_BCH_FLASH2LAYOUT0 (0x000000c0) + +#define BP_BCH_FLASH2LAYOUT0_NBLOCKS 24 +#define BM_BCH_FLASH2LAYOUT0_NBLOCKS 0xFF000000 +#define BF_BCH_FLASH2LAYOUT0_NBLOCKS(v) \ + (((v) << 24) & BM_BCH_FLASH2LAYOUT0_NBLOCKS) +#define BP_BCH_FLASH2LAYOUT0_META_SIZE 16 +#define BM_BCH_FLASH2LAYOUT0_META_SIZE 0x00FF0000 +#define BF_BCH_FLASH2LAYOUT0_META_SIZE(v) \ + (((v) << 16) & BM_BCH_FLASH2LAYOUT0_META_SIZE) +#define BP_BCH_FLASH2LAYOUT0_ECC0 12 +#define BM_BCH_FLASH2LAYOUT0_ECC0 0x0000F000 +#define BF_BCH_FLASH2LAYOUT0_ECC0(v) \ + (((v) << 12) & BM_BCH_FLASH2LAYOUT0_ECC0) +#define BV_BCH_FLASH2LAYOUT0_ECC0__NONE 0x0 +#define BV_BCH_FLASH2LAYOUT0_ECC0__ECC2 0x1 +#define BV_BCH_FLASH2LAYOUT0_ECC0__ECC4 0x2 +#define BV_BCH_FLASH2LAYOUT0_ECC0__ECC6 0x3 +#define BV_BCH_FLASH2LAYOUT0_ECC0__ECC8 0x4 +#define BV_BCH_FLASH2LAYOUT0_ECC0__ECC10 0x5 +#define BV_BCH_FLASH2LAYOUT0_ECC0__ECC12 0x6 +#define BV_BCH_FLASH2LAYOUT0_ECC0__ECC14 0x7 +#define BV_BCH_FLASH2LAYOUT0_ECC0__ECC16 0x8 +#define BV_BCH_FLASH2LAYOUT0_ECC0__ECC18 0x9 +#define BV_BCH_FLASH2LAYOUT0_ECC0__ECC20 0xA +#define BP_BCH_FLASH2LAYOUT0_DATA0_SIZE 0 +#define BM_BCH_FLASH2LAYOUT0_DATA0_SIZE 0x00000FFF +#define BF_BCH_FLASH2LAYOUT0_DATA0_SIZE(v) \ + (((v) << 0) & BM_BCH_FLASH2LAYOUT0_DATA0_SIZE) + +/*============================================================================*/ + +#define HW_BCH_FLASH2LAYOUT1 (0x000000d0) + +#define BP_BCH_FLASH2LAYOUT1_PAGE_SIZE 16 +#define BM_BCH_FLASH2LAYOUT1_PAGE_SIZE 0xFFFF0000 +#define BF_BCH_FLASH2LAYOUT1_PAGE_SIZE(v) \ + (((v) << 16) & BM_BCH_FLASH2LAYOUT1_PAGE_SIZE) +#define BP_BCH_FLASH2LAYOUT1_ECCN 12 +#define BM_BCH_FLASH2LAYOUT1_ECCN 0x0000F000 +#define BF_BCH_FLASH2LAYOUT1_ECCN(v) \ + (((v) << 12) & BM_BCH_FLASH2LAYOUT1_ECCN) +#define BV_BCH_FLASH2LAYOUT1_ECCN__NONE 0x0 +#define BV_BCH_FLASH2LAYOUT1_ECCN__ECC2 0x1 +#define BV_BCH_FLASH2LAYOUT1_ECCN__ECC4 0x2 +#define BV_BCH_FLASH2LAYOUT1_ECCN__ECC6 0x3 +#define BV_BCH_FLASH2LAYOUT1_ECCN__ECC8 0x4 +#define BV_BCH_FLASH2LAYOUT1_ECCN__ECC10 0x5 +#define BV_BCH_FLASH2LAYOUT1_ECCN__ECC12 0x6 +#define BV_BCH_FLASH2LAYOUT1_ECCN__ECC14 0x7 +#define BV_BCH_FLASH2LAYOUT1_ECCN__ECC16 0x8 +#define BV_BCH_FLASH2LAYOUT1_ECCN__ECC18 0x9 +#define BV_BCH_FLASH2LAYOUT1_ECCN__ECC20 0xA +#define BP_BCH_FLASH2LAYOUT1_DATAN_SIZE 0 +#define BM_BCH_FLASH2LAYOUT1_DATAN_SIZE 0x00000FFF +#define BF_BCH_FLASH2LAYOUT1_DATAN_SIZE(v) \ + (((v) << 0) & BM_BCH_FLASH2LAYOUT1_DATAN_SIZE) + +/*============================================================================*/ + +#define HW_BCH_FLASH3LAYOUT0 (0x000000e0) + +#define BP_BCH_FLASH3LAYOUT0_NBLOCKS 24 +#define BM_BCH_FLASH3LAYOUT0_NBLOCKS 0xFF000000 +#define BF_BCH_FLASH3LAYOUT0_NBLOCKS(v) \ + (((v) << 24) & BM_BCH_FLASH3LAYOUT0_NBLOCKS) +#define BP_BCH_FLASH3LAYOUT0_META_SIZE 16 +#define BM_BCH_FLASH3LAYOUT0_META_SIZE 0x00FF0000 +#define BF_BCH_FLASH3LAYOUT0_META_SIZE(v) \ + (((v) << 16) & BM_BCH_FLASH3LAYOUT0_META_SIZE) +#define BP_BCH_FLASH3LAYOUT0_ECC0 12 +#define BM_BCH_FLASH3LAYOUT0_ECC0 0x0000F000 +#define BF_BCH_FLASH3LAYOUT0_ECC0(v) \ + (((v) << 12) & BM_BCH_FLASH3LAYOUT0_ECC0) +#define BV_BCH_FLASH3LAYOUT0_ECC0__NONE 0x0 +#define BV_BCH_FLASH3LAYOUT0_ECC0__ECC2 0x1 +#define BV_BCH_FLASH3LAYOUT0_ECC0__ECC4 0x2 +#define BV_BCH_FLASH3LAYOUT0_ECC0__ECC6 0x3 +#define BV_BCH_FLASH3LAYOUT0_ECC0__ECC8 0x4 +#define BV_BCH_FLASH3LAYOUT0_ECC0__ECC10 0x5 +#define BV_BCH_FLASH3LAYOUT0_ECC0__ECC12 0x6 +#define BV_BCH_FLASH3LAYOUT0_ECC0__ECC14 0x7 +#define BV_BCH_FLASH3LAYOUT0_ECC0__ECC16 0x8 +#define BV_BCH_FLASH3LAYOUT0_ECC0__ECC18 0x9 +#define BV_BCH_FLASH3LAYOUT0_ECC0__ECC20 0xA +#define BP_BCH_FLASH3LAYOUT0_DATA0_SIZE 0 +#define BM_BCH_FLASH3LAYOUT0_DATA0_SIZE 0x00000FFF +#define BF_BCH_FLASH3LAYOUT0_DATA0_SIZE(v) \ + (((v) << 0) & BM_BCH_FLASH3LAYOUT0_DATA0_SIZE) + +/*============================================================================*/ + +#define HW_BCH_FLASH3LAYOUT1 (0x000000f0) + +#define BP_BCH_FLASH3LAYOUT1_PAGE_SIZE 16 +#define BM_BCH_FLASH3LAYOUT1_PAGE_SIZE 0xFFFF0000 +#define BF_BCH_FLASH3LAYOUT1_PAGE_SIZE(v) \ + (((v) << 16) & BM_BCH_FLASH3LAYOUT1_PAGE_SIZE) +#define BP_BCH_FLASH3LAYOUT1_ECCN 12 +#define BM_BCH_FLASH3LAYOUT1_ECCN 0x0000F000 +#define BF_BCH_FLASH3LAYOUT1_ECCN(v) \ + (((v) << 12) & BM_BCH_FLASH3LAYOUT1_ECCN) +#define BV_BCH_FLASH3LAYOUT1_ECCN__NONE 0x0 +#define BV_BCH_FLASH3LAYOUT1_ECCN__ECC2 0x1 +#define BV_BCH_FLASH3LAYOUT1_ECCN__ECC4 0x2 +#define BV_BCH_FLASH3LAYOUT1_ECCN__ECC6 0x3 +#define BV_BCH_FLASH3LAYOUT1_ECCN__ECC8 0x4 +#define BV_BCH_FLASH3LAYOUT1_ECCN__ECC10 0x5 +#define BV_BCH_FLASH3LAYOUT1_ECCN__ECC12 0x6 +#define BV_BCH_FLASH3LAYOUT1_ECCN__ECC14 0x7 +#define BV_BCH_FLASH3LAYOUT1_ECCN__ECC16 0x8 +#define BV_BCH_FLASH3LAYOUT1_ECCN__ECC18 0x9 +#define BV_BCH_FLASH3LAYOUT1_ECCN__ECC20 0xA +#define BP_BCH_FLASH3LAYOUT1_DATAN_SIZE 0 +#define BM_BCH_FLASH3LAYOUT1_DATAN_SIZE 0x00000FFF +#define BF_BCH_FLASH3LAYOUT1_DATAN_SIZE(v) \ + (((v) << 0) & BM_BCH_FLASH3LAYOUT1_DATAN_SIZE) + +/*============================================================================*/ + +#define HW_BCH_DEBUG0 (0x00000100) +#define HW_BCH_DEBUG0_SET (0x00000104) +#define HW_BCH_DEBUG0_CLR (0x00000108) +#define HW_BCH_DEBUG0_TOG (0x0000010c) + +#define BP_BCH_DEBUG0_RSVD1 27 +#define BM_BCH_DEBUG0_RSVD1 0xF8000000 +#define BF_BCH_DEBUG0_RSVD1(v) \ + (((v) << 27) & BM_BCH_DEBUG0_RSVD1) +#define BM_BCH_DEBUG0_ROM_BIST_ENABLE 0x04000000 +#define BM_BCH_DEBUG0_ROM_BIST_COMPLETE 0x02000000 +#define BP_BCH_DEBUG0_KES_DEBUG_SYNDROME_SYMBOL 16 +#define BM_BCH_DEBUG0_KES_DEBUG_SYNDROME_SYMBOL 0x01FF0000 +#define BF_BCH_DEBUG0_KES_DEBUG_SYNDROME_SYMBOL(v) \ + (((v) << 16) & BM_BCH_DEBUG0_KES_DEBUG_SYNDROME_SYMBOL) +#define BV_BCH_DEBUG0_KES_DEBUG_SYNDROME_SYMBOL__NORMAL 0x0 +#define BV_BCH_DEBUG0_KES_DEBUG_SYNDROME_SYMBOL__TEST_MODE 0x1 +#define BM_BCH_DEBUG0_KES_DEBUG_SHIFT_SYND 0x00008000 +#define BM_BCH_DEBUG0_KES_DEBUG_PAYLOAD_FLAG 0x00004000 +#define BV_BCH_DEBUG0_KES_DEBUG_PAYLOAD_FLAG__DATA 0x1 +#define BV_BCH_DEBUG0_KES_DEBUG_PAYLOAD_FLAG__AUX 0x1 +#define BM_BCH_DEBUG0_KES_DEBUG_MODE4K 0x00002000 +#define BV_BCH_DEBUG0_KES_DEBUG_MODE4K__4k 0x1 +#define BV_BCH_DEBUG0_KES_DEBUG_MODE4K__2k 0x1 +#define BM_BCH_DEBUG0_KES_DEBUG_KICK 0x00001000 +#define BM_BCH_DEBUG0_KES_STANDALONE 0x00000800 +#define BV_BCH_DEBUG0_KES_STANDALONE__NORMAL 0x0 +#define BV_BCH_DEBUG0_KES_STANDALONE__TEST_MODE 0x1 +#define BM_BCH_DEBUG0_KES_DEBUG_STEP 0x00000400 +#define BM_BCH_DEBUG0_KES_DEBUG_STALL 0x00000200 +#define BV_BCH_DEBUG0_KES_DEBUG_STALL__NORMAL 0x0 +#define BV_BCH_DEBUG0_KES_DEBUG_STALL__WAIT 0x1 +#define BM_BCH_DEBUG0_BM_KES_TEST_BYPASS 0x00000100 +#define BV_BCH_DEBUG0_BM_KES_TEST_BYPASS__NORMAL 0x0 +#define BV_BCH_DEBUG0_BM_KES_TEST_BYPASS__TEST_MODE 0x1 +#define BP_BCH_DEBUG0_RSVD0 6 +#define BM_BCH_DEBUG0_RSVD0 0x000000C0 +#define BF_BCH_DEBUG0_RSVD0(v) \ + (((v) << 6) & BM_BCH_DEBUG0_RSVD0) +#define BP_BCH_DEBUG0_DEBUG_REG_SELECT 0 +#define BM_BCH_DEBUG0_DEBUG_REG_SELECT 0x0000003F +#define BF_BCH_DEBUG0_DEBUG_REG_SELECT(v) \ + (((v) << 0) & BM_BCH_DEBUG0_DEBUG_REG_SELECT) + +/*============================================================================*/ + +#define HW_BCH_DBGKESREAD (0x00000110) + +#define BP_BCH_DBGKESREAD_VALUES 0 +#define BM_BCH_DBGKESREAD_VALUES 0xFFFFFFFF +#define BF_BCH_DBGKESREAD_VALUES(v) (v) + +/*============================================================================*/ + +#define HW_BCH_DBGCSFEREAD (0x00000120) + +#define BP_BCH_DBGCSFEREAD_VALUES 0 +#define BM_BCH_DBGCSFEREAD_VALUES 0xFFFFFFFF +#define BF_BCH_DBGCSFEREAD_VALUES(v) (v) + +/*============================================================================*/ + +#define HW_BCH_DBGSYNDGENREAD (0x00000130) + +#define BP_BCH_DBGSYNDGENREAD_VALUES 0 +#define BM_BCH_DBGSYNDGENREAD_VALUES 0xFFFFFFFF +#define BF_BCH_DBGSYNDGENREAD_VALUES(v) (v) + +/*============================================================================*/ + +#define HW_BCH_DBGAHBMREAD (0x00000140) + +#define BP_BCH_DBGAHBMREAD_VALUES 0 +#define BM_BCH_DBGAHBMREAD_VALUES 0xFFFFFFFF +#define BF_BCH_DBGAHBMREAD_VALUES(v) (v) + +/*============================================================================*/ + +#define HW_BCH_BLOCKNAME (0x00000150) + +#define BP_BCH_BLOCKNAME_NAME 0 +#define BM_BCH_BLOCKNAME_NAME 0xFFFFFFFF +#define BF_BCH_BLOCKNAME_NAME(v) (v) + +/*============================================================================*/ + +#define HW_BCH_VERSION (0x00000160) + +#define BP_BCH_VERSION_MAJOR 24 +#define BM_BCH_VERSION_MAJOR 0xFF000000 +#define BF_BCH_VERSION_MAJOR(v) \ + (((v) << 24) & BM_BCH_VERSION_MAJOR) +#define BP_BCH_VERSION_MINOR 16 +#define BM_BCH_VERSION_MINOR 0x00FF0000 +#define BF_BCH_VERSION_MINOR(v) \ + (((v) << 16) & BM_BCH_VERSION_MINOR) +#define BP_BCH_VERSION_STEP 0 +#define BM_BCH_VERSION_STEP 0x0000FFFF +#define BF_BCH_VERSION_STEP(v) \ + (((v) << 0) & BM_BCH_VERSION_STEP) + +/*============================================================================*/ + +#endif diff --git a/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-bch-regs-v1.h b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-bch-regs-v1.h new file mode 100644 index 000000000000..692db086de4d --- /dev/null +++ b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-bch-regs-v1.h @@ -0,0 +1,557 @@ +/* + * Freescale GPMI NFC NAND Flash Driver + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * Xml Revision: 2.5 + * Template revision: 26195 + */ + +#ifndef __GPMI_NFC_BCH_REGS_H +#define __GPMI_NFC_BCH_REGS_H + +/*============================================================================*/ + +#define HW_BCH_CTRL (0x00000000) +#define HW_BCH_CTRL_SET (0x00000004) +#define HW_BCH_CTRL_CLR (0x00000008) +#define HW_BCH_CTRL_TOG (0x0000000c) + +#define BM_BCH_CTRL_SFTRST 0x80000000 +#define BV_BCH_CTRL_SFTRST__RUN 0x0 +#define BV_BCH_CTRL_SFTRST__RESET 0x1 +#define BM_BCH_CTRL_CLKGATE 0x40000000 +#define BV_BCH_CTRL_CLKGATE__RUN 0x0 +#define BV_BCH_CTRL_CLKGATE__NO_CLKS 0x1 +#define BP_BCH_CTRL_RSVD5 23 +#define BM_BCH_CTRL_RSVD5 0x3F800000 +#define BF_BCH_CTRL_RSVD5(v) \ + (((v) << 23) & BM_BCH_CTRL_RSVD5) +#define BM_BCH_CTRL_DEBUGSYNDROME 0x00400000 +#define BP_BCH_CTRL_RSVD4 20 +#define BM_BCH_CTRL_RSVD4 0x00300000 +#define BF_BCH_CTRL_RSVD4(v) \ + (((v) << 20) & BM_BCH_CTRL_RSVD4) +#define BP_BCH_CTRL_M2M_LAYOUT 18 +#define BM_BCH_CTRL_M2M_LAYOUT 0x000C0000 +#define BF_BCH_CTRL_M2M_LAYOUT(v) \ + (((v) << 18) & BM_BCH_CTRL_M2M_LAYOUT) +#define BM_BCH_CTRL_M2M_ENCODE 0x00020000 +#define BM_BCH_CTRL_M2M_ENABLE 0x00010000 +#define BP_BCH_CTRL_RSVD3 11 +#define BM_BCH_CTRL_RSVD3 0x0000F800 +#define BF_BCH_CTRL_RSVD3(v) \ + (((v) << 11) & BM_BCH_CTRL_RSVD3) +#define BM_BCH_CTRL_DEBUG_STALL_IRQ_EN 0x00000400 +#define BM_BCH_CTRL_RSVD2 0x00000200 +#define BM_BCH_CTRL_COMPLETE_IRQ_EN 0x00000100 +#define BP_BCH_CTRL_RSVD1 4 +#define BM_BCH_CTRL_RSVD1 0x000000F0 +#define BF_BCH_CTRL_RSVD1(v) \ + (((v) << 4) & BM_BCH_CTRL_RSVD1) +#define BM_BCH_CTRL_BM_ERROR_IRQ 0x00000008 +#define BM_BCH_CTRL_DEBUG_STALL_IRQ 0x00000004 +#define BM_BCH_CTRL_RSVD0 0x00000002 +#define BM_BCH_CTRL_COMPLETE_IRQ 0x00000001 + +/*============================================================================*/ + +#define HW_BCH_STATUS0 (0x00000010) + +#define BP_BCH_STATUS0_HANDLE 20 +#define BM_BCH_STATUS0_HANDLE 0xFFF00000 +#define BF_BCH_STATUS0_HANDLE(v) \ + (((v) << 20) & BM_BCH_STATUS0_HANDLE) +#define BP_BCH_STATUS0_COMPLETED_CE 16 +#define BM_BCH_STATUS0_COMPLETED_CE 0x000F0000 +#define BF_BCH_STATUS0_COMPLETED_CE(v) \ + (((v) << 16) & BM_BCH_STATUS0_COMPLETED_CE) +#define BP_BCH_STATUS0_STATUS_BLK0 8 +#define BM_BCH_STATUS0_STATUS_BLK0 0x0000FF00 +#define BF_BCH_STATUS0_STATUS_BLK0(v) \ + (((v) << 8) & BM_BCH_STATUS0_STATUS_BLK0) +#define BV_BCH_STATUS0_STATUS_BLK0__ZERO 0x00 +#define BV_BCH_STATUS0_STATUS_BLK0__ERROR1 0x01 +#define BV_BCH_STATUS0_STATUS_BLK0__ERROR2 0x02 +#define BV_BCH_STATUS0_STATUS_BLK0__ERROR3 0x03 +#define BV_BCH_STATUS0_STATUS_BLK0__ERROR4 0x04 +#define BV_BCH_STATUS0_STATUS_BLK0__UNCORRECTABLE 0xFE +#define BV_BCH_STATUS0_STATUS_BLK0__ERASED 0xFF +#define BP_BCH_STATUS0_RSVD1 5 +#define BM_BCH_STATUS0_RSVD1 0x000000E0 +#define BF_BCH_STATUS0_RSVD1(v) \ + (((v) << 5) & BM_BCH_STATUS0_RSVD1) +#define BM_BCH_STATUS0_ALLONES 0x00000010 +#define BM_BCH_STATUS0_CORRECTED 0x00000008 +#define BM_BCH_STATUS0_UNCORRECTABLE 0x00000004 +#define BP_BCH_STATUS0_RSVD0 0 +#define BM_BCH_STATUS0_RSVD0 0x00000003 +#define BF_BCH_STATUS0_RSVD0(v) \ + (((v) << 0) & BM_BCH_STATUS0_RSVD0) + +/*============================================================================*/ + +#define HW_BCH_MODE (0x00000020) + +#define BP_BCH_MODE_RSVD 8 +#define BM_BCH_MODE_RSVD 0xFFFFFF00 +#define BF_BCH_MODE_RSVD(v) \ + (((v) << 8) & BM_BCH_MODE_RSVD) +#define BP_BCH_MODE_ERASE_THRESHOLD 0 +#define BM_BCH_MODE_ERASE_THRESHOLD 0x000000FF +#define BF_BCH_MODE_ERASE_THRESHOLD(v) \ + (((v) << 0) & BM_BCH_MODE_ERASE_THRESHOLD) + +/*============================================================================*/ + +#define HW_BCH_ENCODEPTR (0x00000030) + +#define BP_BCH_ENCODEPTR_ADDR 0 +#define BM_BCH_ENCODEPTR_ADDR 0xFFFFFFFF +#define BF_BCH_ENCODEPTR_ADDR(v) (v) + +/*============================================================================*/ + +#define HW_BCH_DATAPTR (0x00000040) + +#define BP_BCH_DATAPTR_ADDR 0 +#define BM_BCH_DATAPTR_ADDR 0xFFFFFFFF +#define BF_BCH_DATAPTR_ADDR(v) (v) + +/*============================================================================*/ + +#define HW_BCH_METAPTR (0x00000050) + +#define BP_BCH_METAPTR_ADDR 0 +#define BM_BCH_METAPTR_ADDR 0xFFFFFFFF +#define BF_BCH_METAPTR_ADDR(v) (v) + +/*============================================================================*/ + +#define HW_BCH_LAYOUTSELECT (0x00000070) + +#define BP_BCH_LAYOUTSELECT_CS15_SELECT 30 +#define BM_BCH_LAYOUTSELECT_CS15_SELECT 0xC0000000 +#define BF_BCH_LAYOUTSELECT_CS15_SELECT(v) \ + (((v) << 30) & BM_BCH_LAYOUTSELECT_CS15_SELECT) +#define BP_BCH_LAYOUTSELECT_CS14_SELECT 28 +#define BM_BCH_LAYOUTSELECT_CS14_SELECT 0x30000000 +#define BF_BCH_LAYOUTSELECT_CS14_SELECT(v) \ + (((v) << 28) & BM_BCH_LAYOUTSELECT_CS14_SELECT) +#define BP_BCH_LAYOUTSELECT_CS13_SELECT 26 +#define BM_BCH_LAYOUTSELECT_CS13_SELECT 0x0C000000 +#define BF_BCH_LAYOUTSELECT_CS13_SELECT(v) \ + (((v) << 26) & BM_BCH_LAYOUTSELECT_CS13_SELECT) +#define BP_BCH_LAYOUTSELECT_CS12_SELECT 24 +#define BM_BCH_LAYOUTSELECT_CS12_SELECT 0x03000000 +#define BF_BCH_LAYOUTSELECT_CS12_SELECT(v) \ + (((v) << 24) & BM_BCH_LAYOUTSELECT_CS12_SELECT) +#define BP_BCH_LAYOUTSELECT_CS11_SELECT 22 +#define BM_BCH_LAYOUTSELECT_CS11_SELECT 0x00C00000 +#define BF_BCH_LAYOUTSELECT_CS11_SELECT(v) \ + (((v) << 22) & BM_BCH_LAYOUTSELECT_CS11_SELECT) +#define BP_BCH_LAYOUTSELECT_CS10_SELECT 20 +#define BM_BCH_LAYOUTSELECT_CS10_SELECT 0x00300000 +#define BF_BCH_LAYOUTSELECT_CS10_SELECT(v) \ + (((v) << 20) & BM_BCH_LAYOUTSELECT_CS10_SELECT) +#define BP_BCH_LAYOUTSELECT_CS9_SELECT 18 +#define BM_BCH_LAYOUTSELECT_CS9_SELECT 0x000C0000 +#define BF_BCH_LAYOUTSELECT_CS9_SELECT(v) \ + (((v) << 18) & BM_BCH_LAYOUTSELECT_CS9_SELECT) +#define BP_BCH_LAYOUTSELECT_CS8_SELECT 16 +#define BM_BCH_LAYOUTSELECT_CS8_SELECT 0x00030000 +#define BF_BCH_LAYOUTSELECT_CS8_SELECT(v) \ + (((v) << 16) & BM_BCH_LAYOUTSELECT_CS8_SELECT) +#define BP_BCH_LAYOUTSELECT_CS7_SELECT 14 +#define BM_BCH_LAYOUTSELECT_CS7_SELECT 0x0000C000 +#define BF_BCH_LAYOUTSELECT_CS7_SELECT(v) \ + (((v) << 14) & BM_BCH_LAYOUTSELECT_CS7_SELECT) +#define BP_BCH_LAYOUTSELECT_CS6_SELECT 12 +#define BM_BCH_LAYOUTSELECT_CS6_SELECT 0x00003000 +#define BF_BCH_LAYOUTSELECT_CS6_SELECT(v) \ + (((v) << 12) & BM_BCH_LAYOUTSELECT_CS6_SELECT) +#define BP_BCH_LAYOUTSELECT_CS5_SELECT 10 +#define BM_BCH_LAYOUTSELECT_CS5_SELECT 0x00000C00 +#define BF_BCH_LAYOUTSELECT_CS5_SELECT(v) \ + (((v) << 10) & BM_BCH_LAYOUTSELECT_CS5_SELECT) +#define BP_BCH_LAYOUTSELECT_CS4_SELECT 8 +#define BM_BCH_LAYOUTSELECT_CS4_SELECT 0x00000300 +#define BF_BCH_LAYOUTSELECT_CS4_SELECT(v) \ + (((v) << 8) & BM_BCH_LAYOUTSELECT_CS4_SELECT) +#define BP_BCH_LAYOUTSELECT_CS3_SELECT 6 +#define BM_BCH_LAYOUTSELECT_CS3_SELECT 0x000000C0 +#define BF_BCH_LAYOUTSELECT_CS3_SELECT(v) \ + (((v) << 6) & BM_BCH_LAYOUTSELECT_CS3_SELECT) +#define BP_BCH_LAYOUTSELECT_CS2_SELECT 4 +#define BM_BCH_LAYOUTSELECT_CS2_SELECT 0x00000030 +#define BF_BCH_LAYOUTSELECT_CS2_SELECT(v) \ + (((v) << 4) & BM_BCH_LAYOUTSELECT_CS2_SELECT) +#define BP_BCH_LAYOUTSELECT_CS1_SELECT 2 +#define BM_BCH_LAYOUTSELECT_CS1_SELECT 0x0000000C +#define BF_BCH_LAYOUTSELECT_CS1_SELECT(v) \ + (((v) << 2) & BM_BCH_LAYOUTSELECT_CS1_SELECT) +#define BP_BCH_LAYOUTSELECT_CS0_SELECT 0 +#define BM_BCH_LAYOUTSELECT_CS0_SELECT 0x00000003 +#define BF_BCH_LAYOUTSELECT_CS0_SELECT(v) \ + (((v) << 0) & BM_BCH_LAYOUTSELECT_CS0_SELECT) + +/*============================================================================*/ + +#define HW_BCH_FLASH0LAYOUT0 (0x00000080) + +#define BP_BCH_FLASH0LAYOUT0_NBLOCKS 24 +#define BM_BCH_FLASH0LAYOUT0_NBLOCKS 0xFF000000 +#define BF_BCH_FLASH0LAYOUT0_NBLOCKS(v) \ + (((v) << 24) & BM_BCH_FLASH0LAYOUT0_NBLOCKS) +#define BP_BCH_FLASH0LAYOUT0_META_SIZE 16 +#define BM_BCH_FLASH0LAYOUT0_META_SIZE 0x00FF0000 +#define BF_BCH_FLASH0LAYOUT0_META_SIZE(v) \ + (((v) << 16) & BM_BCH_FLASH0LAYOUT0_META_SIZE) +#define BP_BCH_FLASH0LAYOUT0_ECC0 12 +#define BM_BCH_FLASH0LAYOUT0_ECC0 0x0000F000 +#define BF_BCH_FLASH0LAYOUT0_ECC0(v) \ + (((v) << 12) & BM_BCH_FLASH0LAYOUT0_ECC0) +#define BV_BCH_FLASH0LAYOUT0_ECC0__NONE 0x0 +#define BV_BCH_FLASH0LAYOUT0_ECC0__ECC2 0x1 +#define BV_BCH_FLASH0LAYOUT0_ECC0__ECC4 0x2 +#define BV_BCH_FLASH0LAYOUT0_ECC0__ECC6 0x3 +#define BV_BCH_FLASH0LAYOUT0_ECC0__ECC8 0x4 +#define BV_BCH_FLASH0LAYOUT0_ECC0__ECC10 0x5 +#define BV_BCH_FLASH0LAYOUT0_ECC0__ECC12 0x6 +#define BV_BCH_FLASH0LAYOUT0_ECC0__ECC14 0x7 +#define BV_BCH_FLASH0LAYOUT0_ECC0__ECC16 0x8 +#define BV_BCH_FLASH0LAYOUT0_ECC0__ECC18 0x9 +#define BV_BCH_FLASH0LAYOUT0_ECC0__ECC20 0xA +#define BP_BCH_FLASH0LAYOUT0_DATA0_SIZE 0 +#define BM_BCH_FLASH0LAYOUT0_DATA0_SIZE 0x00000FFF +#define BF_BCH_FLASH0LAYOUT0_DATA0_SIZE(v) \ + (((v) << 0) & BM_BCH_FLASH0LAYOUT0_DATA0_SIZE) + +/*============================================================================*/ + +#define HW_BCH_FLASH0LAYOUT1 (0x00000090) + +#define BP_BCH_FLASH0LAYOUT1_PAGE_SIZE 16 +#define BM_BCH_FLASH0LAYOUT1_PAGE_SIZE 0xFFFF0000 +#define BF_BCH_FLASH0LAYOUT1_PAGE_SIZE(v) \ + (((v) << 16) & BM_BCH_FLASH0LAYOUT1_PAGE_SIZE) +#define BP_BCH_FLASH0LAYOUT1_ECCN 12 +#define BM_BCH_FLASH0LAYOUT1_ECCN 0x0000F000 +#define BF_BCH_FLASH0LAYOUT1_ECCN(v) \ + (((v) << 12) & BM_BCH_FLASH0LAYOUT1_ECCN) +#define BV_BCH_FLASH0LAYOUT1_ECCN__NONE 0x0 +#define BV_BCH_FLASH0LAYOUT1_ECCN__ECC2 0x1 +#define BV_BCH_FLASH0LAYOUT1_ECCN__ECC4 0x2 +#define BV_BCH_FLASH0LAYOUT1_ECCN__ECC6 0x3 +#define BV_BCH_FLASH0LAYOUT1_ECCN__ECC8 0x4 +#define BV_BCH_FLASH0LAYOUT1_ECCN__ECC10 0x5 +#define BV_BCH_FLASH0LAYOUT1_ECCN__ECC12 0x6 +#define BV_BCH_FLASH0LAYOUT1_ECCN__ECC14 0x7 +#define BV_BCH_FLASH0LAYOUT1_ECCN__ECC16 0x8 +#define BV_BCH_FLASH0LAYOUT1_ECCN__ECC18 0x9 +#define BV_BCH_FLASH0LAYOUT1_ECCN__ECC20 0xA +#define BP_BCH_FLASH0LAYOUT1_DATAN_SIZE 0 +#define BM_BCH_FLASH0LAYOUT1_DATAN_SIZE 0x00000FFF +#define BF_BCH_FLASH0LAYOUT1_DATAN_SIZE(v) \ + (((v) << 0) & BM_BCH_FLASH0LAYOUT1_DATAN_SIZE) + +/*============================================================================*/ + +#define HW_BCH_FLASH1LAYOUT0 (0x000000a0) + +#define BP_BCH_FLASH1LAYOUT0_NBLOCKS 24 +#define BM_BCH_FLASH1LAYOUT0_NBLOCKS 0xFF000000 +#define BF_BCH_FLASH1LAYOUT0_NBLOCKS(v) \ + (((v) << 24) & BM_BCH_FLASH1LAYOUT0_NBLOCKS) +#define BP_BCH_FLASH1LAYOUT0_META_SIZE 16 +#define BM_BCH_FLASH1LAYOUT0_META_SIZE 0x00FF0000 +#define BF_BCH_FLASH1LAYOUT0_META_SIZE(v) \ + (((v) << 16) & BM_BCH_FLASH1LAYOUT0_META_SIZE) +#define BP_BCH_FLASH1LAYOUT0_ECC0 12 +#define BM_BCH_FLASH1LAYOUT0_ECC0 0x0000F000 +#define BF_BCH_FLASH1LAYOUT0_ECC0(v) \ + (((v) << 12) & BM_BCH_FLASH1LAYOUT0_ECC0) +#define BV_BCH_FLASH1LAYOUT0_ECC0__NONE 0x0 +#define BV_BCH_FLASH1LAYOUT0_ECC0__ECC2 0x1 +#define BV_BCH_FLASH1LAYOUT0_ECC0__ECC4 0x2 +#define BV_BCH_FLASH1LAYOUT0_ECC0__ECC6 0x3 +#define BV_BCH_FLASH1LAYOUT0_ECC0__ECC8 0x4 +#define BV_BCH_FLASH1LAYOUT0_ECC0__ECC10 0x5 +#define BV_BCH_FLASH1LAYOUT0_ECC0__ECC12 0x6 +#define BV_BCH_FLASH1LAYOUT0_ECC0__ECC14 0x7 +#define BV_BCH_FLASH1LAYOUT0_ECC0__ECC16 0x8 +#define BV_BCH_FLASH1LAYOUT0_ECC0__ECC18 0x9 +#define BV_BCH_FLASH1LAYOUT0_ECC0__ECC20 0xA +#define BP_BCH_FLASH1LAYOUT0_DATA0_SIZE 0 +#define BM_BCH_FLASH1LAYOUT0_DATA0_SIZE 0x00000FFF +#define BF_BCH_FLASH1LAYOUT0_DATA0_SIZE(v) \ + (((v) << 0) & BM_BCH_FLASH1LAYOUT0_DATA0_SIZE) + +/*============================================================================*/ + +#define HW_BCH_FLASH1LAYOUT1 (0x000000b0) + +#define BP_BCH_FLASH1LAYOUT1_PAGE_SIZE 16 +#define BM_BCH_FLASH1LAYOUT1_PAGE_SIZE 0xFFFF0000 +#define BF_BCH_FLASH1LAYOUT1_PAGE_SIZE(v) \ + (((v) << 16) & BM_BCH_FLASH1LAYOUT1_PAGE_SIZE) +#define BP_BCH_FLASH1LAYOUT1_ECCN 12 +#define BM_BCH_FLASH1LAYOUT1_ECCN 0x0000F000 +#define BF_BCH_FLASH1LAYOUT1_ECCN(v) \ + (((v) << 12) & BM_BCH_FLASH1LAYOUT1_ECCN) +#define BV_BCH_FLASH1LAYOUT1_ECCN__NONE 0x0 +#define BV_BCH_FLASH1LAYOUT1_ECCN__ECC2 0x1 +#define BV_BCH_FLASH1LAYOUT1_ECCN__ECC4 0x2 +#define BV_BCH_FLASH1LAYOUT1_ECCN__ECC6 0x3 +#define BV_BCH_FLASH1LAYOUT1_ECCN__ECC8 0x4 +#define BV_BCH_FLASH1LAYOUT1_ECCN__ECC10 0x5 +#define BV_BCH_FLASH1LAYOUT1_ECCN__ECC12 0x6 +#define BV_BCH_FLASH1LAYOUT1_ECCN__ECC14 0x7 +#define BV_BCH_FLASH1LAYOUT1_ECCN__ECC16 0x8 +#define BV_BCH_FLASH1LAYOUT1_ECCN__ECC18 0x9 +#define BV_BCH_FLASH1LAYOUT1_ECCN__ECC20 0xA +#define BP_BCH_FLASH1LAYOUT1_DATAN_SIZE 0 +#define BM_BCH_FLASH1LAYOUT1_DATAN_SIZE 0x00000FFF +#define BF_BCH_FLASH1LAYOUT1_DATAN_SIZE(v) \ + (((v) << 0) & BM_BCH_FLASH1LAYOUT1_DATAN_SIZE) + +/*============================================================================*/ + +#define HW_BCH_FLASH2LAYOUT0 (0x000000c0) + +#define BP_BCH_FLASH2LAYOUT0_NBLOCKS 24 +#define BM_BCH_FLASH2LAYOUT0_NBLOCKS 0xFF000000 +#define BF_BCH_FLASH2LAYOUT0_NBLOCKS(v) \ + (((v) << 24) & BM_BCH_FLASH2LAYOUT0_NBLOCKS) +#define BP_BCH_FLASH2LAYOUT0_META_SIZE 16 +#define BM_BCH_FLASH2LAYOUT0_META_SIZE 0x00FF0000 +#define BF_BCH_FLASH2LAYOUT0_META_SIZE(v) \ + (((v) << 16) & BM_BCH_FLASH2LAYOUT0_META_SIZE) +#define BP_BCH_FLASH2LAYOUT0_ECC0 12 +#define BM_BCH_FLASH2LAYOUT0_ECC0 0x0000F000 +#define BF_BCH_FLASH2LAYOUT0_ECC0(v) \ + (((v) << 12) & BM_BCH_FLASH2LAYOUT0_ECC0) +#define BV_BCH_FLASH2LAYOUT0_ECC0__NONE 0x0 +#define BV_BCH_FLASH2LAYOUT0_ECC0__ECC2 0x1 +#define BV_BCH_FLASH2LAYOUT0_ECC0__ECC4 0x2 +#define BV_BCH_FLASH2LAYOUT0_ECC0__ECC6 0x3 +#define BV_BCH_FLASH2LAYOUT0_ECC0__ECC8 0x4 +#define BV_BCH_FLASH2LAYOUT0_ECC0__ECC10 0x5 +#define BV_BCH_FLASH2LAYOUT0_ECC0__ECC12 0x6 +#define BV_BCH_FLASH2LAYOUT0_ECC0__ECC14 0x7 +#define BV_BCH_FLASH2LAYOUT0_ECC0__ECC16 0x8 +#define BV_BCH_FLASH2LAYOUT0_ECC0__ECC18 0x9 +#define BV_BCH_FLASH2LAYOUT0_ECC0__ECC20 0xA +#define BP_BCH_FLASH2LAYOUT0_DATA0_SIZE 0 +#define BM_BCH_FLASH2LAYOUT0_DATA0_SIZE 0x00000FFF +#define BF_BCH_FLASH2LAYOUT0_DATA0_SIZE(v) \ + (((v) << 0) & BM_BCH_FLASH2LAYOUT0_DATA0_SIZE) + +/*============================================================================*/ + +#define HW_BCH_FLASH2LAYOUT1 (0x000000d0) + +#define BP_BCH_FLASH2LAYOUT1_PAGE_SIZE 16 +#define BM_BCH_FLASH2LAYOUT1_PAGE_SIZE 0xFFFF0000 +#define BF_BCH_FLASH2LAYOUT1_PAGE_SIZE(v) \ + (((v) << 16) & BM_BCH_FLASH2LAYOUT1_PAGE_SIZE) +#define BP_BCH_FLASH2LAYOUT1_ECCN 12 +#define BM_BCH_FLASH2LAYOUT1_ECCN 0x0000F000 +#define BF_BCH_FLASH2LAYOUT1_ECCN(v) \ + (((v) << 12) & BM_BCH_FLASH2LAYOUT1_ECCN) +#define BV_BCH_FLASH2LAYOUT1_ECCN__NONE 0x0 +#define BV_BCH_FLASH2LAYOUT1_ECCN__ECC2 0x1 +#define BV_BCH_FLASH2LAYOUT1_ECCN__ECC4 0x2 +#define BV_BCH_FLASH2LAYOUT1_ECCN__ECC6 0x3 +#define BV_BCH_FLASH2LAYOUT1_ECCN__ECC8 0x4 +#define BV_BCH_FLASH2LAYOUT1_ECCN__ECC10 0x5 +#define BV_BCH_FLASH2LAYOUT1_ECCN__ECC12 0x6 +#define BV_BCH_FLASH2LAYOUT1_ECCN__ECC14 0x7 +#define BV_BCH_FLASH2LAYOUT1_ECCN__ECC16 0x8 +#define BV_BCH_FLASH2LAYOUT1_ECCN__ECC18 0x9 +#define BV_BCH_FLASH2LAYOUT1_ECCN__ECC20 0xA +#define BP_BCH_FLASH2LAYOUT1_DATAN_SIZE 0 +#define BM_BCH_FLASH2LAYOUT1_DATAN_SIZE 0x00000FFF +#define BF_BCH_FLASH2LAYOUT1_DATAN_SIZE(v) \ + (((v) << 0) & BM_BCH_FLASH2LAYOUT1_DATAN_SIZE) + +/*============================================================================*/ + +#define HW_BCH_FLASH3LAYOUT0 (0x000000e0) + +#define BP_BCH_FLASH3LAYOUT0_NBLOCKS 24 +#define BM_BCH_FLASH3LAYOUT0_NBLOCKS 0xFF000000 +#define BF_BCH_FLASH3LAYOUT0_NBLOCKS(v) \ + (((v) << 24) & BM_BCH_FLASH3LAYOUT0_NBLOCKS) +#define BP_BCH_FLASH3LAYOUT0_META_SIZE 16 +#define BM_BCH_FLASH3LAYOUT0_META_SIZE 0x00FF0000 +#define BF_BCH_FLASH3LAYOUT0_META_SIZE(v) \ + (((v) << 16) & BM_BCH_FLASH3LAYOUT0_META_SIZE) +#define BP_BCH_FLASH3LAYOUT0_ECC0 12 +#define BM_BCH_FLASH3LAYOUT0_ECC0 0x0000F000 +#define BF_BCH_FLASH3LAYOUT0_ECC0(v) \ + (((v) << 12) & BM_BCH_FLASH3LAYOUT0_ECC0) +#define BV_BCH_FLASH3LAYOUT0_ECC0__NONE 0x0 +#define BV_BCH_FLASH3LAYOUT0_ECC0__ECC2 0x1 +#define BV_BCH_FLASH3LAYOUT0_ECC0__ECC4 0x2 +#define BV_BCH_FLASH3LAYOUT0_ECC0__ECC6 0x3 +#define BV_BCH_FLASH3LAYOUT0_ECC0__ECC8 0x4 +#define BV_BCH_FLASH3LAYOUT0_ECC0__ECC10 0x5 +#define BV_BCH_FLASH3LAYOUT0_ECC0__ECC12 0x6 +#define BV_BCH_FLASH3LAYOUT0_ECC0__ECC14 0x7 +#define BV_BCH_FLASH3LAYOUT0_ECC0__ECC16 0x8 +#define BV_BCH_FLASH3LAYOUT0_ECC0__ECC18 0x9 +#define BV_BCH_FLASH3LAYOUT0_ECC0__ECC20 0xA +#define BP_BCH_FLASH3LAYOUT0_DATA0_SIZE 0 +#define BM_BCH_FLASH3LAYOUT0_DATA0_SIZE 0x00000FFF +#define BF_BCH_FLASH3LAYOUT0_DATA0_SIZE(v) \ + (((v) << 0) & BM_BCH_FLASH3LAYOUT0_DATA0_SIZE) + +/*============================================================================*/ + +#define HW_BCH_FLASH3LAYOUT1 (0x000000f0) + +#define BP_BCH_FLASH3LAYOUT1_PAGE_SIZE 16 +#define BM_BCH_FLASH3LAYOUT1_PAGE_SIZE 0xFFFF0000 +#define BF_BCH_FLASH3LAYOUT1_PAGE_SIZE(v) \ + (((v) << 16) & BM_BCH_FLASH3LAYOUT1_PAGE_SIZE) +#define BP_BCH_FLASH3LAYOUT1_ECCN 12 +#define BM_BCH_FLASH3LAYOUT1_ECCN 0x0000F000 +#define BF_BCH_FLASH3LAYOUT1_ECCN(v) \ + (((v) << 12) & BM_BCH_FLASH3LAYOUT1_ECCN) +#define BV_BCH_FLASH3LAYOUT1_ECCN__NONE 0x0 +#define BV_BCH_FLASH3LAYOUT1_ECCN__ECC2 0x1 +#define BV_BCH_FLASH3LAYOUT1_ECCN__ECC4 0x2 +#define BV_BCH_FLASH3LAYOUT1_ECCN__ECC6 0x3 +#define BV_BCH_FLASH3LAYOUT1_ECCN__ECC8 0x4 +#define BV_BCH_FLASH3LAYOUT1_ECCN__ECC10 0x5 +#define BV_BCH_FLASH3LAYOUT1_ECCN__ECC12 0x6 +#define BV_BCH_FLASH3LAYOUT1_ECCN__ECC14 0x7 +#define BV_BCH_FLASH3LAYOUT1_ECCN__ECC16 0x8 +#define BV_BCH_FLASH3LAYOUT1_ECCN__ECC18 0x9 +#define BV_BCH_FLASH3LAYOUT1_ECCN__ECC20 0xA +#define BP_BCH_FLASH3LAYOUT1_DATAN_SIZE 0 +#define BM_BCH_FLASH3LAYOUT1_DATAN_SIZE 0x00000FFF +#define BF_BCH_FLASH3LAYOUT1_DATAN_SIZE(v) \ + (((v) << 0) & BM_BCH_FLASH3LAYOUT1_DATAN_SIZE) + +/*============================================================================*/ + +#define HW_BCH_DEBUG0 (0x00000100) +#define HW_BCH_DEBUG0_SET (0x00000104) +#define HW_BCH_DEBUG0_CLR (0x00000108) +#define HW_BCH_DEBUG0_TOG (0x0000010c) + +#define BP_BCH_DEBUG0_RSVD1 27 +#define BM_BCH_DEBUG0_RSVD1 0xF8000000 +#define BF_BCH_DEBUG0_RSVD1(v) \ + (((v) << 27) & BM_BCH_DEBUG0_RSVD1) +#define BM_BCH_DEBUG0_ROM_BIST_ENABLE 0x04000000 +#define BM_BCH_DEBUG0_ROM_BIST_COMPLETE 0x02000000 +#define BP_BCH_DEBUG0_KES_DEBUG_SYNDROME_SYMBOL 16 +#define BM_BCH_DEBUG0_KES_DEBUG_SYNDROME_SYMBOL 0x01FF0000 +#define BF_BCH_DEBUG0_KES_DEBUG_SYNDROME_SYMBOL(v) \ + (((v) << 16) & BM_BCH_DEBUG0_KES_DEBUG_SYNDROME_SYMBOL) +#define BV_BCH_DEBUG0_KES_DEBUG_SYNDROME_SYMBOL__NORMAL 0x0 +#define BV_BCH_DEBUG0_KES_DEBUG_SYNDROME_SYMBOL__TEST_MODE 0x1 +#define BM_BCH_DEBUG0_KES_DEBUG_SHIFT_SYND 0x00008000 +#define BM_BCH_DEBUG0_KES_DEBUG_PAYLOAD_FLAG 0x00004000 +#define BV_BCH_DEBUG0_KES_DEBUG_PAYLOAD_FLAG__DATA 0x1 +#define BV_BCH_DEBUG0_KES_DEBUG_PAYLOAD_FLAG__AUX 0x1 +#define BM_BCH_DEBUG0_KES_DEBUG_MODE4K 0x00002000 +#define BV_BCH_DEBUG0_KES_DEBUG_MODE4K__4k 0x1 +#define BV_BCH_DEBUG0_KES_DEBUG_MODE4K__2k 0x1 +#define BM_BCH_DEBUG0_KES_DEBUG_KICK 0x00001000 +#define BM_BCH_DEBUG0_KES_STANDALONE 0x00000800 +#define BV_BCH_DEBUG0_KES_STANDALONE__NORMAL 0x0 +#define BV_BCH_DEBUG0_KES_STANDALONE__TEST_MODE 0x1 +#define BM_BCH_DEBUG0_KES_DEBUG_STEP 0x00000400 +#define BM_BCH_DEBUG0_KES_DEBUG_STALL 0x00000200 +#define BV_BCH_DEBUG0_KES_DEBUG_STALL__NORMAL 0x0 +#define BV_BCH_DEBUG0_KES_DEBUG_STALL__WAIT 0x1 +#define BM_BCH_DEBUG0_BM_KES_TEST_BYPASS 0x00000100 +#define BV_BCH_DEBUG0_BM_KES_TEST_BYPASS__NORMAL 0x0 +#define BV_BCH_DEBUG0_BM_KES_TEST_BYPASS__TEST_MODE 0x1 +#define BP_BCH_DEBUG0_RSVD0 6 +#define BM_BCH_DEBUG0_RSVD0 0x000000C0 +#define BF_BCH_DEBUG0_RSVD0(v) \ + (((v) << 6) & BM_BCH_DEBUG0_RSVD0) +#define BP_BCH_DEBUG0_DEBUG_REG_SELECT 0 +#define BM_BCH_DEBUG0_DEBUG_REG_SELECT 0x0000003F +#define BF_BCH_DEBUG0_DEBUG_REG_SELECT(v) \ + (((v) << 0) & BM_BCH_DEBUG0_DEBUG_REG_SELECT) + +/*============================================================================*/ + +#define HW_BCH_DBGKESREAD (0x00000110) + +#define BP_BCH_DBGKESREAD_VALUES 0 +#define BM_BCH_DBGKESREAD_VALUES 0xFFFFFFFF +#define BF_BCH_DBGKESREAD_VALUES(v) (v) + +/*============================================================================*/ + +#define HW_BCH_DBGCSFEREAD (0x00000120) + +#define BP_BCH_DBGCSFEREAD_VALUES 0 +#define BM_BCH_DBGCSFEREAD_VALUES 0xFFFFFFFF +#define BF_BCH_DBGCSFEREAD_VALUES(v) (v) + +/*============================================================================*/ + +#define HW_BCH_DBGSYNDGENREAD (0x00000130) + +#define BP_BCH_DBGSYNDGENREAD_VALUES 0 +#define BM_BCH_DBGSYNDGENREAD_VALUES 0xFFFFFFFF +#define BF_BCH_DBGSYNDGENREAD_VALUES(v) (v) + +/*============================================================================*/ + +#define HW_BCH_DBGAHBMREAD (0x00000140) + +#define BP_BCH_DBGAHBMREAD_VALUES 0 +#define BM_BCH_DBGAHBMREAD_VALUES 0xFFFFFFFF +#define BF_BCH_DBGAHBMREAD_VALUES(v) (v) + +/*============================================================================*/ + +#define HW_BCH_BLOCKNAME (0x00000150) + +#define BP_BCH_BLOCKNAME_NAME 0 +#define BM_BCH_BLOCKNAME_NAME 0xFFFFFFFF +#define BF_BCH_BLOCKNAME_NAME(v) (v) + +/*============================================================================*/ + +#define HW_BCH_VERSION (0x00000160) + +#define BP_BCH_VERSION_MAJOR 24 +#define BM_BCH_VERSION_MAJOR 0xFF000000 +#define BF_BCH_VERSION_MAJOR(v) \ + (((v) << 24) & BM_BCH_VERSION_MAJOR) +#define BP_BCH_VERSION_MINOR 16 +#define BM_BCH_VERSION_MINOR 0x00FF0000 +#define BF_BCH_VERSION_MINOR(v) \ + (((v) << 16) & BM_BCH_VERSION_MINOR) +#define BP_BCH_VERSION_STEP 0 +#define BM_BCH_VERSION_STEP 0x0000FFFF +#define BF_BCH_VERSION_STEP(v) \ + (((v) << 0) & BM_BCH_VERSION_STEP) + +/*============================================================================*/ + +#endif diff --git a/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-event-reporting.c b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-event-reporting.c new file mode 100644 index 000000000000..45574391b0f0 --- /dev/null +++ b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-event-reporting.c @@ -0,0 +1,307 @@ +/* + * Freescale GPMI NFC NAND Flash Driver + * + * Copyright (C) 2010 Freescale Semiconductor, Inc. + * Copyright (C) 2008 Embedded Alley Solutions, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "gpmi-nfc.h" + +#if defined(EVENT_REPORTING) + +/* + * This variable and module parameter controls whether the driver reports event + * information by printing to the console. + */ + +static int report_events; +module_param(report_events, int, 0600); + +/** + * struct event - A single record in the event trace. + * + * @time: The time at which the event occurred. + * @nesting: Indicates function call nesting. + * @description: A description of the event. + */ + +struct event { + ktime_t time; + unsigned int nesting; + char *description; +}; + +/** + * The event trace. + * + * @overhead: The delay to take a time stamp and nothing else. + * @nesting: The current nesting level. + * @overflow: Indicates the trace overflowed. + * @next: Index of the next event to write. + * @events: The array of events. + */ + +#define MAX_EVENT_COUNT (200) + +static struct { + ktime_t overhead; + int nesting; + int overflow; + unsigned int next; + struct event events[MAX_EVENT_COUNT]; +} event_trace; + +/** + * gpmi_nfc_reset_event_trace() - Resets the event trace. + */ +void gpmi_nfc_reset_event_trace(void) +{ + event_trace.nesting = 0; + event_trace.overflow = false; + event_trace.next = 0; +} + +/** + * gpmi_nfc_add_event() - Adds an event to the event trace. + * + * @description: A description of the event. + * @delta: A delta to the nesting level for this event [-1, 0, 1]. + */ +void gpmi_nfc_add_event(char *description, int delta) +{ + struct event *event; + + if (!report_events) + return; + + if (event_trace.overflow) + return; + + if (event_trace.next >= MAX_EVENT_COUNT) { + event_trace.overflow = true; + return; + } + + event = event_trace.events + event_trace.next; + + event->time = ktime_get(); + + event->description = description; + + if (!delta) + event->nesting = event_trace.nesting; + else if (delta < 0) { + event->nesting = event_trace.nesting - 1; + event_trace.nesting -= 2; + } else { + event->nesting = event_trace.nesting + 1; + event_trace.nesting += 2; + } + + if (event_trace.nesting < 0) + event_trace.nesting = 0; + + event_trace.next++; + +} + +/** + * gpmi_nfc_start_event_trace() - Starts an event trace. + * + * @description: A description of the first event. + */ +void gpmi_nfc_start_event_trace(char *description) +{ + + ktime_t t0; + ktime_t t1; + + if (!report_events) + return; + + gpmi_nfc_reset_event_trace(); + + t0 = ktime_get(); + t1 = ktime_get(); + + event_trace.overhead = ktime_sub(t1, t0); + + gpmi_nfc_add_event(description, 1); + +} + +/** + * gpmi_nfc_dump_event_trace() - Dumps the event trace. + */ +void gpmi_nfc_dump_event_trace(void) +{ + unsigned int i; + time_t seconds; + long nanoseconds; + char line[100]; + int o; + struct event *first_event; + struct event *last_event; + struct event *matching_event; + struct event *event; + ktime_t delta; + + /* Check if event reporting is turned off. */ + + if (!report_events) + return; + + /* Print important facts about this event trace. */ + + pr_info("\n+----------------\n"); + + pr_info("| Overhead : [%d:%d]\n", event_trace.overhead.tv.sec, + event_trace.overhead.tv.nsec); + + if (!event_trace.next) { + pr_info("| No Events\n"); + return; + } + + first_event = event_trace.events; + last_event = event_trace.events + (event_trace.next - 1); + + delta = ktime_sub(last_event->time, first_event->time); + pr_info("| Elapsed Time: [%d:%d]\n", delta.tv.sec, delta.tv.nsec); + + if (event_trace.overflow) + pr_info("| Overflow!\n"); + + /* Print the events in this history. */ + + for (i = 0, event = event_trace.events; + i < event_trace.next; i++, event++) { + + /* Get the delta between this event and the previous event. */ + + if (!i) { + seconds = 0; + nanoseconds = 0; + } else { + delta = ktime_sub(event[0].time, event[-1].time); + seconds = delta.tv.sec; + nanoseconds = delta.tv.nsec; + } + + /* Print the current event. */ + + o = 0; + + o = snprintf(line, sizeof(line) - o, "| [%ld:% 10ld]%*s %s", + seconds, nanoseconds, + event->nesting, "", + event->description); + /* Check if this is the last event in a nested series. */ + + if (i && (event[0].nesting < event[-1].nesting)) { + + for (matching_event = event - 1;; matching_event--) { + + if (matching_event < event_trace.events) { + matching_event = 0; + break; + } + + if (matching_event->nesting == event->nesting) + break; + + } + + if (matching_event) { + delta = ktime_sub(event->time, + matching_event->time); + o += snprintf(line + o, sizeof(line) - o, + " <%d:%d]", delta.tv.sec, + delta.tv.nsec); + } + + } + + /* Check if this is the first event in a nested series. */ + + if ((i < event_trace.next - 1) && + (event[0].nesting < event[1].nesting)) { + + for (matching_event = event + 1;; matching_event++) { + + if (matching_event >= + (event_trace.events+event_trace.next)) { + matching_event = 0; + break; + } + + if (matching_event->nesting == event->nesting) + break; + + } + + if (matching_event) { + delta = ktime_sub(matching_event->time, + event->time); + o += snprintf(line + o, sizeof(line) - o, + " [%d:%d>", delta.tv.sec, + delta.tv.nsec); + } + + } + + pr_info("%s\n", line); + + } + + pr_info("+----------------\n"); + +} + +/** + * gpmi_nfc_stop_event_trace() - Stops an event trace. + * + * @description: A description of the last event. + */ +void gpmi_nfc_stop_event_trace(char *description) +{ + struct event *event; + + if (!report_events) + return; + + /* + * We want the end of the trace, no matter what happens. If the trace + * has already overflowed, or is about to, just jam this event into the + * last spot. Otherwise, add this event like any other. + */ + + if (event_trace.overflow || (event_trace.next >= MAX_EVENT_COUNT)) { + event = event_trace.events + (MAX_EVENT_COUNT - 1); + event->time = ktime_get(); + event->description = description; + event->nesting = 0; + } else { + gpmi_nfc_add_event(description, -1); + } + + gpmi_nfc_dump_event_trace(); + gpmi_nfc_reset_event_trace(); + +} + +#endif /* EVENT_REPORTING */ diff --git a/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-gpmi-regs-v0.h b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-gpmi-regs-v0.h new file mode 100644 index 000000000000..2f9fce609a34 --- /dev/null +++ b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-gpmi-regs-v0.h @@ -0,0 +1,416 @@ +/* + * Freescale GPMI NFC NAND Flash Driver + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. + * Copyright 2008 Embedded Alley Solutions, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#ifndef __GPMI_NFC_GPMI_REGS_H +#define __GPMI_NFC_GPMI_REGS_H + +/*============================================================================*/ + +#define HW_GPMI_CTRL0 (0x00000000) +#define HW_GPMI_CTRL0_SET (0x00000004) +#define HW_GPMI_CTRL0_CLR (0x00000008) +#define HW_GPMI_CTRL0_TOG (0x0000000c) + +#define BM_GPMI_CTRL0_SFTRST 0x80000000 +#define BV_GPMI_CTRL0_SFTRST__RUN 0x0 +#define BV_GPMI_CTRL0_SFTRST__RESET 0x1 +#define BM_GPMI_CTRL0_CLKGATE 0x40000000 +#define BV_GPMI_CTRL0_CLKGATE__RUN 0x0 +#define BV_GPMI_CTRL0_CLKGATE__NO_CLKS 0x1 +#define BM_GPMI_CTRL0_RUN 0x20000000 +#define BV_GPMI_CTRL0_RUN__IDLE 0x0 +#define BV_GPMI_CTRL0_RUN__BUSY 0x1 +#define BM_GPMI_CTRL0_DEV_IRQ_EN 0x10000000 +#define BM_GPMI_CTRL0_TIMEOUT_IRQ_EN 0x08000000 +#define BM_GPMI_CTRL0_UDMA 0x04000000 +#define BV_GPMI_CTRL0_UDMA__DISABLED 0x0 +#define BV_GPMI_CTRL0_UDMA__ENABLED 0x1 +#define BP_GPMI_CTRL0_COMMAND_MODE 24 +#define BM_GPMI_CTRL0_COMMAND_MODE 0x03000000 +#define BF_GPMI_CTRL0_COMMAND_MODE(v) \ + (((v) << 24) & BM_GPMI_CTRL0_COMMAND_MODE) +#define BV_GPMI_CTRL0_COMMAND_MODE__WRITE 0x0 +#define BV_GPMI_CTRL0_COMMAND_MODE__READ 0x1 +#define BV_GPMI_CTRL0_COMMAND_MODE__READ_AND_COMPARE 0x2 +#define BV_GPMI_CTRL0_COMMAND_MODE__WAIT_FOR_READY 0x3 +#define BM_GPMI_CTRL0_WORD_LENGTH 0x00800000 +#define BV_GPMI_CTRL0_WORD_LENGTH__16_BIT 0x0 +#define BV_GPMI_CTRL0_WORD_LENGTH__8_BIT 0x1 +#define BM_GPMI_CTRL0_LOCK_CS 0x00400000 +#define BV_GPMI_CTRL0_LOCK_CS__DISABLED 0x0 +#define BV_GPMI_CTRL0_LOCK_CS__ENABLED 0x1 +#define BP_GPMI_CTRL0_CS 20 +#define BM_GPMI_CTRL0_CS 0x00300000 +#define BF_GPMI_CTRL0_CS(v) (((v) << 20) & BM_GPMI_CTRL0_CS) +#define BP_GPMI_CTRL0_ADDRESS 17 +#define BM_GPMI_CTRL0_ADDRESS 0x000E0000 +#define BF_GPMI_CTRL0_ADDRESS(v) (((v) << 17) & BM_GPMI_CTRL0_ADDRESS) +#define BV_GPMI_CTRL0_ADDRESS__NAND_DATA 0x0 +#define BV_GPMI_CTRL0_ADDRESS__NAND_CLE 0x1 +#define BV_GPMI_CTRL0_ADDRESS__NAND_ALE 0x2 +#define BM_GPMI_CTRL0_ADDRESS_INCREMENT 0x00010000 +#define BV_GPMI_CTRL0_ADDRESS_INCREMENT__DISABLED 0x0 +#define BV_GPMI_CTRL0_ADDRESS_INCREMENT__ENABLED 0x1 +#define BP_GPMI_CTRL0_XFER_COUNT 0 +#define BM_GPMI_CTRL0_XFER_COUNT 0x0000FFFF +#define BF_GPMI_CTRL0_XFER_COUNT(v) \ + (((v) << 0) & BM_GPMI_CTRL0_XFER_COUNT) + +/*============================================================================*/ + +#define HW_GPMI_COMPARE (0x00000010) + +#define BP_GPMI_COMPARE_MASK 16 +#define BM_GPMI_COMPARE_MASK 0xFFFF0000 +#define BF_GPMI_COMPARE_MASK(v) (((v) << 16) & BM_GPMI_COMPARE_MASK) +#define BP_GPMI_COMPARE_REFERENCE 0 +#define BM_GPMI_COMPARE_REFERENCE 0x0000FFFF +#define BF_GPMI_COMPARE_REFERENCE(v) \ + (((v) << 0) & BM_GPMI_COMPARE_REFERENCE) + +/*============================================================================*/ + +#define HW_GPMI_ECCCTRL (0x00000020) +#define HW_GPMI_ECCCTRL_SET (0x00000024) +#define HW_GPMI_ECCCTRL_CLR (0x00000028) +#define HW_GPMI_ECCCTRL_TOG (0x0000002c) + +#define BP_GPMI_ECCCTRL_HANDLE 16 +#define BM_GPMI_ECCCTRL_HANDLE 0xFFFF0000 +#define BF_GPMI_ECCCTRL_HANDLE(v) (((v) << 16) & BM_GPMI_ECCCTRL_HANDLE) +#define BM_GPMI_ECCCTRL_RSVD2 0x00008000 +#define BP_GPMI_ECCCTRL_ECC_CMD 13 +#define BM_GPMI_ECCCTRL_ECC_CMD 0x00006000 +#define BF_GPMI_ECCCTRL_ECC_CMD(v) (((v) << 13) & BM_GPMI_ECCCTRL_ECC_CMD) +#define BV_GPMI_ECCCTRL_ECC_CMD__DECODE_4_BIT 0x0 +#define BV_GPMI_ECCCTRL_ECC_CMD__ENCODE_4_BIT 0x1 +#define BV_GPMI_ECCCTRL_ECC_CMD__DECODE_8_BIT 0x2 +#define BV_GPMI_ECCCTRL_ECC_CMD__ENCODE_8_BIT 0x3 +#define BV_GPMI_ECCCTRL_ECC_CMD__BCH_DECODE 0x0 +#define BV_GPMI_ECCCTRL_ECC_CMD__BCH_ENCODE 0x1 +#define BM_GPMI_ECCCTRL_ENABLE_ECC 0x00001000 +#define BV_GPMI_ECCCTRL_ENABLE_ECC__ENABLE 0x1 +#define BV_GPMI_ECCCTRL_ENABLE_ECC__DISABLE 0x0 +#define BP_GPMI_ECCCTRL_RSVD1 9 +#define BM_GPMI_ECCCTRL_RSVD1 0x00000E00 +#define BF_GPMI_ECCCTRL_RSVD1(v) (((v) << 9) & BM_GPMI_ECCCTRL_RSVD1) +#define BP_GPMI_ECCCTRL_BUFFER_MASK 0 +#define BM_GPMI_ECCCTRL_BUFFER_MASK 0x000001FF +#define BF_GPMI_ECCCTRL_BUFFER_MASK(v) \ + (((v) << 0) & BM_GPMI_ECCCTRL_BUFFER_MASK) +#define BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_AUXONLY 0x100 +#define BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_PAGE 0x1FF +#define BV_GPMI_ECCCTRL_BUFFER_MASK__AUXILIARY 0x100 +#define BV_GPMI_ECCCTRL_BUFFER_MASK__BUFFER7 0x080 +#define BV_GPMI_ECCCTRL_BUFFER_MASK__BUFFER6 0x040 +#define BV_GPMI_ECCCTRL_BUFFER_MASK__BUFFER5 0x020 +#define BV_GPMI_ECCCTRL_BUFFER_MASK__BUFFER4 0x010 +#define BV_GPMI_ECCCTRL_BUFFER_MASK__BUFFER3 0x008 +#define BV_GPMI_ECCCTRL_BUFFER_MASK__BUFFER2 0x004 +#define BV_GPMI_ECCCTRL_BUFFER_MASK__BUFFER1 0x002 +#define BV_GPMI_ECCCTRL_BUFFER_MASK__BUFFER0 0x001 + +/*============================================================================*/ + +#define HW_GPMI_ECCCOUNT (0x00000030) + +#define BP_GPMI_ECCCOUNT_RSVD2 16 +#define BM_GPMI_ECCCOUNT_RSVD2 0xFFFF0000 +#define BF_GPMI_ECCCOUNT_RSVD2(v) (((v) << 16) & BM_GPMI_ECCCOUNT_RSVD2) +#define BP_GPMI_ECCCOUNT_COUNT 0 +#define BM_GPMI_ECCCOUNT_COUNT 0x0000FFFF +#define BF_GPMI_ECCCOUNT_COUNT(v) (((v) << 0) & BM_GPMI_ECCCOUNT_COUNT) + +/*============================================================================*/ + +#define HW_GPMI_PAYLOAD (0x00000040) + +#define BP_GPMI_PAYLOAD_ADDRESS 2 +#define BM_GPMI_PAYLOAD_ADDRESS 0xFFFFFFFC +#define BF_GPMI_PAYLOAD_ADDRESS(v) (((v) << 2) & BM_GPMI_PAYLOAD_ADDRESS) +#define BP_GPMI_PAYLOAD_RSVD0 0 +#define BM_GPMI_PAYLOAD_RSVD0 0x00000003 +#define BF_GPMI_PAYLOAD_RSVD0(v) (((v) << 0) & BM_GPMI_PAYLOAD_RSVD0) + +/*============================================================================*/ + +#define HW_GPMI_AUXILIARY (0x00000050) + +#define BP_GPMI_AUXILIARY_ADDRESS 2 +#define BM_GPMI_AUXILIARY_ADDRESS 0xFFFFFFFC +#define BF_GPMI_AUXILIARY_ADDRESS(v) \ + (((v) << 2) & BM_GPMI_AUXILIARY_ADDRESS) +#define BP_GPMI_AUXILIARY_RSVD0 0 +#define BM_GPMI_AUXILIARY_RSVD0 0x00000003 +#define BF_GPMI_AUXILIARY_RSVD0(v) (((v) << 0) & BM_GPMI_AUXILIARY_RSVD0) + +/*============================================================================*/ + +#define HW_GPMI_CTRL1 (0x00000060) +#define HW_GPMI_CTRL1_SET (0x00000064) +#define HW_GPMI_CTRL1_CLR (0x00000068) +#define HW_GPMI_CTRL1_TOG (0x0000006c) + +#define BP_GPMI_CTRL1_RSVD2 24 +#define BM_GPMI_CTRL1_RSVD2 0xFF000000 +#define BF_GPMI_CTRL1_RSVD2(v) \ + (((v) << 24) & BM_GPMI_CTRL1_RSVD2) +#define BM_GPMI_CTRL1_CE3_SEL 0x00800000 +#define BM_GPMI_CTRL1_CE2_SEL 0x00400000 +#define BM_GPMI_CTRL1_CE1_SEL 0x00200000 +#define BM_GPMI_CTRL1_CE0_SEL 0x00100000 +#define BM_GPMI_CTRL1_GANGED_RDYBUSY 0x00080000 +#define BM_GPMI_CTRL1_GPMI_MODE 0x00000001 +#define BP_GPMI_CTRL1_GPMI_MODE 0 +#define BM_GPMI_CTRL1_ATA_IRQRDY_POLARITY 0x00000004 +#define BM_GPMI_CTRL1_DEV_RESET 0x00000008 +#define BM_GPMI_CTRL1_TIMEOUT_IRQ 0x00000200 +#define BM_GPMI_CTRL1_DEV_IRQ 0x00000400 +#define BM_GPMI_CTRL1_RDN_DELAY 0x0000F000 +#define BP_GPMI_CTRL1_RDN_DELAY 12 +#define BM_GPMI_CTRL1_BCH_MODE 0x00040000 +#define BP_GPMI_CTRL1_DLL_ENABLE 17 +#define BM_GPMI_CTRL1_DLL_ENABLE 0x00020000 +#define BP_GPMI_CTRL1_HALF_PERIOD 16 +#define BM_GPMI_CTRL1_HALF_PERIOD 0x00010000 +#define BP_GPMI_CTRL1_RDN_DELAY 12 +#define BM_GPMI_CTRL1_RDN_DELAY 0x0000F000 +#define BF_GPMI_CTRL1_RDN_DELAY(v) \ + (((v) << 12) & BM_GPMI_CTRL1_RDN_DELAY) +#define BM_GPMI_CTRL1_DMA2ECC_MODE 0x00000800 +#define BM_GPMI_CTRL1_DEV_IRQ 0x00000400 +#define BM_GPMI_CTRL1_TIMEOUT_IRQ 0x00000200 +#define BM_GPMI_CTRL1_BURST_EN 0x00000100 +#define BM_GPMI_CTRL1_ABORT_WAIT_FOR_READY3 0x00000080 +#define BM_GPMI_CTRL1_ABORT_WAIT_FOR_READY2 0x00000040 +#define BM_GPMI_CTRL1_ABORT_WAIT_FOR_READY1 0x00000020 +#define BM_GPMI_CTRL1_ABORT_WAIT_FOR_READY0 0x00000010 +#define BM_GPMI_CTRL1_DEV_RESET 0x00000008 +#define BV_GPMI_CTRL1_DEV_RESET__ENABLED 0x0 +#define BV_GPMI_CTRL1_DEV_RESET__DISABLED 0x1 +#define BM_GPMI_CTRL1_ATA_IRQRDY_POLARITY 0x00000004 +#define BV_GPMI_CTRL1_ATA_IRQRDY_POLARITY__ACTIVELOW 0x0 +#define BV_GPMI_CTRL1_ATA_IRQRDY_POLARITY__ACTIVEHIGH 0x1 +#define BM_GPMI_CTRL1_CAMERA_MODE 0x00000002 +#define BM_GPMI_CTRL1_GPMI_MODE 0x00000001 +#define BV_GPMI_CTRL1_GPMI_MODE__NAND 0x0 +#define BV_GPMI_CTRL1_GPMI_MODE__ATA 0x1 + +/*============================================================================*/ + +#define HW_GPMI_TIMING0 (0x00000070) + +#define BP_GPMI_TIMING0_RSVD1 24 +#define BM_GPMI_TIMING0_RSVD1 0xFF000000 +#define BF_GPMI_TIMING0_RSVD1(v) \ + (((v) << 24) & BM_GPMI_TIMING0_RSVD1) +#define BP_GPMI_TIMING0_ADDRESS_SETUP 16 +#define BM_GPMI_TIMING0_ADDRESS_SETUP 0x00FF0000 +#define BF_GPMI_TIMING0_ADDRESS_SETUP(v) \ + (((v) << 16) & BM_GPMI_TIMING0_ADDRESS_SETUP) +#define BP_GPMI_TIMING0_DATA_HOLD 8 +#define BM_GPMI_TIMING0_DATA_HOLD 0x0000FF00 +#define BF_GPMI_TIMING0_DATA_HOLD(v) \ + (((v) << 8) & BM_GPMI_TIMING0_DATA_HOLD) +#define BP_GPMI_TIMING0_DATA_SETUP 0 +#define BM_GPMI_TIMING0_DATA_SETUP 0x000000FF +#define BF_GPMI_TIMING0_DATA_SETUP(v) \ + (((v) << 0) & BM_GPMI_TIMING0_DATA_SETUP) + +/*============================================================================*/ + +#define HW_GPMI_TIMING1 (0x00000080) + +#define BP_GPMI_TIMING1_DEVICE_BUSY_TIMEOUT 16 +#define BM_GPMI_TIMING1_DEVICE_BUSY_TIMEOUT 0xFFFF0000 +#define BF_GPMI_TIMING1_DEVICE_BUSY_TIMEOUT(v) \ + (((v) << 16) & BM_GPMI_TIMING1_DEVICE_BUSY_TIMEOUT) +#define BP_GPMI_TIMING1_RSVD1 0 +#define BM_GPMI_TIMING1_RSVD1 0x0000FFFF +#define BF_GPMI_TIMING1_RSVD1(v) \ + (((v) << 0) & BM_GPMI_TIMING1_RSVD1) + +/*============================================================================*/ + +#define HW_GPMI_TIMING2 (0x00000090) + +#define BP_GPMI_TIMING2_UDMA_TRP 24 +#define BM_GPMI_TIMING2_UDMA_TRP 0xFF000000 +#define BF_GPMI_TIMING2_UDMA_TRP(v) \ + (((v) << 24) & BM_GPMI_TIMING2_UDMA_TRP) +#define BP_GPMI_TIMING2_UDMA_ENV 16 +#define BM_GPMI_TIMING2_UDMA_ENV 0x00FF0000 +#define BF_GPMI_TIMING2_UDMA_ENV(v) \ + (((v) << 16) & BM_GPMI_TIMING2_UDMA_ENV) +#define BP_GPMI_TIMING2_UDMA_HOLD 8 +#define BM_GPMI_TIMING2_UDMA_HOLD 0x0000FF00 +#define BF_GPMI_TIMING2_UDMA_HOLD(v) \ + (((v) << 8) & BM_GPMI_TIMING2_UDMA_HOLD) +#define BP_GPMI_TIMING2_UDMA_SETUP 0 +#define BM_GPMI_TIMING2_UDMA_SETUP 0x000000FF +#define BF_GPMI_TIMING2_UDMA_SETUP(v) \ + (((v) << 0) & BM_GPMI_TIMING2_UDMA_SETUP) + +/*============================================================================*/ + +#define HW_GPMI_DATA (0x000000a0) + +#define BP_GPMI_DATA_DATA 0 +#define BM_GPMI_DATA_DATA 0xFFFFFFFF +#define BF_GPMI_DATA_DATA(v) (v) + +/*============================================================================*/ + +#define HW_GPMI_STAT (0x000000b0) + +#define BM_GPMI_STAT_PRESENT 0x80000000 +#define BV_GPMI_STAT_PRESENT__UNAVAILABLE 0x0 +#define BV_GPMI_STAT_PRESENT__AVAILABLE 0x1 +#define BP_GPMI_STAT_RSVD1 12 +#define BM_GPMI_STAT_RSVD1 0x7FFFF000 +#define BF_GPMI_STAT_RSVD1(v) \ + (((v) << 12) & BM_GPMI_STAT_RSVD1) +#define BP_GPMI_STAT_RDY_TIMEOUT 8 +#define BM_GPMI_STAT_RDY_TIMEOUT 0x00000F00 +#define BF_GPMI_STAT_RDY_TIMEOUT(v) \ + (((v) << 8) & BM_GPMI_STAT_RDY_TIMEOUT) +#define BM_GPMI_STAT_ATA_IRQ 0x00000080 +#define BM_GPMI_STAT_INVALID_BUFFER_MASK 0x00000040 +#define BM_GPMI_STAT_FIFO_EMPTY 0x00000020 +#define BV_GPMI_STAT_FIFO_EMPTY__NOT_EMPTY 0x0 +#define BV_GPMI_STAT_FIFO_EMPTY__EMPTY 0x1 +#define BM_GPMI_STAT_FIFO_FULL 0x00000010 +#define BV_GPMI_STAT_FIFO_FULL__NOT_FULL 0x0 +#define BV_GPMI_STAT_FIFO_FULL__FULL 0x1 +#define BM_GPMI_STAT_DEV3_ERROR 0x00000008 +#define BM_GPMI_STAT_DEV2_ERROR 0x00000004 +#define BM_GPMI_STAT_DEV1_ERROR 0x00000002 +#define BM_GPMI_STAT_DEERROR 0x00000001 + +/*============================================================================*/ + +#define HW_GPMI_DEBUG (0x000000c0) + +#define BM_GPMI_DEBUG_READY3 0x80000000 +#define BM_GPMI_DEBUG_READY2 0x40000000 +#define BM_GPMI_DEBUG_READY1 0x20000000 +#define BM_GPMI_DEBUG_READY0 0x10000000 +#define BM_GPMI_DEBUG_WAIT_FOR_READY_END3 0x08000000 +#define BM_GPMI_DEBUG_WAIT_FOR_READY_END2 0x04000000 +#define BM_GPMI_DEBUG_WAIT_FOR_READY_END1 0x02000000 +#define BM_GPMI_DEBUG_WAIT_FOR_READY_END0 0x01000000 +#define BM_GPMI_DEBUG_SENSE3 0x00800000 +#define BM_GPMI_DEBUG_SENSE2 0x00400000 +#define BM_GPMI_DEBUG_SENSE1 0x00200000 +#define BM_GPMI_DEBUG_SENSE0 0x00100000 +#define BM_GPMI_DEBUG_DMAREQ3 0x00080000 +#define BM_GPMI_DEBUG_DMAREQ2 0x00040000 +#define BM_GPMI_DEBUG_DMAREQ1 0x00020000 +#define BM_GPMI_DEBUG_DMAREQ0 0x00010000 +#define BP_GPMI_DEBUG_CMD_END 12 +#define BM_GPMI_DEBUG_CMD_END 0x0000F000 +#define BF_GPMI_DEBUG_CMD_END(v) \ + (((v) << 12) & BM_GPMI_DEBUG_CMD_END) +#define BP_GPMI_DEBUG_UDMA_STATE 8 +#define BM_GPMI_DEBUG_UDMA_STATE 0x00000F00 +#define BF_GPMI_DEBUG_UDMA_STATE(v) \ + (((v) << 8) & BM_GPMI_DEBUG_UDMA_STATE) +#define BM_GPMI_DEBUG_BUSY 0x00000080 +#define BV_GPMI_DEBUG_BUSY__DISABLED 0x0 +#define BV_GPMI_DEBUG_BUSY__ENABLED 0x1 +#define BP_GPMI_DEBUG_PIN_STATE 4 +#define BM_GPMI_DEBUG_PIN_STATE 0x00000070 +#define BF_GPMI_DEBUG_PIN_STATE(v) \ + (((v) << 4) & BM_GPMI_DEBUG_PIN_STATE) +#define BV_GPMI_DEBUG_PIN_STATE__PSM_IDLE 0x0 +#define BV_GPMI_DEBUG_PIN_STATE__PSM_BYTCNT 0x1 +#define BV_GPMI_DEBUG_PIN_STATE__PSM_ADDR 0x2 +#define BV_GPMI_DEBUG_PIN_STATE__PSM_STALL 0x3 +#define BV_GPMI_DEBUG_PIN_STATE__PSM_STROBE 0x4 +#define BV_GPMI_DEBUG_PIN_STATE__PSM_ATARDY 0x5 +#define BV_GPMI_DEBUG_PIN_STATE__PSM_DHOLD 0x6 +#define BV_GPMI_DEBUG_PIN_STATE__PSM_DONE 0x7 +#define BP_GPMI_DEBUG_MAIN_STATE 0 +#define BM_GPMI_DEBUG_MAIN_STATE 0x0000000F +#define BF_GPMI_DEBUG_MAIN_STATE(v) \ + (((v) << 0) & BM_GPMI_DEBUG_MAIN_STATE) +#define BV_GPMI_DEBUG_MAIN_STATE__MSM_IDLE 0x0 +#define BV_GPMI_DEBUG_MAIN_STATE__MSM_BYTCNT 0x1 +#define BV_GPMI_DEBUG_MAIN_STATE__MSM_WAITFE 0x2 +#define BV_GPMI_DEBUG_MAIN_STATE__MSM_WAITFR 0x3 +#define BV_GPMI_DEBUG_MAIN_STATE__MSM_DMAREQ 0x4 +#define BV_GPMI_DEBUG_MAIN_STATE__MSM_DMAACK 0x5 +#define BV_GPMI_DEBUG_MAIN_STATE__MSM_WAITFF 0x6 +#define BV_GPMI_DEBUG_MAIN_STATE__MSM_LDFIFO 0x7 +#define BV_GPMI_DEBUG_MAIN_STATE__MSM_LDDMAR 0x8 +#define BV_GPMI_DEBUG_MAIN_STATE__MSM_RDCMP 0x9 +#define BV_GPMI_DEBUG_MAIN_STATE__MSM_DONE 0xA + +/*============================================================================*/ + +#define HW_GPMI_VERSION (0x000000d0) + +#define BP_GPMI_VERSION_MAJOR 24 +#define BM_GPMI_VERSION_MAJOR 0xFF000000 +#define BF_GPMI_VERSION_MAJOR(v) (((v) << 24) & BM_GPMI_VERSION_MAJOR) +#define BP_GPMI_VERSION_MINOR 16 +#define BM_GPMI_VERSION_MINOR 0x00FF0000 +#define BF_GPMI_VERSION_MINOR(v) (((v) << 16) & BM_GPMI_VERSION_MINOR) +#define BP_GPMI_VERSION_STEP 0 +#define BM_GPMI_VERSION_STEP 0x0000FFFF +#define BF_GPMI_VERSION_STEP(v) (((v) << 0) & BM_GPMI_VERSION_STEP) + +/*============================================================================*/ + +#define HW_GPMI_DEBUG2 (0x000000e0) + +#define BP_GPMI_DEBUG2_RSVD1 16 +#define BM_GPMI_DEBUG2_RSVD1 0xFFFF0000 +#define BF_GPMI_DEBUG2_RSVD1(v) (((v) << 16) & BM_GPMI_DEBUG2_RSVD1) +#define BP_GPMI_DEBUG2_SYND2GPMI_BE 12 +#define BM_GPMI_DEBUG2_SYND2GPMI_BE 0x0000F000 +#define BF_GPMI_DEBUG2_SYND2GPMI_BE(v) \ + (((v) << 12) & BM_GPMI_DEBUG2_SYND2GPMI_BE) +#define BM_GPMI_DEBUG2_GPMI2SYND_VALID 0x00000800 +#define BM_GPMI_DEBUG2_GPMI2SYND_READY 0x00000400 +#define BM_GPMI_DEBUG2_SYND2GPMI_VALID 0x00000200 +#define BM_GPMI_DEBUG2_SYND2GPMI_READY 0x00000100 +#define BM_GPMI_DEBUG2_VIEW_DELAYED_RDN 0x00000080 +#define BM_GPMI_DEBUG2_UPDATE_WINDOW 0x00000040 +#define BP_GPMI_DEBUG2_RDN_TAP 0 +#define BM_GPMI_DEBUG2_RDN_TAP 0x0000003F +#define BF_GPMI_DEBUG2_RDN_TAP(v) (((v) << 0) & BM_GPMI_DEBUG2_RDN_TAP) + +/*============================================================================*/ + +#define HW_GPMI_DEBUG3 (0x000000f0) + +#define BP_GPMI_DEBUG3_APB_WORD_CNTR 16 +#define BM_GPMI_DEBUG3_APB_WORD_CNTR 0xFFFF0000 +#define BF_GPMI_DEBUG3_APB_WORD_CNTR(v) \ + (((v) << 16) & BM_GPMI_DEBUG3_APB_WORD_CNTR) +#define BP_GPMI_DEBUG3_DEV_WORD_CNTR 0 +#define BM_GPMI_DEBUG3_DEV_WORD_CNTR 0x0000FFFF +#define BF_GPMI_DEBUG3_DEV_WORD_CNTR(v) \ + (((v) << 0) & BM_GPMI_DEBUG3_DEV_WORD_CNTR) + +/*============================================================================*/ +#endif diff --git a/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-gpmi-regs-v1.h b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-gpmi-regs-v1.h new file mode 100644 index 000000000000..dcb3b7d3fc88 --- /dev/null +++ b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-gpmi-regs-v1.h @@ -0,0 +1,421 @@ +/* + * Freescale GPMI NFC NAND Flash Driver + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * Xml Revision: 2.2 + * Template revision: 26195 + */ + +#ifndef __GPMI_NFC_GPMI_REGS_H +#define __GPMI_NFC_GPMI_REGS_H + +/*============================================================================*/ + +#define HW_GPMI_CTRL0 (0x00000000) +#define HW_GPMI_CTRL0_SET (0x00000004) +#define HW_GPMI_CTRL0_CLR (0x00000008) +#define HW_GPMI_CTRL0_TOG (0x0000000c) + +#define BM_GPMI_CTRL0_SFTRST 0x80000000 +#define BV_GPMI_CTRL0_SFTRST__RUN 0x0 +#define BV_GPMI_CTRL0_SFTRST__RESET 0x1 +#define BM_GPMI_CTRL0_CLKGATE 0x40000000 +#define BV_GPMI_CTRL0_CLKGATE__RUN 0x0 +#define BV_GPMI_CTRL0_CLKGATE__NO_CLKS 0x1 +#define BM_GPMI_CTRL0_RUN 0x20000000 +#define BV_GPMI_CTRL0_RUN__IDLE 0x0 +#define BV_GPMI_CTRL0_RUN__BUSY 0x1 +#define BM_GPMI_CTRL0_DEV_IRQ_EN 0x10000000 +#define BM_GPMI_CTRL0_LOCK_CS 0x08000000 +#define BV_GPMI_CTRL0_LOCK_CS__DISABLED 0x0 +#define BV_GPMI_CTRL0_LOCK_CS__ENABLED 0x1 +#define BM_GPMI_CTRL0_UDMA 0x04000000 +#define BV_GPMI_CTRL0_UDMA__DISABLED 0x0 +#define BV_GPMI_CTRL0_UDMA__ENABLED 0x1 +#define BP_GPMI_CTRL0_COMMAND_MODE 24 +#define BM_GPMI_CTRL0_COMMAND_MODE 0x03000000 +#define BF_GPMI_CTRL0_COMMAND_MODE(v) \ + (((v) << 24) & BM_GPMI_CTRL0_COMMAND_MODE) +#define BV_GPMI_CTRL0_COMMAND_MODE__WRITE 0x0 +#define BV_GPMI_CTRL0_COMMAND_MODE__READ 0x1 +#define BV_GPMI_CTRL0_COMMAND_MODE__READ_AND_COMPARE 0x2 +#define BV_GPMI_CTRL0_COMMAND_MODE__WAIT_FOR_READY 0x3 +#define BM_GPMI_CTRL0_WORD_LENGTH 0x00800000 +#define BV_GPMI_CTRL0_WORD_LENGTH__16_BIT 0x0 +#define BV_GPMI_CTRL0_WORD_LENGTH__8_BIT 0x1 +#define BP_GPMI_CTRL0_CS 20 +#define BM_GPMI_CTRL0_CS 0x00700000 +#define BF_GPMI_CTRL0_CS(v) \ + (((v) << 20) & BM_GPMI_CTRL0_CS) +#define BP_GPMI_CTRL0_ADDRESS 17 +#define BM_GPMI_CTRL0_ADDRESS 0x000E0000 +#define BF_GPMI_CTRL0_ADDRESS(v) \ + (((v) << 17) & BM_GPMI_CTRL0_ADDRESS) +#define BV_GPMI_CTRL0_ADDRESS__NAND_DATA 0x0 +#define BV_GPMI_CTRL0_ADDRESS__NAND_CLE 0x1 +#define BV_GPMI_CTRL0_ADDRESS__NAND_ALE 0x2 +#define BM_GPMI_CTRL0_ADDRESS_INCREMENT 0x00010000 +#define BV_GPMI_CTRL0_ADDRESS_INCREMENT__DISABLED 0x0 +#define BV_GPMI_CTRL0_ADDRESS_INCREMENT__ENABLED 0x1 +#define BP_GPMI_CTRL0_XFER_COUNT 0 +#define BM_GPMI_CTRL0_XFER_COUNT 0x0000FFFF +#define BF_GPMI_CTRL0_XFER_COUNT(v) \ + (((v) << 0) & BM_GPMI_CTRL0_XFER_COUNT) + +/*============================================================================*/ + +#define HW_GPMI_COMPARE (0x00000010) + +#define BP_GPMI_COMPARE_MASK 16 +#define BM_GPMI_COMPARE_MASK 0xFFFF0000 +#define BF_GPMI_COMPARE_MASK(v) \ + (((v) << 16) & BM_GPMI_COMPARE_MASK) +#define BP_GPMI_COMPARE_REFERENCE 0 +#define BM_GPMI_COMPARE_REFERENCE 0x0000FFFF +#define BF_GPMI_COMPARE_REFERENCE(v) \ + (((v) << 0) & BM_GPMI_COMPARE_REFERENCE) + +/*============================================================================*/ + +#define HW_GPMI_ECCCTRL (0x00000020) +#define HW_GPMI_ECCCTRL_SET (0x00000024) +#define HW_GPMI_ECCCTRL_CLR (0x00000028) +#define HW_GPMI_ECCCTRL_TOG (0x0000002c) + +#define BP_GPMI_ECCCTRL_HANDLE 16 +#define BM_GPMI_ECCCTRL_HANDLE 0xFFFF0000 +#define BF_GPMI_ECCCTRL_HANDLE(v) \ + (((v) << 16) & BM_GPMI_ECCCTRL_HANDLE) +#define BM_GPMI_ECCCTRL_RSVD2 0x00008000 +#define BP_GPMI_ECCCTRL_ECC_CMD 13 +#define BM_GPMI_ECCCTRL_ECC_CMD 0x00006000 +#define BF_GPMI_ECCCTRL_ECC_CMD(v) \ + (((v) << 13) & BM_GPMI_ECCCTRL_ECC_CMD) +#define BV_GPMI_ECCCTRL_ECC_CMD__DECODE 0x0 +#define BV_GPMI_ECCCTRL_ECC_CMD__ENCODE 0x1 +#define BV_GPMI_ECCCTRL_ECC_CMD__RESERVE2 0x2 +#define BV_GPMI_ECCCTRL_ECC_CMD__RESERVE3 0x3 +#define BM_GPMI_ECCCTRL_ENABLE_ECC 0x00001000 +#define BV_GPMI_ECCCTRL_ENABLE_ECC__ENABLE 0x1 +#define BV_GPMI_ECCCTRL_ENABLE_ECC__DISABLE 0x0 +#define BP_GPMI_ECCCTRL_RSVD1 9 +#define BM_GPMI_ECCCTRL_RSVD1 0x00000E00 +#define BF_GPMI_ECCCTRL_RSVD1(v) \ + (((v) << 9) & BM_GPMI_ECCCTRL_RSVD1) +#define BP_GPMI_ECCCTRL_BUFFER_MASK 0 +#define BM_GPMI_ECCCTRL_BUFFER_MASK 0x000001FF +#define BF_GPMI_ECCCTRL_BUFFER_MASK(v) \ + (((v) << 0) & BM_GPMI_ECCCTRL_BUFFER_MASK) +#define BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_AUXONLY 0x100 +#define BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_PAGE 0x1FF + +/*============================================================================*/ + +#define HW_GPMI_ECCCOUNT (0x00000030) + +#define BP_GPMI_ECCCOUNT_RSVD2 16 +#define BM_GPMI_ECCCOUNT_RSVD2 0xFFFF0000 +#define BF_GPMI_ECCCOUNT_RSVD2(v) \ + (((v) << 16) & BM_GPMI_ECCCOUNT_RSVD2) +#define BP_GPMI_ECCCOUNT_COUNT 0 +#define BM_GPMI_ECCCOUNT_COUNT 0x0000FFFF +#define BF_GPMI_ECCCOUNT_COUNT(v) \ + (((v) << 0) & BM_GPMI_ECCCOUNT_COUNT) + +/*============================================================================*/ + +#define HW_GPMI_PAYLOAD (0x00000040) + +#define BP_GPMI_PAYLOAD_ADDRESS 2 +#define BM_GPMI_PAYLOAD_ADDRESS 0xFFFFFFFC +#define BF_GPMI_PAYLOAD_ADDRESS(v) \ + (((v) << 2) & BM_GPMI_PAYLOAD_ADDRESS) +#define BP_GPMI_PAYLOAD_RSVD0 0 +#define BM_GPMI_PAYLOAD_RSVD0 0x00000003 +#define BF_GPMI_PAYLOAD_RSVD0(v) \ + (((v) << 0) & BM_GPMI_PAYLOAD_RSVD0) + +/*============================================================================*/ + +#define HW_GPMI_AUXILIARY (0x00000050) + +#define BP_GPMI_AUXILIARY_ADDRESS 2 +#define BM_GPMI_AUXILIARY_ADDRESS 0xFFFFFFFC +#define BF_GPMI_AUXILIARY_ADDRESS(v) \ + (((v) << 2) & BM_GPMI_AUXILIARY_ADDRESS) +#define BP_GPMI_AUXILIARY_RSVD0 0 +#define BM_GPMI_AUXILIARY_RSVD0 0x00000003 +#define BF_GPMI_AUXILIARY_RSVD0(v) \ + (((v) << 0) & BM_GPMI_AUXILIARY_RSVD0) + +/*============================================================================*/ + +#define HW_GPMI_CTRL1 (0x00000060) +#define HW_GPMI_CTRL1_SET (0x00000064) +#define HW_GPMI_CTRL1_CLR (0x00000068) +#define HW_GPMI_CTRL1_TOG (0x0000006c) + +#define BP_GPMI_CTRL1_RSVD2 25 +#define BM_GPMI_CTRL1_RSVD2 0xFE000000 +#define BF_GPMI_CTRL1_RSVD2(v) \ + (((v) << 25) & BM_GPMI_CTRL1_RSVD2) +#define BM_GPMI_CTRL1_DECOUPLE_CS 0x01000000 +#define BP_GPMI_CTRL1_WRN_DLY_SEL 22 +#define BM_GPMI_CTRL1_WRN_DLY_SEL 0x00C00000 +#define BF_GPMI_CTRL1_WRN_DLY_SEL(v) \ + (((v) << 22) & BM_GPMI_CTRL1_WRN_DLY_SEL) +#define BM_GPMI_CTRL1_RSVD1 0x00200000 +#define BM_GPMI_CTRL1_TIMEOUT_IRQ_EN 0x00100000 +#define BM_GPMI_CTRL1_GANGED_RDYBUSY 0x00080000 +#define BM_GPMI_CTRL1_BCH_MODE 0x00040000 +#define BP_GPMI_CTRL1_DLL_ENABLE 17 +#define BM_GPMI_CTRL1_DLL_ENABLE 0x00020000 +#define BP_GPMI_CTRL1_HALF_PERIOD 16 +#define BM_GPMI_CTRL1_HALF_PERIOD 0x00010000 +#define BP_GPMI_CTRL1_RDN_DELAY 12 +#define BM_GPMI_CTRL1_RDN_DELAY 0x0000F000 +#define BF_GPMI_CTRL1_RDN_DELAY(v) \ + (((v) << 12) & BM_GPMI_CTRL1_RDN_DELAY) +#define BM_GPMI_CTRL1_DMA2ECC_MODE 0x00000800 +#define BM_GPMI_CTRL1_DEV_IRQ 0x00000400 +#define BM_GPMI_CTRL1_TIMEOUT_IRQ 0x00000200 +#define BM_GPMI_CTRL1_BURST_EN 0x00000100 +#define BM_GPMI_CTRL1_ABORT_WAIT_REQUEST 0x00000080 +#define BP_GPMI_CTRL1_ABORT_WAIT_FOR_READY_CHANNEL 4 +#define BM_GPMI_CTRL1_ABORT_WAIT_FOR_READY_CHANNEL 0x00000070 +#define BF_GPMI_CTRL1_ABORT_WAIT_FOR_READY_CHANNEL(v) \ + (((v) << 4) & BM_GPMI_CTRL1_ABORT_WAIT_FOR_READY_CHANNEL) +#define BM_GPMI_CTRL1_DEV_RESET 0x00000008 +#define BV_GPMI_CTRL1_DEV_RESET__ENABLED 0x0 +#define BV_GPMI_CTRL1_DEV_RESET__DISABLED 0x1 +#define BM_GPMI_CTRL1_ATA_IRQRDY_POLARITY 0x00000004 +#define BV_GPMI_CTRL1_ATA_IRQRDY_POLARITY__ACTIVELOW 0x0 +#define BV_GPMI_CTRL1_ATA_IRQRDY_POLARITY__ACTIVEHIGH 0x1 +#define BM_GPMI_CTRL1_CAMERA_MODE 0x00000002 +#define BM_GPMI_CTRL1_GPMI_MODE 0x00000001 +#define BV_GPMI_CTRL1_GPMI_MODE__NAND 0x0 +#define BV_GPMI_CTRL1_GPMI_MODE__ATA 0x1 + +/*============================================================================*/ + +#define HW_GPMI_TIMING0 (0x00000070) + +#define BP_GPMI_TIMING0_RSVD1 24 +#define BM_GPMI_TIMING0_RSVD1 0xFF000000 +#define BF_GPMI_TIMING0_RSVD1(v) \ + (((v) << 24) & BM_GPMI_TIMING0_RSVD1) +#define BP_GPMI_TIMING0_ADDRESS_SETUP 16 +#define BM_GPMI_TIMING0_ADDRESS_SETUP 0x00FF0000 +#define BF_GPMI_TIMING0_ADDRESS_SETUP(v) \ + (((v) << 16) & BM_GPMI_TIMING0_ADDRESS_SETUP) +#define BP_GPMI_TIMING0_DATA_HOLD 8 +#define BM_GPMI_TIMING0_DATA_HOLD 0x0000FF00 +#define BF_GPMI_TIMING0_DATA_HOLD(v) \ + (((v) << 8) & BM_GPMI_TIMING0_DATA_HOLD) +#define BP_GPMI_TIMING0_DATA_SETUP 0 +#define BM_GPMI_TIMING0_DATA_SETUP 0x000000FF +#define BF_GPMI_TIMING0_DATA_SETUP(v) \ + (((v) << 0) & BM_GPMI_TIMING0_DATA_SETUP) + +/*============================================================================*/ + +#define HW_GPMI_TIMING1 (0x00000080) + +#define BP_GPMI_TIMING1_DEVICE_BUSY_TIMEOUT 16 +#define BM_GPMI_TIMING1_DEVICE_BUSY_TIMEOUT 0xFFFF0000 +#define BF_GPMI_TIMING1_DEVICE_BUSY_TIMEOUT(v) \ + (((v) << 16) & BM_GPMI_TIMING1_DEVICE_BUSY_TIMEOUT) +#define BP_GPMI_TIMING1_RSVD1 0 +#define BM_GPMI_TIMING1_RSVD1 0x0000FFFF +#define BF_GPMI_TIMING1_RSVD1(v) \ + (((v) << 0) & BM_GPMI_TIMING1_RSVD1) + +/*============================================================================*/ + +#define HW_GPMI_TIMING2 (0x00000090) + +#define BP_GPMI_TIMING2_UDMA_TRP 24 +#define BM_GPMI_TIMING2_UDMA_TRP 0xFF000000 +#define BF_GPMI_TIMING2_UDMA_TRP(v) \ + (((v) << 24) & BM_GPMI_TIMING2_UDMA_TRP) +#define BP_GPMI_TIMING2_UDMA_ENV 16 +#define BM_GPMI_TIMING2_UDMA_ENV 0x00FF0000 +#define BF_GPMI_TIMING2_UDMA_ENV(v) \ + (((v) << 16) & BM_GPMI_TIMING2_UDMA_ENV) +#define BP_GPMI_TIMING2_UDMA_HOLD 8 +#define BM_GPMI_TIMING2_UDMA_HOLD 0x0000FF00 +#define BF_GPMI_TIMING2_UDMA_HOLD(v) \ + (((v) << 8) & BM_GPMI_TIMING2_UDMA_HOLD) +#define BP_GPMI_TIMING2_UDMA_SETUP 0 +#define BM_GPMI_TIMING2_UDMA_SETUP 0x000000FF +#define BF_GPMI_TIMING2_UDMA_SETUP(v) \ + (((v) << 0) & BM_GPMI_TIMING2_UDMA_SETUP) + +/*============================================================================*/ + +#define HW_GPMI_DATA (0x000000a0) + +#define BP_GPMI_DATA_DATA 0 +#define BM_GPMI_DATA_DATA 0xFFFFFFFF +#define BF_GPMI_DATA_DATA(v) (v) + +#define HW_GPMI_STAT (0x000000b0) + +#define BP_GPMI_STAT_READY_BUSY 24 +#define BM_GPMI_STAT_READY_BUSY 0xFF000000 +#define BF_GPMI_STAT_READY_BUSY(v) \ + (((v) << 24) & BM_GPMI_STAT_READY_BUSY) +#define BP_GPMI_STAT_RDY_TIMEOUT 16 +#define BM_GPMI_STAT_RDY_TIMEOUT 0x00FF0000 +#define BF_GPMI_STAT_RDY_TIMEOUT(v) \ + (((v) << 16) & BM_GPMI_STAT_RDY_TIMEOUT) +#define BM_GPMI_STAT_DEV7_ERROR 0x00008000 +#define BM_GPMI_STAT_DEV6_ERROR 0x00004000 +#define BM_GPMI_STAT_DEV5_ERROR 0x00002000 +#define BM_GPMI_STAT_DEV4_ERROR 0x00001000 +#define BM_GPMI_STAT_DEV3_ERROR 0x00000800 +#define BM_GPMI_STAT_DEV2_ERROR 0x00000400 +#define BM_GPMI_STAT_DEERROR 0x00000200 +#define BM_GPMI_STAT_DEV0_ERROR 0x00000100 +#define BP_GPMI_STAT_RSVD1 5 +#define BM_GPMI_STAT_RSVD1 0x000000E0 +#define BF_GPMI_STAT_RSVD1(v) \ + (((v) << 5) & BM_GPMI_STAT_RSVD1) +#define BM_GPMI_STAT_ATA_IRQ 0x00000010 +#define BM_GPMI_STAT_INVALID_BUFFER_MASK 0x00000008 +#define BM_GPMI_STAT_FIFO_EMPTY 0x00000004 +#define BV_GPMI_STAT_FIFO_EMPTY__NOT_EMPTY 0x0 +#define BV_GPMI_STAT_FIFO_EMPTY__EMPTY 0x1 +#define BM_GPMI_STAT_FIFO_FULL 0x00000002 +#define BV_GPMI_STAT_FIFO_FULL__NOT_FULL 0x0 +#define BV_GPMI_STAT_FIFO_FULL__FULL 0x1 +#define BM_GPMI_STAT_PRESENT 0x00000001 +#define BV_GPMI_STAT_PRESENT__UNAVAILABLE 0x0 +#define BV_GPMI_STAT_PRESENT__AVAILABLE 0x1 + +/*============================================================================*/ + +#define HW_GPMI_DEBUG (0x000000c0) + +#define BP_GPMI_DEBUG_WAIT_FOR_READY_END 24 +#define BM_GPMI_DEBUG_WAIT_FOR_READY_END 0xFF000000 +#define BF_GPMI_DEBUG_WAIT_FOR_READY_END(v) \ + (((v) << 24) & BM_GPMI_DEBUG_WAIT_FOR_READY_END) +#define BP_GPMI_DEBUG_DMA_SENSE 16 +#define BM_GPMI_DEBUG_DMA_SENSE 0x00FF0000 +#define BF_GPMI_DEBUG_DMA_SENSE(v) \ + (((v) << 16) & BM_GPMI_DEBUG_DMA_SENSE) +#define BP_GPMI_DEBUG_DMAREQ 8 +#define BM_GPMI_DEBUG_DMAREQ 0x0000FF00 +#define BF_GPMI_DEBUG_DMAREQ(v) \ + (((v) << 8) & BM_GPMI_DEBUG_DMAREQ) +#define BP_GPMI_DEBUG_CMD_END 0 +#define BM_GPMI_DEBUG_CMD_END 0x000000FF +#define BF_GPMI_DEBUG_CMD_END(v) \ + (((v) << 0) & BM_GPMI_DEBUG_CMD_END) + +/*============================================================================*/ + +#define HW_GPMI_VERSION (0x000000d0) + +#define BP_GPMI_VERSION_MAJOR 24 +#define BM_GPMI_VERSION_MAJOR 0xFF000000 +#define BF_GPMI_VERSION_MAJOR(v) \ + (((v) << 24) & BM_GPMI_VERSION_MAJOR) +#define BP_GPMI_VERSION_MINOR 16 +#define BM_GPMI_VERSION_MINOR 0x00FF0000 +#define BF_GPMI_VERSION_MINOR(v) \ + (((v) << 16) & BM_GPMI_VERSION_MINOR) +#define BP_GPMI_VERSION_STEP 0 +#define BM_GPMI_VERSION_STEP 0x0000FFFF +#define BF_GPMI_VERSION_STEP(v) \ + (((v) << 0) & BM_GPMI_VERSION_STEP) + +/*============================================================================*/ + +#define HW_GPMI_DEBUG2 (0x000000e0) + +#define BP_GPMI_DEBUG2_RSVD1 28 +#define BM_GPMI_DEBUG2_RSVD1 0xF0000000 +#define BF_GPMI_DEBUG2_RSVD1(v) \ + (((v) << 28) & BM_GPMI_DEBUG2_RSVD1) +#define BP_GPMI_DEBUG2_UDMA_STATE 24 +#define BM_GPMI_DEBUG2_UDMA_STATE 0x0F000000 +#define BF_GPMI_DEBUG2_UDMA_STATE(v) \ + (((v) << 24) & BM_GPMI_DEBUG2_UDMA_STATE) +#define BM_GPMI_DEBUG2_BUSY 0x00800000 +#define BV_GPMI_DEBUG2_BUSY__DISABLED 0x0 +#define BV_GPMI_DEBUG2_BUSY__ENABLED 0x1 +#define BP_GPMI_DEBUG2_PIN_STATE 20 +#define BM_GPMI_DEBUG2_PIN_STATE 0x00700000 +#define BF_GPMI_DEBUG2_PIN_STATE(v) \ + (((v) << 20) & BM_GPMI_DEBUG2_PIN_STATE) +#define BV_GPMI_DEBUG2_PIN_STATE__PSM_IDLE 0x0 +#define BV_GPMI_DEBUG2_PIN_STATE__PSM_BYTCNT 0x1 +#define BV_GPMI_DEBUG2_PIN_STATE__PSM_ADDR 0x2 +#define BV_GPMI_DEBUG2_PIN_STATE__PSM_STALL 0x3 +#define BV_GPMI_DEBUG2_PIN_STATE__PSM_STROBE 0x4 +#define BV_GPMI_DEBUG2_PIN_STATE__PSM_ATARDY 0x5 +#define BV_GPMI_DEBUG2_PIN_STATE__PSM_DHOLD 0x6 +#define BV_GPMI_DEBUG2_PIN_STATE__PSM_DONE 0x7 +#define BP_GPMI_DEBUG2_MAIN_STATE 16 +#define BM_GPMI_DEBUG2_MAIN_STATE 0x000F0000 +#define BF_GPMI_DEBUG2_MAIN_STATE(v) \ + (((v) << 16) & BM_GPMI_DEBUG2_MAIN_STATE) +#define BV_GPMI_DEBUG2_MAIN_STATE__MSM_IDLE 0x0 +#define BV_GPMI_DEBUG2_MAIN_STATE__MSM_BYTCNT 0x1 +#define BV_GPMI_DEBUG2_MAIN_STATE__MSM_WAITFE 0x2 +#define BV_GPMI_DEBUG2_MAIN_STATE__MSM_WAITFR 0x3 +#define BV_GPMI_DEBUG2_MAIN_STATE__MSM_DMAREQ 0x4 +#define BV_GPMI_DEBUG2_MAIN_STATE__MSM_DMAACK 0x5 +#define BV_GPMI_DEBUG2_MAIN_STATE__MSM_WAITFF 0x6 +#define BV_GPMI_DEBUG2_MAIN_STATE__MSM_LDFIFO 0x7 +#define BV_GPMI_DEBUG2_MAIN_STATE__MSM_LDDMAR 0x8 +#define BV_GPMI_DEBUG2_MAIN_STATE__MSM_RDCMP 0x9 +#define BV_GPMI_DEBUG2_MAIN_STATE__MSM_DONE 0xA +#define BP_GPMI_DEBUG2_SYND2GPMI_BE 12 +#define BM_GPMI_DEBUG2_SYND2GPMI_BE 0x0000F000 +#define BF_GPMI_DEBUG2_SYND2GPMI_BE(v) \ + (((v) << 12) & BM_GPMI_DEBUG2_SYND2GPMI_BE) +#define BM_GPMI_DEBUG2_GPMI2SYND_VALID 0x00000800 +#define BM_GPMI_DEBUG2_GPMI2SYND_READY 0x00000400 +#define BM_GPMI_DEBUG2_SYND2GPMI_VALID 0x00000200 +#define BM_GPMI_DEBUG2_SYND2GPMI_READY 0x00000100 +#define BM_GPMI_DEBUG2_VIEW_DELAYED_RDN 0x00000080 +#define BM_GPMI_DEBUG2_UPDATE_WINDOW 0x00000040 +#define BP_GPMI_DEBUG2_RDN_TAP 0 +#define BM_GPMI_DEBUG2_RDN_TAP 0x0000003F +#define BF_GPMI_DEBUG2_RDN_TAP(v) \ + (((v) << 0) & BM_GPMI_DEBUG2_RDN_TAP) + +/*============================================================================*/ + +#define HW_GPMI_DEBUG3 (0x000000f0) + +#define BP_GPMI_DEBUG3_APB_WORD_CNTR 16 +#define BM_GPMI_DEBUG3_APB_WORD_CNTR 0xFFFF0000 +#define BF_GPMI_DEBUG3_APB_WORD_CNTR(v) \ + (((v) << 16) & BM_GPMI_DEBUG3_APB_WORD_CNTR) +#define BP_GPMI_DEBUG3_DEV_WORD_CNTR 0 +#define BM_GPMI_DEBUG3_DEV_WORD_CNTR 0x0000FFFF +#define BF_GPMI_DEBUG3_DEV_WORD_CNTR(v) \ + (((v) << 0) & BM_GPMI_DEBUG3_DEV_WORD_CNTR) + +/*============================================================================*/ + +#endif diff --git a/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-hal-common.c b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-hal-common.c new file mode 100644 index 000000000000..b38d653a21fd --- /dev/null +++ b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-hal-common.c @@ -0,0 +1,1037 @@ +/* + * Freescale GPMI NFC NAND Flash Driver + * + * Copyright (C) 2010 Freescale Semiconductor, Inc. + * Copyright (C) 2008 Embedded Alley Solutions, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "gpmi-nfc.h" + +/** + * gpmi_nfc_bch_isr - BCH interrupt service routine. + * + * @interrupt_number: The interrupt number. + * @cookie: A cookie that contains a pointer to the owning device + * data structure. + */ +irqreturn_t gpmi_nfc_bch_isr(int irq, void *cookie) +{ + struct gpmi_nfc_data *this = cookie; + struct nfc_hal *nfc = this->nfc; + + gpmi_nfc_add_event("> gpmi_nfc_bch_isr", 1); + + /* Clear the interrupt. */ + + nfc->clear_bch(this); + + /* Release the base level. */ + + complete(&(nfc->bch_done)); + + /* Return success. */ + + gpmi_nfc_add_event("< gpmi_nfc_bch_isr", -1); + + return IRQ_HANDLED; + +} + +/** + * gpmi_nfc_dma_isr - DMA interrupt service routine. + * + * @interrupt_number: The interrupt number. + * @cookie: A cookie that contains a pointer to the owning device + * data structure. + */ +irqreturn_t gpmi_nfc_dma_isr(int irq, void *cookie) +{ + struct gpmi_nfc_data *this = cookie; + struct nfc_hal *nfc = this->nfc; + + gpmi_nfc_add_event("> gpmi_nfc_dma_isr", 1); + + /* Acknowledge the DMA channel's interrupt. */ + + mxs_dma_ack_irq(nfc->isr_dma_channel); + + /* Release the base level. */ + + complete(&(nfc->dma_done)); + + /* Return success. */ + + gpmi_nfc_add_event("< gpmi_nfc_dma_isr", -1); + + return IRQ_HANDLED; + +} + +/** + * gpmi_nfc_dma_init() - Initializes DMA. + * + * @this: Per-device data. + */ +int gpmi_nfc_dma_init(struct gpmi_nfc_data *this) +{ + struct device *dev = this->dev; + struct nfc_hal *nfc = this->nfc; + int i; + int error; + + /* Allocate the DMA descriptors. */ + + for (i = 0; i < NFC_DMA_DESCRIPTOR_COUNT; i++) { + nfc->dma_descriptors[i] = mxs_dma_alloc_desc(); + if (!nfc->dma_descriptors[i]) { + dev_err(dev, "Cannot allocate all DMA descriptors.\n"); + error = -ENOMEM; + goto exit_descriptor_allocation; + } + } + + /* If control arrives here, all is well. */ + + return 0; + + /* Control arrives here when something has gone wrong. */ + +exit_descriptor_allocation: + while (--i >= 0) + mxs_dma_free_desc(this->nfc->dma_descriptors[i]); + + return error; + +} + +/** + * gpmi_nfc_dma_exit() - Shuts down DMA. + * + * @this: Per-device data. + */ +void gpmi_nfc_dma_exit(struct gpmi_nfc_data *this) +{ + struct nfc_hal *nfc = this->nfc; + int i; + + /* Free the DMA descriptors. */ + + for (i = 0; i < NFC_DMA_DESCRIPTOR_COUNT; i++) + mxs_dma_free_desc(nfc->dma_descriptors[i]); + +} + +/** + * gpmi_nfc_set_geometry() - Shared NFC geometry configuration. + * + * In principle, computing the NFC geometry is version-specific. However, at + * this writing all, versions share the same page model, so this code can also + * be shared. + * + * @this: Per-device data. + */ +int gpmi_nfc_set_geometry(struct gpmi_nfc_data *this) +{ + struct device *dev = this->dev; + struct physical_geometry *physical = &this->physical_geometry; + struct nfc_geometry *geometry = &this->nfc_geometry; + struct boot_rom_helper *rom = this->rom; + unsigned int metadata_size; + unsigned int status_size; + unsigned int chunk_data_size_in_bits; + unsigned int chunk_ecc_size_in_bits; + unsigned int chunk_total_size_in_bits; + unsigned int block_mark_chunk_number; + unsigned int block_mark_chunk_bit_offset; + unsigned int block_mark_bit_offset; + + /* At this writing, we support only BCH. */ + + geometry->ecc_algorithm = "BCH"; + + /* + * We always choose a metadata size of 10. Don't try to make sense of + * it -- this is really only for historical compatibility. + */ + + geometry->metadata_size_in_bytes = 10; + + /* + * At this writing, we always use 512-byte ECC chunks. Later hardware + * will be able to support larger chunks, which will cause this + * decision to move into version-specific code. + */ + + geometry->ecc_chunk_size_in_bytes = 512; + + /* Compute the page size based on the physical geometry. */ + + geometry->page_size_in_bytes = + physical->page_data_size_in_bytes + + physical->page_oob_size_in_bytes ; + + /* + * Compute the total number of ECC chunks in a page. This includes the + * slightly larger chunk at the beginning of the page, which contains + * both data and metadata. + */ + + geometry->ecc_chunk_count = + physical->page_data_size_in_bytes / + /*---------------------------------*/ + geometry->ecc_chunk_size_in_bytes; + + /* + * We use the same ECC strength for all chunks, including the first one. + * At this writing, we base our ECC strength choice entirely on the + * the physical page geometry. In the future, this should be changed to + * pay attention to the detailed device information we gathered earlier. + */ + + geometry->ecc_strength = 0; + + switch (physical->page_data_size_in_bytes) { + case 2048: + geometry->ecc_strength = 8; + break; + case 4096: + switch (physical->page_oob_size_in_bytes) { + case 128: + geometry->ecc_strength = 8; + break; + case 218: + geometry->ecc_strength = 16; + break; + } + break; + } + + /* Check if we were able to figure out the ECC strength. */ + + if (!geometry->ecc_strength) { + dev_err(dev, "Unsupported page geometry: %u:%u\n", + physical->page_data_size_in_bytes, + physical->page_oob_size_in_bytes); + return !0; + } + + /* + * The payload buffer contains the data area of a page. The ECC engine + * only needs what's required to hold the data. + */ + + geometry->payload_size_in_bytes = physical->page_data_size_in_bytes; + + /* + * In principle, computing the auxiliary buffer geometry is NFC + * version-specific. However, at this writing, all versions share the + * same model, so this code can also be shared. + * + * The auxiliary buffer contains the metadata and the ECC status. The + * metadata is padded to the nearest 32-bit boundary. The ECC status + * contains one byte for every ECC chunk, and is also padded to the + * nearest 32-bit boundary. + */ + + metadata_size = (geometry->metadata_size_in_bytes + 0x3) & ~0x3; + status_size = (geometry->ecc_chunk_count + 0x3) & ~0x3; + + geometry->auxiliary_size_in_bytes = metadata_size + status_size; + geometry->auxiliary_status_offset = metadata_size; + + /* Check if we're going to do block mark swapping. */ + + if (!rom->swap_block_mark) + return 0; + + /* + * If control arrives here, we're doing block mark swapping, so we need + * to compute the byte and bit offsets of the physical block mark within + * the ECC-based view of the page data. In principle, this isn't a + * difficult computation -- but it's very important and it's easy to get + * it wrong, so we do it carefully. + * + * Note that this calculation is simpler because we use the same ECC + * strength for all chunks, including the zero'th one, which contains + * the metadata. The calculation would be slightly more complicated + * otherwise. + * + * We start by computing the physical bit offset of the block mark. We + * then subtract the number of metadata and ECC bits appearing before + * the mark to arrive at its bit offset within the data alone. + */ + + /* Compute some important facts about chunk geometry. */ + + chunk_data_size_in_bits = geometry->ecc_chunk_size_in_bytes * 8; + chunk_ecc_size_in_bits = geometry->ecc_strength * 13; + + chunk_total_size_in_bits = + chunk_data_size_in_bits + chunk_ecc_size_in_bits; + + /* Compute the bit offset of the block mark within the physical page. */ + + block_mark_bit_offset = physical->page_data_size_in_bytes * 8; + + /* Subtract the metadata bits. */ + + block_mark_bit_offset -= geometry->metadata_size_in_bytes * 8; + + /* + * Compute the chunk number (starting at zero) in which the block mark + * appears. + */ + + block_mark_chunk_number = + block_mark_bit_offset / chunk_total_size_in_bits; + + /* + * Compute the bit offset of the block mark within its chunk, and + * validate it. + */ + + block_mark_chunk_bit_offset = + block_mark_bit_offset - + (block_mark_chunk_number * chunk_total_size_in_bits); + + if (block_mark_chunk_bit_offset > chunk_data_size_in_bits) { + + /* + * If control arrives here, the block mark actually appears in + * the ECC bits of this chunk. This wont' work. + */ + + dev_err(dev, "Unsupported page geometry " + "(block mark in ECC): %u:%u\n", + physical->page_data_size_in_bytes, + physical->page_oob_size_in_bytes); + return !0; + + } + + /* + * Now that we know the chunk number in which the block mark appears, + * we can subtract all the ECC bits that appear before it. + */ + + block_mark_bit_offset -= + block_mark_chunk_number * chunk_ecc_size_in_bits; + + /* + * We now know the absolute bit offset of the block mark within the + * ECC-based data. We can now compute the byte offset and the bit + * offset within the byte. + */ + + geometry->block_mark_byte_offset = block_mark_bit_offset / 8; + geometry->block_mark_bit_offset = block_mark_bit_offset % 8; + + /* Return success. */ + + return 0; + +} + +/* + * This code is useful for debugging. + */ + +/*#define DUMP_DMA_CONTEXT*/ + +#if (defined DUMP_DMA_CONTEXT) + +int dump_dma_context_flag; + +void dump_dma_context(struct gpmi_nfc_data *this, char *title) +{ + + struct resources *resources = &this->resources; + struct nfc_hal *nfc = this->nfc; + struct mxs_dma_desc **d = nfc->dma_descriptors; + void *q; + uint32_t *p; + unsigned int i; + unsigned int j; + + if (!dump_dma_context_flag) + return; + + pr_info("%s\n", title); + pr_info("======\n"); + pr_info("\n"); + + /*--------------------------------------------------------------------*/ + + pr_info(" Descriptors\n"); + pr_info(" -----------\n"); + { + + for (i = 0; i < NFC_DMA_DESCRIPTOR_COUNT; i++, d++) { + pr_info(" #%u\n", i); + pr_info(" --\n"); + pr_info(" Physical Address: 0x%08x\n" , (*d)->address); + pr_info(" Next : 0x%08lx\n", (*d)->cmd.next); + pr_info(" Command : 0x%08lx\n", (*d)->cmd.cmd.data); + pr_info(" Buffer : 0x%08x\n" , (*d)->cmd.address); + for (j = 0; j < 6; j++) + pr_info(" PIO[%u] : 0x%08lx\n", + j, (*d)->cmd.pio_words[j]); + } + + } + pr_info("\n"); + + /*--------------------------------------------------------------------*/ + + pr_info(" DMA\n"); + pr_info(" ---\n"); + { + void *DMA = IO_ADDRESS(APBH_DMA_PHYS_ADDR); + + p = q = DMA + 0x200; + + for (i = 0; i < 7; i++) { + pr_info(" [0x%03x] 0x%08x\n", q - DMA, *p); + q += 0x10; + p = q; + } + + } + pr_info("\n"); + + /*--------------------------------------------------------------------*/ + + pr_info(" GPMI\n"); + pr_info(" ----\n"); + { + void *GPMI = resources->gpmi_regs; + + p = q = GPMI; + + for (i = 0; i < 33; i++) { + pr_info(" [0x%03x] 0x%08x\n", q - GPMI, *p); + q += 0x10; + p = q; + } + + } + pr_info("\n"); + + /*--------------------------------------------------------------------*/ + + pr_info(" BCH\n"); + pr_info(" ---\n"); + { + void *BCH = resources->bch_regs; + + p = q = BCH; + + for (i = 0; i < 22; i++) { + pr_info(" [0x%03x] 0x%08x\n", q - BCH, *p); + q += 0x10; + p = q; + } + + } + pr_info("\n"); + +} + +#endif + +/** + * gpmi_nfc_dma_go - Run a DMA channel. + * + * @this: Per-device data structure. + * @dma_channel: The DMA channel we're going to use. + */ +int gpmi_nfc_dma_go(struct gpmi_nfc_data *this, int dma_channel) +{ + struct device *dev = this->dev; + struct resources *resources = &this->resources; + struct nfc_hal *nfc = this->nfc; + unsigned long timeout; + int error; + LIST_HEAD(tmp_desc_list); + + gpmi_nfc_add_event("> gpmi_nfc_dma_go", 1); + + /* Get ready... */ + + nfc->isr_dma_channel = dma_channel; + init_completion(&nfc->dma_done); + mxs_dma_enable_irq(dma_channel, 1); + + /* Go! */ + + #if defined(DUMP_DMA_CONTEXT) + dump_dma_context(this, "BEFORE"); + #endif + + mxs_dma_enable(dma_channel); + + /* Wait for it to finish. */ + + timeout = wait_for_completion_timeout(&nfc->dma_done, + msecs_to_jiffies(1000)); + + #if defined(DUMP_DMA_CONTEXT) + dump_dma_context(this, "AFTER"); + #endif + + error = (!timeout) ? -ETIMEDOUT : 0; + + if (error) { + dev_err(dev, "[%s] Chip: %u, DMA Channel: %d, Error %d\n", + __func__, dma_channel - resources->dma_low_channel, + dma_channel, error); + gpmi_nfc_add_event("...DMA timed out", 0); + } else + gpmi_nfc_add_event("...Finished DMA successfully", 0); + + /* Clear out the descriptors we just ran. */ + + mxs_dma_cooked(dma_channel, &tmp_desc_list); + + /* Shut the DMA channel down. */ + + mxs_dma_reset(dma_channel); + mxs_dma_enable_irq(dma_channel, 0); + mxs_dma_disable(dma_channel); + + /* Return. */ + + gpmi_nfc_add_event("< gpmi_nfc_dma_go", -1); + + return error; + +} + +/** + * ns_to_cycles - Converts time in nanoseconds to cycles. + * + * @ntime: The time, in nanoseconds. + * @period: The cycle period, in nanoseconds. + * @min: The minimum allowable number of cycles. + */ +static unsigned int ns_to_cycles(unsigned int time, + unsigned int period, unsigned int min) +{ + unsigned int k; + + /* + * Compute the minimum number of cycles that entirely contain the + * given time. + */ + + k = (time + period - 1) / period; + + return max(k, min); + +} + +/** + * gpmi_compute_hardware_timing - Apply timing to current hardware conditions. + * + * @this: Per-device data. + * @hardware_timing: A pointer to a hardware timing structure that will receive + * the results of our calculations. + */ +int gpmi_nfc_compute_hardware_timing(struct gpmi_nfc_data *this, + struct gpmi_nfc_hardware_timing *hw) +{ + struct gpmi_nfc_platform_data *pdata = this->pdata; + struct physical_geometry *physical = &this->physical_geometry; + struct nfc_hal *nfc = this->nfc; + struct gpmi_nfc_timing target = nfc->timing; + bool improved_timing_is_available; + unsigned long clock_frequency_in_hz; + unsigned int clock_period_in_ns; + bool dll_use_half_periods; + unsigned int dll_delay_shift; + unsigned int max_sample_delay_in_ns; + unsigned int address_setup_in_cycles; + unsigned int data_setup_in_ns; + unsigned int data_setup_in_cycles; + unsigned int data_hold_in_cycles; + int ideal_sample_delay_in_ns; + unsigned int sample_delay_factor; + int tEYE; + unsigned int min_prop_delay_in_ns = pdata->min_prop_delay_in_ns; + unsigned int max_prop_delay_in_ns = pdata->max_prop_delay_in_ns; + + /* + * If there are multiple chips, we need to relax the timings to allow + * for signal distortion due to higher capacitance. + */ + + if (physical->chip_count > 2) { + target.data_setup_in_ns += 10; + target.data_hold_in_ns += 10; + target.address_setup_in_ns += 10; + } else if (physical->chip_count > 1) { + target.data_setup_in_ns += 5; + target.data_hold_in_ns += 5; + target.address_setup_in_ns += 5; + } + + /* Check if improved timing information is available. */ + + improved_timing_is_available = + (target.tREA_in_ns >= 0) && + (target.tRLOH_in_ns >= 0) && + (target.tRHOH_in_ns >= 0) ; + + /* Inspect the clock. */ + + clock_frequency_in_hz = nfc->clock_frequency_in_hz; + clock_period_in_ns = 1000000000 / clock_frequency_in_hz; + + /* + * The NFC quantizes setup and hold parameters in terms of clock cycles. + * Here, we quantize the setup and hold timing parameters to the + * next-highest clock period to make sure we apply at least the + * specified times. + * + * For data setup and data hold, the hardware interprets a value of zero + * as the largest possible delay. This is not what's intended by a zero + * in the input parameter, so we impose a minimum of one cycle. + */ + + data_setup_in_cycles = ns_to_cycles(target.data_setup_in_ns, + clock_period_in_ns, 1); + data_hold_in_cycles = ns_to_cycles(target.data_hold_in_ns, + clock_period_in_ns, 1); + address_setup_in_cycles = ns_to_cycles(target.address_setup_in_ns, + clock_period_in_ns, 0); + + /* + * The clock's period affects the sample delay in a number of ways: + * + * (1) The NFC HAL tells us the maximum clock period the sample delay + * DLL can tolerate. If the clock period is greater than half that + * maximum, we must configure the DLL to be driven by half periods. + * + * (2) We need to convert from an ideal sample delay, in ns, to a + * "sample delay factor," which the NFC uses. This factor depends on + * whether we're driving the DLL with full or half periods. + * Paraphrasing the reference manual: + * + * AD = SDF x 0.125 x RP + * + * where: + * + * AD is the applied delay, in ns. + * SDF is the sample delay factor, which is dimensionless. + * RP is the reference period, in ns, which is a full clock period + * if the DLL is being driven by full periods, or half that if + * the DLL is being driven by half periods. + * + * Let's re-arrange this in a way that's more useful to us: + * + * 8 + * SDF = AD x ---- + * RP + * + * The reference period is either the clock period or half that, so this + * is: + * + * 8 AD x DDF + * SDF = AD x ----- = -------- + * f x P P + * + * where: + * + * f is 1 or 1/2, depending on how we're driving the DLL. + * P is the clock period. + * DDF is the DLL Delay Factor, a dimensionless value that + * incorporates all the constants in the conversion. + * + * DDF will be either 8 or 16, both of which are powers of two. We can + * reduce the cost of this conversion by using bit shifts instead of + * multiplication or division. Thus: + * + * AD << DDS + * SDF = --------- + * P + * + * or + * + * AD = (SDF >> DDS) x P + * + * where: + * + * DDS is the DLL Delay Shift, the logarithm to base 2 of the DDF. + */ + + if (clock_period_in_ns > (nfc->max_dll_clock_period_in_ns >> 1)) { + dll_use_half_periods = true; + dll_delay_shift = 3 + 1; + } else { + dll_use_half_periods = false; + dll_delay_shift = 3; + } + + /* + * Compute the maximum sample delay the NFC allows, under current + * conditions. If the clock is running too slowly, no sample delay is + * possible. + */ + + if (clock_period_in_ns > nfc->max_dll_clock_period_in_ns) + max_sample_delay_in_ns = 0; + else { + + /* + * Compute the delay implied by the largest sample delay factor + * the NFC allows. + */ + + max_sample_delay_in_ns = + (nfc->max_sample_delay_factor * clock_period_in_ns) >> + dll_delay_shift; + + /* + * Check if the implied sample delay larger than the NFC + * actually allows. + */ + + if (max_sample_delay_in_ns > nfc->max_dll_delay_in_ns) + max_sample_delay_in_ns = nfc->max_dll_delay_in_ns; + + } + + /* + * Check if improved timing information is available. If not, we have to + * use a less-sophisticated algorithm. + */ + + if (!improved_timing_is_available) { + + /* + * Fold the read setup time required by the NFC into the ideal + * sample delay. + */ + + ideal_sample_delay_in_ns = target.gpmi_sample_delay_in_ns + + nfc->internal_data_setup_in_ns; + + /* + * The ideal sample delay may be greater than the maximum + * allowed by the NFC. If so, we can trade off sample delay time + * for more data setup time. + * + * In each iteration of the following loop, we add a cycle to + * the data setup time and subtract a corresponding amount from + * the sample delay until we've satisified the constraints or + * can't do any better. + */ + + while ((ideal_sample_delay_in_ns > max_sample_delay_in_ns) && + (data_setup_in_cycles < nfc->max_data_setup_cycles)) { + + data_setup_in_cycles++; + ideal_sample_delay_in_ns -= clock_period_in_ns; + + if (ideal_sample_delay_in_ns < 0) + ideal_sample_delay_in_ns = 0; + + } + + /* + * Compute the sample delay factor that corresponds most closely + * to the ideal sample delay. If the result is too large for the + * NFC, use the maximum value. + * + * Notice that we use the ns_to_cycles function to compute the + * sample delay factor. We do this because the form of the + * computation is the same as that for calculating cycles. + */ + + sample_delay_factor = + ns_to_cycles( + ideal_sample_delay_in_ns << dll_delay_shift, + clock_period_in_ns, 0); + + if (sample_delay_factor > nfc->max_sample_delay_factor) + sample_delay_factor = nfc->max_sample_delay_factor; + + /* Skip to the part where we return our results. */ + + goto return_results; + + } + + /* + * If control arrives here, we have more detailed timing information, + * so we can use a better algorithm. + */ + + /* + * Fold the read setup time required by the NFC into the maximum + * propagation delay. + */ + + max_prop_delay_in_ns += nfc->internal_data_setup_in_ns; + + /* + * Earlier, we computed the number of clock cycles required to satisfy + * the data setup time. Now, we need to know the actual nanoseconds. + */ + + data_setup_in_ns = clock_period_in_ns * data_setup_in_cycles; + + /* + * Compute tEYE, the width of the data eye when reading from the NAND + * Flash. The eye width is fundamentally determined by the data setup + * time, perturbed by propagation delays and some characteristics of the + * NAND Flash device. + * + * start of the eye = max_prop_delay + tREA + * end of the eye = min_prop_delay + tRHOH + data_setup + */ + + tEYE = (int)min_prop_delay_in_ns + (int)target.tRHOH_in_ns + + (int)data_setup_in_ns; + + tEYE -= (int)max_prop_delay_in_ns + (int)target.tREA_in_ns; + + /* + * The eye must be open. If it's not, we can try to open it by + * increasing its main forcer, the data setup time. + * + * In each iteration of the following loop, we increase the data setup + * time by a single clock cycle. We do this until either the eye is + * open or we run into NFC limits. + */ + + while ((tEYE <= 0) && + (data_setup_in_cycles < nfc->max_data_setup_cycles)) { + /* Give a cycle to data setup. */ + data_setup_in_cycles++; + /* Synchronize the data setup time with the cycles. */ + data_setup_in_ns += clock_period_in_ns; + /* Adjust tEYE accordingly. */ + tEYE += clock_period_in_ns; + } + + /* + * When control arrives here, the eye is open. The ideal time to sample + * the data is in the center of the eye: + * + * end of the eye + start of the eye + * --------------------------------- - data_setup + * 2 + * + * After some algebra, this simplifies to the code immediately below. + */ + + ideal_sample_delay_in_ns = + ((int)max_prop_delay_in_ns + + (int)target.tREA_in_ns + + (int)min_prop_delay_in_ns + + (int)target.tRHOH_in_ns - + (int)data_setup_in_ns) >> 1; + + /* + * The following figure illustrates some aspects of a NAND Flash read: + * + * + * __ _____________________________________ + * RDN \_________________/ + * + * <---- tEYE -----> + * /-----------------\ + * Read Data ----------------------------< >--------- + * \-----------------/ + * ^ ^ ^ ^ + * | | | | + * |<--Data Setup -->|<--Delay Time -->| | + * | | | | + * | | | + * | |<-- Quantized Delay Time -->| + * | | | + * + * + * We have some issues we must now address: + * + * (1) The *ideal* sample delay time must not be negative. If it is, we + * jam it to zero. + * + * (2) The *ideal* sample delay time must not be greater than that + * allowed by the NFC. If it is, we can increase the data setup + * time, which will reduce the delay between the end of the data + * setup and the center of the eye. It will also make the eye + * larger, which might help with the next issue... + * + * (3) The *quantized* sample delay time must not fall either before the + * eye opens or after it closes (the latter is the problem + * illustrated in the above figure). + */ + + /* Jam a negative ideal sample delay to zero. */ + + if (ideal_sample_delay_in_ns < 0) + ideal_sample_delay_in_ns = 0; + + /* + * Extend the data setup as needed to reduce the ideal sample delay + * below the maximum permitted by the NFC. + */ + + while ((ideal_sample_delay_in_ns > max_sample_delay_in_ns) && + (data_setup_in_cycles < nfc->max_data_setup_cycles)) { + + /* Give a cycle to data setup. */ + data_setup_in_cycles++; + /* Synchronize the data setup time with the cycles. */ + data_setup_in_ns += clock_period_in_ns; + /* Adjust tEYE accordingly. */ + tEYE += clock_period_in_ns; + + /* + * Decrease the ideal sample delay by one half cycle, to keep it + * in the middle of the eye. + */ + ideal_sample_delay_in_ns -= (clock_period_in_ns >> 1); + + /* Jam a negative ideal sample delay to zero. */ + if (ideal_sample_delay_in_ns < 0) + ideal_sample_delay_in_ns = 0; + + } + + /* + * Compute the sample delay factor that corresponds to the ideal sample + * delay. If the result is too large, then use the maximum allowed + * value. + * + * Notice that we use the ns_to_cycles function to compute the sample + * delay factor. We do this because the form of the computation is the + * same as that for calculating cycles. + */ + + sample_delay_factor = + ns_to_cycles(ideal_sample_delay_in_ns << dll_delay_shift, + clock_period_in_ns, 0); + + if (sample_delay_factor > nfc->max_sample_delay_factor) + sample_delay_factor = nfc->max_sample_delay_factor; + + /* + * These macros conveniently encapsulate a computation we'll use to + * continuously evaluate whether or not the data sample delay is inside + * the eye. + */ + + #define IDEAL_DELAY ((int) ideal_sample_delay_in_ns) + + #define QUANTIZED_DELAY \ + ((int) ((sample_delay_factor * clock_period_in_ns) >> \ + dll_delay_shift)) + + #define DELAY_ERROR (abs(QUANTIZED_DELAY - IDEAL_DELAY)) + + #define SAMPLE_IS_NOT_WITHIN_THE_EYE (DELAY_ERROR > (tEYE >> 1)) + + /* + * While the quantized sample time falls outside the eye, reduce the + * sample delay or extend the data setup to move the sampling point back + * toward the eye. Do not allow the number of data setup cycles to + * exceed the maximum allowed by the NFC. + */ + + while (SAMPLE_IS_NOT_WITHIN_THE_EYE && + (data_setup_in_cycles < nfc->max_data_setup_cycles)) { + + /* + * If control arrives here, the quantized sample delay falls + * outside the eye. Check if it's before the eye opens, or after + * the eye closes. + */ + + if (QUANTIZED_DELAY > IDEAL_DELAY) { + + /* + * If control arrives here, the quantized sample delay + * falls after the eye closes. Decrease the quantized + * delay time and then go back to re-evaluate. + */ + + if (sample_delay_factor != 0) + sample_delay_factor--; + + continue; + + } + + /* + * If control arrives here, the quantized sample delay falls + * before the eye opens. Shift the sample point by increasing + * data setup time. This will also make the eye larger. + */ + + /* Give a cycle to data setup. */ + data_setup_in_cycles++; + /* Synchronize the data setup time with the cycles. */ + data_setup_in_ns += clock_period_in_ns; + /* Adjust tEYE accordingly. */ + tEYE += clock_period_in_ns; + + /* + * Decrease the ideal sample delay by one half cycle, to keep it + * in the middle of the eye. + */ + ideal_sample_delay_in_ns -= (clock_period_in_ns >> 1); + + /* ...and one less period for the delay time. */ + ideal_sample_delay_in_ns -= clock_period_in_ns; + + /* Jam a negative ideal sample delay to zero. */ + if (ideal_sample_delay_in_ns < 0) + ideal_sample_delay_in_ns = 0; + + /* + * We have a new ideal sample delay, so re-compute the quantized + * delay. + */ + + sample_delay_factor = + ns_to_cycles( + ideal_sample_delay_in_ns << dll_delay_shift, + clock_period_in_ns, 0); + + if (sample_delay_factor > nfc->max_sample_delay_factor) + sample_delay_factor = nfc->max_sample_delay_factor; + + } + + /* Control arrives here when we're ready to return our results. */ + +return_results: + + hw->data_setup_in_cycles = data_setup_in_cycles; + hw->data_hold_in_cycles = data_hold_in_cycles; + hw->address_setup_in_cycles = address_setup_in_cycles; + hw->use_half_periods = dll_use_half_periods; + hw->sample_delay_factor = sample_delay_factor; + + /* Return success. */ + + return 0; + +} diff --git a/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-hal-v0.c b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-hal-v0.c new file mode 100644 index 000000000000..294bb9409581 --- /dev/null +++ b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-hal-v0.c @@ -0,0 +1,924 @@ +/* + * Freescale GPMI NFC NAND Flash Driver + * + * Copyright (C) 2010 Freescale Semiconductor, Inc. + * Copyright (C) 2008 Embedded Alley Solutions, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "gpmi-nfc.h" + +#include "gpmi-nfc-gpmi-regs-v0.h" +#include "gpmi-nfc-bch-regs-v0.h" + +/** + * init() - Initializes the NFC hardware. + * + * @this: Per-device data. + */ +static int init(struct gpmi_nfc_data *this) +{ + struct resources *resources = &this->resources; + int error; + + /* Initialize DMA. */ + + error = gpmi_nfc_dma_init(this); + + if (error) + return error; + + /* Enable the clock. It will stay on until the end of set_geometry(). */ + + clk_enable(resources->clock); + + /* Reset the GPMI block. */ + + mxs_reset_block(resources->gpmi_regs + HW_GPMI_CTRL0, true); + + /* Choose NAND mode. */ + __raw_writel(BM_GPMI_CTRL1_GPMI_MODE, + resources->gpmi_regs + HW_GPMI_CTRL1_CLR); + + /* Set the IRQ polarity. */ + __raw_writel(BM_GPMI_CTRL1_ATA_IRQRDY_POLARITY, + resources->gpmi_regs + HW_GPMI_CTRL1_SET); + + /* Disable write protection. */ + __raw_writel(BM_GPMI_CTRL1_DEV_RESET, + resources->gpmi_regs + HW_GPMI_CTRL1_SET); + + /* Select BCH ECC. */ + __raw_writel(BM_GPMI_CTRL1_BCH_MODE, + resources->gpmi_regs + HW_GPMI_CTRL1_SET); + + /* Disable the clock. */ + + clk_disable(resources->clock); + + /* If control arrives here, all is well. */ + + return 0; + +} + +/** + * set_geometry() - Configures the NFC geometry. + * + * @this: Per-device data. + */ +static int set_geometry(struct gpmi_nfc_data *this) +{ + struct resources *resources = &this->resources; + struct nfc_geometry *nfc = &this->nfc_geometry; + unsigned int block_count; + unsigned int block_size; + unsigned int metadata_size; + unsigned int ecc_strength; + unsigned int page_size; + + /* We make the abstract choices in a common function. */ + + if (gpmi_nfc_set_geometry(this)) + return !0; + + /* Translate the abstract choices into register fields. */ + + block_count = nfc->ecc_chunk_count - 1; + block_size = nfc->ecc_chunk_size_in_bytes; + metadata_size = nfc->metadata_size_in_bytes; + ecc_strength = nfc->ecc_strength >> 1; + page_size = nfc->page_size_in_bytes; + + /* Enable the clock. */ + + clk_enable(resources->clock); + + /* + * Reset the BCH block. Notice that we pass in true for the just_enable + * flag. This is because the soft reset for the version 0 BCH block + * doesn't work. If you try to soft reset the BCH block, it becomes + * unusable until the next hard reset. + */ + + mxs_reset_block(resources->bch_regs, true); + + /* Configure layout 0. */ + + __raw_writel( + BF_BCH_FLASH0LAYOUT0_NBLOCKS(block_count) | + BF_BCH_FLASH0LAYOUT0_META_SIZE(metadata_size) | + BF_BCH_FLASH0LAYOUT0_ECC0(ecc_strength) | + BF_BCH_FLASH0LAYOUT0_DATA0_SIZE(block_size) , + resources->bch_regs + HW_BCH_FLASH0LAYOUT0); + + __raw_writel( + BF_BCH_FLASH0LAYOUT1_PAGE_SIZE(page_size) | + BF_BCH_FLASH0LAYOUT1_ECCN(ecc_strength) | + BF_BCH_FLASH0LAYOUT1_DATAN_SIZE(block_size) , + resources->bch_regs + HW_BCH_FLASH0LAYOUT1); + + /* Set *all* chip selects to use layout 0. */ + + __raw_writel(0, resources->bch_regs + HW_BCH_LAYOUTSELECT); + + /* Enable interrupts. */ + + __raw_writel(BM_BCH_CTRL_COMPLETE_IRQ_EN, + resources->bch_regs + HW_BCH_CTRL_SET); + + /* Disable the clock. */ + + clk_disable(resources->clock); + + /* Return success. */ + + return 0; + +} + +/** + * set_timing() - Configures the NFC timing. + * + * @this: Per-device data. + * @timing: The timing of interest. + */ +static int set_timing(struct gpmi_nfc_data *this, + const struct gpmi_nfc_timing *timing) +{ + struct nfc_hal *nfc = this->nfc; + + /* Accept the new timing. */ + + nfc->timing = *timing; + + /* Return success. */ + + return 0; + +} + +/** + * get_timing() - Retrieves the NFC hardware timing. + * + * @this: Per-device data. + * @clock_frequency_in_hz: The clock frequency, in Hz, during the current + * I/O transaction. If no I/O transaction is in + * progress, this is the clock frequency during the + * most recent I/O transaction. + * @hardware_timing: The hardware timing configuration in effect during + * the current I/O transaction. If no I/O transaction + * is in progress, this is the hardware timing + * configuration during the most recent I/O + * transaction. + */ +static void get_timing(struct gpmi_nfc_data *this, + unsigned long *clock_frequency_in_hz, + struct gpmi_nfc_hardware_timing *hardware_timing) +{ + struct resources *resources = &this->resources; + struct nfc_hal *nfc = this->nfc; + unsigned char *gpmi_regs = resources->gpmi_regs; + uint32_t register_image; + + /* Return the clock frequency. */ + + *clock_frequency_in_hz = nfc->clock_frequency_in_hz; + + /* We'll be reading the hardware, so let's enable the clock. */ + + clk_enable(resources->clock); + + /* Retrieve the hardware timing. */ + + register_image = __raw_readl(gpmi_regs + HW_GPMI_TIMING0); + + hardware_timing->data_setup_in_cycles = + (register_image & BM_GPMI_TIMING0_DATA_SETUP) >> + BP_GPMI_TIMING0_DATA_SETUP; + + hardware_timing->data_hold_in_cycles = + (register_image & BM_GPMI_TIMING0_DATA_HOLD) >> + BP_GPMI_TIMING0_DATA_HOLD; + + hardware_timing->address_setup_in_cycles = + (register_image & BM_GPMI_TIMING0_ADDRESS_SETUP) >> + BP_GPMI_TIMING0_ADDRESS_SETUP; + + register_image = __raw_readl(gpmi_regs + HW_GPMI_CTRL1); + + hardware_timing->use_half_periods = + (register_image & BM_GPMI_CTRL1_HALF_PERIOD) >> + BP_GPMI_CTRL1_HALF_PERIOD; + + hardware_timing->sample_delay_factor = + (register_image & BM_GPMI_CTRL1_RDN_DELAY) >> + BP_GPMI_CTRL1_RDN_DELAY; + + /* We're done reading the hardware, so disable the clock. */ + + clk_disable(resources->clock); + +} + +/** + * exit() - Shuts down the NFC hardware. + * + * @this: Per-device data. + */ +static void exit(struct gpmi_nfc_data *this) +{ + gpmi_nfc_dma_exit(this); +} + +/** + * begin() - Begin NFC I/O. + * + * @this: Per-device data. + */ +static void begin(struct gpmi_nfc_data *this) +{ + struct resources *resources = &this->resources; + struct nfc_hal *nfc = this->nfc; + struct gpmi_nfc_hardware_timing hw; + unsigned char *gpmi_regs = resources->gpmi_regs; + unsigned int clock_period_in_ns; + uint32_t register_image; + unsigned int dll_wait_time_in_us; + + /* Enable the clock. */ + + clk_enable(resources->clock); + + /* Get the timing information we need. */ + + nfc->clock_frequency_in_hz = clk_get_rate(resources->clock); + clock_period_in_ns = 1000000000 / nfc->clock_frequency_in_hz; + + gpmi_nfc_compute_hardware_timing(this, &hw); + + /* Set up all the simple timing parameters. */ + + register_image = + BF_GPMI_TIMING0_ADDRESS_SETUP(hw.address_setup_in_cycles) | + BF_GPMI_TIMING0_DATA_HOLD(hw.data_hold_in_cycles) | + BF_GPMI_TIMING0_DATA_SETUP(hw.data_setup_in_cycles) ; + + __raw_writel(register_image, gpmi_regs + HW_GPMI_TIMING0); + + /* + * HEY - PAY ATTENTION! + * + * DLL_ENABLE must be set to zero when setting RDN_DELAY or HALF_PERIOD. + */ + + __raw_writel(BM_GPMI_CTRL1_DLL_ENABLE, gpmi_regs + HW_GPMI_CTRL1_CLR); + + /* Clear out the DLL control fields. */ + + __raw_writel(BM_GPMI_CTRL1_RDN_DELAY, gpmi_regs + HW_GPMI_CTRL1_CLR); + __raw_writel(BM_GPMI_CTRL1_HALF_PERIOD, gpmi_regs + HW_GPMI_CTRL1_CLR); + + /* If no sample delay is called for, return immediately. */ + + if (!hw.sample_delay_factor) + return; + + /* Configure the HALF_PERIOD flag. */ + + if (hw.use_half_periods) + __raw_writel(BM_GPMI_CTRL1_HALF_PERIOD, + gpmi_regs + HW_GPMI_CTRL1_SET); + + /* Set the delay factor. */ + + __raw_writel(BF_GPMI_CTRL1_RDN_DELAY(hw.sample_delay_factor), + gpmi_regs + HW_GPMI_CTRL1_SET); + + /* Enable the DLL. */ + + __raw_writel(BM_GPMI_CTRL1_DLL_ENABLE, gpmi_regs + HW_GPMI_CTRL1_SET); + + /* + * After we enable the GPMI DLL, we have to wait 64 clock cycles before + * we can use the GPMI. + * + * Calculate the amount of time we need to wait, in microseconds. + */ + + dll_wait_time_in_us = (clock_period_in_ns * 64) / 1000; + + if (!dll_wait_time_in_us) + dll_wait_time_in_us = 1; + + /* Wait for the DLL to settle. */ + + udelay(dll_wait_time_in_us); + +} + +/** + * end() - End NFC I/O. + * + * @this: Per-device data. + */ +static void end(struct gpmi_nfc_data *this) +{ + struct resources *resources = &this->resources; + + /* Disable the clock. */ + + clk_disable(resources->clock); + +} + +/** + * clear_bch() - Clears a BCH interrupt. + * + * @this: Per-device data. + */ +static void clear_bch(struct gpmi_nfc_data *this) +{ + struct resources *resources = &this->resources; + + __raw_writel(BM_BCH_CTRL_COMPLETE_IRQ, + resources->bch_regs + HW_BCH_CTRL_CLR); + +} + +/** + * is_ready() - Returns the ready/busy status of the given chip. + * + * @this: Per-device data. + * @chip: The chip of interest. + */ +static int is_ready(struct gpmi_nfc_data *this, unsigned chip) +{ + struct resources *resources = &this->resources; + uint32_t mask; + uint32_t register_image; + + /* Extract and return the status. */ + + mask = BM_GPMI_DEBUG_READY0 << chip; + + register_image = __raw_readl(resources->gpmi_regs + HW_GPMI_DEBUG); + + return !!(register_image & mask); + +} + +/** + * send_command() - Sends a command and associated addresses. + * + * @this: Per-device data. + * @chip: The chip of interest. + * @buffer: The physical address of a buffer that contains the command bytes. + * @length: The number of bytes in the buffer. + */ +static int send_command(struct gpmi_nfc_data *this, unsigned chip, + dma_addr_t buffer, unsigned int length) +{ + struct device *dev = this->dev; + struct resources *resources = &this->resources; + struct nfc_hal *nfc = this->nfc; + struct mxs_dma_desc **d = nfc->dma_descriptors; + int dma_channel; + int error; + uint32_t command_mode; + uint32_t address; + + /* Compute the DMA channel. */ + + dma_channel = resources->dma_low_channel + chip; + + /* A DMA descriptor that sends out the command. */ + + command_mode = BV_GPMI_CTRL0_COMMAND_MODE__WRITE; + address = BV_GPMI_CTRL0_ADDRESS__NAND_CLE; + + (*d)->cmd.cmd.data = 0; + (*d)->cmd.cmd.bits.command = DMA_READ; + (*d)->cmd.cmd.bits.chain = 1; + (*d)->cmd.cmd.bits.irq = 1; + (*d)->cmd.cmd.bits.nand_lock = 0; + (*d)->cmd.cmd.bits.nand_wait_4_ready = 0; + (*d)->cmd.cmd.bits.dec_sem = 1; + (*d)->cmd.cmd.bits.wait4end = 1; + (*d)->cmd.cmd.bits.halt_on_terminate = 0; + (*d)->cmd.cmd.bits.terminate_flush = 0; + (*d)->cmd.cmd.bits.pio_words = 3; + (*d)->cmd.cmd.bits.bytes = length; + + (*d)->cmd.address = buffer; + + (*d)->cmd.pio_words[0] = + BF_GPMI_CTRL0_COMMAND_MODE(command_mode) | + BM_GPMI_CTRL0_WORD_LENGTH | + BF_GPMI_CTRL0_CS(chip) | + BF_GPMI_CTRL0_ADDRESS(address) | + BM_GPMI_CTRL0_ADDRESS_INCREMENT | + BF_GPMI_CTRL0_XFER_COUNT(length) ; + + (*d)->cmd.pio_words[1] = 0; + (*d)->cmd.pio_words[2] = 0; + + mxs_dma_desc_append(dma_channel, (*d)); + d++; + + /* Go! */ + + error = gpmi_nfc_dma_go(this, dma_channel); + + if (error) + dev_err(dev, "[%s] DMA error\n", __func__); + + /* Return success. */ + + return error; + +} + +/** + * send_data() - Sends data to the given chip. + * + * @this: Per-device data. + * @chip: The chip of interest. + * @buffer: The physical address of a buffer that contains the data. + * @length: The number of bytes in the buffer. + */ +static int send_data(struct gpmi_nfc_data *this, unsigned chip, + dma_addr_t buffer, unsigned int length) +{ + struct device *dev = this->dev; + struct resources *resources = &this->resources; + struct nfc_hal *nfc = this->nfc; + struct mxs_dma_desc **d = nfc->dma_descriptors; + int dma_channel; + int error = 0; + uint32_t command_mode; + uint32_t address; + + /* Compute the DMA channel. */ + + dma_channel = resources->dma_low_channel + chip; + + /* A DMA descriptor that writes a buffer out. */ + + command_mode = BV_GPMI_CTRL0_COMMAND_MODE__WRITE; + address = BV_GPMI_CTRL0_ADDRESS__NAND_DATA; + + (*d)->cmd.cmd.data = 0; + (*d)->cmd.cmd.bits.command = DMA_READ; + (*d)->cmd.cmd.bits.chain = 0; + (*d)->cmd.cmd.bits.irq = 1; + (*d)->cmd.cmd.bits.nand_lock = 0; + (*d)->cmd.cmd.bits.nand_wait_4_ready = 0; + (*d)->cmd.cmd.bits.dec_sem = 1; + (*d)->cmd.cmd.bits.wait4end = 1; + (*d)->cmd.cmd.bits.halt_on_terminate = 0; + (*d)->cmd.cmd.bits.terminate_flush = 0; + (*d)->cmd.cmd.bits.pio_words = 4; + (*d)->cmd.cmd.bits.bytes = length; + + (*d)->cmd.address = buffer; + + (*d)->cmd.pio_words[0] = + BF_GPMI_CTRL0_COMMAND_MODE(command_mode) | + BM_GPMI_CTRL0_WORD_LENGTH | + BF_GPMI_CTRL0_CS(chip) | + BF_GPMI_CTRL0_ADDRESS(address) | + BF_GPMI_CTRL0_XFER_COUNT(length) ; + (*d)->cmd.pio_words[1] = 0; + (*d)->cmd.pio_words[2] = 0; + (*d)->cmd.pio_words[3] = 0; + + mxs_dma_desc_append(dma_channel, (*d)); + d++; + + /* Go! */ + + error = gpmi_nfc_dma_go(this, dma_channel); + + if (error) + dev_err(dev, "[%s] DMA error\n", __func__); + + /* Return success. */ + + return error; + +} + +/** + * read_data() - Receives data from the given chip. + * + * @this: Per-device data. + * @chip: The chip of interest. + * @buffer: The physical address of a buffer that will receive the data. + * @length: The number of bytes to read. + */ +static int read_data(struct gpmi_nfc_data *this, unsigned chip, + dma_addr_t buffer, unsigned int length) +{ + struct device *dev = this->dev; + struct resources *resources = &this->resources; + struct nfc_hal *nfc = this->nfc; + struct mxs_dma_desc **d = nfc->dma_descriptors; + int dma_channel; + int error = 0; + uint32_t command_mode; + uint32_t address; + + /* Compute the DMA channel. */ + + dma_channel = resources->dma_low_channel + chip; + + /* A DMA descriptor that reads the data. */ + + command_mode = BV_GPMI_CTRL0_COMMAND_MODE__READ; + address = BV_GPMI_CTRL0_ADDRESS__NAND_DATA; + + (*d)->cmd.cmd.data = 0; + (*d)->cmd.cmd.bits.command = DMA_WRITE; + (*d)->cmd.cmd.bits.chain = 1; + (*d)->cmd.cmd.bits.irq = 0; + (*d)->cmd.cmd.bits.nand_lock = 0; + (*d)->cmd.cmd.bits.nand_wait_4_ready = 0; + (*d)->cmd.cmd.bits.dec_sem = 1; + (*d)->cmd.cmd.bits.wait4end = 1; + (*d)->cmd.cmd.bits.halt_on_terminate = 0; + (*d)->cmd.cmd.bits.terminate_flush = 0; + (*d)->cmd.cmd.bits.pio_words = 1; + (*d)->cmd.cmd.bits.bytes = length; + + (*d)->cmd.address = buffer; + + (*d)->cmd.pio_words[0] = + BF_GPMI_CTRL0_COMMAND_MODE(command_mode) | + BM_GPMI_CTRL0_WORD_LENGTH | + BF_GPMI_CTRL0_CS(chip) | + BF_GPMI_CTRL0_ADDRESS(address) | + BF_GPMI_CTRL0_XFER_COUNT(length) ; + + mxs_dma_desc_append(dma_channel, (*d)); + d++; + + /* + * A DMA descriptor that waits for the command to end and the chip to + * become ready. + * + * I think we actually should *not* be waiting for the chip to become + * ready because, after all, we don't care. I think the original code + * did that and no one has re-thought it yet. + */ + + command_mode = BV_GPMI_CTRL0_COMMAND_MODE__WAIT_FOR_READY; + address = BV_GPMI_CTRL0_ADDRESS__NAND_DATA; + + (*d)->cmd.cmd.data = 0; + (*d)->cmd.cmd.bits.command = NO_DMA_XFER; + (*d)->cmd.cmd.bits.chain = 0; + (*d)->cmd.cmd.bits.irq = 1; + (*d)->cmd.cmd.bits.nand_lock = 0; + (*d)->cmd.cmd.bits.nand_wait_4_ready = 1; + (*d)->cmd.cmd.bits.dec_sem = 1; + (*d)->cmd.cmd.bits.wait4end = 1; + (*d)->cmd.cmd.bits.halt_on_terminate = 0; + (*d)->cmd.cmd.bits.terminate_flush = 0; + (*d)->cmd.cmd.bits.pio_words = 4; + (*d)->cmd.cmd.bits.bytes = 0; + + (*d)->cmd.address = 0; + + (*d)->cmd.pio_words[0] = + BF_GPMI_CTRL0_COMMAND_MODE(command_mode) | + BM_GPMI_CTRL0_WORD_LENGTH | + BF_GPMI_CTRL0_CS(chip) | + BF_GPMI_CTRL0_ADDRESS(address) | + BF_GPMI_CTRL0_XFER_COUNT(0) ; + (*d)->cmd.pio_words[1] = 0; + (*d)->cmd.pio_words[2] = 0; + (*d)->cmd.pio_words[3] = 0; + + mxs_dma_desc_append(dma_channel, (*d)); + d++; + + /* Go! */ + + error = gpmi_nfc_dma_go(this, dma_channel); + + if (error) + dev_err(dev, "[%s] DMA error\n", __func__); + + /* Return success. */ + + return error; + +} + +/** + * send_page() - Sends a page, using ECC. + * + * @this: Per-device data. + * @chip: The chip of interest. + * @payload: The physical address of the payload buffer. + * @auxiliary: The physical address of the auxiliary buffer. + */ +static int send_page(struct gpmi_nfc_data *this, unsigned chip, + dma_addr_t payload, dma_addr_t auxiliary) +{ + struct device *dev = this->dev; + struct resources *resources = &this->resources; + struct nfc_hal *nfc = this->nfc; + struct nfc_geometry *nfc_geo = &this->nfc_geometry; + struct mxs_dma_desc **d = nfc->dma_descriptors; + int dma_channel; + int error = 0; + uint32_t command_mode; + uint32_t address; + uint32_t ecc_command; + uint32_t buffer_mask; + + /* Compute the DMA channel. */ + + dma_channel = resources->dma_low_channel + chip; + + /* A DMA descriptor that does an ECC page read. */ + + command_mode = BV_GPMI_CTRL0_COMMAND_MODE__WRITE; + address = BV_GPMI_CTRL0_ADDRESS__NAND_DATA; + ecc_command = BV_GPMI_ECCCTRL_ECC_CMD__BCH_ENCODE; + buffer_mask = BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_PAGE | + BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_AUXONLY; + + (*d)->cmd.cmd.data = 0; + (*d)->cmd.cmd.bits.command = NO_DMA_XFER; + (*d)->cmd.cmd.bits.chain = 0; + (*d)->cmd.cmd.bits.irq = 1; + (*d)->cmd.cmd.bits.nand_lock = 0; + (*d)->cmd.cmd.bits.nand_wait_4_ready = 0; + (*d)->cmd.cmd.bits.dec_sem = 1; + (*d)->cmd.cmd.bits.wait4end = 1; + (*d)->cmd.cmd.bits.halt_on_terminate = 0; + (*d)->cmd.cmd.bits.terminate_flush = 0; + (*d)->cmd.cmd.bits.pio_words = 6; + (*d)->cmd.cmd.bits.bytes = 0; + + (*d)->cmd.address = 0; + + (*d)->cmd.pio_words[0] = + BF_GPMI_CTRL0_COMMAND_MODE(command_mode) | + BM_GPMI_CTRL0_WORD_LENGTH | + BF_GPMI_CTRL0_CS(chip) | + BF_GPMI_CTRL0_ADDRESS(address) | + BF_GPMI_CTRL0_XFER_COUNT(0) ; + + (*d)->cmd.pio_words[1] = 0; + + (*d)->cmd.pio_words[2] = + BM_GPMI_ECCCTRL_ENABLE_ECC | + BF_GPMI_ECCCTRL_ECC_CMD(ecc_command) | + BF_GPMI_ECCCTRL_BUFFER_MASK(buffer_mask) ; + + (*d)->cmd.pio_words[3] = nfc_geo->page_size_in_bytes; + (*d)->cmd.pio_words[4] = payload; + (*d)->cmd.pio_words[5] = auxiliary; + + mxs_dma_desc_append(dma_channel, (*d)); + d++; + + /* Prepare to receive an interrupt from the BCH block. */ + + init_completion(&nfc->bch_done); + + /* Go! */ + + error = gpmi_nfc_dma_go(this, dma_channel); + + if (error) + dev_err(dev, "[%s] DMA error\n", __func__); + + /* Wait for the interrupt from the BCH block. */ + + wait_for_completion(&nfc->bch_done); + + /* Return success. */ + + return error; + +} + +/** + * read_page() - Reads a page, using ECC. + * + * @this: Per-device data. + * @chip: The chip of interest. + * @payload: The physical address of the payload buffer. + * @auxiliary: The physical address of the auxiliary buffer. + */ +static int read_page(struct gpmi_nfc_data *this, unsigned chip, + dma_addr_t payload, dma_addr_t auxiliary) +{ + struct device *dev = this->dev; + struct resources *resources = &this->resources; + struct nfc_hal *nfc = this->nfc; + struct nfc_geometry *nfc_geo = &this->nfc_geometry; + struct mxs_dma_desc **d = nfc->dma_descriptors; + int dma_channel; + int error = 0; + uint32_t command_mode; + uint32_t address; + uint32_t ecc_command; + uint32_t buffer_mask; + + /* Compute the DMA channel. */ + + dma_channel = resources->dma_low_channel + chip; + + /* Wait for the chip to report ready. */ + + command_mode = BV_GPMI_CTRL0_COMMAND_MODE__WAIT_FOR_READY; + address = BV_GPMI_CTRL0_ADDRESS__NAND_DATA; + + (*d)->cmd.cmd.data = 0; + (*d)->cmd.cmd.bits.command = NO_DMA_XFER; + (*d)->cmd.cmd.bits.chain = 1; + (*d)->cmd.cmd.bits.irq = 0; + (*d)->cmd.cmd.bits.nand_lock = 0; + (*d)->cmd.cmd.bits.nand_wait_4_ready = 1; + (*d)->cmd.cmd.bits.dec_sem = 1; + (*d)->cmd.cmd.bits.wait4end = 1; + (*d)->cmd.cmd.bits.halt_on_terminate = 0; + (*d)->cmd.cmd.bits.terminate_flush = 0; + (*d)->cmd.cmd.bits.pio_words = 1; + (*d)->cmd.cmd.bits.bytes = 0; + + (*d)->cmd.address = 0; + + (*d)->cmd.pio_words[0] = + BF_GPMI_CTRL0_COMMAND_MODE(command_mode) | + BM_GPMI_CTRL0_WORD_LENGTH | + BF_GPMI_CTRL0_CS(chip) | + BF_GPMI_CTRL0_ADDRESS(address) | + BF_GPMI_CTRL0_XFER_COUNT(0) ; + + mxs_dma_desc_append(dma_channel, (*d)); + d++; + + /* Enable the BCH block and read. */ + + command_mode = BV_GPMI_CTRL0_COMMAND_MODE__READ; + address = BV_GPMI_CTRL0_ADDRESS__NAND_DATA; + ecc_command = BV_GPMI_ECCCTRL_ECC_CMD__BCH_DECODE; + buffer_mask = BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_PAGE | + BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_AUXONLY; + + (*d)->cmd.cmd.data = 0; + (*d)->cmd.cmd.bits.command = NO_DMA_XFER; + (*d)->cmd.cmd.bits.chain = 1; + (*d)->cmd.cmd.bits.irq = 0; + (*d)->cmd.cmd.bits.nand_lock = 0; + (*d)->cmd.cmd.bits.nand_wait_4_ready = 0; + (*d)->cmd.cmd.bits.dec_sem = 1; + (*d)->cmd.cmd.bits.wait4end = 1; + (*d)->cmd.cmd.bits.halt_on_terminate = 0; + (*d)->cmd.cmd.bits.terminate_flush = 0; + (*d)->cmd.cmd.bits.pio_words = 6; + (*d)->cmd.cmd.bits.bytes = 0; + + (*d)->cmd.address = 0; + + (*d)->cmd.pio_words[0] = + BF_GPMI_CTRL0_COMMAND_MODE(command_mode) | + BM_GPMI_CTRL0_WORD_LENGTH | + BF_GPMI_CTRL0_CS(chip) | + BF_GPMI_CTRL0_ADDRESS(address) | + BF_GPMI_CTRL0_XFER_COUNT(nfc_geo->page_size_in_bytes) ; + + (*d)->cmd.pio_words[1] = 0; + (*d)->cmd.pio_words[2] = + BM_GPMI_ECCCTRL_ENABLE_ECC | + BF_GPMI_ECCCTRL_ECC_CMD(ecc_command) | + BF_GPMI_ECCCTRL_BUFFER_MASK(buffer_mask) ; + (*d)->cmd.pio_words[3] = nfc_geo->page_size_in_bytes; + (*d)->cmd.pio_words[4] = payload; + (*d)->cmd.pio_words[5] = auxiliary; + + mxs_dma_desc_append(dma_channel, (*d)); + d++; + + /* Disable the BCH block */ + + command_mode = BV_GPMI_CTRL0_COMMAND_MODE__WAIT_FOR_READY; + address = BV_GPMI_CTRL0_ADDRESS__NAND_DATA; + + (*d)->cmd.cmd.data = 0; + (*d)->cmd.cmd.bits.command = NO_DMA_XFER; + (*d)->cmd.cmd.bits.chain = 1; + (*d)->cmd.cmd.bits.irq = 0; + (*d)->cmd.cmd.bits.nand_lock = 0; + (*d)->cmd.cmd.bits.nand_wait_4_ready = 1; + (*d)->cmd.cmd.bits.dec_sem = 1; + (*d)->cmd.cmd.bits.wait4end = 1; + (*d)->cmd.cmd.bits.halt_on_terminate = 0; + (*d)->cmd.cmd.bits.terminate_flush = 0; + (*d)->cmd.cmd.bits.pio_words = 3; + (*d)->cmd.cmd.bits.bytes = 0; + + (*d)->cmd.address = 0; + + (*d)->cmd.pio_words[0] = + BF_GPMI_CTRL0_COMMAND_MODE(command_mode) | + BM_GPMI_CTRL0_WORD_LENGTH | + BF_GPMI_CTRL0_CS(chip) | + BF_GPMI_CTRL0_ADDRESS(address) | + BF_GPMI_CTRL0_XFER_COUNT(nfc_geo->page_size_in_bytes) ; + + (*d)->cmd.pio_words[1] = 0; + (*d)->cmd.pio_words[2] = 0; + + mxs_dma_desc_append(dma_channel, (*d)); + d++; + + /* Deassert the NAND lock and interrupt. */ + + (*d)->cmd.cmd.data = 0; + (*d)->cmd.cmd.bits.command = NO_DMA_XFER; + (*d)->cmd.cmd.bits.chain = 0; + (*d)->cmd.cmd.bits.irq = 1; + (*d)->cmd.cmd.bits.nand_lock = 0; + (*d)->cmd.cmd.bits.nand_wait_4_ready = 0; + (*d)->cmd.cmd.bits.dec_sem = 1; + (*d)->cmd.cmd.bits.wait4end = 0; + (*d)->cmd.cmd.bits.halt_on_terminate = 0; + (*d)->cmd.cmd.bits.terminate_flush = 0; + (*d)->cmd.cmd.bits.pio_words = 0; + (*d)->cmd.cmd.bits.bytes = 0; + + (*d)->cmd.address = 0; + + mxs_dma_desc_append(dma_channel, (*d)); + d++; + + /* Prepare to receive an interrupt from the BCH block. */ + + init_completion(&nfc->bch_done); + + /* Go! */ + + error = gpmi_nfc_dma_go(this, dma_channel); + + if (error) + dev_err(dev, "[%s] DMA error\n", __func__); + + /* Wait for the interrupt from the BCH block. */ + + wait_for_completion(&nfc->bch_done); + + /* Return success. */ + + return error; + +} + +/* This structure represents the NFC HAL for this version of the hardware. */ + +struct nfc_hal gpmi_nfc_hal_v0 = { + .version = 0, + .description = "4-chip GPMI and BCH", + .max_chip_count = 4, + .max_data_setup_cycles = (BM_GPMI_TIMING0_DATA_SETUP >> + BP_GPMI_TIMING0_DATA_SETUP), + .internal_data_setup_in_ns = 0, + .max_sample_delay_factor = (BM_GPMI_CTRL1_RDN_DELAY >> + BP_GPMI_CTRL1_RDN_DELAY), + .max_dll_clock_period_in_ns = 32, + .max_dll_delay_in_ns = 16, + .init = init, + .set_geometry = set_geometry, + .set_timing = set_timing, + .get_timing = get_timing, + .exit = exit, + .begin = begin, + .end = end, + .clear_bch = clear_bch, + .is_ready = is_ready, + .send_command = send_command, + .send_data = send_data, + .read_data = read_data, + .send_page = send_page, + .read_page = read_page, +}; diff --git a/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-hal-v1.c b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-hal-v1.c new file mode 100644 index 000000000000..962efe686853 --- /dev/null +++ b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-hal-v1.c @@ -0,0 +1,866 @@ +/* + * Freescale GPMI NFC NAND Flash Driver + * + * Copyright (C) 2010 Freescale Semiconductor, Inc. + * Copyright (C) 2008 Embedded Alley Solutions, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "gpmi-nfc.h" + +#include "gpmi-nfc-gpmi-regs-v1.h" +#include "gpmi-nfc-bch-regs-v1.h" + +/** + * init() - Initializes the NFC hardware. + * + * @this: Per-device data. + */ +static int init(struct gpmi_nfc_data *this) +{ + struct resources *resources = &this->resources; + int error; + + /* Initialize DMA. */ + + error = gpmi_nfc_dma_init(this); + + if (error) + return error; + + /* Enable the clock. */ + + clk_enable(resources->clock); + + /* Reset the GPMI block. */ + + mxs_reset_block(resources->gpmi_regs + HW_GPMI_CTRL0, true); + + /* Choose NAND mode. */ + __raw_writel(BM_GPMI_CTRL1_GPMI_MODE, + resources->gpmi_regs + HW_GPMI_CTRL1_CLR); + + /* Set the IRQ polarity. */ + __raw_writel(BM_GPMI_CTRL1_ATA_IRQRDY_POLARITY, + resources->gpmi_regs + HW_GPMI_CTRL1_SET); + + /* Disable write protection. */ + __raw_writel(BM_GPMI_CTRL1_DEV_RESET, + resources->gpmi_regs + HW_GPMI_CTRL1_SET); + + /* Select BCH ECC. */ + __raw_writel(BM_GPMI_CTRL1_BCH_MODE, + resources->gpmi_regs + HW_GPMI_CTRL1_SET); + + /* Disable the clock. */ + + clk_disable(resources->clock); + + /* If control arrives here, all is well. */ + + return 0; + +} + +/** + * set_geometry() - Configures the NFC geometry. + * + * @this: Per-device data. + */ +static int set_geometry(struct gpmi_nfc_data *this) +{ + struct resources *resources = &this->resources; + struct nfc_geometry *nfc = &this->nfc_geometry; + unsigned int block_count; + unsigned int block_size; + unsigned int metadata_size; + unsigned int ecc_strength; + unsigned int page_size; + + /* We make the abstract choices in a common function. */ + + if (gpmi_nfc_set_geometry(this)) + return !0; + + /* Translate the abstract choices into register fields. */ + + block_count = nfc->ecc_chunk_count - 1; + block_size = nfc->ecc_chunk_size_in_bytes; + metadata_size = nfc->metadata_size_in_bytes; + ecc_strength = nfc->ecc_strength >> 1; + page_size = nfc->page_size_in_bytes; + + /* Enable the clock. */ + + clk_enable(resources->clock); + + /* + * Reset the BCH block. Notice that we pass in true for the just_enable + * flag. This is because the soft reset for the version 0 BCH block + * doesn't work and the version 1 BCH block is similar enough that we + * suspect the same (though this has not been officially tested). If you + * try to soft reset a version 0 BCH block, it becomes unusable until + * the next hard reset. + */ + + mxs_reset_block(resources->bch_regs, true); + + /* Configure layout 0. */ + + __raw_writel( + BF_BCH_FLASH0LAYOUT0_NBLOCKS(block_count) | + BF_BCH_FLASH0LAYOUT0_META_SIZE(metadata_size) | + BF_BCH_FLASH0LAYOUT0_ECC0(ecc_strength) | + BF_BCH_FLASH0LAYOUT0_DATA0_SIZE(block_size) , + resources->bch_regs + HW_BCH_FLASH0LAYOUT0); + + __raw_writel( + BF_BCH_FLASH0LAYOUT1_PAGE_SIZE(page_size) | + BF_BCH_FLASH0LAYOUT1_ECCN(ecc_strength) | + BF_BCH_FLASH0LAYOUT1_DATAN_SIZE(block_size) , + resources->bch_regs + HW_BCH_FLASH0LAYOUT1); + + /* Set *all* chip selects to use layout 0. */ + + __raw_writel(0, resources->bch_regs + HW_BCH_LAYOUTSELECT); + + /* Enable interrupts. */ + + __raw_writel(BM_BCH_CTRL_COMPLETE_IRQ_EN, + resources->bch_regs + HW_BCH_CTRL_SET); + + /* Disable the clock. */ + + clk_disable(resources->clock); + + /* Return success. */ + + return 0; + +} + +/** + * set_timing() - Configures the NFC timing. + * + * @this: Per-device data. + * @timing: The timing of interest. + */ +static int set_timing(struct gpmi_nfc_data *this, + const struct gpmi_nfc_timing *timing) +{ + struct nfc_hal *nfc = this->nfc; + + /* Accept the new timing. */ + + nfc->timing = *timing; + + /* Return success. */ + + return 0; + +} + +/** + * get_timing() - Retrieves the NFC hardware timing. + * + * @this: Per-device data. + * @clock_frequency_in_hz: The clock frequency, in Hz, during the current + * I/O transaction. If no I/O transaction is in + * progress, this is the clock frequency during the + * most recent I/O transaction. + * @hardware_timing: The hardware timing configuration in effect during + * the current I/O transaction. If no I/O transaction + * is in progress, this is the hardware timing + * configuration during the most recent I/O + * transaction. + */ +static void get_timing(struct gpmi_nfc_data *this, + unsigned long *clock_frequency_in_hz, + struct gpmi_nfc_hardware_timing *hardware_timing) +{ + struct resources *resources = &this->resources; + struct nfc_hal *nfc = this->nfc; + unsigned char *gpmi_regs = resources->gpmi_regs; + uint32_t register_image; + + /* Return the clock frequency. */ + + *clock_frequency_in_hz = nfc->clock_frequency_in_hz; + + /* We'll be reading the hardware, so let's enable the clock. */ + + clk_enable(resources->clock); + + /* Retrieve the hardware timing. */ + + register_image = __raw_readl(gpmi_regs + HW_GPMI_TIMING0); + + hardware_timing->data_setup_in_cycles = + (register_image & BM_GPMI_TIMING0_DATA_SETUP) >> + BP_GPMI_TIMING0_DATA_SETUP; + + hardware_timing->data_hold_in_cycles = + (register_image & BM_GPMI_TIMING0_DATA_HOLD) >> + BP_GPMI_TIMING0_DATA_HOLD; + + hardware_timing->address_setup_in_cycles = + (register_image & BM_GPMI_TIMING0_ADDRESS_SETUP) >> + BP_GPMI_TIMING0_ADDRESS_SETUP; + + register_image = __raw_readl(gpmi_regs + HW_GPMI_CTRL1); + + hardware_timing->use_half_periods = + (register_image & BM_GPMI_CTRL1_HALF_PERIOD) >> + BP_GPMI_CTRL1_HALF_PERIOD; + + hardware_timing->sample_delay_factor = + (register_image & BM_GPMI_CTRL1_RDN_DELAY) >> + BP_GPMI_CTRL1_RDN_DELAY; + + /* We're done reading the hardware, so disable the clock. */ + + clk_disable(resources->clock); + +} + +/** + * exit() - Shuts down the NFC hardware. + * + * @this: Per-device data. + */ +static void exit(struct gpmi_nfc_data *this) +{ + gpmi_nfc_dma_exit(this); +} + +/** + * begin() - Begin NFC I/O. + * + * @this: Per-device data. + */ +static void begin(struct gpmi_nfc_data *this) +{ + struct resources *resources = &this->resources; + struct nfc_hal *nfc = this->nfc; + struct gpmi_nfc_hardware_timing hw; + + /* Enable the clock. */ + + clk_enable(resources->clock); + + /* Get the timing information we need. */ + + nfc->clock_frequency_in_hz = clk_get_rate(resources->clock); + gpmi_nfc_compute_hardware_timing(this, &hw); + + /* Apply the hardware timing. */ + + /* Coming soon - the clock handling code isn't ready yet. */ + +} + +/** + * end() - End NFC I/O. + * + * @this: Per-device data. + */ +static void end(struct gpmi_nfc_data *this) +{ + struct resources *resources = &this->resources; + + /* Disable the clock. */ + + clk_disable(resources->clock); + +} + +/** + * clear_bch() - Clears a BCH interrupt. + * + * @this: Per-device data. + */ +static void clear_bch(struct gpmi_nfc_data *this) +{ + struct resources *resources = &this->resources; + + __raw_writel(BM_BCH_CTRL_COMPLETE_IRQ, + resources->bch_regs + HW_BCH_CTRL_CLR); + +} + +/** + * is_ready() - Returns the ready/busy status of the given chip. + * + * @this: Per-device data. + * @chip: The chip of interest. + */ +static int is_ready(struct gpmi_nfc_data *this, unsigned chip) +{ + struct resources *resources = &this->resources; + uint32_t mask; + uint32_t register_image; + + /* Extract and return the status. */ + + mask = BF_GPMI_STAT_READY_BUSY(1 << chip); + + register_image = __raw_readl(resources->gpmi_regs + HW_GPMI_STAT); + + return !!(register_image & mask); + +} + +/** + * send_command() - Sends a command and associated addresses. + * + * @this: Per-device data. + * @chip: The chip of interest. + * @buffer: The physical address of a buffer that contains the command bytes. + * @length: The number of bytes in the buffer. + */ +static int send_command(struct gpmi_nfc_data *this, unsigned chip, + dma_addr_t buffer, unsigned int length) +{ + struct device *dev = this->dev; + struct resources *resources = &this->resources; + struct nfc_hal *nfc = this->nfc; + struct mxs_dma_desc **d = nfc->dma_descriptors; + int dma_channel; + int error; + uint32_t command_mode; + uint32_t address; + + /* Compute the DMA channel. */ + + dma_channel = resources->dma_low_channel + chip; + + /* A DMA descriptor that sends out the command. */ + + command_mode = BV_GPMI_CTRL0_COMMAND_MODE__WRITE; + address = BV_GPMI_CTRL0_ADDRESS__NAND_CLE; + + (*d)->cmd.cmd.data = 0; + (*d)->cmd.cmd.bits.command = DMA_READ; + (*d)->cmd.cmd.bits.chain = 1; + (*d)->cmd.cmd.bits.irq = 1; + (*d)->cmd.cmd.bits.nand_lock = 0; + (*d)->cmd.cmd.bits.nand_wait_4_ready = 0; + (*d)->cmd.cmd.bits.dec_sem = 1; + (*d)->cmd.cmd.bits.wait4end = 1; + (*d)->cmd.cmd.bits.halt_on_terminate = 0; + (*d)->cmd.cmd.bits.terminate_flush = 0; + (*d)->cmd.cmd.bits.pio_words = 3; + (*d)->cmd.cmd.bits.bytes = length; + + (*d)->cmd.address = buffer; + + (*d)->cmd.pio_words[0] = + BF_GPMI_CTRL0_COMMAND_MODE(command_mode) | + BM_GPMI_CTRL0_WORD_LENGTH | + BF_GPMI_CTRL0_CS(chip) | + BF_GPMI_CTRL0_ADDRESS(address) | + BM_GPMI_CTRL0_ADDRESS_INCREMENT | + BF_GPMI_CTRL0_XFER_COUNT(length) ; + + (*d)->cmd.pio_words[1] = 0; + (*d)->cmd.pio_words[2] = 0; + + mxs_dma_desc_append(dma_channel, (*d)); + d++; + + /* Go! */ + + error = gpmi_nfc_dma_go(this, dma_channel); + + if (error) + dev_err(dev, "[%s] DMA error\n", __func__); + + /* Return success. */ + + return error; + +} + +/** + * send_data() - Sends data to the given chip. + * + * @this: Per-device data. + * @chip: The chip of interest. + * @buffer: The physical address of a buffer that contains the data. + * @length: The number of bytes in the buffer. + */ +static int send_data(struct gpmi_nfc_data *this, unsigned chip, + dma_addr_t buffer, unsigned int length) +{ + struct device *dev = this->dev; + struct resources *resources = &this->resources; + struct nfc_hal *nfc = this->nfc; + struct mxs_dma_desc **d = nfc->dma_descriptors; + int dma_channel; + int error = 0; + uint32_t command_mode; + uint32_t address; + + /* Compute the DMA channel. */ + + dma_channel = resources->dma_low_channel + chip; + + /* A DMA descriptor that writes a buffer out. */ + + command_mode = BV_GPMI_CTRL0_COMMAND_MODE__WRITE; + address = BV_GPMI_CTRL0_ADDRESS__NAND_DATA; + + (*d)->cmd.cmd.data = 0; + (*d)->cmd.cmd.bits.command = DMA_READ; + (*d)->cmd.cmd.bits.chain = 0; + (*d)->cmd.cmd.bits.irq = 1; + (*d)->cmd.cmd.bits.nand_lock = 0; + (*d)->cmd.cmd.bits.nand_wait_4_ready = 0; + (*d)->cmd.cmd.bits.dec_sem = 1; + (*d)->cmd.cmd.bits.wait4end = 1; + (*d)->cmd.cmd.bits.halt_on_terminate = 0; + (*d)->cmd.cmd.bits.terminate_flush = 0; + (*d)->cmd.cmd.bits.pio_words = 4; + (*d)->cmd.cmd.bits.bytes = length; + + (*d)->cmd.address = buffer; + + (*d)->cmd.pio_words[0] = + BF_GPMI_CTRL0_COMMAND_MODE(command_mode) | + BM_GPMI_CTRL0_WORD_LENGTH | + BF_GPMI_CTRL0_CS(chip) | + BF_GPMI_CTRL0_ADDRESS(address) | + BF_GPMI_CTRL0_XFER_COUNT(length) ; + (*d)->cmd.pio_words[1] = 0; + (*d)->cmd.pio_words[2] = 0; + (*d)->cmd.pio_words[3] = 0; + + mxs_dma_desc_append(dma_channel, (*d)); + d++; + + /* Go! */ + + error = gpmi_nfc_dma_go(this, dma_channel); + + if (error) + dev_err(dev, "[%s] DMA error\n", __func__); + + /* Return success. */ + + return error; + +} + +/** + * read_data() - Receives data from the given chip. + * + * @this: Per-device data. + * @chip: The chip of interest. + * @buffer: The physical address of a buffer that will receive the data. + * @length: The number of bytes to read. + */ +static int read_data(struct gpmi_nfc_data *this, unsigned chip, + dma_addr_t buffer, unsigned int length) +{ + struct device *dev = this->dev; + struct resources *resources = &this->resources; + struct nfc_hal *nfc = this->nfc; + struct mxs_dma_desc **d = nfc->dma_descriptors; + int dma_channel; + int error = 0; + uint32_t command_mode; + uint32_t address; + + /* Compute the DMA channel. */ + + dma_channel = resources->dma_low_channel + chip; + + /* A DMA descriptor that reads the data. */ + + command_mode = BV_GPMI_CTRL0_COMMAND_MODE__READ; + address = BV_GPMI_CTRL0_ADDRESS__NAND_DATA; + + (*d)->cmd.cmd.data = 0; + (*d)->cmd.cmd.bits.command = DMA_WRITE; + (*d)->cmd.cmd.bits.chain = 1; + (*d)->cmd.cmd.bits.irq = 0; + (*d)->cmd.cmd.bits.nand_lock = 0; + (*d)->cmd.cmd.bits.nand_wait_4_ready = 0; + (*d)->cmd.cmd.bits.dec_sem = 1; + (*d)->cmd.cmd.bits.wait4end = 1; + (*d)->cmd.cmd.bits.halt_on_terminate = 0; + (*d)->cmd.cmd.bits.terminate_flush = 0; + (*d)->cmd.cmd.bits.pio_words = 1; + (*d)->cmd.cmd.bits.bytes = length; + + (*d)->cmd.address = buffer; + + (*d)->cmd.pio_words[0] = + BF_GPMI_CTRL0_COMMAND_MODE(command_mode) | + BM_GPMI_CTRL0_WORD_LENGTH | + BF_GPMI_CTRL0_CS(chip) | + BF_GPMI_CTRL0_ADDRESS(address) | + BF_GPMI_CTRL0_XFER_COUNT(length) ; + + mxs_dma_desc_append(dma_channel, (*d)); + d++; + + /* + * A DMA descriptor that waits for the command to end and the chip to + * become ready. + * + * I think we actually should *not* be waiting for the chip to become + * ready because, after all, we don't care. I think the original code + * did that and no one has re-thought it yet. + */ + + command_mode = BV_GPMI_CTRL0_COMMAND_MODE__WAIT_FOR_READY; + address = BV_GPMI_CTRL0_ADDRESS__NAND_DATA; + + (*d)->cmd.cmd.data = 0; + (*d)->cmd.cmd.bits.command = NO_DMA_XFER; + (*d)->cmd.cmd.bits.chain = 0; + (*d)->cmd.cmd.bits.irq = 1; + (*d)->cmd.cmd.bits.nand_lock = 0; + (*d)->cmd.cmd.bits.nand_wait_4_ready = 1; + (*d)->cmd.cmd.bits.dec_sem = 1; + (*d)->cmd.cmd.bits.wait4end = 1; + (*d)->cmd.cmd.bits.halt_on_terminate = 0; + (*d)->cmd.cmd.bits.terminate_flush = 0; + (*d)->cmd.cmd.bits.pio_words = 4; + (*d)->cmd.cmd.bits.bytes = 0; + + (*d)->cmd.address = 0; + + (*d)->cmd.pio_words[0] = + BF_GPMI_CTRL0_COMMAND_MODE(command_mode) | + BM_GPMI_CTRL0_WORD_LENGTH | + BF_GPMI_CTRL0_CS(chip) | + BF_GPMI_CTRL0_ADDRESS(address) | + BF_GPMI_CTRL0_XFER_COUNT(0) ; + (*d)->cmd.pio_words[1] = 0; + (*d)->cmd.pio_words[2] = 0; + (*d)->cmd.pio_words[3] = 0; + + mxs_dma_desc_append(dma_channel, (*d)); + d++; + + /* Go! */ + + error = gpmi_nfc_dma_go(this, dma_channel); + + if (error) + dev_err(dev, "[%s] DMA error\n", __func__); + + /* Return success. */ + + return error; + +} + +/** + * send_page() - Sends a page, using ECC. + * + * @this: Per-device data. + * @chip: The chip of interest. + * @payload: The physical address of the payload buffer. + * @auxiliary: The physical address of the auxiliary buffer. + */ +static int send_page(struct gpmi_nfc_data *this, unsigned chip, + dma_addr_t payload, dma_addr_t auxiliary) +{ + struct device *dev = this->dev; + struct resources *resources = &this->resources; + struct nfc_hal *nfc = this->nfc; + struct nfc_geometry *nfc_geo = &this->nfc_geometry; + struct mxs_dma_desc **d = nfc->dma_descriptors; + int dma_channel; + int error = 0; + uint32_t command_mode; + uint32_t address; + uint32_t ecc_command; + uint32_t buffer_mask; + + /* Compute the DMA channel. */ + + dma_channel = resources->dma_low_channel + chip; + + /* A DMA descriptor that does an ECC page read. */ + + command_mode = BV_GPMI_CTRL0_COMMAND_MODE__WRITE; + address = BV_GPMI_CTRL0_ADDRESS__NAND_DATA; + ecc_command = BV_GPMI_ECCCTRL_ECC_CMD__ENCODE; + buffer_mask = BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_PAGE | + BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_AUXONLY; + + (*d)->cmd.cmd.data = 0; + (*d)->cmd.cmd.bits.command = NO_DMA_XFER; + (*d)->cmd.cmd.bits.chain = 0; + (*d)->cmd.cmd.bits.irq = 1; + (*d)->cmd.cmd.bits.nand_lock = 0; + (*d)->cmd.cmd.bits.nand_wait_4_ready = 0; + (*d)->cmd.cmd.bits.dec_sem = 1; + (*d)->cmd.cmd.bits.wait4end = 1; + (*d)->cmd.cmd.bits.halt_on_terminate = 0; + (*d)->cmd.cmd.bits.terminate_flush = 0; + (*d)->cmd.cmd.bits.pio_words = 6; + (*d)->cmd.cmd.bits.bytes = 0; + + (*d)->cmd.address = 0; + + (*d)->cmd.pio_words[0] = + BF_GPMI_CTRL0_COMMAND_MODE(command_mode) | + BM_GPMI_CTRL0_WORD_LENGTH | + BF_GPMI_CTRL0_CS(chip) | + BF_GPMI_CTRL0_ADDRESS(address) | + BF_GPMI_CTRL0_XFER_COUNT(0) ; + + (*d)->cmd.pio_words[1] = 0; + + (*d)->cmd.pio_words[2] = + BM_GPMI_ECCCTRL_ENABLE_ECC | + BF_GPMI_ECCCTRL_ECC_CMD(ecc_command) | + BF_GPMI_ECCCTRL_BUFFER_MASK(buffer_mask) ; + + (*d)->cmd.pio_words[3] = nfc_geo->page_size_in_bytes; + (*d)->cmd.pio_words[4] = payload; + (*d)->cmd.pio_words[5] = auxiliary; + + mxs_dma_desc_append(dma_channel, (*d)); + d++; + + /* Prepare to receive an interrupt from the BCH block. */ + + init_completion(&nfc->bch_done); + + /* Go! */ + + error = gpmi_nfc_dma_go(this, dma_channel); + + if (error) + dev_err(dev, "[%s] DMA error\n", __func__); + + /* Wait for the interrupt from the BCH block. */ + + wait_for_completion(&nfc->bch_done); + + /* Return success. */ + + return error; + +} + +/** + * read_page() - Reads a page, using ECC. + * + * @this: Per-device data. + * @chip: The chip of interest. + * @payload: The physical address of the payload buffer. + * @auxiliary: The physical address of the auxiliary buffer. + */ +static int read_page(struct gpmi_nfc_data *this, unsigned chip, + dma_addr_t payload, dma_addr_t auxiliary) +{ + struct device *dev = this->dev; + struct resources *resources = &this->resources; + struct nfc_hal *nfc = this->nfc; + struct nfc_geometry *nfc_geo = &this->nfc_geometry; + struct mxs_dma_desc **d = nfc->dma_descriptors; + int dma_channel; + int error = 0; + uint32_t command_mode; + uint32_t address; + uint32_t ecc_command; + uint32_t buffer_mask; + + /* Compute the DMA channel. */ + + dma_channel = resources->dma_low_channel + chip; + + /* Wait for the chip to report ready. */ + + command_mode = BV_GPMI_CTRL0_COMMAND_MODE__WAIT_FOR_READY; + address = BV_GPMI_CTRL0_ADDRESS__NAND_DATA; + + (*d)->cmd.cmd.data = 0; + (*d)->cmd.cmd.bits.command = NO_DMA_XFER; + (*d)->cmd.cmd.bits.chain = 1; + (*d)->cmd.cmd.bits.irq = 0; + (*d)->cmd.cmd.bits.nand_lock = 0; + (*d)->cmd.cmd.bits.nand_wait_4_ready = 1; + (*d)->cmd.cmd.bits.dec_sem = 1; + (*d)->cmd.cmd.bits.wait4end = 1; + (*d)->cmd.cmd.bits.halt_on_terminate = 0; + (*d)->cmd.cmd.bits.terminate_flush = 0; + (*d)->cmd.cmd.bits.pio_words = 1; + (*d)->cmd.cmd.bits.bytes = 0; + + (*d)->cmd.address = 0; + + (*d)->cmd.pio_words[0] = + BF_GPMI_CTRL0_COMMAND_MODE(command_mode) | + BM_GPMI_CTRL0_WORD_LENGTH | + BF_GPMI_CTRL0_CS(chip) | + BF_GPMI_CTRL0_ADDRESS(address) | + BF_GPMI_CTRL0_XFER_COUNT(0) ; + + mxs_dma_desc_append(dma_channel, (*d)); + d++; + + /* Enable the BCH block and read. */ + + command_mode = BV_GPMI_CTRL0_COMMAND_MODE__READ; + address = BV_GPMI_CTRL0_ADDRESS__NAND_DATA; + ecc_command = BV_GPMI_ECCCTRL_ECC_CMD__DECODE; + buffer_mask = BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_PAGE | + BV_GPMI_ECCCTRL_BUFFER_MASK__BCH_AUXONLY; + + (*d)->cmd.cmd.data = 0; + (*d)->cmd.cmd.bits.command = NO_DMA_XFER; + (*d)->cmd.cmd.bits.chain = 1; + (*d)->cmd.cmd.bits.irq = 0; + (*d)->cmd.cmd.bits.nand_lock = 0; + (*d)->cmd.cmd.bits.nand_wait_4_ready = 0; + (*d)->cmd.cmd.bits.dec_sem = 1; + (*d)->cmd.cmd.bits.wait4end = 1; + (*d)->cmd.cmd.bits.halt_on_terminate = 0; + (*d)->cmd.cmd.bits.terminate_flush = 0; + (*d)->cmd.cmd.bits.pio_words = 6; + (*d)->cmd.cmd.bits.bytes = 0; + + (*d)->cmd.address = 0; + + (*d)->cmd.pio_words[0] = + BF_GPMI_CTRL0_COMMAND_MODE(command_mode) | + BM_GPMI_CTRL0_WORD_LENGTH | + BF_GPMI_CTRL0_CS(chip) | + BF_GPMI_CTRL0_ADDRESS(address) | + BF_GPMI_CTRL0_XFER_COUNT(nfc_geo->page_size_in_bytes) ; + + (*d)->cmd.pio_words[1] = 0; + (*d)->cmd.pio_words[2] = + BM_GPMI_ECCCTRL_ENABLE_ECC | + BF_GPMI_ECCCTRL_ECC_CMD(ecc_command) | + BF_GPMI_ECCCTRL_BUFFER_MASK(buffer_mask) ; + (*d)->cmd.pio_words[3] = nfc_geo->page_size_in_bytes; + (*d)->cmd.pio_words[4] = payload; + (*d)->cmd.pio_words[5] = auxiliary; + + mxs_dma_desc_append(dma_channel, (*d)); + d++; + + /* Disable the BCH block */ + + command_mode = BV_GPMI_CTRL0_COMMAND_MODE__WAIT_FOR_READY; + address = BV_GPMI_CTRL0_ADDRESS__NAND_DATA; + + (*d)->cmd.cmd.data = 0; + (*d)->cmd.cmd.bits.command = NO_DMA_XFER; + (*d)->cmd.cmd.bits.chain = 1; + (*d)->cmd.cmd.bits.irq = 0; + (*d)->cmd.cmd.bits.nand_lock = 0; + (*d)->cmd.cmd.bits.nand_wait_4_ready = 1; + (*d)->cmd.cmd.bits.dec_sem = 1; + (*d)->cmd.cmd.bits.wait4end = 1; + (*d)->cmd.cmd.bits.halt_on_terminate = 0; + (*d)->cmd.cmd.bits.terminate_flush = 0; + (*d)->cmd.cmd.bits.pio_words = 3; + (*d)->cmd.cmd.bits.bytes = 0; + + (*d)->cmd.address = 0; + + (*d)->cmd.pio_words[0] = + BF_GPMI_CTRL0_COMMAND_MODE(command_mode) | + BM_GPMI_CTRL0_WORD_LENGTH | + BF_GPMI_CTRL0_CS(chip) | + BF_GPMI_CTRL0_ADDRESS(address) | + BF_GPMI_CTRL0_XFER_COUNT(nfc_geo->page_size_in_bytes) ; + + (*d)->cmd.pio_words[1] = 0; + (*d)->cmd.pio_words[2] = 0; + + mxs_dma_desc_append(dma_channel, (*d)); + d++; + + /* Deassert the NAND lock and interrupt. */ + + (*d)->cmd.cmd.data = 0; + (*d)->cmd.cmd.bits.command = NO_DMA_XFER; + (*d)->cmd.cmd.bits.chain = 0; + (*d)->cmd.cmd.bits.irq = 1; + (*d)->cmd.cmd.bits.nand_lock = 0; + (*d)->cmd.cmd.bits.nand_wait_4_ready = 0; + (*d)->cmd.cmd.bits.dec_sem = 1; + (*d)->cmd.cmd.bits.wait4end = 0; + (*d)->cmd.cmd.bits.halt_on_terminate = 0; + (*d)->cmd.cmd.bits.terminate_flush = 0; + (*d)->cmd.cmd.bits.pio_words = 0; + (*d)->cmd.cmd.bits.bytes = 0; + + (*d)->cmd.address = 0; + + mxs_dma_desc_append(dma_channel, (*d)); + d++; + + /* Prepare to receive an interrupt from the BCH block. */ + + init_completion(&nfc->bch_done); + + /* Go! */ + + error = gpmi_nfc_dma_go(this, dma_channel); + + if (error) + dev_err(dev, "[%s] DMA error\n", __func__); + + /* Wait for the interrupt from the BCH block. */ + + wait_for_completion(&nfc->bch_done); + + /* Return success. */ + + return error; + +} + +/* This structure represents the NFC HAL for this version of the hardware. */ + +struct nfc_hal gpmi_nfc_hal_v1 = { + .version = 1, + .description = "8-chip GPMI and BCH", + .max_chip_count = 8, + .max_data_setup_cycles = (BM_GPMI_TIMING0_DATA_SETUP >> + BP_GPMI_TIMING0_DATA_SETUP), + .internal_data_setup_in_ns = 0, + .max_sample_delay_factor = (BM_GPMI_CTRL1_RDN_DELAY >> + BP_GPMI_CTRL1_RDN_DELAY), + .max_dll_clock_period_in_ns = 32, + .max_dll_delay_in_ns = 16, + .init = init, + .set_geometry = set_geometry, + .set_timing = set_timing, + .get_timing = get_timing, + .exit = exit, + .begin = begin, + .end = end, + .clear_bch = clear_bch, + .is_ready = is_ready, + .send_command = send_command, + .send_data = send_data, + .read_data = read_data, + .send_page = send_page, + .read_page = read_page, +}; diff --git a/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-main.c b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-main.c new file mode 100644 index 000000000000..1400deb58e52 --- /dev/null +++ b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-main.c @@ -0,0 +1,1880 @@ +/* + * Freescale GPMI NFC NAND Flash Driver + * + * Copyright (C) 2010 Freescale Semiconductor, Inc. + * Copyright (C) 2008 Embedded Alley Solutions, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include +#include "gpmi-nfc.h" + +/* + * This structure contains the "safe" GPMI timing that should succeed with any + * NAND Flash device (although, with less-than-optimal performance). + */ + +static struct gpmi_nfc_timing safe_timing = { + .data_setup_in_ns = 80, + .data_hold_in_ns = 60, + .address_setup_in_ns = 25, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, +}; + +/* + * This array has a pointer to every NFC HAL structure. The probing process will + * find and install the one that matches the version given by the platform. + */ + +static struct nfc_hal *(nfc_hals[]) = { + &gpmi_nfc_hal_v0, + &gpmi_nfc_hal_v1, +}; + +/* + * This array has a pointer to every Boot ROM Helper structure. The probing + * process will find and install the one that matches the version given by the + * platform. + */ + +static struct boot_rom_helper *(boot_rom_helpers[]) = { + &gpmi_nfc_boot_rom_helper_v0, + &gpmi_nfc_boot_rom_helper_v1, +}; + +/** + * show_device_report() - Contains a shell script that creates a handy report. + * + * @d: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer that will receive a representation of the attribute. + */ +static ssize_t show_device_report(struct device *dev, + struct device_attribute *attr, char *buf) +{ + + static const char *script = + "GPMISysDirectory=/sys/bus/platform/devices/gpmi-nfc.0\n" + "\n" + "NodeList='\n" + "physical_geometry\n" + "nfc_info\n" + "nfc_geometry\n" + "timing\n" + "timing_diagram\n" + "rom_geometry\n" + "mtd_nand_info\n" + "mtd_info\n" + "'\n" + "\n" + "cd ${GPMISysDirectory}\n" + "\n" + "printf '\\n'\n" + "\n" + "for NodeName in ${NodeList}\n" + "do\n" + "\n" + " printf '--------------------------------------------\\n'\n" + " printf '%s\\n' ${NodeName}\n" + " printf '--------------------------------------------\\n'\n" + " printf '\\n'\n" + "\n" + " cat ${NodeName}\n" + "\n" + " printf '\\n'\n" + "\n" + "done\n" + ; + + return sprintf(buf, "%s", script); + +} + +/** + * show_device_numchips() - Shows the number of physical chips. + * + * This node is made obsolete by the physical_geometry node, but we keep it for + * backward compatibility (especially for kobs). + * + * @d: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer that will receive a representation of the attribute. + */ +static ssize_t show_device_numchips(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct gpmi_nfc_data *this = dev_get_drvdata(dev); + struct physical_geometry *physical = &this->physical_geometry; + + return sprintf(buf, "%d\n", physical->chip_count); + +} + +/** + * show_device_physical_geometry() - Shows the physical Flash device geometry. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer that will receive a representation of the attribute. + */ +static ssize_t show_device_physical_geometry(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct gpmi_nfc_data *this = dev_get_drvdata(dev); + struct nand_device_info *info = &this->device_info; + struct physical_geometry *physical = &this->physical_geometry; + + return sprintf(buf, + "Description : %s\n" + "Chip Count : %u\n" + "Chip Size in Bytes : %llu\n" + "Block Size in Bytes : %u\n" + "Page Data Size in Bytes: %u\n" + "Page OOB Size in Bytes : %u\n" + , + info->description, + physical->chip_count, + physical->chip_size_in_bytes, + physical->block_size_in_bytes, + physical->page_data_size_in_bytes, + physical->page_oob_size_in_bytes + ); + +} + +/** + * show_device_nfc_info() - Shows the NFC-specific information. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer that will receive a representation of the attribute. + */ +static ssize_t show_device_nfc_info(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct gpmi_nfc_data *this = dev_get_drvdata(dev); + struct nfc_hal *nfc = this->nfc; + + return sprintf(buf, + "Version : %u\n" + "Description : %s\n" + "Max Chip Count : %u\n" + "Max Data Setup Cycles : 0x%x\n" + "Internal Data Setup in ns : %u\n" + "Max Sample Delay Factor : 0x%x\n" + "Max DLL Clock Period in ns: %u\n" + "Max DLL Delay in ns : %u\n" + , + nfc->version, + nfc->description, + nfc->max_chip_count, + nfc->max_data_setup_cycles, + nfc->internal_data_setup_in_ns, + nfc->max_sample_delay_factor, + nfc->max_dll_clock_period_in_ns, + nfc->max_dll_delay_in_ns + ); + +} + +/** + * show_device_nfc_geometry() - Shows the NFC view of the device geometry. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer that will receive a representation of the attribute. + */ +static ssize_t show_device_nfc_geometry(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct gpmi_nfc_data *this = dev_get_drvdata(dev); + struct nfc_geometry *nfc = &this->nfc_geometry; + + return sprintf(buf, + "ECC Algorithm : %s\n" + "ECC Strength : %u\n" + "Page Size in Bytes : %u\n" + "Metadata Size in Bytes : %u\n" + "ECC Chunk Size in Bytes: %u\n" + "ECC Chunk Count : %u\n" + "Payload Size in Bytes : %u\n" + "Auxiliary Size in Bytes: %u\n" + "Auxiliary Status Offset: %u\n" + "Block Mark Byte Offset : %u\n" + "Block Mark Bit Offset : %u\n" + , + nfc->ecc_algorithm, + nfc->ecc_strength, + nfc->page_size_in_bytes, + nfc->metadata_size_in_bytes, + nfc->ecc_chunk_size_in_bytes, + nfc->ecc_chunk_count, + nfc->payload_size_in_bytes, + nfc->auxiliary_size_in_bytes, + nfc->auxiliary_status_offset, + nfc->block_mark_byte_offset, + nfc->block_mark_bit_offset + ); + +} + +/** + * show_device_rom_geometry() - Shows the Boot ROM Helper's geometry. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer that will receive a representation of the attribute. + */ +static ssize_t show_device_rom_geometry(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct gpmi_nfc_data *this = dev_get_drvdata(dev); + struct boot_rom_geometry *rom = &this->rom_geometry; + + return sprintf(buf, + "Boot Area Count : %u\n" + "Boot Area Size in Bytes : %u\n" + "Stride Size in Pages : %u\n" + "Seach Area Stride Exponent: %u\n" + , + rom->boot_area_count, + rom->boot_area_size_in_bytes, + rom->stride_size_in_pages, + rom->search_area_stride_exponent + ); + +} + +/** + * show_device_mtd_nand_info() - Shows the device's MTD NAND-specific info. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer that will receive a representation of the attribute. + */ +static ssize_t show_device_mtd_nand_info(struct device *dev, + struct device_attribute *attr, char *buf) +{ + int o = 0; + unsigned int i; + unsigned int j; + static const unsigned int columns = 8; + struct gpmi_nfc_data *this = dev_get_drvdata(dev); + struct mil *mil = &this->mil; + struct nand_chip *nand = &mil->nand; + + o += sprintf(buf + o, + "Options : 0x%08x\n" + "Chip Count : %u\n" + "Chip Size in Bytes : %llu\n" + "Minimum Writable Size in Bytes: %u\n" + "Page Shift : %u\n" + "Page Mask : 0x%x\n" + "Block Shift : %u\n" + "BBT Block Shift : %u\n" + "Chip Shift : %u\n" + "Block Mark Offset : %u\n" + "Cached Page Number : %d\n" + , + nand->options, + nand->numchips, + nand->chipsize, + nand->subpagesize, + nand->page_shift, + nand->pagemask, + nand->phys_erase_shift, + nand->bbt_erase_shift, + nand->chip_shift, + nand->badblockpos, + nand->pagebuf + ); + + o += sprintf(buf + o, + "ECC Byte Count : %u\n" + , + nand->ecc.layout->eccbytes + ); + + /* Loop over rows. */ + + for (i = 0; (i * columns) < nand->ecc.layout->eccbytes; i++) { + + /* Loop over columns within rows. */ + + for (j = 0; j < columns; j++) { + + if (((i * columns) + j) >= nand->ecc.layout->eccbytes) + break; + + o += sprintf(buf + o, " %3u", + nand->ecc.layout->eccpos[(i * columns) + j]); + + } + + o += sprintf(buf + o, "\n"); + + } + + o += sprintf(buf + o, + "OOB Available Bytes : %u\n" + , + nand->ecc.layout->oobavail + ); + + j = 0; + + for (i = 0; j < nand->ecc.layout->oobavail; i++) { + + j += nand->ecc.layout->oobfree[i].length; + + o += sprintf(buf + o, + " [%3u, %2u]\n" + , + nand->ecc.layout->oobfree[i].offset, + nand->ecc.layout->oobfree[i].length + ); + + } + + return o; + +} + +/** + * show_device_mtd_info() - Shows the device's MTD-specific information. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer that will receive a representation of the attribute. + */ +static ssize_t show_device_mtd_info(struct device *dev, + struct device_attribute *attr, char *buf) +{ + int o = 0; + unsigned int i; + unsigned int j; + static const unsigned int columns = 8; + struct gpmi_nfc_data *this = dev_get_drvdata(dev); + struct mil *mil = &this->mil; + struct mtd_info *mtd = &mil->mtd; + + o += sprintf(buf + o, + "Name : %s\n" + "Type : %u\n" + "Flags : 0x%08x\n" + "Size in Bytes : %llu\n" + "Erase Region Count : %d\n" + "Erase Size in Bytes: %u\n" + "Write Size in Bytes: %u\n" + "OOB Size in Bytes : %u\n" + "Errors Corrected : %u\n" + "Failed Reads : %u\n" + "Bad Block Count : %u\n" + "BBT Block Count : %u\n" + , + mtd->name, + mtd->type, + mtd->flags, + mtd->size, + mtd->numeraseregions, + mtd->erasesize, + mtd->writesize, + mtd->oobsize, + mtd->ecc_stats.corrected, + mtd->ecc_stats.failed, + mtd->ecc_stats.badblocks, + mtd->ecc_stats.bbtblocks + ); + + o += sprintf(buf + o, + "ECC Byte Count : %u\n" + , + mtd->ecclayout->eccbytes + ); + + /* Loop over rows. */ + + for (i = 0; (i * columns) < mtd->ecclayout->eccbytes; i++) { + + /* Loop over columns within rows. */ + + for (j = 0; j < columns; j++) { + + if (((i * columns) + j) >= mtd->ecclayout->eccbytes) + break; + + o += sprintf(buf + o, " %3u", + mtd->ecclayout->eccpos[(i * columns) + j]); + + } + + o += sprintf(buf + o, "\n"); + + } + + o += sprintf(buf + o, + "OOB Available Bytes: %u\n" + , + mtd->ecclayout->oobavail + ); + + j = 0; + + for (i = 0; j < mtd->ecclayout->oobavail; i++) { + + j += mtd->ecclayout->oobfree[i].length; + + o += sprintf(buf + o, + " [%3u, %2u]\n" + , + mtd->ecclayout->oobfree[i].offset, + mtd->ecclayout->oobfree[i].length + ); + + } + + return o; + +} + +/** + * show_device_timing_diagram() - Shows a timing diagram. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer that will receive a representation of the attribute. + */ +static ssize_t show_device_timing_diagram(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct gpmi_nfc_data *this = dev_get_drvdata(dev); + struct gpmi_nfc_platform_data *pdata = this->pdata; + struct nfc_hal *nfc = this->nfc; + struct gpmi_nfc_timing timing = nfc->timing; + struct gpmi_nfc_hardware_timing hardware_timing; + unsigned long clock_frequency_in_hz; + unsigned long clock_period_in_ns; + unsigned int data_setup_in_ns; + unsigned int dll_delay_shift; + unsigned int sample_delay_in_ns; + unsigned int tDS_in_ns; + unsigned int tOPEN_in_ns; + unsigned int tCLOSE_in_ns; + unsigned int tEYE_in_ns; + unsigned int tDELAY_in_ns; + unsigned int tDS; + unsigned int tOPEN; + unsigned int tCLOSE; + unsigned int tEYE; + unsigned int tDELAY; + const unsigned int diagram_width_in_chars = 55; + unsigned int diagram_width_in_ns; + int o = 0; + unsigned int i; + + /* + * If there are any timing characteristics we need, but don't know, we + * pretend they're zero. + */ + + if (timing.tREA_in_ns < 0) + timing.tREA_in_ns = 0; + + if (timing.tRHOH_in_ns < 0) + timing.tRHOH_in_ns = 0; + + /* Get information about the current/last I/O transaction. */ + + nfc->get_timing(this, &clock_frequency_in_hz, &hardware_timing); + + clock_period_in_ns = 1000000000 / clock_frequency_in_hz; + + /* Compute basic timing facts. */ + + data_setup_in_ns = + hardware_timing.data_setup_in_cycles * clock_period_in_ns; + + /* Compute data sample delay facts. */ + + dll_delay_shift = 3; + + if (hardware_timing.use_half_periods) + dll_delay_shift++; + + sample_delay_in_ns = + (hardware_timing.sample_delay_factor * clock_period_in_ns) >> + dll_delay_shift; + + /* Compute the basic metrics in the diagram, in nanoseconds. */ + + tDS_in_ns = data_setup_in_ns; + tOPEN_in_ns = pdata->max_prop_delay_in_ns + timing.tREA_in_ns; + tCLOSE_in_ns = pdata->min_prop_delay_in_ns + timing.tRHOH_in_ns; + tEYE_in_ns = tDS_in_ns + tCLOSE_in_ns - tOPEN_in_ns; + tDELAY_in_ns = sample_delay_in_ns; + + /* + * We need to translate nanosecond timings into character widths in the + * diagram. The first step is to discover how "wide" the diagram is in + * nanoseconds. That depends on which happens latest: the sample point + * or the close of the eye. + */ + + if (tCLOSE_in_ns >= tDELAY_in_ns) + diagram_width_in_ns = tDS_in_ns + tCLOSE_in_ns; + else + diagram_width_in_ns = tDS_in_ns + tDELAY_in_ns; + + /* Convert the metrics that appear in the diagram. */ + + tDS = (tDS_in_ns * diagram_width_in_chars) / diagram_width_in_ns; + tOPEN = (tOPEN_in_ns * diagram_width_in_chars) / diagram_width_in_ns; + tCLOSE = (tCLOSE_in_ns * diagram_width_in_chars) / diagram_width_in_ns; + tEYE = (tEYE_in_ns * diagram_width_in_chars) / diagram_width_in_ns; + tDELAY = (tDELAY_in_ns * diagram_width_in_chars) / diagram_width_in_ns; + + /* + * Show the results. + * + * This code is really ugly, but it draws a pretty picture :) + */ + + o += sprintf(buf + o, "\n"); + + + o += sprintf(buf + o, "Sample ______"); + for (i = 0; i < tDS; i++) + o += sprintf(buf + o, "_"); + if (tDELAY > 0) + for (i = 0; i < (tDELAY - 1); i++) + o += sprintf(buf + o, "_"); + o += sprintf(buf + o, "|"); + for (i = 0; i < (diagram_width_in_chars - (tDS + tDELAY)); i++) + o += sprintf(buf + o, "_"); + o += sprintf(buf + o, "\n"); + + + o += sprintf(buf + o, "Strobe "); + for (i = 0; i < tDS; i++) + o += sprintf(buf + o, " "); + o += sprintf(buf + o, "|"); + if (tDELAY > 1) { + for (i = 2; i < tDELAY; i++) + o += sprintf(buf + o, "-"); + o += sprintf(buf + o, "|"); + } + o += sprintf(buf + o, " tDELAY\n"); + + + o += sprintf(buf + o, "\n"); + + + o += sprintf(buf + o, " tDS "); + o += sprintf(buf + o, "|"); + if (tDS > 1) { + for (i = 2; i < tDS; i++) + o += sprintf(buf + o, "-"); + o += sprintf(buf + o, "|"); + } + o += sprintf(buf + o, "\n"); + + + o += sprintf(buf + o, " ______"); + for (i = 0; i < tDS; i++) + o += sprintf(buf + o, " "); + for (i = 0; i < (diagram_width_in_chars - tDS); i++) + o += sprintf(buf + o, "_"); + o += sprintf(buf + o, "\n"); + + + o += sprintf(buf + o, "RDN "); + if (tDS > 0) { + if (tDS == 1) + o += sprintf(buf + o, "V"); + else { + o += sprintf(buf + o, "\\"); + for (i = 2; i < tDS; i++) + o += sprintf(buf + o, "_"); + o += sprintf(buf + o, "/"); + } + } + o += sprintf(buf + o, "\n"); + + + o += sprintf(buf + o, "\n"); + + + o += sprintf(buf + o, " tOPEN "); + o += sprintf(buf + o, "|"); + if (tOPEN > 1) { + for (i = 2; i < tOPEN; i++) + o += sprintf(buf + o, "-"); + o += sprintf(buf + o, "|"); + } + o += sprintf(buf + o, "\n"); + + + o += sprintf(buf + o, " "); + for (i = 0; i < tDS; i++) + o += sprintf(buf + o, " "); + o += sprintf(buf + o, "|"); + if (tCLOSE > 1) { + for (i = 2; i < tCLOSE; i++) + o += sprintf(buf + o, "-"); + o += sprintf(buf + o, "|"); + } + o += sprintf(buf + o, " tCLOSE\n"); + + + o += sprintf(buf + o, " "); + for (i = 0; i < tOPEN; i++) + o += sprintf(buf + o, " "); + if (tEYE > 2) { + o += sprintf(buf + o, " "); + for (i = 2; i < tEYE; i++) + o += sprintf(buf + o, "_"); + } + o += sprintf(buf + o, "\n"); + + + o += sprintf(buf + o, "Data ______"); + for (i = 0; i < tOPEN; i++) + o += sprintf(buf + o, "_"); + if (tEYE > 0) { + if (tEYE == 1) + o += sprintf(buf + o, "|"); + else { + o += sprintf(buf + o, "/"); + for (i = 2; i < tEYE; i++) + o += sprintf(buf + o, " "); + o += sprintf(buf + o, "\\"); + } + } + for (i = 0; i < (diagram_width_in_chars - (tOPEN + tEYE)); i++) + o += sprintf(buf + o, "_"); + o += sprintf(buf + o, "\n"); + + + o += sprintf(buf + o, " "); + for (i = 0; i < tOPEN; i++) + o += sprintf(buf + o, " "); + if (tEYE > 0) { + if (tEYE == 1) + o += sprintf(buf + o, "|"); + else { + o += sprintf(buf + o, "\\"); + for (i = 2; i < tEYE; i++) + o += sprintf(buf + o, "_"); + o += sprintf(buf + o, "/"); + } + } + o += sprintf(buf + o, "\n"); + + + o += sprintf(buf + o, " "); + for (i = 0; i < tOPEN; i++) + o += sprintf(buf + o, " "); + o += sprintf(buf + o, "|"); + if (tEYE > 1) { + for (i = 2; i < tEYE; i++) + o += sprintf(buf + o, "-"); + o += sprintf(buf + o, "|"); + } + o += sprintf(buf + o, " tEYE\n"); + + + o += sprintf(buf + o, "\n"); + o += sprintf(buf + o, "tDS : %u ns\n", tDS_in_ns); + o += sprintf(buf + o, "tOPEN : %u ns\n", tOPEN_in_ns); + o += sprintf(buf + o, "tCLOSE: %u ns\n", tCLOSE_in_ns); + o += sprintf(buf + o, "tEYE : %u ns\n", tEYE_in_ns); + o += sprintf(buf + o, "tDELAY: %u ns\n", tDELAY_in_ns); + o += sprintf(buf + o, "\n"); + + + return o; + +} + +/** + * store_device_invalidate_page_cache() - Invalidates the device's page cache. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer containing a new attribute value. + * @size: The size of the buffer. + */ +static ssize_t store_device_invalidate_page_cache(struct device *dev, + struct device_attribute *attr, const char *buf, size_t size) +{ + struct gpmi_nfc_data *this = dev_get_drvdata(dev); + + /* Invalidate the page cache. */ + + this->mil.nand.pagebuf = -1; + + /* Return success. */ + + return size; + +} + +/** + * store_device_mark_block_bad() - Marks a block as bad. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer containing a new attribute value. + * @size: The size of the buffer. + */ +static ssize_t store_device_mark_block_bad(struct device *dev, + struct device_attribute *attr, const char *buf, size_t size) +{ + struct gpmi_nfc_data *this = dev_get_drvdata(dev); + struct mil *mil = &this->mil; + struct mtd_info *mtd = &mil->mtd; + struct nand_chip *nand = &mil->nand; + unsigned long block_number; + loff_t byte_address; + int error; + + /* Look for nonsense. */ + + if (!size) + return -EINVAL; + + /* Try to understand the block number. */ + + if (strict_strtoul(buf, 0, &block_number)) + return -EINVAL; + + /* Compute the byte address of this block. */ + + byte_address = block_number << nand->phys_erase_shift; + + /* Attempt to mark the block bad. */ + + error = mtd->block_markbad(mtd, byte_address); + + if (error) + return error; + + /* Return success. */ + + return size; + +} + +/** + * show_device_ignorebad() - Shows the value of the 'ignorebad' flag. + * + * @d: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer that will receive a representation of the attribute. + */ +static ssize_t show_device_ignorebad(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct gpmi_nfc_data *this = dev_get_drvdata(dev); + struct mil *mil = &this->mil; + + return sprintf(buf, "%d\n", mil->ignore_bad_block_marks); +} + +/** + * store_device_ignorebad() - Sets the value of the 'ignorebad' flag. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer containing a new attribute value. + * @size: The size of the buffer. + */ +static ssize_t store_device_ignorebad(struct device *dev, + struct device_attribute *attr, const char *buf, size_t size) +{ + struct gpmi_nfc_data *this = dev_get_drvdata(dev); + struct mil *mil = &this->mil; + const char *p = buf; + unsigned long v; + + /* Try to make sense of what arrived from user space. */ + + if (strict_strtoul(p, 0, &v) < 0) + return size; + + if (v > 0) + v = 1; + + /* Only do something if the value is changing. */ + + if (v != mil->ignore_bad_block_marks) { + + if (v) { + + /* + * If control arrives here, we want to begin ignoring + * bad block marks. Reach into the NAND Flash MTD data + * structures and set the in-memory BBT pointer to NULL. + * This will cause the NAND Flash MTD code to believe + * that it never created a BBT and force it to call our + * block_bad function. + * + * See mil_block_bad for more details. + */ + + mil->saved_bbt = mil->nand.bbt; + mil->nand.bbt = 0; + + } else { + + /* + * If control arrives here, we want to stop ignoring + * bad block marks. Restore the NAND Flash MTD's pointer + * to its in-memory BBT. + */ + + mil->nand.bbt = mil->saved_bbt; + + } + + mil->ignore_bad_block_marks = v; + + } + + return size; + +} + +/** + * show_device_inject_ecc_error() - Shows the device's error injection flag. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer that will receive a representation of the attribute. + */ +static ssize_t show_device_inject_ecc_error(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct gpmi_nfc_data *this = dev_get_drvdata(dev); + struct mil *mil = &this->mil; + + return sprintf(buf, "%d\n", mil->inject_ecc_error); + +} + +/** + * store_device_inject_ecc_error() - Sets the device's error injection flag. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer containing a new attribute value. + * @size: The size of the buffer. + */ +static ssize_t store_device_inject_ecc_error(struct device *dev, + struct device_attribute *attr, const char *buf, size_t size) +{ + struct gpmi_nfc_data *this = dev_get_drvdata(dev); + struct mil *mil = &this->mil; + long new_inject_ecc_error; + + /* Look for nonsense. */ + + if (!size) + return -EINVAL; + + /* Try to understand the ECC error count. */ + + if (strict_strtol(buf, 0, &new_inject_ecc_error)) + return -EINVAL; + + /* Store the value. */ + + mil->inject_ecc_error = new_inject_ecc_error; + + /* Return success. */ + + return size; + +} + +/** + * show_device_timing_help() - Show help for setting timing. + * + * @d: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer that will receive a representation of the attribute. + */ +static ssize_t show_device_timing_help(struct device *dev, + struct device_attribute *attr, char *buf) +{ + + static const char *help = + ",,
,," + ",,\n"; + + return sprintf(buf, "%s", help); + +} + +/** + * show_device_timing() - Shows the current timing. + * + * @d: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer that will receive a representation of the attribute. + */ +static ssize_t show_device_timing(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct gpmi_nfc_data *this = dev_get_drvdata(dev); + struct gpmi_nfc_platform_data *pdata = this->pdata; + struct nfc_hal *nfc = this->nfc; + struct gpmi_nfc_timing *recorded = &nfc->timing; + unsigned long clock_frequency_in_hz; + unsigned long clock_period_in_ns; + struct gpmi_nfc_hardware_timing hardware; + unsigned int effective_data_setup_in_ns; + unsigned int effective_data_hold_in_ns; + unsigned int effective_address_setup_in_ns; + unsigned int dll_delay_shift; + unsigned int effective_sample_delay_in_ns; + + /* Get information about the current/last I/O transaction. */ + + nfc->get_timing(this, &clock_frequency_in_hz, &hardware); + + clock_period_in_ns = 1000000000 / clock_frequency_in_hz; + + /* Compute basic timing facts. */ + + effective_data_setup_in_ns = + hardware.data_setup_in_cycles * clock_period_in_ns; + effective_data_hold_in_ns = + hardware.data_hold_in_cycles * clock_period_in_ns; + effective_address_setup_in_ns = + hardware.address_setup_in_cycles * clock_period_in_ns; + + /* Compute data sample delay facts. */ + + dll_delay_shift = 3; + + if (hardware.use_half_periods) + dll_delay_shift++; + + effective_sample_delay_in_ns = + (hardware.sample_delay_factor * clock_period_in_ns) >> + dll_delay_shift; + + /* Show the results. */ + + return sprintf(buf, + "Minimum Propagation Delay in ns : %u\n" + "Maximum Propagation Delay in ns : %u\n" + "Clock Frequency in Hz : %lu\n" + "Clock Period in ns : %lu\n" + "Recorded Data Setup in ns : %d\n" + "Hardware Data Setup in cycles : %u\n" + "Effective Data Setup in ns : %u\n" + "Recorded Data Hold in ns : %d\n" + "Hardware Data Hold in cycles : %u\n" + "Effective Data Hold in ns : %u\n" + "Recorded Address Setup in ns : %d\n" + "Hardware Address Setup in cycles: %u\n" + "Effective Address Setup in ns : %u\n" + "Using Half Period : %s\n" + "Recorded Sample Delay in ns : %d\n" + "Hardware Sample Delay Factor : %u\n" + "Effective Sample Delay in ns : %u\n" + "Recorded tREA in ns : %d\n" + "Recorded tRLOH in ns : %d\n" + "Recorded tRHOH in ns : %d\n" + , + pdata->min_prop_delay_in_ns, + pdata->max_prop_delay_in_ns, + clock_frequency_in_hz, + clock_period_in_ns, + recorded->data_setup_in_ns, + hardware .data_setup_in_cycles, + effective_data_setup_in_ns, + recorded->data_hold_in_ns, + hardware .data_hold_in_cycles, + effective_data_hold_in_ns, + recorded->address_setup_in_ns, + hardware .address_setup_in_cycles, + effective_address_setup_in_ns, + hardware .use_half_periods ? "Yes" : "No", + recorded->gpmi_sample_delay_in_ns, + hardware .sample_delay_factor, + effective_sample_delay_in_ns, + recorded->tREA_in_ns, + recorded->tRLOH_in_ns, + recorded->tRHOH_in_ns); + +} + +/** + * store_device_timing() - Sets the current timing. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer containing a new attribute value. + * @size: The size of the buffer. + */ +static ssize_t store_device_timing(struct device *dev, + struct device_attribute *attr, const char *buf, size_t size) +{ + struct gpmi_nfc_data *this = dev_get_drvdata(dev); + struct nfc_hal *nfc = this->nfc; + const char *p = buf; + const char *q; + char tmps[20]; + long t; + struct gpmi_nfc_timing new; + + int8_t *field_pointers[] = { + &new.data_setup_in_ns, + &new.data_hold_in_ns, + &new.address_setup_in_ns, + &new.gpmi_sample_delay_in_ns, + &new.tREA_in_ns, + &new.tRLOH_in_ns, + &new.tRHOH_in_ns, + NULL, + }; + + int8_t **field_pointer = field_pointers; + + /* + * Loop over comma-separated timing values in the incoming buffer, + * assigning them to fields in the timing structure as we go along. + */ + + while (*field_pointer != NULL) { + + /* Clear out the temporary buffer. */ + + memset(tmps, 0, sizeof(tmps)); + + /* Copy the timing value into the temporary buffer. */ + + q = strchr(p, ','); + if (q) + strncpy(tmps, p, min_t(int, sizeof(tmps) - 1, q - p)); + else + strncpy(tmps, p, sizeof(tmps) - 1); + + /* Attempt to convert the current timing value. */ + + if (strict_strtol(tmps, 0, &t) < 0) + return -EINVAL; + + if ((t > 127) || (t < -128)) + return -EINVAL; + + /* Assign this value to the current field. */ + + **field_pointer = (int8_t) t; + field_pointer++; + + /* Check if we ran out of input too soon. */ + + if (!q && *field_pointer) + return -EINVAL; + + /* Move past the comma to the next timing value. */ + + p = q + 1; + + } + + /* Hand over the timing to the NFC. */ + + nfc->set_timing(this, &new); + + /* Return success. */ + + return size; + +} + +/* Device attributes that appear in sysfs. */ + +static DEVICE_ATTR(report , 0555, show_device_report , 0); +static DEVICE_ATTR(numchips , 0444, show_device_numchips , 0); +static DEVICE_ATTR(physical_geometry, 0444, show_device_physical_geometry, 0); +static DEVICE_ATTR(nfc_info , 0444, show_device_nfc_info , 0); +static DEVICE_ATTR(nfc_geometry , 0444, show_device_nfc_geometry , 0); +static DEVICE_ATTR(rom_geometry , 0444, show_device_rom_geometry , 0); +static DEVICE_ATTR(mtd_nand_info , 0444, show_device_mtd_nand_info , 0); +static DEVICE_ATTR(mtd_info , 0444, show_device_mtd_info , 0); +static DEVICE_ATTR(timing_diagram , 0444, show_device_timing_diagram , 0); +static DEVICE_ATTR(timing_help , 0444, show_device_timing_help , 0); + +static DEVICE_ATTR(invalidate_page_cache, 0644, + 0, store_device_invalidate_page_cache); + +static DEVICE_ATTR(mark_block_bad, 0200, + 0, store_device_mark_block_bad); + +static DEVICE_ATTR(ignorebad, 0644, + show_device_ignorebad, store_device_ignorebad); + +static DEVICE_ATTR(inject_ecc_error, 0644, + show_device_inject_ecc_error, store_device_inject_ecc_error); + +static DEVICE_ATTR(timing, 0644, + show_device_timing, store_device_timing); + +static struct device_attribute *device_attributes[] = { + &dev_attr_report, + &dev_attr_numchips, + &dev_attr_physical_geometry, + &dev_attr_nfc_info, + &dev_attr_nfc_geometry, + &dev_attr_rom_geometry, + &dev_attr_mtd_nand_info, + &dev_attr_mtd_info, + &dev_attr_invalidate_page_cache, + &dev_attr_mark_block_bad, + &dev_attr_ignorebad, + &dev_attr_inject_ecc_error, + &dev_attr_timing, + &dev_attr_timing_help, + &dev_attr_timing_diagram, +}; + +/** + * validate_the_platform() - Validates information about the platform. + * + * @pdev: A pointer to the platform device data structure. + */ +static int validate_the_platform(struct platform_device *pdev) +{ + struct device *dev = &pdev->dev; + struct gpmi_nfc_platform_data *pdata = pdev->dev.platform_data; + + /* Validate the clock name. */ + + if (!pdata->clock_name) { + dev_err(dev, "No clock name\n"); + return -ENXIO; + } + + /* Validate the partitions. */ + + if ((pdata->partitions && (!pdata->partition_count)) || + (!pdata->partitions && (pdata->partition_count))) { + dev_err(dev, "Bad partition data\n"); + return -ENXIO; + } + + /* Return success */ + + return 0; + +} + +/** + * acquire_register_block() - Tries to acquire and map a register block. + * + * @this: Per-device data. + * @resource_name: The name of the resource. + * @reg_block_base: A pointer to a variable that will receive the address of + * the mapped register block. + */ +static int acquire_register_block(struct gpmi_nfc_data *this, + const char *resource_name, void **reg_block_base) +{ + struct platform_device *pdev = this->pdev; + struct device *dev = this->dev; + void *p; + struct resource *r; + + /* Attempt to get information about the given resource. */ + + r = platform_get_resource_byname(pdev, IORESOURCE_MEM, resource_name); + + if (!r) { + dev_err(dev, "Can't get resource information for '%s'\n", + resource_name); + return -ENXIO; + } + + /* Attempt to remap the register block. */ + + p = ioremap(r->start, r->end - r->start + 1); + + if (!p) { + dev_err(dev, "Can't remap %s\n", resource_name); + return -EIO; + } + + /* If control arrives here, everything went fine. */ + + *reg_block_base = p; + + return 0; + +} + +/** + * release_register_block() - Releases a register block. + * + * @this: Per-device data. + * @reg_block_base: A pointer to the mapped register block. + */ +static void release_register_block(struct gpmi_nfc_data *this, + void *reg_block_base) +{ + iounmap(reg_block_base); +} + +/** + * acquire_interrupt() - Tries to acquire an interrupt. + * + * @this: Per-device data. + * @resource_name: The name of the resource. + * @interrupt_handler: A pointer to the function that will handle interrupts + * from this interrupt number. + * @interrupt_number: A pointer to a variable that will receive the acquired + * interrupt number. + */ +static int acquire_interrupt( + struct gpmi_nfc_data *this, const char *resource_name, + irq_handler_t interrupt_handler, int *interrupt_number) +{ + struct platform_device *pdev = this->pdev; + struct device *dev = this->dev; + int error = 0; + int i; + + /* Attempt to get information about the given resource. */ + + i = platform_get_irq_byname(pdev, resource_name); + + if (i < 0) { + dev_err(dev, "Can't get resource information for '%s'\n", + resource_name); + return -ENXIO; + } + + /* Attempt to own the interrupt. */ + + error = request_irq(i, interrupt_handler, 0, resource_name, this); + + if (error) { + dev_err(dev, "Can't own %s\n", resource_name); + return -EIO; + } + + /* If control arrives here, everything went fine. */ + + *interrupt_number = i; + + return 0; + +} + +/** + * release_interrupt() - Releases an interrupt. + * + * @this: Per-device data. + * @interrupt_number: The interrupt number. + */ +static void release_interrupt(struct gpmi_nfc_data *this, int interrupt_number) +{ + free_irq(interrupt_number, this); +} + +/** + * acquire_dma_channels() - Tries to acquire DMA channels. + * + * @this: Per-device data. + * @resource_name: The name of the resource. + * @low_channel: A pointer to a variable that will receive the acquired + * low DMA channel number. + * @high_channel: A pointer to a variable that will receive the acquired + * high DMA channel number. + */ +static int acquire_dma_channels( + struct gpmi_nfc_data *this, const char *resource_name, + unsigned *low_channel, unsigned *high_channel) +{ + struct platform_device *pdev = this->pdev; + struct device *dev = this->dev; + int error = 0; + struct resource *r; + unsigned int dma_channel; + + /* Attempt to get information about the given resource. */ + + r = platform_get_resource_byname(pdev, IORESOURCE_DMA, resource_name); + + if (!r) { + dev_err(dev, "Can't get resource information for '%s'\n", + resource_name); + return -ENXIO; + } + + /* Loop over DMA channels, attempting to own them. */ + + for (dma_channel = r->start; dma_channel <= r->end; dma_channel++) { + + /* Attempt to own the current channel. */ + + error = mxs_dma_request(dma_channel, dev, resource_name); + + /* Check if we successfully acquired the current channel. */ + + if (error) { + + dev_err(dev, "Can't acquire DMA channel %u\n", + dma_channel); + + /* Free all the channels we've already acquired. */ + + while (--dma_channel >= 0) + mxs_dma_release(dma_channel, dev); + + return error; + + } + + /* + * If control arrives here, we successfully acquired the + * current channel. Continue initializing it. + */ + + mxs_dma_reset(dma_channel); + mxs_dma_ack_irq(dma_channel); + + } + + /* If control arrives here, all went well. */ + + *low_channel = r->start; + *high_channel = r->end; + + return 0; + +} + +/** + * release_dma_channels() - Releases DMA channels. + * + * @this: Per-device data. + * @low_channel: The low DMA channel number. + * @high_channel: The high DMA channel number. + */ +static void release_dma_channels(struct gpmi_nfc_data *this, + unsigned low_channel, unsigned high_channel) +{ + struct device *dev = this->dev; + unsigned int i; + + for (i = low_channel; i <= high_channel; i++) + mxs_dma_release(i, dev); +} + +/** + * acquire_clock() - Tries to acquire a clock. + * + * @this: Per-device data. + * @resource_name: The name of the clock. + * @high_channel: A pointer to a variable that will receive the acquired + * clock address. + */ +static int acquire_clock(struct gpmi_nfc_data *this, + const char *clock_name, struct clk **clock) +{ + struct device *dev = this->dev; + int error = 0; + struct clk *c; + + /* Try to get the clock. */ + + c = clk_get(dev, clock_name); + + if (IS_ERR(c)) { + error = PTR_ERR(c); + dev_err(dev, "Can't own clock %s\n", clock_name); + return error; + } + + /* If control arrives here, everything went fine. */ + + *clock = c; + + return 0; + +} + +/** + * release_clock() - Releases a clock. + * + * @this: Per-device data. + * @clock: A pointer to the clock structure. + */ +static void release_clock(struct gpmi_nfc_data *this, struct clk *clock) +{ + clk_disable(clock); + clk_put(clock); +} + +/** + * acquire_resources() - Tries to acquire resources. + * + * @this: Per-device data. + */ +static int acquire_resources(struct gpmi_nfc_data *this) +{ + struct gpmi_nfc_platform_data *pdata = this->pdata; + struct resources *resources = &this->resources; + int error = 0; + + /* Attempt to acquire the GPMI register block. */ + + error = acquire_register_block(this, + GPMI_NFC_GPMI_REGS_ADDR_RES_NAME, &(resources->gpmi_regs)); + + if (error) + goto exit_gpmi_regs; + + /* Attempt to acquire the BCH register block. */ + + error = acquire_register_block(this, + GPMI_NFC_BCH_REGS_ADDR_RES_NAME, &(resources->bch_regs)); + + if (error) + goto exit_bch_regs; + + /* Attempt to acquire the BCH interrupt. */ + + error = acquire_interrupt(this, + GPMI_NFC_BCH_INTERRUPT_RES_NAME, + gpmi_nfc_bch_isr, &(resources->bch_interrupt)); + + if (error) + goto exit_bch_interrupt; + + /* Attempt to acquire the DMA channels. */ + + error = acquire_dma_channels(this, + GPMI_NFC_DMA_CHANNELS_RES_NAME, + &(resources->dma_low_channel), &(resources->dma_high_channel)); + + if (error) + goto exit_dma_channels; + + /* Attempt to acquire the DMA interrupt. */ + + error = acquire_interrupt(this, + GPMI_NFC_DMA_INTERRUPT_RES_NAME, + gpmi_nfc_dma_isr, &(resources->dma_interrupt)); + + if (error) + goto exit_dma_interrupt; + + /* Attempt to acquire our clock. */ + + error = acquire_clock(this, pdata->clock_name, &(resources->clock)); + + if (error) + goto exit_clock; + + /* If control arrives here, all went well. */ + + return 0; + + /* Control arrives here if something went wrong. */ + +exit_clock: + release_interrupt(this, resources->dma_interrupt); +exit_dma_interrupt: + release_dma_channels(this, + resources->dma_low_channel, resources->dma_high_channel); +exit_dma_channels: + release_interrupt(this, resources->bch_interrupt); +exit_bch_interrupt: + release_register_block(this, resources->bch_regs); +exit_bch_regs: + release_register_block(this, resources->gpmi_regs); +exit_gpmi_regs: + + return error; + +} + +/** + * release_resources() - Releases resources. + * + * @this: Per-device data. + */ +static void release_resources(struct gpmi_nfc_data *this) +{ + struct resources *resources = &this->resources; + + release_clock(this, resources->clock); + release_register_block(this, resources->gpmi_regs); + release_register_block(this, resources->bch_regs); + release_interrupt(this, resources->bch_interrupt); + release_dma_channels(this, + resources->dma_low_channel, resources->dma_high_channel); + release_interrupt(this, resources->dma_interrupt); +} + +/** + * set_up_nfc_hal() - Sets up the NFC HAL. + * + * @this: Per-device data. + */ +static int set_up_nfc_hal(struct gpmi_nfc_data *this) +{ + struct gpmi_nfc_platform_data *pdata = this->pdata; + struct device *dev = this->dev; + struct nfc_hal *nfc; + int error = 0; + unsigned int i; + + /* Attempt to find an NFC HAL that matches the given version. */ + + for (i = 0; i < ARRAY_SIZE(nfc_hals); i++) { + + nfc = nfc_hals[i]; + + if (nfc->version == pdata->nfc_version) { + this->nfc = nfc; + break; + } + + } + + /* Check if we found a HAL. */ + + if (i >= ARRAY_SIZE(nfc_hals)) { + dev_err(dev, "Unkown NFC version %u\n", pdata->nfc_version); + return -ENXIO; + } + + pr_info("NFC: Version %u, %s\n", nfc->version, nfc->description); + + /* + * Check if we can handle the number of chips called for by the platform + * data. + */ + + if (pdata->max_chip_count > nfc->max_chip_count) { + dev_err(dev, "Platform data calls for %u chips " + "but NFC supports a max of %u.\n", + pdata->max_chip_count, nfc->max_chip_count); + return -ENXIO; + } + + /* Initialize the NFC HAL. */ + + error = nfc->init(this); + + if (error) + return error; + + /* Set up safe timing. */ + + nfc->set_timing(this, &safe_timing); + + /* + * If control arrives here, all is well. + */ + + return 0; + +} + +/** + * set_up_boot_rom_helper() - Sets up the Boot ROM Helper. + * + * @this: Per-device data. + */ +static int set_up_boot_rom_helper(struct gpmi_nfc_data *this) +{ + struct gpmi_nfc_platform_data *pdata = this->pdata; + struct device *dev = this->dev; + unsigned int i; + struct boot_rom_helper *rom; + + /* Attempt to find a Boot ROM Helper that matches the given version. */ + + for (i = 0; i < ARRAY_SIZE(boot_rom_helpers); i++) { + + rom = boot_rom_helpers[i]; + + if (rom->version == pdata->boot_rom_version) { + this->rom = rom; + break; + } + + } + + /* Check if we found a Boot ROM Helper. */ + + if (i >= ARRAY_SIZE(boot_rom_helpers)) { + dev_err(dev, "Unkown Boot ROM version %u\n", + pdata->boot_rom_version); + return -ENXIO; + } + + pr_info("Boot ROM: Version %u, %s\n", rom->version, rom->description); + + /* + * If control arrives here, all is well. + */ + + return 0; + +} + +/** + * manage_sysfs_files() - Creates/removes sysfs files for this device. + * + * @this: Per-device data. + */ +static void manage_sysfs_files(struct gpmi_nfc_data *this, int create) +{ + struct device *dev = this->dev; + int error; + unsigned int i; + struct device_attribute **attr; + + for (i = 0, attr = device_attributes; + i < ARRAY_SIZE(device_attributes); i++, attr++) { + + if (create) { + error = device_create_file(dev, *attr); + if (error) { + while (--attr >= device_attributes) + device_remove_file(dev, *attr); + return; + } + } else { + device_remove_file(dev, *attr); + } + + } + +} + +/** + * gpmi_nfc_probe() - Probes for a device and, if possible, takes ownership. + * + * @pdev: A pointer to the platform device data structure. + */ +static int gpmi_nfc_probe(struct platform_device *pdev) +{ + int error = 0; + struct device *dev = &pdev->dev; + struct gpmi_nfc_platform_data *pdata = pdev->dev.platform_data; + struct gpmi_nfc_data *this = 0; + + /* Validate the platform device data. */ + + error = validate_the_platform(pdev); + + if (error) + goto exit_validate_platform; + + /* Allocate memory for the per-device data. */ + + this = kzalloc(sizeof(*this), GFP_KERNEL); + + if (!this) { + dev_err(dev, "Failed to allocate per-device memory\n"); + error = -ENOMEM; + goto exit_allocate_this; + } + + /* Set up our data structures. */ + + platform_set_drvdata(pdev, this); + + this->pdev = pdev; + this->dev = &pdev->dev; + this->pdata = pdata; + + /* Acquire the resources we need. */ + + error = acquire_resources(this); + + if (error) + goto exit_acquire_resources; + + /* Set up the NFC. */ + + error = set_up_nfc_hal(this); + + if (error) + goto exit_nfc_init; + + /* Set up the platform. */ + + if (pdata->platform_init) + error = pdata->platform_init(pdata->max_chip_count); + + if (error) + goto exit_platform_init; + + /* Set up the Boot ROM Helper. */ + + error = set_up_boot_rom_helper(this); + + if (error) + goto exit_boot_rom_helper_init; + + /* Initialize the MTD Interface Layer. */ + + error = gpmi_nfc_mil_init(this); + + if (error) + goto exit_mil_init; + + /* Create sysfs entries for this device. */ + + manage_sysfs_files(this, true); + + /* Return success. */ + + return 0; + + /* Error return paths begin here. */ + +exit_mil_init: +exit_boot_rom_helper_init: + if (pdata->platform_exit) + pdata->platform_exit(pdata->max_chip_count); +exit_platform_init: + this->nfc->exit(this); +exit_nfc_init: + release_resources(this); +exit_acquire_resources: + platform_set_drvdata(pdev, NULL); + kfree(this); +exit_allocate_this: +exit_validate_platform: + return error; + +} + +/** + * gpmi_nfc_remove() - Dissociates this driver from the given device. + * + * @pdev: A pointer to the platform device data structure. + */ +static int __exit gpmi_nfc_remove(struct platform_device *pdev) +{ + struct gpmi_nfc_data *this = platform_get_drvdata(pdev); + struct gpmi_nfc_platform_data *pdata = this->pdata; + + manage_sysfs_files(this, false); + gpmi_nfc_mil_exit(this); + if (pdata->platform_exit) + pdata->platform_exit(pdata->max_chip_count); + this->nfc->exit(this); + release_resources(this); + platform_set_drvdata(pdev, NULL); + kfree(this); + + return 0; +} + +#ifdef CONFIG_PM + +/** + * gpmi_nfc_suspend() - Puts the NFC into a low power state. + * + * @pdev: A pointer to the platform device data structure. + * @state: The new power state. + */ +static int gpmi_nfc_suspend(struct platform_device *pdev, pm_message_t state) +{ + return 0; +} + +/** + * gpmi_nfc_resume() - Brings the NFC back from a low power state. + * + * @pdev: A pointer to the platform device data structure. + */ +static int gpmi_nfc_resume(struct platform_device *pdev) +{ + return 0; +} + +#else + +#define suspend NULL +#define resume NULL + +#endif /* CONFIG_PM */ + +/* + * This structure represents this driver to the platform management system. + */ +static struct platform_driver gpmi_nfc_driver = { + .driver = { + .name = GPMI_NFC_DRIVER_NAME, + }, + .probe = gpmi_nfc_probe, + .remove = __exit_p(gpmi_nfc_remove), + .suspend = gpmi_nfc_suspend, + .resume = gpmi_nfc_resume, +}; + +/** + * gpmi_nfc_init() - Initializes this module. + */ +static int __init gpmi_nfc_init(void) +{ + + pr_info("i.MX GPMI NFC\n"); + + /* Register this driver with the platform management system. */ + + if (platform_driver_register(&gpmi_nfc_driver) != 0) { + pr_err("i.MX GPMI NFC driver registration failed\n"); + return -ENODEV; + } + + /* Return success. */ + + return 0; + +} + +/** + * gpmi_nfc_exit() - Deactivates this module. + */ +static void __exit gpmi_nfc_exit(void) +{ + platform_driver_unregister(&gpmi_nfc_driver); +} + +module_init(gpmi_nfc_init); +module_exit(gpmi_nfc_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("i.MX GPMI NAND Flash Controller Driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-mil.c b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-mil.c new file mode 100644 index 000000000000..cb5dc4d50e87 --- /dev/null +++ b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-mil.c @@ -0,0 +1,2600 @@ +/* + * Freescale GPMI NFC NAND Flash Driver + * + * Copyright (C) 2010 Freescale Semiconductor, Inc. + * Copyright (C) 2008 Embedded Alley Solutions, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include +#include "gpmi-nfc.h" + +/* + * Indicates the driver should register the MTD that represents the entire + * medium, thus making it visible. + */ + +static int register_main_mtd; +module_param(register_main_mtd, int, 0400); + +/* + * Indicates the driver should attempt to perform DMA directly to/from buffers + * passed into this driver. This is true by default. If false, the driver will + * *always* copy incoming/outgoing data to/from its own DMA buffers. + */ + +static int map_io_buffers = true; +module_param(map_io_buffers, int, 0600); + +/** + * mil_outgoing_buffer_dma_begin() - Begins DMA on an outgoing buffer. + * + * @this: Per-device data. + * @source: The source buffer. + * @length: The length of the data in the source buffer. + * @alt_virt: The virtual address of an alternate buffer which is ready to be + * used for DMA. + * @alt_phys: The physical address of an alternate buffer which is ready to be + * used for DMA. + * @alt_size: The size of the alternate buffer. + * @use_virt: A pointer to a variable that will receive the virtual address to + * use. + * @use_phys: A pointer to a variable that will receive the physical address to + * use. + */ +static int mil_outgoing_buffer_dma_begin(struct gpmi_nfc_data *this, + const void *source, unsigned length, + void *alt_virt, dma_addr_t alt_phys, unsigned alt_size, + const void **use_virt, dma_addr_t *use_phys) +{ + struct device *dev = this->dev; + dma_addr_t source_phys = ~0; + + /* + * If we can, we want to use the caller's buffer directly for DMA. Check + * if the system will let us map them. + */ + + if (map_io_buffers && virt_addr_valid(source)) + source_phys = + dma_map_single(dev, + (void *) source, length, DMA_TO_DEVICE); + + if (dma_mapping_error(dev, source_phys)) { + + /* + * If control arrives here, we're not mapping the source buffer. + * Make sure the alternate is large enough. + */ + + if (alt_size < length) { + dev_err(dev, "Alternate buffer is too small " + "for outgoing I/O\n"); + return -ENOMEM; + } + + /* + * Copy the contents of the source buffer into the alternate + * buffer and set up the return values accordingly. + */ + + memcpy(alt_virt, source, length); + + *use_virt = alt_virt; + *use_phys = alt_phys; + + } else { + + /* + * If control arrives here, we're mapping the source buffer. Set + * up the return values accordingly. + */ + + *use_virt = source; + *use_phys = source_phys; + + } + + /* If control arrives here, all is well. */ + + return 0; + +} + +/** + * mil_outgoing_buffer_dma_end() - Ends DMA on an outgoing buffer. + * + * @this: Per-device data. + * @source: The source buffer. + * @length: The length of the data in the source buffer. + * @alt_virt: The virtual address of an alternate buffer which was ready to be + * used for DMA. + * @alt_phys: The physical address of an alternate buffer which was ready to + * be used for DMA. + * @alt_size: The size of the alternate buffer. + * @used_virt: The virtual address that was used. + * @used_phys: The physical address that was used. + */ +static void mil_outgoing_buffer_dma_end(struct gpmi_nfc_data *this, + const void *source, unsigned length, + void *alt_virt, dma_addr_t alt_phys, unsigned alt_size, + const void *used_virt, dma_addr_t used_phys) +{ + struct device *dev = this->dev; + + /* + * Check if we used the source buffer, and it's not one of our own DMA + * buffers. If so, we need to unmap it. + */ + + if (used_virt == source) + dma_unmap_single(dev, used_phys, length, DMA_TO_DEVICE); + +} + +/** + * mil_incoming_buffer_dma_begin() - Begins DMA on an incoming buffer. + * + * @this: Per-device data. + * @destination: The destination buffer. + * @length: The length of the data that will arrive. + * @alt_virt: The virtual address of an alternate buffer which is ready + * to be used for DMA. + * @alt_phys: The physical address of an alternate buffer which is ready + * to be used for DMA. + * @alt_size: The size of the alternate buffer. + * @use_virt: A pointer to a variable that will receive the virtual address + * to use. + * @use_phys: A pointer to a variable that will receive the physical address + * to use. + */ +static int mil_incoming_buffer_dma_begin(struct gpmi_nfc_data *this, + void *destination, unsigned length, + void *alt_virt, dma_addr_t alt_phys, unsigned alt_size, + void **use_virt, dma_addr_t *use_phys) +{ + struct device *dev = this->dev; + dma_addr_t destination_phys = ~0; + + /* + * If we can, we want to use the caller's buffer directly for DMA. Check + * if the system will let us map them. + */ + + if (map_io_buffers && virt_addr_valid(destination)) + destination_phys = + dma_map_single(dev, + (void *) destination, length, DMA_FROM_DEVICE); + + if (dma_mapping_error(dev, destination_phys)) { + + /* + * If control arrives here, we're not mapping the destination + * buffer. Make sure the alternate is large enough. + */ + + if (alt_size < length) { + dev_err(dev, "Alternate buffer is too small " + "for incoming I/O\n"); + return -ENOMEM; + } + + /* Set up the return values to use the alternate. */ + + *use_virt = alt_virt; + *use_phys = alt_phys; + + } else { + + /* + * If control arrives here, we're mapping the destination + * buffer. Set up the return values accordingly. + */ + + *use_virt = destination; + *use_phys = destination_phys; + + } + + /* If control arrives here, all is well. */ + + return 0; + +} + +/** + * mil_incoming_buffer_dma_end() - Ends DMA on an incoming buffer. + * + * @this: Per-device data. + * @destination: The destination buffer. + * @length: The length of the data that arrived. + * @alt_virt: The virtual address of an alternate buffer which was ready to + * be used for DMA. + * @alt_phys: The physical address of an alternate buffer which was ready to + * be used for DMA. + * @alt_size: The size of the alternate buffer. + * @used_virt: The virtual address that was used. + * @used_phys: The physical address that was used. + */ +static void mil_incoming_buffer_dma_end(struct gpmi_nfc_data *this, + void *destination, unsigned length, + void *alt_virt, dma_addr_t alt_phys, unsigned alt_size, + void *used_virt, dma_addr_t used_phys) +{ + struct device *dev = this->dev; + + /* + * Check if we used the destination buffer, and it's not one of our own + * DMA buffers. If so, we need to unmap it. + */ + + if (used_virt == destination) + dma_unmap_single(dev, used_phys, length, DMA_FROM_DEVICE); + else + memcpy(destination, alt_virt, length); + +} + +/** + * mil_cmd_ctrl - MTD Interface cmd_ctrl() + * + * This is the function that we install in the cmd_ctrl function pointer of the + * owning struct nand_chip. The only functions in the reference implementation + * that use these functions pointers are cmdfunc and select_chip. + * + * In this driver, we implement our own select_chip, so this function will only + * be called by the reference implementation's cmdfunc. For this reason, we can + * ignore the chip enable bit and concentrate only on sending bytes to the + * NAND Flash. + * + * @mtd: The owning MTD. + * @data: The value to push onto the data signals. + * @ctrl: The values to push onto the control signals. + */ +static void mil_cmd_ctrl(struct mtd_info *mtd, int data, unsigned int ctrl) +{ + struct nand_chip *nand = mtd->priv; + struct gpmi_nfc_data *this = nand->priv; + struct device *dev = this->dev; + struct mil *mil = &this->mil; + struct nfc_hal *nfc = this->nfc; + int error; +#if defined(CONFIG_MTD_DEBUG) + unsigned int i; + char display[MIL_COMMAND_BUFFER_SIZE * 5]; +#endif + + /* + * Every operation begins with a command byte and a series of zero or + * more address bytes. These are distinguished by either the Address + * Latch Enable (ALE) or Command Latch Enable (CLE) signals being + * asserted. When MTD is ready to execute the command, it will deassert + * both latch enables. + * + * Rather than run a separate DMA operation for every single byte, we + * queue them up and run a single DMA operation for the entire series + * of command and data bytes. + */ + + if ((ctrl & (NAND_ALE | NAND_CLE))) { + if (data != NAND_CMD_NONE) + mil->cmd_virt[mil->command_length++] = data; + return; + } + + /* + * If control arrives here, MTD has deasserted both the ALE and CLE, + * which means it's ready to run an operation. Check if we have any + * bytes to send. + */ + + if (!mil->command_length) + return; + + /* Hand the command over to the NFC. */ + + gpmi_nfc_add_event("mil_cmd_ctrl sending command...", 1); + +#if defined(CONFIG_MTD_DEBUG) + display[0] = 0; + for (i = 0; i < mil->command_length; i++) + sprintf(display + strlen(display), " 0x%02x", + mil->cmd_virt[i] & 0xff); + DEBUG(MTD_DEBUG_LEVEL2, "[gpmi_nfc cmd_ctrl] command: %s\n", display); +#endif + + error = nfc->send_command(this, + mil->current_chip, mil->cmd_phys, mil->command_length); + + if (error) { + dev_err(dev, "[%s] Chip: %u, Error %d\n", + __func__, mil->current_chip, error); + print_hex_dump(KERN_ERR, + " Command Bytes: ", DUMP_PREFIX_NONE, 16, 1, + mil->cmd_virt, mil->command_length, 0); + } + + gpmi_nfc_add_event("...Finished", -1); + + /* Reset. */ + + mil->command_length = 0; + +} + +/** + * mil_dev_ready() - MTD Interface dev_ready() + * + * @mtd: A pointer to the owning MTD. + */ +static int mil_dev_ready(struct mtd_info *mtd) +{ + struct nand_chip *nand = mtd->priv; + struct gpmi_nfc_data *this = nand->priv; + struct nfc_hal *nfc = this->nfc; + struct mil *mil = &this->mil; + + DEBUG(MTD_DEBUG_LEVEL2, "[gpmi_nfc dev_ready]\n"); + + gpmi_nfc_add_event("> mil_dev_ready", 1); + + if (nfc->is_ready(this, mil->current_chip)) { + gpmi_nfc_add_event("< mil_dev_ready - Returning ready", -1); + return !0; + } else { + gpmi_nfc_add_event("< mil_dev_ready - Returning busy", -1); + return 0; + } + +} + +/** + * mil_select_chip() - MTD Interface select_chip() + * + * @mtd: A pointer to the owning MTD. + * @chip: The chip number to select, or -1 to select no chip. + */ +static void mil_select_chip(struct mtd_info *mtd, int chip) +{ + struct nand_chip *nand = mtd->priv; + struct gpmi_nfc_data *this = nand->priv; + struct mil *mil = &this->mil; + struct nfc_hal *nfc = this->nfc; + struct clk *clock = this->resources.clock; + + DEBUG(MTD_DEBUG_LEVEL2, "[gpmi_nfc select_chip] chip: %d\n", chip); + + /* Figure out what kind of transition this is. */ + + if ((mil->current_chip < 0) && (chip >= 0)) { + gpmi_nfc_start_event_trace("> mil_select_chip"); + clk_enable(clock); + nfc->begin(this); + gpmi_nfc_add_event("< mil_select_chip", -1); + } else if ((mil->current_chip >= 0) && (chip < 0)) { + gpmi_nfc_add_event("> mil_select_chip", 1); + clk_disable(clock); + nfc->end(this); + gpmi_nfc_stop_event_trace("< mil_select_chip"); + } else { + gpmi_nfc_add_event("> mil_select_chip", 1); + gpmi_nfc_add_event("< mil_select_chip", -1); + } + + mil->current_chip = chip; + +} + +/** + * mil_read_buf() - MTD Interface read_buf(). + * + * @mtd: A pointer to the owning MTD. + * @buf: The destination buffer. + * @len: The number of bytes to read. + */ +static void mil_read_buf(struct mtd_info *mtd, uint8_t *buf, int len) +{ + struct nand_chip *nand = mtd->priv; + struct gpmi_nfc_data *this = nand->priv; + struct device *dev = this->dev; + struct nfc_hal *nfc = this->nfc; + struct nfc_geometry *nfc_geo = &this->nfc_geometry; + struct mil *mil = &this->mil; + void *use_virt = 0; + dma_addr_t use_phys = ~0; + int error; + + DEBUG(MTD_DEBUG_LEVEL2, "[gpmi_nfc readbuf] len: %d\n", len); + + gpmi_nfc_add_event("> mil_read_buf", 1); + + /* Set up DMA. */ + + error = mil_incoming_buffer_dma_begin(this, buf, len, + mil->payload_virt, mil->payload_phys, + nfc_geo->payload_size_in_bytes, + &use_virt, &use_phys); + + if (error) { + dev_err(dev, "[%s] Inadequate DMA buffer\n", __func__); + goto exit; + } + + /* Ask the NFC. */ + + nfc->read_data(this, mil->current_chip, use_phys, len); + + /* Finish with DMA. */ + + mil_incoming_buffer_dma_end(this, buf, len, + mil->payload_virt, mil->payload_phys, + nfc_geo->payload_size_in_bytes, + use_virt, use_phys); + + /* Return. */ + +exit: + + gpmi_nfc_add_event("< mil_read_buf", -1); + +} + +/** + * mil_write_buf() - MTD Interface write_buf(). + * + * @mtd: A pointer to the owning MTD. + * @buf: The source buffer. + * @len: The number of bytes to read. + */ +static void mil_write_buf(struct mtd_info *mtd, const uint8_t *buf, int len) +{ + struct nand_chip *nand = mtd->priv; + struct gpmi_nfc_data *this = nand->priv; + struct device *dev = this->dev; + struct nfc_hal *nfc = this->nfc; + struct nfc_geometry *nfc_geo = &this->nfc_geometry; + struct mil *mil = &this->mil; + const void *use_virt = 0; + dma_addr_t use_phys = ~0; + int error; + + DEBUG(MTD_DEBUG_LEVEL2, "[gpmi_nfc writebuf] len: %d\n", len); + + gpmi_nfc_add_event("> mil_write_buf", 1); + + /* Set up DMA. */ + + error = mil_outgoing_buffer_dma_begin(this, buf, len, + mil->payload_virt, mil->payload_phys, + nfc_geo->payload_size_in_bytes, + &use_virt, &use_phys); + + if (error) { + dev_err(dev, "[%s] Inadequate DMA buffer\n", __func__); + goto exit; + } + + /* Ask the NFC. */ + + nfc->send_data(this, mil->current_chip, use_phys, len); + + /* Finish with DMA. */ + + mil_outgoing_buffer_dma_end(this, buf, len, + mil->payload_virt, mil->payload_phys, + nfc_geo->payload_size_in_bytes, + use_virt, use_phys); + + /* Return. */ + +exit: + + gpmi_nfc_add_event("< mil_write_buf", -1); + +} + +/** + * mil_read_byte() - MTD Interface read_byte(). + * + * @mtd: A pointer to the owning MTD. + */ +static uint8_t mil_read_byte(struct mtd_info *mtd) +{ + uint8_t byte; + + DEBUG(MTD_DEBUG_LEVEL2, "[gpmi_nfc read_byte]\n"); + + gpmi_nfc_add_event("> mil_read_byte", 1); + + mil_read_buf(mtd, (uint8_t *) &byte, 1); + + gpmi_nfc_add_event("< mil_read_byte", -1); + + DEBUG(MTD_DEBUG_LEVEL2, "[gpmi_nfc read_byte]: 0x%02x\n", byte); + + return byte; + +} + +/** + * mil_handle_block_mark_swapping() - Handles block mark swapping. + * + * Note that, when this function is called, it doesn't know whether it's + * swapping the block mark, or swapping it *back* -- but it doesn't matter + * because the the operation is the same. + * + * @this: Per-device data. + * @payload: A pointer to the payload buffer. + * @auxiliary: A pointer to the auxiliary buffer. + */ +static void mil_handle_block_mark_swapping(struct gpmi_nfc_data *this, + void *payload, void *auxiliary) +{ + struct nfc_geometry *nfc_geo = &this->nfc_geometry; + struct boot_rom_helper *rom = this->rom; + unsigned char *p; + unsigned char *a; + unsigned int bit; + unsigned char mask; + unsigned char from_data; + unsigned char from_oob; + + /* Check if we're doing block mark swapping. */ + + if (!rom->swap_block_mark) + return; + + /* + * If control arrives here, we're swapping. Make some convenience + * variables. + */ + + bit = nfc_geo->block_mark_bit_offset; + p = ((unsigned char *) payload) + nfc_geo->block_mark_byte_offset; + a = auxiliary; + + /* + * Get the byte from the data area that overlays the block mark. Since + * the ECC engine applies its own view to the bits in the page, the + * physical block mark won't (in general) appear on a byte boundary in + * the data. + */ + + from_data = (p[0] >> bit) | (p[1] << (8 - bit)); + + /* Get the byte from the OOB. */ + + from_oob = a[0]; + + /* Swap them. */ + + a[0] = from_data; + + mask = (0x1 << bit) - 1; + p[0] = (p[0] & mask) | (from_oob << bit); + + mask = ~0 << bit; + p[1] = (p[1] & mask) | (from_oob >> (8 - bit)); + +} + +/** + * mil_ecc_read_page() - MTD Interface ecc.read_page(). + * + * @mtd: A pointer to the owning MTD. + * @nand: A pointer to the owning NAND Flash MTD. + * @buf: A pointer to the destination buffer. + */ +static int mil_ecc_read_page(struct mtd_info *mtd, + struct nand_chip *nand, uint8_t *buf) +{ + struct gpmi_nfc_data *this = nand->priv; + struct device *dev = this->dev; + struct nfc_hal *nfc = this->nfc; + struct nfc_geometry *nfc_geo = &this->nfc_geometry; + struct mil *mil = &this->mil; + void *payload_virt = 0; + dma_addr_t payload_phys = ~0; + void *auxiliary_virt = 0; + dma_addr_t auxiliary_phys = ~0; + unsigned int i; + unsigned char *status; + unsigned int failed; + unsigned int corrected; + int error = 0; + + DEBUG(MTD_DEBUG_LEVEL2, "[gpmi_nfc ecc_read_page]\n"); + + gpmi_nfc_add_event("> mil_ecc_read_page", 1); + + /* + * Set up DMA. + * + * Notice that we don't try to use the caller's buffer as the auxiliary. + * We need to do a lot of fiddling to deliver the OOB, so there's no + * point. + */ + + error = mil_incoming_buffer_dma_begin(this, buf, mtd->writesize, + mil->payload_virt, mil->payload_phys, + nfc_geo->payload_size_in_bytes, + &payload_virt, &payload_phys); + + if (error) { + dev_err(dev, "[%s] Inadequate DMA buffer\n", __func__); + error = -ENOMEM; + goto exit_payload; + } + + auxiliary_virt = mil->auxiliary_virt; + auxiliary_phys = mil->auxiliary_phys; + + /* Ask the NFC. */ + + error = nfc->read_page(this, mil->current_chip, + payload_phys, auxiliary_phys); + + if (error) { + dev_err(dev, "[%s] Error in ECC-based read: %d\n", + __func__, error); + goto exit_nfc; + } + + /* Handle block mark swapping. */ + + mil_handle_block_mark_swapping(this, payload_virt, auxiliary_virt); + + /* Loop over status bytes, accumulating ECC status. */ + + failed = 0; + corrected = 0; + + status = ((unsigned char *) auxiliary_virt) + + nfc_geo->auxiliary_status_offset; + + for (i = 0; i < nfc_geo->ecc_chunk_count; i++, status++) { + + if ((*status == 0x00) || (*status == 0xff)) + continue; + + if (*status == 0xfe) { + failed++; + continue; + } + + corrected += *status; + + } + + /* Propagate ECC status to the owning MTD. */ + + mtd->ecc_stats.failed += failed; + mtd->ecc_stats.corrected += corrected; + + /* + * It's time to deliver the OOB bytes. See mil_ecc_read_oob() for + * details about our policy for delivering the OOB. + * + * We fill the caller's buffer with set bits, and then copy the block + * mark to th caller's buffer. Note that, if block mark swapping was + * necessary, it has already been done, so we can rely on the first + * byte of the auxiliary buffer to contain the block mark. + */ + + memset(nand->oob_poi, ~0, mtd->oobsize); + + nand->oob_poi[0] = ((uint8_t *) auxiliary_virt)[0]; + + /* Return. */ + +exit_nfc: + mil_incoming_buffer_dma_end(this, buf, mtd->writesize, + mil->payload_virt, mil->payload_phys, + nfc_geo->payload_size_in_bytes, + payload_virt, payload_phys); +exit_payload: + + gpmi_nfc_add_event("< mil_ecc_read_page", -1); + + return error; + +} + +/** + * mil_ecc_write_page() - MTD Interface ecc.write_page(). + * + * @mtd: A pointer to the owning MTD. + * @nand: A pointer to the owning NAND Flash MTD. + * @buf: A pointer to the source buffer. + */ +static void mil_ecc_write_page(struct mtd_info *mtd, + struct nand_chip *nand, const uint8_t *buf) +{ + struct gpmi_nfc_data *this = nand->priv; + struct device *dev = this->dev; + struct nfc_hal *nfc = this->nfc; + struct nfc_geometry *nfc_geo = &this->nfc_geometry; + struct boot_rom_helper *rom = this->rom; + struct mil *mil = &this->mil; + const void *payload_virt = 0; + dma_addr_t payload_phys = ~0; + const void *auxiliary_virt = 0; + dma_addr_t auxiliary_phys = ~0; + int error; + + DEBUG(MTD_DEBUG_LEVEL2, "[gpmi_nfc ecc_write_page]\n"); + + gpmi_nfc_add_event("> mil_ecc_write_page", 1); + + /* Set up DMA. */ + + if (rom->swap_block_mark) { + + /* + * If control arrives here, we're doing block mark swapping. + * Since we can't modify the caller's buffers, we must copy them + * into our own. + */ + + memcpy(mil->payload_virt, buf, mtd->writesize); + payload_virt = mil->payload_virt; + payload_phys = mil->payload_phys; + + memcpy(mil->auxiliary_virt, nand->oob_poi, mtd->oobsize); + auxiliary_virt = mil->auxiliary_virt; + auxiliary_phys = mil->auxiliary_phys; + + /* Handle block mark swapping. */ + + mil_handle_block_mark_swapping(this, + (void *) payload_virt, (void *) auxiliary_virt); + + } else { + + /* + * If control arrives here, we're not doing block mark swapping, + * so we can to try and use the caller's buffers. + */ + + error = mil_outgoing_buffer_dma_begin(this, + buf, mtd->writesize, + mil->payload_virt, mil->payload_phys, + nfc_geo->payload_size_in_bytes, + &payload_virt, &payload_phys); + + if (error) { + dev_err(dev, "[%s] Inadequate payload DMA buffer\n", + __func__); + goto exit_payload; + } + + error = mil_outgoing_buffer_dma_begin(this, + nand->oob_poi, mtd->oobsize, + mil->auxiliary_virt, mil->auxiliary_phys, + nfc_geo->auxiliary_size_in_bytes, + &auxiliary_virt, &auxiliary_phys); + + if (error) { + dev_err(dev, "[%s] Inadequate auxiliary DMA buffer\n", + __func__); + goto exit_auxiliary; + } + + } + + /* Ask the NFC. */ + + error = nfc->send_page(this, mil->current_chip, + payload_phys, auxiliary_phys); + + if (error) + dev_err(dev, "[%s] Error in ECC-based write: %d\n", + __func__, error); + + /* Return. */ + + if (!rom->swap_block_mark) + mil_outgoing_buffer_dma_end(this, nand->oob_poi, mtd->oobsize, + mil->auxiliary_virt, mil->auxiliary_phys, + nfc_geo->auxiliary_size_in_bytes, + auxiliary_virt, auxiliary_phys); +exit_auxiliary: + if (!rom->swap_block_mark) + mil_outgoing_buffer_dma_end(this, buf, mtd->writesize, + mil->payload_virt, mil->payload_phys, + nfc_geo->payload_size_in_bytes, + payload_virt, payload_phys); +exit_payload: + + gpmi_nfc_add_event("< mil_ecc_write_page", -1); + +} + +/** + * mil_hook_read_oob() - Hooked MTD Interface read_oob(). + * + * This function is a veneer that replaces the function originally installed by + * the NAND Flash MTD code. See the description of the raw_oob_mode field in + * struct mil for more information about this. + * + * @mtd: A pointer to the MTD. + * @from: The starting address to read. + * @ops: Describes the operation. + */ +static int mil_hook_read_oob(struct mtd_info *mtd, + loff_t from, struct mtd_oob_ops *ops) +{ + register struct nand_chip *chip = mtd->priv; + struct gpmi_nfc_data *this = chip->priv; + struct mil *mil = &this->mil; + int ret; + + mil->raw_oob_mode = ops->mode == MTD_OOB_RAW; + ret = mil->hooked_read_oob(mtd, from, ops); + mil->raw_oob_mode = false; + return ret; +} + +/** + * mil_hook_write_oob() - Hooked MTD Interface write_oob(). + * + * This function is a veneer that replaces the function originally installed by + * the NAND Flash MTD code. See the description of the raw_oob_mode field in + * struct mil for more information about this. + * + * @mtd: A pointer to the MTD. + * @to: The starting address to write. + * @ops: Describes the operation. + */ +static int mil_hook_write_oob(struct mtd_info *mtd, + loff_t to, struct mtd_oob_ops *ops) +{ + register struct nand_chip *chip = mtd->priv; + struct gpmi_nfc_data *this = chip->priv; + struct mil *mil = &this->mil; + int ret; + + mil->raw_oob_mode = ops->mode == MTD_OOB_RAW; + ret = mil->hooked_write_oob(mtd, to, ops); + mil->raw_oob_mode = false; + return ret; +} + +/** + * mil_hook_block_markbad() - Hooked MTD Interface block_markbad(). + * + * This function is a veneer that replaces the function originally installed by + * the NAND Flash MTD code. See the description of the marking_a_bad_block field + * in struct mil for more information about this. + * + * @mtd: A pointer to the MTD. + * @ofs: Byte address of the block to mark. + */ +static int mil_hook_block_markbad(struct mtd_info *mtd, loff_t ofs) +{ + register struct nand_chip *chip = mtd->priv; + struct gpmi_nfc_data *this = chip->priv; + struct mil *mil = &this->mil; + int ret; + + mil->marking_a_bad_block = true; + ret = mil->hooked_block_markbad(mtd, ofs); + mil->marking_a_bad_block = false; + return ret; +} + +/** + * mil_ecc_read_oob() - MTD Interface ecc.read_oob(). + * + * There are several places in this driver where we have to handle the OOB and + * block marks. This is the function where things are the most complicated, so + * this is where we try to explain it all. All the other places refer back to + * here. + * + * These are the rules, in order of decreasing importance: + * + * 1) Nothing the caller does can be allowed to imperil the block mark, so all + * write operations take measures to protect it. + * + * 2) In read operations, the first byte of the OOB we return must reflect the + * true state of the block mark, no matter where that block mark appears in + * the physical page. + * + * 3) ECC-based read operations return an OOB full of set bits (since we never + * allow ECC-based writes to the OOB, it doesn't matter what ECC-based reads + * return). + * + * 4) "Raw" read operations return a direct view of the physical bytes in the + * page, using the conventional definition of which bytes are data and which + * are OOB. This gives the caller a way to see the actual, physical bytes + * in the page, without the distortions applied by our ECC engine. + * + * + * What we do for this specific read operation depends on two questions: + * + * 1) Are we doing a "raw" read, or an ECC-based read? + * + * 2) Are we using block mark swapping or transcription? + * + * There are four cases, illustrated by the following Karnaugh map: + * + * | Raw | ECC-based | + * -------------+-------------------------+-------------------------+ + * | Read the conventional | | + * | OOB at the end of the | | + * Swapping | page and return it. It | | + * | contains exactly what | | + * | we want. | Read the block mark and | + * -------------+-------------------------+ return it in a buffer | + * | Read the conventional | full of set bits. | + * | OOB at the end of the | | + * | page and also the block | | + * Transcribing | mark in the metadata. | | + * | Copy the block mark | | + * | into the first byte of | | + * | the OOB. | | + * -------------+-------------------------+-------------------------+ + * + * Note that we break rule #4 in the Transcribing/Raw case because we're not + * giving an accurate view of the actual, physical bytes in the page (we're + * overwriting the block mark). That's OK because it's more important to follow + * rule #2. + * + * It turns out that knowing whether we want an "ECC-based" or "raw" read is not + * easy. When reading a page, for example, the NAND Flash MTD code calls our + * ecc.read_page or ecc.read_page_raw function. Thus, the fact that MTD wants an + * ECC-based or raw view of the page is implicit in which function it calls + * (there is a similar pair of ECC-based/raw functions for writing). + * + * Since MTD assumes the OOB is not covered by ECC, there is no pair of + * ECC-based/raw functions for reading or or writing the OOB. The fact that the + * caller wants an ECC-based or raw view of the page is not propagated down to + * this driver. + * + * Since our OOB *is* covered by ECC, we need this information. So, we hook the + * ecc.read_oob and ecc.write_oob function pointers in the owning + * struct mtd_info with our own functions. These hook functions set the + * raw_oob_mode field so that, when control finally arrives here, we'll know + * what to do. + * + * @mtd: A pointer to the owning MTD. + * @nand: A pointer to the owning NAND Flash MTD. + * @page: The page number to read. + * @sndcmd: Indicates this function should send a command to the chip before + * reading the out-of-band bytes. This is only false for small page + * chips that support auto-increment. + */ +static int mil_ecc_read_oob(struct mtd_info *mtd, struct nand_chip *nand, + int page, int sndcmd) +{ + struct gpmi_nfc_data *this = nand->priv; + struct physical_geometry *physical = &this->physical_geometry; + struct mil *mil = &this->mil; + struct boot_rom_helper *rom = this->rom; + int block_mark_column; + + DEBUG(MTD_DEBUG_LEVEL2, "[gpmi_nfc ecc_read_oob] " + "page: 0x%06x, sndcmd: %s\n", page, sndcmd ? "Yes" : "No"); + + gpmi_nfc_add_event("> mil_ecc_read_oob", 1); + + /* + * First, fill in the OOB buffer. If we're doing a raw read, we need to + * get the bytes from the physical page. If we're not doing a raw read, + * we need to fill the buffer with set bits. + */ + + if (mil->raw_oob_mode) { + + /* + * If control arrives here, we're doing a "raw" read. Send the + * command to read the conventional OOB. + */ + + nand->cmdfunc(mtd, NAND_CMD_READ0, + physical->page_data_size_in_bytes, page); + + /* Read out the conventional OOB. */ + + nand->read_buf(mtd, nand->oob_poi, mtd->oobsize); + + } else { + + /* + * If control arrives here, we're not doing a "raw" read. Fill + * the OOB buffer with set bits. + */ + + memset(nand->oob_poi, ~0, mtd->oobsize); + + } + + /* + * Now, we want to make sure the block mark is correct. In the + * Swapping/Raw case, we already have it. Otherwise, we need to + * explicitly read it. + */ + + if (!(rom->swap_block_mark && mil->raw_oob_mode)) { + + /* First, figure out where the block mark is. */ + + if (rom->swap_block_mark) + block_mark_column = physical->page_data_size_in_bytes; + else + block_mark_column = 0; + + /* Send the command to read the block mark. */ + + nand->cmdfunc(mtd, NAND_CMD_READ0, block_mark_column, page); + + /* Read the block mark into the first byte of the OOB buffer. */ + + nand->oob_poi[0] = nand->read_byte(mtd); + + } + + /* + * Return true, indicating that the next call to this function must send + * a command. + */ + + gpmi_nfc_add_event("< mil_ecc_read_oob", -1); + + return true; + +} + +/** + * mil_ecc_write_oob() - MTD Interface ecc.write_oob(). + * + * @mtd: A pointer to the owning MTD. + * @nand: A pointer to the owning NAND Flash MTD. + * @page: The page number to write. + */ +static int mil_ecc_write_oob(struct mtd_info *mtd, + struct nand_chip *nand, int page) +{ + struct gpmi_nfc_data *this = nand->priv; + struct device *dev = this->dev; + struct physical_geometry *physical = &this->physical_geometry; + struct mil *mil = &this->mil; + struct boot_rom_helper *rom = this->rom; + uint8_t block_mark = 0; + int block_mark_column; + int status; + int error = 0; + + DEBUG(MTD_DEBUG_LEVEL2, + "[gpmi_nfc ecc_write_oob] page: 0x%06x\n", page); + + gpmi_nfc_add_event("> mil_ecc_write_oob", -1); + + /* + * There are fundamental incompatibilities between the i.MX GPMI NFC and + * the NAND Flash MTD model that make it essentially impossible to write + * the out-of-band bytes. + * + * We permit *ONE* exception. If the *intent* of writing the OOB is to + * mark a block bad, we can do that. + */ + + if (!mil->marking_a_bad_block) { + dev_emerg(dev, "This driver doesn't support writing the OOB\n"); + WARN_ON(1); + error = -EIO; + goto exit; + } + + /* + * If control arrives here, we're marking a block bad. First, figure out + * where the block mark is. + * + * If we're using swapping, the block mark is in the conventional + * location. Otherwise, we're using transcription, and the block mark + * appears in the first byte of the page. + */ + + if (rom->swap_block_mark) + block_mark_column = physical->page_data_size_in_bytes; + else + block_mark_column = 0; + + /* Write the block mark. */ + + nand->cmdfunc(mtd, NAND_CMD_SEQIN, block_mark_column, page); + nand->write_buf(mtd, &block_mark, 1); + nand->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1); + + status = nand->waitfunc(mtd, nand); + + /* Check if it worked. */ + + if (status & NAND_STATUS_FAIL) + error = -EIO; + + /* Return. */ + +exit: + + gpmi_nfc_add_event("< mil_ecc_write_oob", -1); + + return error; + +} + +/** + * mil_block_bad - Claims all blocks are good. + * + * In principle, this function is *only* called when the NAND Flash MTD system + * isn't allowed to keep an in-memory bad block table, so it is forced to ask + * the driver for bad block information. + * + * In fact, we permit the NAND Flash MTD system to have an in-memory BBT, so + * this function is *only* called when we take it away. + * + * We take away the in-memory BBT when the user sets the "ignorebad" parameter, + * which indicates that all blocks should be reported good. + * + * Thus, this function is only called when we want *all* blocks to look good, + * so it *always* return success. + * + * @mtd: Ignored. + * @ofs: Ignored. + * @getchip: Ignored. + */ +static int mil_block_bad(struct mtd_info *mtd, loff_t ofs, int getchip) +{ + return 0; +} + +/** + * mil_set_physical_geometry() - Set up the physical medium geometry. + * + * This function retrieves the physical geometry information discovered by + * nand_scan(), corrects it, and records it in the per-device data structure. + * + * @this: Per-device data. + */ +static int mil_set_physical_geometry(struct gpmi_nfc_data *this) +{ + struct mil *mil = &this->mil; + struct physical_geometry *physical = &this->physical_geometry; + struct nand_chip *nand = &mil->nand; + struct nand_device_info *info = &this->device_info; + unsigned int block_size_in_pages; + unsigned int chip_size_in_blocks; + unsigned int chip_size_in_pages; + uint64_t medium_size_in_bytes; + + /* + * Record the number of physical chips that MTD found. + */ + + physical->chip_count = nand->numchips; + + /* + * We know the total size of a page. We need to break that down into the + * data size and OOB size. The data size is the largest power of two + * that will fit in the given page size. The OOB size is what's left + * over. + */ + + physical->page_data_size_in_bytes = + 1 << (fls(info->page_total_size_in_bytes) - 1); + + physical->page_oob_size_in_bytes = + info->page_total_size_in_bytes - + physical->page_data_size_in_bytes; + + /* + * Now that we know the page data size, we can multiply this by the + * number of pages in a block to compute the block size. + */ + + physical->block_size_in_bytes = + physical->page_data_size_in_bytes * info->block_size_in_pages; + + /* Get the chip size. */ + + physical->chip_size_in_bytes = info->chip_size_in_bytes; + + /* Compute some interesting facts. */ + + block_size_in_pages = + physical->block_size_in_bytes >> + (fls(physical->page_data_size_in_bytes) - 1); + chip_size_in_pages = + physical->chip_size_in_bytes >> + (fls(physical->page_data_size_in_bytes) - 1); + chip_size_in_blocks = + physical->chip_size_in_bytes >> + (fls(physical->block_size_in_bytes) - 1); + medium_size_in_bytes = + physical->chip_size_in_bytes * physical->chip_count; + + /* Report. */ + + #if defined(DETAILED_INFO) + + pr_info("-----------------\n"); + pr_info("Physical Geometry\n"); + pr_info("-----------------\n"); + pr_info("Chip Count : %d\n", physical->chip_count); + pr_info("Page Data Size in Bytes: %u (0x%x)\n", + physical->page_data_size_in_bytes, + physical->page_data_size_in_bytes); + pr_info("Page OOB Size in Bytes : %u\n", + physical->page_oob_size_in_bytes); + pr_info("Block Size in Bytes : %u (0x%x)\n", + physical->block_size_in_bytes, + physical->block_size_in_bytes); + pr_info("Block Size in Pages : %u (0x%x)\n", + block_size_in_pages, + block_size_in_pages); + pr_info("Chip Size in Bytes : %llu (0x%llx)\n", + physical->chip_size_in_bytes, + physical->chip_size_in_bytes); + pr_info("Chip Size in Pages : %u (0x%x)\n", + chip_size_in_pages, chip_size_in_pages); + pr_info("Chip Size in Blocks : %u (0x%x)\n", + chip_size_in_blocks, chip_size_in_blocks); + pr_info("Medium Size in Bytes : %llu (0x%llx)\n", + medium_size_in_bytes, medium_size_in_bytes); + + #endif + + /* Return success. */ + + return 0; + +} + +/** + * mil_set_nfc_geometry() - Set up the NFC geometry. + * + * This function calls the NFC HAL to select an NFC geometry that is compatible + * with the medium's physical geometry. + * + * @this: Per-device data. + */ +static int mil_set_nfc_geometry(struct gpmi_nfc_data *this) +{ + struct nfc_hal *nfc = this->nfc; +#if defined(DETAILED_INFO) + struct nfc_geometry *geo = &this->nfc_geometry; +#endif + /* Set the NFC geometry. */ + + if (nfc->set_geometry(this)) + return !0; + + /* Report. */ + + #if defined(DETAILED_INFO) + + pr_info("------------\n"); + pr_info("NFC Geometry\n"); + pr_info("------------\n"); + pr_info("ECC Algorithm : %s\n", geo->ecc_algorithm); + pr_info("ECC Strength : %u\n", geo->ecc_strength); + pr_info("Page Size in Bytes : %u\n", geo->page_size_in_bytes); + pr_info("Metadata Size in Bytes : %u\n", geo->metadata_size_in_bytes); + pr_info("ECC Chunk Size in Bytes: %u\n", geo->ecc_chunk_size_in_bytes); + pr_info("ECC Chunk Count : %u\n", geo->ecc_chunk_count); + pr_info("Payload Size in Bytes : %u\n", geo->payload_size_in_bytes); + pr_info("Auxiliary Size in Bytes: %u\n", geo->auxiliary_size_in_bytes); + pr_info("Auxiliary Status Offset: %u\n", geo->auxiliary_status_offset); + pr_info("Block Mark Byte Offset : %u\n", geo->block_mark_byte_offset); + pr_info("Block Mark Bit Offset : %u\n", geo->block_mark_bit_offset); + + #endif + + /* Return success. */ + + return 0; + +} + +/** + * mil_set_boot_rom_helper_geometry() - Set up the Boot ROM Helper geometry. + * + * @this: Per-device data. + */ +static int mil_set_boot_rom_helper_geometry(struct gpmi_nfc_data *this) +{ + struct boot_rom_helper *rom = this->rom; +#if defined(DETAILED_INFO) + struct boot_rom_geometry *geo = &this->rom_geometry; +#endif + + /* Set the Boot ROM Helper geometry. */ + + if (rom->set_geometry(this)) + return !0; + + /* Report. */ + + #if defined(DETAILED_INFO) + + pr_info("-----------------\n"); + pr_info("Boot ROM Geometry\n"); + pr_info("-----------------\n"); + pr_info("Boot Area Count : %u\n", geo->boot_area_count); + pr_info("Boot Area Size in Bytes : %u (0x%x)\n", + geo->boot_area_size_in_bytes, geo->boot_area_size_in_bytes); + pr_info("Stride Size in Pages : %u\n", geo->stride_size_in_pages); + pr_info("Search Area Stride Exponent: %u\n", + geo->search_area_stride_exponent); + + #endif + + /* Return success. */ + + return 0; + +} + +/** + * mil_set_mtd_geometry() - Set up the MTD geometry. + * + * This function adjusts the owning MTD data structures to match the logical + * geometry we've chosen. + * + * @this: Per-device data. + */ +static int mil_set_mtd_geometry(struct gpmi_nfc_data *this) +{ + struct physical_geometry *physical = &this->physical_geometry; + struct mil *mil = &this->mil; + struct nand_ecclayout *layout = &mil->oob_layout; + struct nand_chip *nand = &mil->nand; + struct mtd_info *mtd = &mil->mtd; + + /* Configure the struct nand_ecclayout. */ + + layout->eccbytes = 0; + layout->oobavail = physical->page_oob_size_in_bytes; + layout->oobfree[0].offset = 0; + layout->oobfree[0].length = physical->page_oob_size_in_bytes; + + /* Configure the struct mtd_info. */ + + mtd->size = nand->numchips * physical->chip_size_in_bytes; + mtd->erasesize = physical->block_size_in_bytes; + mtd->writesize = physical->page_data_size_in_bytes; + mtd->ecclayout = layout; + mtd->oobavail = mtd->ecclayout->oobavail; + mtd->oobsize = mtd->ecclayout->oobavail + mtd->ecclayout->eccbytes; + mtd->subpage_sft = 0; /* We don't support sub-page writing. */ + + /* Configure the struct nand_chip. */ + + nand->chipsize = physical->chip_size_in_bytes; + nand->page_shift = ffs(mtd->writesize) - 1; + nand->pagemask = (nand->chipsize >> nand->page_shift) - 1; + nand->subpagesize = mtd->writesize >> mtd->subpage_sft; + nand->phys_erase_shift = ffs(mtd->erasesize) - 1; + nand->bbt_erase_shift = nand->phys_erase_shift; + nand->oob_poi = nand->buffers->databuf + mtd->writesize; + nand->ecc.layout = layout; + if (nand->chipsize & 0xffffffff) + nand->chip_shift = ffs((unsigned) nand->chipsize) - 1; + else + nand->chip_shift = + ffs((unsigned) (nand->chipsize >> 32)) + 32 - 1; + + /* Return success. */ + + return 0; + +} + +/** + * mil_set_geometry() - Set up the medium geometry. + * + * @this: Per-device data. + */ +static int mil_set_geometry(struct gpmi_nfc_data *this) +{ + struct device *dev = this->dev; + struct nfc_geometry *nfc_geo = &this->nfc_geometry; + struct mil *mil = &this->mil; + + /* Set up the various layers of geometry, in this specific order. */ + + if (mil_set_physical_geometry(this)) + return -ENXIO; + + if (mil_set_nfc_geometry(this)) + return -ENXIO; + + if (mil_set_boot_rom_helper_geometry(this)) + return -ENXIO; + + if (mil_set_mtd_geometry(this)) + return -ENXIO; + + /* + * Allocate the page buffer. + * + * Both the payload buffer and the auxiliary buffer must appear on + * 32-bit boundaries. We presume the size of the payload buffer is a + * power of two and is much larger than four, which guarantees the + * auxiliary buffer will appear on a 32-bit boundary. + */ + + mil->page_buffer_size = nfc_geo->payload_size_in_bytes + + nfc_geo->auxiliary_size_in_bytes; + + mil->page_buffer_virt = + dma_alloc_coherent(dev, mil->page_buffer_size, + &mil->page_buffer_phys, GFP_DMA); + + if (!mil->page_buffer_virt) + return -ENOMEM; + + /* Slice up the page buffer. */ + + mil->payload_virt = mil->page_buffer_virt; + mil->payload_phys = mil->page_buffer_phys; + + mil->auxiliary_virt = ((char *) mil->payload_virt) + + nfc_geo->payload_size_in_bytes; + mil->auxiliary_phys = mil->payload_phys + + nfc_geo->payload_size_in_bytes; + + /* Return success. */ + + return 0; + +} + +/** + * mil_pre_bbt_scan() - Prepare for the BBT scan. + * + * @this: Per-device data. + */ +static int mil_pre_bbt_scan(struct gpmi_nfc_data *this) +{ + struct device *dev = this->dev; + struct physical_geometry *physical = &this->physical_geometry; + struct boot_rom_helper *rom = this->rom; + struct mil *mil = &this->mil; + struct nand_chip *nand = &mil->nand; + struct mtd_info *mtd = &mil->mtd; + unsigned int block_count; + unsigned int block; + int chip; + int page; + loff_t byte; + uint8_t block_mark; + int error; + + /* + * Check if we can use block mark swapping, which enables us to leave + * the block marks where they are. If so, we don't need to do anything + * at all. + */ + + if (rom->swap_block_mark) + return 0; + + /* + * If control arrives here, we can't use block mark swapping, which + * means we're forced to use transcription. First, scan for the + * transcription stamp. If we find it, then we don't have to do + * anything -- the block marks are already transcribed. + */ + + if (rom->check_transcription_stamp(this)) + return 0; + + /* + * If control arrives here, we couldn't find a transcription stamp, so + * so we presume the block marks are in the conventional location. + */ + + pr_info("Transcribing bad block marks...\n"); + + /* Compute the number of blocks in the entire medium. */ + + block_count = + physical->chip_size_in_bytes >> nand->phys_erase_shift; + + /* + * Loop over all the blocks in the medium, transcribing block marks as + * we go. + */ + + for (block = 0; block < block_count; block++) { + + /* + * Compute the chip, page and byte addresses for this block's + * conventional mark. + */ + + chip = block >> (nand->chip_shift - nand->phys_erase_shift); + page = block << (nand->phys_erase_shift - nand->page_shift); + byte = block << nand->phys_erase_shift; + + /* Select the chip. */ + + nand->select_chip(mtd, chip); + + /* Send the command to read the conventional block mark. */ + + nand->cmdfunc(mtd, NAND_CMD_READ0, + physical->page_data_size_in_bytes, page); + + /* Read the conventional block mark. */ + + block_mark = nand->read_byte(mtd); + + /* + * Check if the block is marked bad. If so, we need to mark it + * again, but this time the result will be a mark in the + * location where we transcribe block marks. + * + * Notice that we have to explicitly set the marking_a_bad_block + * member before we call through the block_markbad function + * pointer in the owning struct nand_chip. If we could call + * though the block_markbad function pointer in the owning + * struct mtd_info, which we have hooked, then this would be + * taken care of for us. Unfortunately, we can't because that + * higher-level code path will do things like consulting the + * in-memory bad block table -- which doesn't even exist yet! + * So, we have to call at a lower level and handle some details + * ourselves. + */ + + if (block_mark != 0xff) { + pr_info("Transcribing mark in block %u\n", block); + mil->marking_a_bad_block = true; + error = nand->block_markbad(mtd, byte); + mil->marking_a_bad_block = false; + if (error) + dev_err(dev, "Failed to mark block bad with " + "error %d\n", error); + } + + /* Deselect the chip. */ + + nand->select_chip(mtd, -1); + + } + + /* Write the stamp that indicates we've transcribed the block marks. */ + + rom->write_transcription_stamp(this); + + /* Return success. */ + + return 0; + +} + +/** + * mil_scan_bbt() - MTD Interface scan_bbt(). + * + * The HIL calls this function once, when it initializes the NAND Flash MTD. + * + * Nominally, the purpose of this function is to look for or create the bad + * block table. In fact, since the HIL calls this function at the very end of + * the initialization process started by nand_scan(), and the HIL doesn't have a + * more formal mechanism, everyone "hooks" this function to continue the + * initialization process. + * + * At this point, the physical NAND Flash chips have been identified and + * counted, so we know the physical geometry. This enables us to make some + * important configuration decisions. + * + * The return value of this function propogates directly back to this driver's + * call to nand_scan(). Anything other than zero will cause this driver to + * tear everything down and declare failure. + * + * @mtd: A pointer to the owning MTD. + */ +static int mil_scan_bbt(struct mtd_info *mtd) +{ + struct nand_chip *nand = mtd->priv; + struct gpmi_nfc_data *this = nand->priv; + struct nfc_hal *nfc = this->nfc; + struct mil *mil = &this->mil; + int saved_chip_number; + uint8_t id_bytes[NAND_DEVICE_ID_BYTE_COUNT]; + struct nand_device_info *info; + struct gpmi_nfc_timing timing; + int error; + + DEBUG(MTD_DEBUG_LEVEL2, "[gpmi_nfc scan_bbt] \n"); + + /* + * Tell MTD users that the out-of-band area can't be written. + * + * This flag is not part of the standard kernel source tree. It comes + * from a patch that touches both MTD and JFFS2. + * + * The problem is that, without this patch, JFFS2 believes it can write + * the data area and the out-of-band area separately. This is wrong for + * two reasons: + * + * 1) Our NFC distributes out-of-band bytes throughout the page, + * intermingled with the data, and covered by the same ECC. + * Thus, it's not possible to write the out-of-band bytes and + * data bytes separately. + * + * 2) Large page (MLC) Flash chips don't support partial page + * writes. You must write the entire page at a time. Thus, even + * if our NFC didn't force you to write out-of-band and data + * bytes together, it would *still* be a bad idea to do + * otherwise. + */ + + mtd->flags &= ~MTD_OOB_WRITEABLE; + + /* + * MTD identified the attached NAND Flash devices, but we have a much + * better database that we want to consult. First, we need to gather all + * the ID bytes from the first chip (MTD only read the first two). + */ + + saved_chip_number = mil->current_chip; + nand->select_chip(mtd, 0); + + nand->cmdfunc(mtd, NAND_CMD_READID, 0, -1); + nand->read_buf(mtd, id_bytes, NAND_DEVICE_ID_BYTE_COUNT); + + nand->select_chip(mtd, saved_chip_number); + + /* Look up this device in our database. */ + + info = nand_device_get_info(id_bytes); + + /* Check if we understand this device. */ + + if (!info) { + pr_err("Unrecognized NAND Flash device.\n"); + return !0; + } + + /* Display the information we discovered. */ + + #if defined(DETAILED_INFO) + pr_info("-----------------------------\n"); + pr_info("NAND Flash Device Information\n"); + pr_info("-----------------------------\n"); + nand_device_print_info(info); + #endif + + /* + * Copy the device info into the per-device data. We can't just keep + * the pointer because that storage is reclaimed after initialization. + */ + + this->device_info = *info; + this->device_info.description = kstrdup(info->description, GFP_KERNEL); + + /* Set up geometry. */ + + error = mil_set_geometry(this); + + if (error) + return error; + + /* Set up timing. */ + + timing.data_setup_in_ns = info->data_setup_in_ns; + timing.data_hold_in_ns = info->data_hold_in_ns; + timing.address_setup_in_ns = info->address_setup_in_ns; + timing.gpmi_sample_delay_in_ns = info->gpmi_sample_delay_in_ns; + timing.tREA_in_ns = info->tREA_in_ns; + timing.tRLOH_in_ns = info->tRLOH_in_ns; + timing.tRHOH_in_ns = info->tRHOH_in_ns; + + error = nfc->set_timing(this, &timing); + + if (error) + return error; + + /* Prepare for the BBT scan. */ + + error = mil_pre_bbt_scan(this); + + if (error) + return error; + + /* We use the reference implementation for bad block management. */ + + error = nand_default_bbt(mtd); + + if (error) + return error; + + /* Return success. */ + + return 0; + +} + +/** + * mil_boot_areas_init() - Initializes boot areas. + * + * @this: Per-device data. + */ +static int mil_boot_areas_init(struct gpmi_nfc_data *this) +{ + struct device *dev = this->dev; + struct physical_geometry *physical = &this->physical_geometry; + struct boot_rom_geometry *rom = &this->rom_geometry; + struct mil *mil = &this->mil; + struct mtd_info *mtd = &mil->mtd; + struct nand_chip *nand = &mil->nand; + int mtd_support_is_adequate; + unsigned int i; + struct mtd_partition partitions[4]; + struct mtd_info *search_mtd; + struct mtd_info *chip_0_remainder_mtd = 0; + struct mtd_info *medium_remainder_mtd = 0; + struct mtd_info *concatenate[2]; + + /* + * Here we declare the static strings we use to name partitions. We use + * static strings because, as of 2.6.31, the partitioning code *always* + * registers the partition MTDs it creates and leaves behind *no* other + * trace of its work. So, once we've created a partition, we must search + * the master MTD table to find the MTDs we created. Since we're using + * static strings, we can simply search the master table for an MTD with + * a name field pointing to a known address. + */ + + static char *chip_0_boot_name = "gpmi-nfc-0-boot"; + static char *chip_0_remainder_name = "gpmi-nfc-0-remainder"; + static char *chip_1_boot_name = "gpmi-nfc-1-boot"; + static char *medium_remainder_name = "gpmi-nfc-remainder"; + static char *general_use_name = "gpmi-nfc-general-use"; + + /* Check if we're protecting the boot areas.*/ + + if (!rom->boot_area_count) { + + /* + * If control arrives here, we're not protecting the boot areas. + * In this case, there are not boot area partitons, and the main + * MTD is the general use MTD. + */ + + mil->general_use_mtd = &mil->mtd; + + return 0; + + } + + /* + * If control arrives here, we're protecting the boot areas. Check if we + * have the MTD support we need. + */ + + pr_info("Boot area protection is enabled.\n"); + + if (rom->boot_area_count > 1) { + + /* + * If the Boot ROM wants more than one boot area, then we'll + * need to create partitions *and* concatenate them. + */ + + #if defined(CONFIG_MTD_PARTITIONS) && defined(CONFIG_MTD_CONCAT) + mtd_support_is_adequate = true; + #else + mtd_support_is_adequate = false; + #endif + + } else if (rom->boot_area_count == 1) { + + /* + * If the Boot ROM wants only one boot area, then we only need + * to create partitions -- we don't need to concatenate them. + */ + + #if defined(CONFIG_MTD_PARTITIONS) + mtd_support_is_adequate = true; + #else + mtd_support_is_adequate = false; + #endif + + } else { + + /* + * If control arrives here, we're protecting the boot area, but + * somehow the boot area count was set to zero. This doesn't + * make any sense. + */ + + dev_err(dev, "Internal error: boot area count is " + "incorrectly set to zero."); + return -ENXIO; + + } + + if (!mtd_support_is_adequate) { + dev_err(dev, "Configured MTD support is inadequate to " + "protect the boot area(s)."); + return -ENXIO; + } + + /* + * If control arrives here, we're protecting boot areas and we have + * everything we need to do so. + * + * We have special code to handle the case for one boot area. + * + * The code that handles "more than one" boot area actually only handles + * two. We *could* write the general case, but that would take a lot of + * time to both write and test -- and, right now, we don't have a chip + * that cares. + */ + + /* Check if a boot area is larger than a single chip. */ + + if (rom->boot_area_size_in_bytes > physical->chip_size_in_bytes) { + dev_emerg(dev, "Boot area size is larger than a chip"); + return -ENXIO; + } + + if (rom->boot_area_count == 1) { + +#if defined(CONFIG_MTD_PARTITIONS) + + /* + * We partition the medium like so: + * + * +------+----------------------------------------------------+ + * | Boot | General Use | + * +------+----------------------------------------------------+ + */ + + /* Chip 0 Boot */ + + partitions[0].name = chip_0_boot_name; + partitions[0].offset = 0; + partitions[0].size = rom->boot_area_size_in_bytes; + partitions[0].mask_flags = 0; + + /* General Use */ + + partitions[1].name = general_use_name; + partitions[1].offset = rom->boot_area_size_in_bytes; + partitions[1].size = MTDPART_SIZ_FULL; + partitions[1].mask_flags = 0; + + /* Construct and register the partitions. */ + + add_mtd_partitions(mtd, partitions, 2); + + /* Find the general use MTD. */ + + for (i = 0; i < MAX_MTD_DEVICES; i++) { + + /* Get the current MTD so we can examine it. */ + + search_mtd = get_mtd_device(0, i); + + /* Check if we got nonsense. */ + + if ((!search_mtd) || (search_mtd == ERR_PTR(-ENODEV))) + continue; + + /* Check if the current MTD is one of our remainders. */ + + if (search_mtd->name == general_use_name) + mil->general_use_mtd = search_mtd; + + /* Put the MTD back. We only wanted a quick look. */ + + put_mtd_device(search_mtd); + + } + + if (!mil->general_use_mtd) { + dev_emerg(dev, "Can't find general use MTD"); + BUG(); + } + +#endif + + } else if (rom->boot_area_count == 2) { + +#if defined(CONFIG_MTD_PARTITIONS) && defined(CONFIG_MTD_CONCAT) + + /* + * If control arrives here, there is more than one boot area. + * We partition the medium and concatenate the remainders like + * so: + * + * --- Chip 0 --- --- Chip 1 --- ... ------- Chip N ------- + * / \ / \ + * +----+----------+----+--------------- ... ------------------+ + * |Boot|Remainder |Boot| Remainder | + * +----+----------+----+--------------- ... ------------------+ + * | | / / + * | | / / + * | | / / + * | |/ / + * +----------+----------- ... ----------------------+ + * | General Use | + * +---------------------- ... ----------------------+ + * + * Notice that the results we leave in the master MTD table + * look like this: + * + * * Chip 0 Boot Area + * * Chip 1 Boot Area + * * General Use + * + * Some user space programs expect the boot partitions to + * appear first. This is naive, but let's try not to cause + * any trouble, where we can avoid it. + */ + + /* Chip 0 Boot */ + + partitions[0].name = chip_0_boot_name; + partitions[0].offset = 0; + partitions[0].size = rom->boot_area_size_in_bytes; + partitions[0].mask_flags = 0; + + /* Chip 1 Boot */ + + partitions[1].name = chip_1_boot_name; + partitions[1].offset = nand->chipsize; + partitions[1].size = rom->boot_area_size_in_bytes; + partitions[1].mask_flags = 0; + + /* Chip 0 Remainder */ + + partitions[2].name = chip_0_remainder_name; + partitions[2].offset = rom->boot_area_size_in_bytes; + partitions[2].size = nand->chipsize - + rom->boot_area_size_in_bytes; + partitions[2].mask_flags = 0; + + /* Medium Remainder */ + + partitions[3].name = medium_remainder_name; + partitions[3].offset = nand->chipsize + + rom->boot_area_size_in_bytes; + partitions[3].size = MTDPART_SIZ_FULL; + partitions[3].mask_flags = 0; + + /* Construct and register the partitions. */ + + add_mtd_partitions(mtd, partitions, 4); + + /* Find the remainder partitions. */ + + for (i = 0; i < MAX_MTD_DEVICES; i++) { + + /* Get the current MTD so we can examine it. */ + + search_mtd = get_mtd_device(0, i); + + /* Check if we got nonsense. */ + + if ((!search_mtd) || (search_mtd == ERR_PTR(-ENODEV))) + continue; + + /* Check if the current MTD is one of our remainders. */ + + if (search_mtd->name == chip_0_remainder_name) + chip_0_remainder_mtd = search_mtd; + + if (search_mtd->name == medium_remainder_name) + medium_remainder_mtd = search_mtd; + + /* Put the MTD back. We only wanted a quick look. */ + + put_mtd_device(search_mtd); + + } + + if (!chip_0_remainder_mtd || !medium_remainder_mtd) { + dev_emerg(dev, "Can't find remainder partitions"); + BUG(); + } + + /* + * Unregister the remainder MTDs. Note that we are *not* + * destroying these MTDs -- we're just removing from the + * globally-visible list. There's no need for anyone to see + * these. + */ + + del_mtd_device(chip_0_remainder_mtd); + del_mtd_device(medium_remainder_mtd); + + /* Concatenate the remainders and register the result. */ + + concatenate[0] = chip_0_remainder_mtd; + concatenate[1] = medium_remainder_mtd; + + mil->general_use_mtd = mtd_concat_create(concatenate, + 2, general_use_name); + + add_mtd_device(mil->general_use_mtd); + +#endif + + } else { + dev_err(dev, "Boot area count greater than two is " + "unimplemented.\n"); + return -ENXIO; + } + + /* Return success. */ + + return 0; + +} + +/** + * mil_boot_areas_exit() - Shuts down boot areas. + * + * @this: Per-device data. + */ +static void mil_boot_areas_exit(struct gpmi_nfc_data *this) +{ + struct boot_rom_geometry *rom = &this->rom_geometry; + struct mil *mil = &this->mil; + struct mtd_info *mtd = &mil->mtd; + + /* Check if we're protecting the boot areas.*/ + + if (!rom->boot_area_count) { + + /* + * If control arrives here, we're not protecting the boot areas. + * That means we never created any boot area partitions, and the + * general use MTD is just the main MTD. + */ + + mil->general_use_mtd = 0; + + return; + + } + + /* + * If control arrives here, we're protecting the boot areas. + * + * Start by checking if there is more than one boot area. If so, then + * we both partitioned the medium and then concatenated some of the + * partitions to form the general use MTD. The first step is to get rid + * of the concatenation. + */ + + #if defined(CONFIG_MTD_PARTITIONS) && defined(CONFIG_MTD_CONCAT) + if (rom->boot_area_count > 1) { + del_mtd_device(mil->general_use_mtd); + mtd_concat_destroy(mil->general_use_mtd); + } + #endif + + /* + * At this point, we're left only with the partitions of the main MTD. + * Delete them. + */ + + #if defined(CONFIG_MTD_PARTITIONS) + del_mtd_partitions(mtd); + #endif + + /* The general use MTD no longer exists. */ + + mil->general_use_mtd = 0; + +} + +/** + * mil_construct_ubi_partitions() - Constructs partitions for UBI. + * + * MTD uses a 64-bit value to express the size of MTDs, but UBI is still using + * a 32-bit value. For this reason, UBI can't work on top of an MTD with size + * greater than 2GiB. In this function, we examine the general use MTD and, if + * it's larger than 2GiB, we construct a set of partitions for that MTD such + * that none are too large for UBI to comprehend. + * + * @this: Per-device data. + */ +static void mil_construct_ubi_partitions(struct gpmi_nfc_data *this) +{ +#if defined(CONFIG_MTD_PARTITIONS) + struct device *dev = this->dev; + struct mil *mil = &this->mil; + unsigned int partition_count; + struct mtd_partition *partitions; + unsigned int name_size; + char *names; + unsigned int memory_block_size; + unsigned int i; + + static const char *name_prefix = "gpmi-nfc-ubi-"; + + /* + * If the general use MTD isn't larger than 2GiB, we have nothing to do. + */ + + if (mil->general_use_mtd->size <= SZ_2G) + return; + + /* + * If control arrives here, the general use MTD is larger than 2GiB. We + * need to split it up into some number of partitions. Find out how many + * 2GiB partitions we'll be creating. + */ + + partition_count = mil->general_use_mtd->size >> 31; + + /* + * If the MTD size doesn't evenly divide by 2GiB, we'll need another + * partition to hold the extra. + */ + + if (mil->general_use_mtd->size & ((1 << 30) - 1)) + partition_count++; + + /* + * We're going to allocate a single memory block to contain all the + * partition structures and their names. Calculate how large it must be. + */ + + name_size = strlen(name_prefix) + 4; + + memory_block_size = (sizeof(*partitions) + name_size) * partition_count; + + /* + * Attempt to allocate the block. + */ + + partitions = kzalloc(memory_block_size, GFP_KERNEL); + + if (!partitions) { + dev_err(dev, "Could not allocate memory for UBI partitions.\n"); + return; + } + + names = (char *)(partitions + partition_count); + + /* Loop over partitions, filling in the details. */ + + for (i = 0; i < partition_count; i++) { + + partitions[i].name = names; + partitions[i].size = SZ_2G; + partitions[i].offset = MTDPART_OFS_NXTBLK; + + sprintf(names, "%s%u", name_prefix, i); + names += name_size; + + } + + /* Adjust the last partition to take up the remainder. */ + + partitions[i - 1].size = MTDPART_SIZ_FULL; + + /* Record everything in the device data structure. */ + + mil->partitions = partitions; + mil->partition_count = partition_count; + mil->ubi_partition_memory = partitions; + +#endif +} + +/** + * mil_partitions_init() - Initializes partitions. + * + * @this: Per-device data. + */ +static int mil_partitions_init(struct gpmi_nfc_data *this) +{ + struct gpmi_nfc_platform_data *pdata = this->pdata; + struct mil *mil = &this->mil; + struct mtd_info *mtd = &mil->mtd; + int error; + + /* + * Set up the boot areas. When this function returns, if there has been + * no error, the boot area partitions (if any) will have been created + * and registered. Also, the general_use_mtd field will point to an MTD + * we can use. + */ + + error = mil_boot_areas_init(this); + + if (error) + return error; + + /* + * If we've been told to, register the MTD that represents the entire + * medium. Normally, we don't register the main MTD because we only want + * to expose the medium through the boot area partitions and the general + * use partition. + * + * We do this *after* setting up the boot areas because, for historical + * reasons, we like the lowest-numbered MTDs to be the boot areas. + */ + + if (register_main_mtd) { + pr_info("Registering the main MTD.\n"); + add_mtd_device(mtd); + } + +#if defined(CONFIG_MTD_PARTITIONS) + + /* + * If control arrives here, partitioning is available. + * + * There are three possible sets of partitions we might apply, in order + * of decreasing priority: + * + * 1) Partitions dynamically discovered from sources defined by the + * platform. These can come from, for example, the command line or + * a partition table. + * + * 2) Partitions attached to the platform data. + * + * 3) Partitions we generate to deal with limitations in UBI. + * + * Recall that the pointer to the general use MTD *may* just point to + * the main MTD. + */ + + /* + * First, try to get partition information from the sources defined by + * the platform. + */ + + if (pdata->partition_source_types) + mil->partition_count = + parse_mtd_partitions(mil->general_use_mtd, + pdata->partition_source_types, + &mil->partitions, 0); + + /* + * Check if we got anything. If not, then accept whatever partitions are + * attached to the platform data. + */ + + if ((mil->partition_count <= 0) && (pdata->partitions)) { + mil->partition_count = mil->partition_count; + mil->partitions = mil->partitions; + } + + /* + * If we still don't have any partitions to apply, then we might want to + * apply some of our own, to account for UBI's limitations. + */ + + if (!mil->partition_count) + mil_construct_ubi_partitions(this); + + /* If we came up with any partitions, apply them. */ + + if (mil->partition_count) + add_mtd_partitions(mil->general_use_mtd, + mil->partitions, + mil->partition_count); + +#endif + + /* Return success. */ + + return 0; + +} + +/** + * mil_partitions_exit() - Shuts down partitions. + * + * @this: Per-device data. + */ +static void mil_partitions_exit(struct gpmi_nfc_data *this) +{ + struct mil *mil = &this->mil; + struct mtd_info *mtd = &mil->mtd; + + /* Check if we applied any partitions to the general use MTD. */ + + #if defined(CONFIG_MTD_PARTITIONS) + + if (mil->partition_count) + del_mtd_partitions(mil->general_use_mtd); + + kfree(mil->ubi_partition_memory); + + #endif + + /* + * If we were told to register the MTD that represents the entire + * medium, unregister it now. Note that this does *not* "destroy" the + * MTD - it merely unregisters it. That's important because all our + * other MTDs depend on this one. + */ + + if (register_main_mtd) + del_mtd_device(mtd); + + /* Tear down the boot areas. */ + + mil_boot_areas_exit(this); + +} + +/** + * gpmi_nfc_mil_init() - Initializes the MTD Interface Layer. + * + * @this: Per-device data. + */ +int gpmi_nfc_mil_init(struct gpmi_nfc_data *this) +{ + struct device *dev = this->dev; + struct gpmi_nfc_platform_data *pdata = this->pdata; + struct mil *mil = &this->mil; + struct mtd_info *mtd = &mil->mtd; + struct nand_chip *nand = &mil->nand; + static struct nand_ecclayout fake_ecc_layout; + int error = 0; + + /* Initialize MIL data. */ + + mil->current_chip = -1; + mil->command_length = 0; + + mil->page_buffer_virt = 0; + mil->page_buffer_phys = ~0; + mil->page_buffer_size = 0; + + /* Initialize the MTD data structures. */ + + mtd->priv = nand; + mtd->name = "gpmi-nfc-main"; + mtd->owner = THIS_MODULE; + nand->priv = this; + + /* + * Signal Control + */ + + nand->cmd_ctrl = mil_cmd_ctrl; + + /* + * Chip Control + * + * We rely on the reference implementations of: + * - cmdfunc + * - waitfunc + */ + + nand->dev_ready = mil_dev_ready; + nand->select_chip = mil_select_chip; + + /* + * Low-level I/O + * + * We don't support a 16-bit NAND Flash bus, so we don't implement + * read_word. + * + * We rely on the reference implentation of verify_buf. + */ + + nand->read_byte = mil_read_byte; + nand->read_buf = mil_read_buf; + nand->write_buf = mil_write_buf; + + /* + * ECC Control + * + * None of these functions are necessary for us: + * - ecc.hwctl + * - ecc.calculate + * - ecc.correct + */ + + /* + * ECC-aware I/O + * + * We rely on the reference implementations of: + * - ecc.read_page_raw + * - ecc.write_page_raw + */ + + nand->ecc.read_page = mil_ecc_read_page; + nand->ecc.write_page = mil_ecc_write_page; + + /* + * High-level I/O + * + * We rely on the reference implementations of: + * - write_page + * - erase_cmd + */ + + nand->ecc.read_oob = mil_ecc_read_oob; + nand->ecc.write_oob = mil_ecc_write_oob; + + /* + * Bad Block Management + * + * We rely on the reference implementations of: + * - block_bad + * - block_markbad + */ + + nand->block_bad = mil_block_bad; + nand->scan_bbt = mil_scan_bbt; + + /* + * Error Recovery Functions + * + * We don't fill in the errstat function pointer because it's optional + * and we don't have a need for it. + */ + + /* + * Set up NAND Flash options. Specifically: + * + * - Disallow partial page writes. + */ + + nand->options |= NAND_NO_SUBPAGE_WRITE; + + /* + * Tell the NAND Flash MTD system that we'll be handling ECC with our + * own hardware. It turns out that we still have to fill in the ECC size + * because the MTD code will divide by it -- even though it doesn't + * actually care. + */ + + nand->ecc.mode = NAND_ECC_HW; + nand->ecc.size = 1; + + /* + * Install a "fake" ECC layout. + * + * We'll be calling nand_scan() to do the final MTD setup. If we haven't + * already chosen an ECC layout, then nand_scan() will choose one based + * on the part geometry it discovers. Unfortunately, it doesn't make + * good choices. It would be best if we could install the correct ECC + * layout now, before we call nand_scan(). We can't do that because we + * don't know the medium geometry yet. Here, we install a "fake" ECC + * layout just to stop nand_scan() from trying to pick one for itself. + * Later, when we know the medium geometry, we'll install the correct + * one. + * + * Of course, this tactic depends critically on the MTD code not doing + * an I/O operation that depends on the ECC layout being sensible. This + * is in fact the case. + */ + + memset(&fake_ecc_layout, 0, sizeof(fake_ecc_layout)); + + nand->ecc.layout = &fake_ecc_layout; + + /* Allocate a command buffer. */ + + mil->cmd_virt = + dma_alloc_coherent(dev, + MIL_COMMAND_BUFFER_SIZE, &mil->cmd_phys, GFP_DMA); + + if (!mil->cmd_virt) + goto exit_cmd_allocation; + + /* + * Ask the NAND Flash system to scan for chips. + * + * This will fill in reference implementations for all the members of + * the MTD structures that we didn't set, and will make the medium fully + * usable. + */ + + pr_info("Scanning for NAND Flash chips...\n"); + + error = nand_scan(mtd, pdata->max_chip_count); + + if (error) { + dev_err(dev, "Chip scan failed\n"); + goto exit_nand_scan; + } + + /* + * Hook some operations at the MTD level. See the descriptions of the + * saved function pointer fields for details about why we hook these. + */ + + mil->hooked_read_oob = mtd->read_oob; + mtd->read_oob = mil_hook_read_oob; + + mil->hooked_write_oob = mtd->write_oob; + mtd->write_oob = mil_hook_write_oob; + + mil->hooked_block_markbad = mtd->block_markbad; + mtd->block_markbad = mil_hook_block_markbad; + + /* Construct partitions as necessary. */ + + error = mil_partitions_init(this); + + if (error) + goto exit_partitions; + + /* Return success. */ + + return 0; + + /* Control arrives here if something went wrong. */ + +exit_partitions: + nand_release(&mil->mtd); +exit_nand_scan: + dma_free_coherent(dev, MIL_COMMAND_BUFFER_SIZE, + mil->cmd_virt, mil->cmd_phys); + mil->cmd_virt = 0; + mil->cmd_phys = ~0; +exit_cmd_allocation: + + return error; + +} + +/** + * gpmi_nfc_mil_exit() - Shuts down the MTD Interface Layer. + * + * @this: Per-device data. + */ +void gpmi_nfc_mil_exit(struct gpmi_nfc_data *this) +{ + struct device *dev = this->dev; + struct mil *mil = &this->mil; + + /* Shut down partitions as necessary. */ + + mil_partitions_exit(this); + + /* Get MTD to let go of our MTD. */ + + nand_release(&mil->mtd); + + /* Free the page buffer, if it's been allocated. */ + + if (mil->page_buffer_virt) + dma_free_coherent(dev, mil->page_buffer_size, + mil->page_buffer_virt, mil->page_buffer_phys); + + mil->page_buffer_size = 0; + mil->page_buffer_virt = 0; + mil->page_buffer_phys = ~0; + + /* Free the command buffer, if it's been allocated. */ + + if (mil->cmd_virt) + dma_free_coherent(dev, MIL_COMMAND_BUFFER_SIZE, + mil->cmd_virt, mil->cmd_phys); + + mil->cmd_virt = 0; + mil->cmd_phys = ~0; + +} diff --git a/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-rom-common.c b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-rom-common.c new file mode 100644 index 000000000000..0cd0b39141fd --- /dev/null +++ b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-rom-common.c @@ -0,0 +1,59 @@ +/* + * Freescale GPMI NFC NAND Flash Driver + * + * Copyright (C) 2010 Freescale Semiconductor, Inc. + * Copyright (C) 2008 Embedded Alley Solutions, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "gpmi-nfc.h" + +/** + * gpmi_nfc_rom_helper_set_geometry() - Sets geometry for the Boot ROM Helper. + * + * @this: Per-device data. + */ +int gpmi_nfc_rom_helper_set_geometry(struct gpmi_nfc_data *this) +{ + struct boot_rom_geometry *geometry = &this->rom_geometry; + + /* + * Set the boot block stride size. + * + * In principle, we should be reading this from the OTP bits, since + * that's where the ROM is going to get it. In fact, we don't have any + * way to read the OTP bits, so we go with the default and hope for the + * best. + */ + + geometry->stride_size_in_pages = 64; + + /* + * Set the search area stride exponent. + * + * In principle, we should be reading this from the OTP bits, since + * that's where the ROM is going to get it. In fact, we don't have any + * way to read the OTP bits, so we go with the default and hope for the + * best. + */ + + geometry->search_area_stride_exponent = 2; + + /* Return success. */ + + return 0; + +} diff --git a/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-rom-v0.c b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-rom-v0.c new file mode 100644 index 000000000000..35321cc25546 --- /dev/null +++ b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-rom-v0.c @@ -0,0 +1,297 @@ +/* + * Freescale GPMI NFC NAND Flash Driver + * + * Copyright (C) 2010 Freescale Semiconductor, Inc. + * Copyright (C) 2008 Embedded Alley Solutions, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "gpmi-nfc.h" + +/* + * Useful variables for Boot ROM Helper version 0. + */ + +static const char *fingerprint = "STMP"; + +/** + * set_geometry() - Sets geometry for the Boot ROM Helper. + * + * @this: Per-device data. + */ +static int set_geometry(struct gpmi_nfc_data *this) +{ + struct gpmi_nfc_platform_data *pdata = this->pdata; + struct physical_geometry *physical = &this->physical_geometry; + struct boot_rom_geometry *geometry = &this->rom_geometry; + int error; + + /* Version-independent geometry. */ + + error = gpmi_nfc_rom_helper_set_geometry(this); + + if (error) + return error; + + /* + * Check if the platform data indicates we are to protect the boot area. + */ + + if (!pdata->boot_area_size_in_bytes) { + geometry->boot_area_count = 0; + geometry->boot_area_size_in_bytes = 0; + return 0; + } + + /* + * If control arrives here, we are supposed to set up partitions to + * protect the boot areas. In this version of the ROM, the number of + * boot areas and their size depends on the number of chips. + */ + + if (physical->chip_count == 1) { + geometry->boot_area_count = 1; + geometry->boot_area_size_in_bytes = + pdata->boot_area_size_in_bytes * 2; + } else { + geometry->boot_area_count = 2; + geometry->boot_area_size_in_bytes = + pdata->boot_area_size_in_bytes; + } + + /* Return success. */ + + return 0; + +} + +/** + * check_transcription_stamp() - Checks for a transcription stamp. + * + * Returns 0 if a stamp is not found. + * + * @this: Per-device data. + */ +static int check_transcription_stamp(struct gpmi_nfc_data *this) +{ + struct physical_geometry *physical = &this->physical_geometry; + struct boot_rom_geometry *rom_geo = &this->rom_geometry; + struct mil *mil = &this->mil; + struct mtd_info *mtd = &mil->mtd; + struct nand_chip *nand = &mil->nand; + unsigned int search_area_size_in_strides; + unsigned int stride; + unsigned int page; + loff_t byte; + uint8_t *buffer = nand->buffers->databuf; + int saved_chip_number; + int found_an_ncb_fingerprint = false; + + /* Compute the number of strides in a search area. */ + + search_area_size_in_strides = 1 << rom_geo->search_area_stride_exponent; + + /* Select chip 0. */ + + saved_chip_number = mil->current_chip; + nand->select_chip(mtd, 0); + + /* + * Loop through the first search area, looking for the NCB fingerprint. + */ + + pr_info("Scanning for an NCB fingerprint...\n"); + + for (stride = 0; stride < search_area_size_in_strides; stride++) { + + /* Compute the page and byte addresses. */ + + page = stride * rom_geo->stride_size_in_pages; + byte = page * physical->page_data_size_in_bytes; + + pr_info(" Looking for a fingerprint in page 0x%x\n", page); + + /* + * Read the NCB fingerprint. The fingerprint is four bytes long + * and starts in the 12th byte of the page. + */ + + nand->cmdfunc(mtd, NAND_CMD_READ0, 12, page); + nand->read_buf(mtd, buffer, strlen(fingerprint)); + + /* Look for the fingerprint. */ + + if (!memcmp(buffer, fingerprint, + strlen(fingerprint))) { + found_an_ncb_fingerprint = true; + break; + } + + } + + /* Deselect chip 0. */ + + nand->select_chip(mtd, saved_chip_number); + + /* Return. */ + + if (found_an_ncb_fingerprint) + pr_info(" Found a fingerprint\n"); + else + pr_info(" No fingerprint found\n"); + + return found_an_ncb_fingerprint; + +} + +/** + * write_transcription_stamp() - Writes a transcription stamp. + * + * @this: Per-device data. + */ +static int write_transcription_stamp(struct gpmi_nfc_data *this) +{ + struct device *dev = this->dev; + struct physical_geometry *physical = &this->physical_geometry; + struct boot_rom_geometry *rom_geo = &this->rom_geometry; + struct mil *mil = &this->mil; + struct mtd_info *mtd = &mil->mtd; + struct nand_chip *nand = &mil->nand; + unsigned int block_size_in_pages; + unsigned int search_area_size_in_strides; + unsigned int search_area_size_in_pages; + unsigned int search_area_size_in_blocks; + unsigned int block; + unsigned int stride; + unsigned int page; + loff_t byte; + uint8_t *buffer = nand->buffers->databuf; + int saved_chip_number; + int status; + + /* Compute the search area geometry. */ + + block_size_in_pages = physical->block_size_in_bytes >> + (ffs(physical->page_data_size_in_bytes) - 1); + + search_area_size_in_strides = 1 << rom_geo->search_area_stride_exponent; + + search_area_size_in_pages = search_area_size_in_strides * + rom_geo->stride_size_in_pages; + + search_area_size_in_blocks = + (search_area_size_in_pages + (block_size_in_pages - 1)) / + /*-------------------------------------------------------*/ + block_size_in_pages; + + #if defined(DETAILED_INFO) + + pr_info("--------------------\n"); + pr_info("Search Area Geometry\n"); + pr_info("--------------------\n"); + pr_info("Search Area Size in Blocks : %u", search_area_size_in_blocks); + pr_info("Search Area Size in Strides: %u", search_area_size_in_strides); + pr_info("Search Area Size in Pages : %u", search_area_size_in_pages); + + #endif + + /* Select chip 0. */ + + saved_chip_number = mil->current_chip; + nand->select_chip(mtd, 0); + + /* Loop over blocks in the first search area, erasing them. */ + + pr_info("Erasing the search area...\n"); + + for (block = 0; block < search_area_size_in_blocks; block++) { + + /* Compute the page address. */ + + page = block * block_size_in_pages; + + /* Erase this block. */ + + pr_info(" Erasing block 0x%x\n", block); + + nand->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page); + nand->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1); + + /* Wait for the erase to finish. */ + + status = nand->waitfunc(mtd, nand); + + if (status & NAND_STATUS_FAIL) + dev_err(dev, "[%s] Erase failed.\n", __func__); + + } + + /* Write the NCB fingerprint into the page buffer. */ + + memset(buffer, ~0, mtd->writesize); + memset(nand->oob_poi, ~0, mtd->oobsize); + + memcpy(buffer + 12, fingerprint, strlen(fingerprint)); + + /* Loop through the first search area, writing NCB fingerprints. */ + + pr_info("Writing NCB fingerprints...\n"); + + for (stride = 0; stride < search_area_size_in_strides; stride++) { + + /* Compute the page and byte addresses. */ + + page = stride * rom_geo->stride_size_in_pages; + byte = page * physical->page_data_size_in_bytes; + + /* Write the first page of the current stride. */ + + pr_info(" Writing an NCB fingerprint in page 0x%x\n", page); + + nand->cmdfunc(mtd, NAND_CMD_SEQIN, 0x00, page); + nand->ecc.write_page_raw(mtd, nand, buffer); + nand->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1); + + /* Wait for the write to finish. */ + + status = nand->waitfunc(mtd, nand); + + if (status & NAND_STATUS_FAIL) + dev_err(dev, "[%s] Write failed.\n", __func__); + + } + + /* Deselect chip 0. */ + + nand->select_chip(mtd, saved_chip_number); + + /* Return success. */ + + return 0; + +} + +/* This structure represents the Boot ROM Helper for this version. */ + +struct boot_rom_helper gpmi_nfc_boot_rom_helper_v0 = { + .version = 0, + .description = "Single/dual-chip boot area, " + "no block mark swapping", + .swap_block_mark = false, + .set_geometry = set_geometry, + .check_transcription_stamp = check_transcription_stamp, + .write_transcription_stamp = write_transcription_stamp, +}; diff --git a/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-rom-v1.c b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-rom-v1.c new file mode 100644 index 000000000000..49cb329ccdd4 --- /dev/null +++ b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc-rom-v1.c @@ -0,0 +1,82 @@ +/* + * Freescale GPMI NFC NAND Flash Driver + * + * Copyright (C) 2010 Freescale Semiconductor, Inc. + * Copyright (C) 2008 Embedded Alley Solutions, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "gpmi-nfc.h" + +/** + * set_geometry() - Sets geometry for the Boot ROM Helper. + * + * @this: Per-device data. + */ +static int set_geometry(struct gpmi_nfc_data *this) +{ + struct gpmi_nfc_platform_data *pdata = this->pdata; + struct boot_rom_geometry *geometry = &this->rom_geometry; + int error; + + /* Version-independent geometry. */ + + error = gpmi_nfc_rom_helper_set_geometry(this); + + if (error) + return error; + + /* + * Check if the platform data indicates we are to protect the boot area. + */ + + if (!pdata->boot_area_size_in_bytes) { + geometry->boot_area_count = 0; + geometry->boot_area_size_in_bytes = 0; + return 0; + } + + /* + * If control arrives here, we are supposed to set up partitions to + * protect the boot areas. In this version of the ROM, we support only + * one boot area. + */ + + geometry->boot_area_count = 1; + + /* + * Use the platform's boot area size. + */ + + geometry->boot_area_size_in_bytes = pdata->boot_area_size_in_bytes; + + /* Return success. */ + + return 0; + +} + +/* This structure represents the Boot ROM Helper for this version. */ + +struct boot_rom_helper gpmi_nfc_boot_rom_helper_v1 = { + .version = 1, + .description = "Single-chip boot area, " + "block mark swapping supported", + .swap_block_mark = true, + .set_geometry = set_geometry, + .check_transcription_stamp = 0, + .write_transcription_stamp = 0, +}; diff --git a/drivers/mtd/nand/gpmi-nfc/gpmi-nfc.h b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc.h new file mode 100644 index 000000000000..6f14b73dd93d --- /dev/null +++ b/drivers/mtd/nand/gpmi-nfc/gpmi-nfc.h @@ -0,0 +1,643 @@ +/* + * Freescale GPMI NFC NAND Flash Driver + * + * Copyright (C) 2010 Freescale Semiconductor, Inc. + * Copyright (C) 2008 Embedded Alley Solutions, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#ifndef __DRIVERS_MTD_NAND_GPMI_NFC_H +#define __DRIVERS_MTD_NAND_GPMI_NFC_H + +/* Linux header files. */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* Platform header files. */ + +#include +#include +#include +#include + +/* Driver header files. */ + +#include "../nand_device_info.h" + +/* + *------------------------------------------------------------------------------ + * Fundamental Macros + *------------------------------------------------------------------------------ + */ + +/* Define this macro to enable detailed information messages. */ + +#define DETAILED_INFO + +/* Define this macro to enable event reporting. */ + +/*#define EVENT_REPORTING*/ + +/* + *------------------------------------------------------------------------------ + * Fundamental Data Structures + *------------------------------------------------------------------------------ + */ + +/** + * struct resources - The collection of resources the driver needs. + * + * @gpmi_regs: A pointer to the GPMI registers. + * @bch_regs: A pointer to the BCH registers. + * @bch_interrupt: The BCH interrupt number. + * @dma_low_channel: The low DMA channel. + * @dma_high_channel: The high DMA channel. + * @dma_interrupt: The DMA interrupt number. + * @clock: A pointer to the struct clk for the NFC's clock. + */ + +struct resources { + void *gpmi_regs; + void *bch_regs; + unsigned int bch_interrupt; + unsigned int dma_low_channel; + unsigned int dma_high_channel; + unsigned int dma_interrupt; + struct clk *clock; +}; + +/** + * struct mil - State for the MTD Interface Layer. + * + * @nand: The NAND Flash MTD data structure that represents + * the NAND Flash medium. + * @mtd: The MTD data structure that represents the NAND + * Flash medium. + * @oob_layout: A structure that describes how bytes are laid out + * in the OOB. + * @general_use_mtd: A pointer to an MTD we export for general use. + * This *may* simply be a pointer to the mtd field, if + * we've been instructed NOT to protect the boot + * areas. + * @partitions: A pointer to a set of partitions applied to the + * general use MTD. + * @partition_count: The number of partitions. + * @ubi_partition_memory: If not NULL, a block of memory used to create a set + * of partitions that help with the problem that UBI + * can't handle an MTD larger than 2GiB. + * @current_chip: The chip currently selected by the NAND Fash MTD + * code. A negative value indicates that no chip is + * selected. + * @command_length: The length of the command that appears in the + * command buffer (see cmd_virt, below). + * @inject_ecc_error: Indicates the driver should inject a "fake" ECC + * error into the next read operation that uses ECC. + * User space programs can set this value through the + * sysfs node of the same name. If this value is less + * than zero, the driver will inject an uncorrectable + * ECC error. If this value is greater than zero, the + * driver will inject that number of correctable + * errors, capped by the maximum possible number of + * errors that could appear in a single read. + * @ignore_bad_block_marks: Indicates we are ignoring bad block marks. + * @saved_bbt: A saved pointer to the in-memory NAND Flash MTD bad + * block table. See show_device_ignorebad() for more + * details. + * @raw_oob_mode: Indicates the OOB is to be read/written in "raw" + * mode. See mil_ecc_read_oob() for details. + * @hooked_read_oob: A pointer to the ecc.read_oob() function we + * "hooked." See mil_ecc_read_oob() for details. + * @hooked_write_oob: A pointer to the ecc.write_oob() function pointer + * we "hooked." See mil_ecc_read_oob() for details. + * @marking_a_bad_block: Indicates the caller is marking a bad block. See + * mil_ecc_write_oob() for details. + * @hooked_block_markbad: A pointer to the block_markbad() function we + * we "hooked." See mil_ecc_write_oob() for details. + * @cmd_virt: A pointer to a DMA-coherent buffer in which we + * accumulate command bytes before we give them to the + * NFC layer. See mil_cmd_ctrl() for more details. + * @cmd_phys: The physical address for the cmd_virt buffer. + * @page_buffer_virt: A pointer to a DMA-coherent buffer we use for + * reading and writing pages. This buffer includes + * space for both the payload data and the auxiliary + * data (including status bytes, but not syndrome + * bytes). + * @page_buffer_phys: The physical address for the page_buffer_virt + * buffer. + * @page_buffer_size: The size of the page buffer. + * @payload_virt: A pointer to a location in the page buffer used + * for payload bytes. The size of this buffer is + * determined by struct nfc_geometry. + * @payload_phys: The physical address for payload_virt. + * @payload_size: The size of the payload area in the page buffer. + * @auxiliary_virt: A pointer to a location in the page buffer used + * for auxiliary bytes. The size of this buffer is + * determined by struct nfc_geometry. + * @auxiliary_phys: The physical address for auxiliary_virt. + * @auxiliary_size: The size of the auxiliary area in the page buffer. + */ + +#define MIL_COMMAND_BUFFER_SIZE (10) + +struct mil { + + /* MTD Data Structures */ + + struct nand_chip nand; + struct mtd_info mtd; + struct nand_ecclayout oob_layout; + + /* Partitioning and Boot Area Protection */ + + struct mtd_info *general_use_mtd; + struct mtd_partition *partitions; + unsigned int partition_count; + void *ubi_partition_memory; + + /* General-use Variables */ + + int current_chip; + unsigned int command_length; + int inject_ecc_error; + int ignore_bad_block_marks; + void *saved_bbt; + + /* MTD Function Pointer Hooks */ + + int raw_oob_mode; + int (*hooked_read_oob)(struct mtd_info *mtd, + loff_t from, struct mtd_oob_ops *ops); + int (*hooked_write_oob)(struct mtd_info *mtd, + loff_t to, struct mtd_oob_ops *ops); + + int marking_a_bad_block; + int (*hooked_block_markbad)(struct mtd_info *mtd, + loff_t ofs); + + /* DMA Buffers */ + + char *cmd_virt; + dma_addr_t cmd_phys; + + void *page_buffer_virt; + dma_addr_t page_buffer_phys; + unsigned int page_buffer_size; + + void *payload_virt; + dma_addr_t payload_phys; + + void *auxiliary_virt; + dma_addr_t auxiliary_phys; + +}; + +/** + * struct physical_geometry - Physical geometry description. + * + * This structure describes the physical geometry of the medium. + * + * @chip_count: The number of chips in the medium. + * @chip_size_in_bytes: The size, in bytes, of a single chip + * (excluding the out-of-band bytes). + * @block_size_in_bytes: The size, in bytes, of a single block + * (excluding the out-of-band bytes). + * @page_data_size_in_bytes: The size, in bytes, of the data area in a + * page (excluding the out-of-band bytes). + * @page_oob_size_in_bytes: The size, in bytes, of the out-of-band area + * in a page. + */ + +struct physical_geometry { + unsigned int chip_count; + uint64_t chip_size_in_bytes; + unsigned int block_size_in_bytes; + unsigned int page_data_size_in_bytes; + unsigned int page_oob_size_in_bytes; +}; + +/** + * struct nfc_geometry - NFC geometry description. + * + * This structure describes the NFC's view of the medium geometry. + * + * @ecc_algorithm: The human-readable name of the ECC algorithm + * (e.g., "Reed-Solomon" or "BCH"). + * @ecc_strength: A number that describes the strength of the ECC + * algorithm. + * @page_size_in_bytes: The size, in bytes, of a physical page, including + * both data and OOB. + * @metadata_size_in_bytes: The size, in bytes, of the metadata. + * @ecc_chunk_size_in_bytes: The size, in bytes, of a single ECC chunk. Note + * the first chunk in the page includes both data and + * metadata, so it's a bit larger than this value. + * @ecc_chunk_count: The number of ECC chunks in the page, + * @payload_size_in_bytes: The size, in bytes, of the payload buffer. + * @auxiliary_size_in_bytes: The size, in bytes, of the auxiliary buffer. + * @auxiliary_status_offset: The offset into the auxiliary buffer at which + * the ECC status appears. + * @block_mark_byte_offset: The byte offset in the ECC-based page view at + * which the underlying physical block mark appears. + * @block_mark_bit_offset: The bit offset into the ECC-based page view at + * which the underlying physical block mark appears. + */ + +struct nfc_geometry { + char *ecc_algorithm; + unsigned int ecc_strength; + unsigned int page_size_in_bytes; + unsigned int metadata_size_in_bytes; + unsigned int ecc_chunk_size_in_bytes; + unsigned int ecc_chunk_count; + unsigned int payload_size_in_bytes; + unsigned int auxiliary_size_in_bytes; + unsigned int auxiliary_status_offset; + unsigned int block_mark_byte_offset; + unsigned int block_mark_bit_offset; +}; + +/** + * struct boot_rom_geometry - Boot ROM geometry description. + * + * This structure encapsulates decisions made by the Boot ROM Helper. + * + * @boot_area_count: The number of boot areas. The first boot area + * appears at the beginning of chip 0, the next + * at the beginning of chip 1, etc. + * @boot_area_size_in_bytes: The size, in bytes, of each boot area. + * @stride_size_in_pages: The size of a boot block stride, in pages. + * @search_area_stride_exponent: The logarithm to base 2 of the size of a + * search area in boot block strides. + */ + +struct boot_rom_geometry { + unsigned int boot_area_count; + unsigned int boot_area_size_in_bytes; + unsigned int stride_size_in_pages; + unsigned int search_area_stride_exponent; +}; + +/** + * struct gpmi_nfc_data - i.MX NFC per-device data. + * + * Note that the "device" managed by this driver represents the NAND Flash + * controller *and* the NAND Flash medium behind it. Thus, the per-device data + * structure has information about the controller, the chips to which it is + * connected, and properties of the medium as a whole. + * + * @dev: A pointer to the owning struct device. + * @pdev: A pointer to the owning struct platform_device. + * @pdata: A pointer to the device's platform data. + * @resources: Information about system resources used by this driver. + * @device_info: A structure that contains detailed information about + * the NAND Flash device. + * @physical_geometry: A description of the medium's physical geometry. + * @nfc: A pointer to a structure that represents the underlying + * NFC hardware. + * @nfc_geometry: A description of the medium geometry as viewed by the + * NFC. + * @rom: A pointer to a structure that represents the underlying + * Boot ROM. + * @rom_geometry: A description of the medium geometry as viewed by the + * Boot ROM. + * @mil: A collection of information used by the MTD Interface + * Layer. + */ + +struct gpmi_nfc_data { + + /* System Interface */ + struct device *dev; + struct platform_device *pdev; + struct gpmi_nfc_platform_data *pdata; + + /* Resources */ + struct resources resources; + + /* Flash Hardware */ + struct nand_device_info device_info; + struct physical_geometry physical_geometry; + + /* NFC HAL */ + struct nfc_hal *nfc; + struct nfc_geometry nfc_geometry; + + /* Boot ROM Helper */ + struct boot_rom_helper *rom; + struct boot_rom_geometry rom_geometry; + + /* MTD Interface Layer */ + struct mil mil; + +}; + +/** + * struct gpmi_nfc_timing - GPMI NFC timing parameters. + * + * This structure contains the fundamental timing attributes for the NAND Flash + * bus and the GPMI NFC hardware. + * + * @data_setup_in_ns: The data setup time, in nanoseconds. Usually the + * maximum of tDS and tWP. A negative value + * indicates this characteristic isn't known. + * @data_hold_in_ns: The data hold time, in nanoseconds. Usually the + * maximum of tDH, tWH and tREH. A negative value + * indicates this characteristic isn't known. + * @address_setup_in_ns: The address setup time, in nanoseconds. Usually + * the maximum of tCLS, tCS and tALS. A negative + * value indicates this characteristic isn't known. + * @gpmi_sample_delay_in_ns: A GPMI-specific timing parameter. A negative value + * indicates this characteristic isn't known. + * @tREA_in_ns: tREA, in nanoseconds, from the data sheet. A + * negative value indicates this characteristic isn't + * known. + * @tRLOH_in_ns: tRLOH, in nanoseconds, from the data sheet. A + * negative value indicates this characteristic isn't + * known. + * @tRHOH_in_ns: tRHOH, in nanoseconds, from the data sheet. A + * negative value indicates this characteristic isn't + * known. + */ + +struct gpmi_nfc_timing { + int8_t data_setup_in_ns; + int8_t data_hold_in_ns; + int8_t address_setup_in_ns; + int8_t gpmi_sample_delay_in_ns; + int8_t tREA_in_ns; + int8_t tRLOH_in_ns; + int8_t tRHOH_in_ns; +}; + +/** + * struct gpmi_nfc_hardware_timing - GPMI NFC hardware timing parameters. + * + * This structure contains timing information expressed in a form directly + * usable by the GPMI NFC hardware. + * + * @data_setup_in_cycles: The data setup time, in cycles. + * @data_hold_in_cycles: The data hold time, in cycles. + * @address_setup_in_cycles: The address setup time, in cycles. + * @use_half_periods: Indicates the clock is running slowly, so the + * NFC DLL should use half-periods. + * @sample_delay_factor: The sample delay factor. + */ + +struct gpmi_nfc_hardware_timing { + uint8_t data_setup_in_cycles; + uint8_t data_hold_in_cycles; + uint8_t address_setup_in_cycles; + bool use_half_periods; + uint8_t sample_delay_factor; +}; + +/** + * struct nfc_hal - GPMI NFC HAL + * + * This structure embodies an abstract interface to the underlying NFC hardware. + * + * @version: The NFC hardware version. + * @description: A pointer to a human-readable description of + * the NFC hardware. + * @max_chip_count: The maximum number of chips the NFC can + * possibly support (this value is a constant for + * each NFC version). This may *not* be the actual + * number of chips connected. + * @max_data_setup_cycles: The maximum number of data setup cycles that + * can be expressed in the hardware. + * @internal_data_setup_in_ns: The time, in ns, that the NFC hardware requires + * for data read internal setup. In the Reference + * Manual, see the chapter "High-Speed NAND + * Timing" for more details. + * @max_sample_delay_factor: The maximum sample delay factor that can be + * expressed in the hardware. + * @max_dll_clock_period_in_ns: The maximum period of the GPMI clock that the + * sample delay DLL hardware can possibly work + * with (the DLL is unusable with longer periods). + * If the full-cycle period is greater than HALF + * this value, the DLL must be configured to use + * half-periods. + * @max_dll_delay_in_ns: The maximum amount of delay, in ns, that the + * DLL can implement. + * @dma_descriptors: A pool of DMA descriptors. + * @isr_dma_channel: The DMA channel with which the NFC HAL is + * working. We record this here so the ISR knows + * which DMA channel to acknowledge. + * @dma_done: The completion structure used for DMA + * interrupts. + * @bch_done: The completion structure used for BCH + * interrupts. + * @timing: The current timing configuration. + * @clock_frequency_in_hz: The clock frequency, in Hz, during the current + * I/O transaction. If no I/O transaction is in + * progress, this is the clock frequency during + * the most recent I/O transaction. + * @hardware_timing: The hardware timing configuration in effect + * during the current I/O transaction. If no I/O + * transaction is in progress, this is the + * hardware timing configuration during the most + * recent I/O transaction. + * @init: Initializes the NFC hardware and data + * structures. This function will be called after + * everything has been set up for communication + * with the NFC itself, but before the platform + * has set up off-chip communication. Thus, this + * function must not attempt to communicate with + * the NAND Flash hardware. + * @set_geometry: Configures the NFC hardware and data structures + * to match the physical NAND Flash geometry. + * @set_geometry: Configures the NFC hardware and data structures + * to match the physical NAND Flash geometry. + * @set_timing: Configures the NFC hardware and data structures + * to match the given NAND Flash bus timing. + * @get_timing: Returns the the clock frequency, in Hz, and + * the hardware timing configuration during the + * current I/O transaction. If no I/O transaction + * is in progress, this is the timing state during + * the most recent I/O transaction. + * @exit: Shuts down the NFC hardware and data + * structures. This function will be called after + * the platform has shut down off-chip + * communication but while communication with the + * NFC itself still works. + * @clear_bch: Clears a BCH interrupt (intended to be called + * by a more general interrupt handler to do + * device-specific clearing). + * @is_ready: Returns true if the given chip is ready. + * @begin: Begins an interaction with the NFC. This + * function must be called before *any* of the + * following functions so the NFC can prepare + * itself. + * @end: Ends interaction with the NFC. This function + * should be called to give the NFC a chance to, + * among other things, enter a lower-power state. + * @send_command: Sends the given buffer of command bytes. + * @send_data: Sends the given buffer of data bytes. + * @read_data: Reads data bytes into the given buffer. + * @send_page: Sends the given given data and OOB bytes, + * using the ECC engine. + * @read_page: Reads a page through the ECC engine and + * delivers the data and OOB bytes to the given + * buffers. + */ + +#define NFC_DMA_DESCRIPTOR_COUNT (4) + +struct nfc_hal { + + /* Hardware attributes. */ + + const unsigned int version; + const char *description; + const unsigned int max_chip_count; + const unsigned int max_data_setup_cycles; + const unsigned int internal_data_setup_in_ns; + const unsigned int max_sample_delay_factor; + const unsigned int max_dll_clock_period_in_ns; + const unsigned int max_dll_delay_in_ns; + + /* Working variables. */ + + struct mxs_dma_desc *dma_descriptors[NFC_DMA_DESCRIPTOR_COUNT]; + int isr_dma_channel; + struct completion dma_done; + struct completion bch_done; + struct gpmi_nfc_timing timing; + unsigned long clock_frequency_in_hz; + + /* Configuration functions. */ + + int (*init) (struct gpmi_nfc_data *); + int (*set_geometry)(struct gpmi_nfc_data *); + int (*set_timing) (struct gpmi_nfc_data *, + const struct gpmi_nfc_timing *); + void (*get_timing) (struct gpmi_nfc_data *, + unsigned long *clock_frequency_in_hz, + struct gpmi_nfc_hardware_timing *); + void (*exit) (struct gpmi_nfc_data *); + + /* Call these functions to begin and end I/O. */ + + void (*begin) (struct gpmi_nfc_data *); + void (*end) (struct gpmi_nfc_data *); + + /* Call these I/O functions only between begin() and end(). */ + + void (*clear_bch) (struct gpmi_nfc_data *); + int (*is_ready) (struct gpmi_nfc_data *, unsigned chip); + int (*send_command)(struct gpmi_nfc_data *, unsigned chip, + dma_addr_t buffer, unsigned length); + int (*send_data) (struct gpmi_nfc_data *, unsigned chip, + dma_addr_t buffer, unsigned length); + int (*read_data) (struct gpmi_nfc_data *, unsigned chip, + dma_addr_t buffer, unsigned length); + int (*send_page) (struct gpmi_nfc_data *, unsigned chip, + dma_addr_t payload, dma_addr_t auxiliary); + int (*read_page) (struct gpmi_nfc_data *, unsigned chip, + dma_addr_t payload, dma_addr_t auxiliary); +}; + +/** + * struct boot_rom_helper - Boot ROM Helper + * + * This structure embodies the interface to an object that assists the driver + * in making decisions that relate to the Boot ROM. + * + * @version: The Boot ROM version. + * @description: A pointer to a human-readable description of the + * Boot ROM. + * @swap_block_mark: Indicates that the Boot ROM will swap the block + * mark with the first byte of the OOB. + * @set_geometry: Configures the Boot ROM geometry. + * @check_transcription_stamp: Checks for a transcription stamp. This pointer + * is ignored if swap_block_mark is set. + * @write_transcription_stamp: Writes a transcription stamp. This pointer + * is ignored if swap_block_mark is set. + */ + +struct boot_rom_helper { + const unsigned int version; + const char *description; + const int swap_block_mark; + int (*set_geometry) (struct gpmi_nfc_data *); + int (*check_transcription_stamp)(struct gpmi_nfc_data *); + int (*write_transcription_stamp)(struct gpmi_nfc_data *); +}; + +/* + *------------------------------------------------------------------------------ + * External Symbols + *------------------------------------------------------------------------------ + */ + +/* Event Reporting */ + +#if defined(EVENT_REPORTING) + extern void gpmi_nfc_start_event_trace(char *description); + extern void gpmi_nfc_add_event(char *description, int delta); + extern void gpmi_nfc_stop_event_trace(char *description); + extern void gpmi_nfc_dump_event_trace(void); +#else + #define gpmi_nfc_start_event_trace(description) do {} while (0) + #define gpmi_nfc_add_event(description, delta) do {} while (0) + #define gpmi_nfc_stop_event_trace(description) do {} while (0) + #define gpmi_nfc_dump_event_trace() do {} while (0) +#endif + +/* NFC HAL Common Services */ + +extern irqreturn_t gpmi_nfc_bch_isr(int irq, void *cookie); +extern irqreturn_t gpmi_nfc_dma_isr(int irq, void *cookie); +extern int gpmi_nfc_dma_init(struct gpmi_nfc_data *this); +extern void gpmi_nfc_dma_exit(struct gpmi_nfc_data *this); +extern int gpmi_nfc_set_geometry(struct gpmi_nfc_data *this); +extern int gpmi_nfc_dma_go(struct gpmi_nfc_data *this, int dma_channel); +extern int gpmi_nfc_compute_hardware_timing(struct gpmi_nfc_data *this, + struct gpmi_nfc_hardware_timing *hw); + +/* NFC HAL Structures */ + +extern struct nfc_hal gpmi_nfc_hal_v0; +extern struct nfc_hal gpmi_nfc_hal_v1; + +/* Boot ROM Helper Common Services */ + +extern int gpmi_nfc_rom_helper_set_geometry(struct gpmi_nfc_data *this); + +/* Boot ROM Helper Structures */ + +extern struct boot_rom_helper gpmi_nfc_boot_rom_helper_v0; +extern struct boot_rom_helper gpmi_nfc_boot_rom_helper_v1; + +/* MTD Interface Layer */ + +extern int gpmi_nfc_mil_init(struct gpmi_nfc_data *this); +extern void gpmi_nfc_mil_exit(struct gpmi_nfc_data *this); + +#endif diff --git a/drivers/mtd/nand/imx_nfc.c b/drivers/mtd/nand/imx_nfc.c new file mode 100644 index 000000000000..065ff338b06d --- /dev/null +++ b/drivers/mtd/nand/imx_nfc.c @@ -0,0 +1,8286 @@ +/* + * Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define DRIVER_VERSION "1.0" + +/* Define this macro to enable event reporting. */ + +#define EVENT_REPORTING + +/* + * For detailed information that will be helpful in understanding this driver, + * see: + * + * Documentation/imx_nfc.txt + */ + +/* + * Macros that describe NFC hardware have names of the form: + * + * NFC_* + * + * Macros that apply only to specific versions of the NFC have names of the + * following form: + * + * NFC___* + * + * where: + * + * is the major version of the NFC hardware. + * is the minor version of the NFC hardware. + * + * The minor version can be 'X', which means that the macro applies to *all* + * NFCs of the same major version. + * + * For NFC versions with only one set of registers, macros that give offsets + * against the base address have names of the form: + * + * *_REG_OFF + * + * Macros that give the position of a field's LSB within a given register have + * names of the form: + * + * *__POS + * + * Macros that mask a field within a given register have names of the form: + * + * *__MSK + */ + +/* + * Macro definitions for ALL NFC versions. + */ + +#define NFC_MAIN_BUF_SIZE (512) + +/* + * Macro definitions for version 1.0 NFCs. + */ + +#define NFC_1_0_BUF_SIZE_REG_OFF (0x00) +#define NFC_1_0_BUF_ADDR_REG_OFF (0x04) +#define NFC_1_0_FLASH_ADDR_REG_OFF (0x06) +#define NFC_1_0_FLASH_CMD_REG_OFF (0x08) +#define NFC_1_0_CONFIG_REG_OFF (0x0A) +#define NFC_1_0_ECC_STATUS_RESULT_REG_OFF (0x0C) +#define NFC_1_0_RSLTMAIN_AREA_REG_OFF (0x0E) +#define NFC_1_0_RSLTSPARE_AREA_REG_OFF (0x10) +#define NFC_1_0_WRPROT_REG_OFF (0x12) +#define NFC_1_0_UNLOCKSTART_BLKADDR_REG_OFF (0x14) +#define NFC_1_0_UNLOCKEND_BLKADDR_REG_OFF (0x16) +#define NFC_1_0_NF_WRPRST_REG_OFF (0x18) + +#define NFC_1_0_CONFIG1_REG_OFF (0x1A) +#define NFC_1_0_CONFIG1_NF_CE_POS (7) +#define NFC_1_0_CONFIG1_NF_CE_MSK (0x1 << 7) + +#define NFC_1_0_CONFIG2_REG_OFF (0x1C) + +/* +* Macro definitions for version 2.X NFCs. +*/ + +#define NFC_2_X_FLASH_ADDR_REG_OFF (0x06) +#define NFC_2_X_FLASH_CMD_REG_OFF (0x08) +#define NFC_2_X_CONFIG_REG_OFF (0x0A) + +#define NFC_2_X_WR_PROT_REG_OFF (0x12) + +#define NFC_2_X_NF_WR_PR_ST_REG_OFF (0x18) + +#define NFC_2_X_CONFIG2_REG_OFF (0x1C) +#define NFC_2_X_CONFIG2_FCMD_POS (0) +#define NFC_2_X_CONFIG2_FCMD_MSK (0x1 << 0) +#define NFC_2_X_CONFIG2_FADD_POS (1) +#define NFC_2_X_CONFIG2_FADD_MSK (0x1 << 1) +#define NFC_2_X_CONFIG2_FDI_POS (2) +#define NFC_2_X_CONFIG2_FDI_MSK (0x1 << 2) +#define NFC_2_X_CONFIG2_FDO_POS (3) +#define NFC_2_X_CONFIG2_FDO_MSK (0x7 << 3) +#define NFC_2_X_CONFIG2_INT_POS (15) +#define NFC_2_X_CONFIG2_INT_MSK (0x1 << 15) + +/* +* Macro definitions for version 2.0 NFCs. +*/ + +#define NFC_2_0_BUF_ADDR_REG_OFF (0x04) +#define NFC_2_0_BUF_ADDR_RBA_POS (0) +#define NFC_2_0_BUF_ADDR_RBA_MSK (0xf << 0) + +#define NFC_2_0_ECC_STATUS_REG_OFF (0x0C) +#define NFC_2_0_ECC_STATUS_NOSER1_POS (0) +#define NFC_2_0_ECC_STATUS_NOSER1_MSK (0xF << 0) +#define NFC_2_0_ECC_STATUS_NOSER2_POS (4) +#define NFC_2_0_ECC_STATUS_NOSER2_MSK (0xF << 4) +#define NFC_2_0_ECC_STATUS_NOSER3_POS (8) +#define NFC_2_0_ECC_STATUS_NOSER3_MSK (0xF << 8) +#define NFC_2_0_ECC_STATUS_NOSER4_POS (12) +#define NFC_2_0_ECC_STATUS_NOSER4_MSK (0xF << 12) + +#define NFC_2_0_CONFIG1_REG_OFF (0x1A) +#define NFC_2_0_CONFIG1_SP_EN_POS (2) +#define NFC_2_0_CONFIG1_SP_EN_MSK (0x1 << 2) +#define NFC_2_0_CONFIG1_ECC_EN_POS (3) +#define NFC_2_0_CONFIG1_ECC_EN_MSK (0x1 << 3) +#define NFC_2_0_CONFIG1_INT_MSK_POS (4) +#define NFC_2_0_CONFIG1_INT_MSK_MSK (0x1 << 4) +#define NFC_2_0_CONFIG1_NF_BIG_POS (5) +#define NFC_2_0_CONFIG1_NF_BIG_MSK (0x1 << 5) +#define NFC_2_0_CONFIG1_NFC_RST_POS (6) +#define NFC_2_0_CONFIG1_NFC_RST_MSK (0x1 << 6) +#define NFC_2_0_CONFIG1_NF_CE_POS (7) +#define NFC_2_0_CONFIG1_NF_CE_MSK (0x1 << 7) +#define NFC_2_0_CONFIG1_ONE_CYLE_POS (8) +#define NFC_2_0_CONFIG1_ONE_CYLE_MSK (0x1 << 8) +#define NFC_2_0_CONFIG1_MLC_POS (9) +#define NFC_2_0_CONFIG1_MLC_MSK (0x1 << 9) + +#define NFC_2_0_UNLOCK_START_REG_OFF (0x14) +#define NFC_2_0_UNLOCK_END_REG_OFF (0x16) + +/* +* Macro definitions for version 2.1 NFCs. +*/ + +#define NFC_2_1_BUF_ADDR_REG_OFF (0x04) +#define NFC_2_1_BUF_ADDR_RBA_POS (0) +#define NFC_2_1_BUF_ADDR_RBA_MSK (0x7 << 0) +#define NFC_2_1_BUF_ADDR_CS_POS (4) +#define NFC_2_1_BUF_ADDR_CS_MSK (0x3 << 4) + +#define NFC_2_1_ECC_STATUS_REG_OFF (0x0C) +#define NFC_2_1_ECC_STATUS_NOSER1_POS (0) +#define NFC_2_1_ECC_STATUS_NOSER1_MSK (0xF << 0) +#define NFC_2_1_ECC_STATUS_NOSER2_POS (4) +#define NFC_2_1_ECC_STATUS_NOSER2_MSK (0xF << 4) +#define NFC_2_1_ECC_STATUS_NOSER3_POS (8) +#define NFC_2_1_ECC_STATUS_NOSER3_MSK (0xF << 8) +#define NFC_2_1_ECC_STATUS_NOSER4_POS (12) +#define NFC_2_1_ECC_STATUS_NOSER4_MSK (0xF << 12) + +#define NFC_2_1_CONFIG1_REG_OFF (0x1A) +#define NFC_2_1_CONFIG1_ECC_MODE_POS (0) +#define NFC_2_1_CONFIG1_ECC_MODE_MSK (0x1 << 0) +#define NFC_2_1_CONFIG1_DMA_MODE_POS (1) +#define NFC_2_1_CONFIG1_DMA_MODE_MSK (0x1 << 1) +#define NFC_2_1_CONFIG1_SP_EN_POS (2) +#define NFC_2_1_CONFIG1_SP_EN_MSK (0x1 << 2) +#define NFC_2_1_CONFIG1_ECC_EN_POS (3) +#define NFC_2_1_CONFIG1_ECC_EN_MSK (0x1 << 3) +#define NFC_2_1_CONFIG1_INT_MSK_POS (4) +#define NFC_2_1_CONFIG1_INT_MSK_MSK (0x1 << 4) +#define NFC_2_1_CONFIG1_NF_BIG_POS (5) +#define NFC_2_1_CONFIG1_NF_BIG_MSK (0x1 << 5) +#define NFC_2_1_CONFIG1_NFC_RST_POS (6) +#define NFC_2_1_CONFIG1_NFC_RST_MSK (0x1 << 6) +#define NFC_2_1_CONFIG1_NF_CE_POS (7) +#define NFC_2_1_CONFIG1_NF_CE_MSK (0x1 << 7) +#define NFC_2_1_CONFIG1_SYM_POS (8) +#define NFC_2_1_CONFIG1_SYM_MSK (0x1 << 8) +#define NFC_2_1_CONFIG1_PPB_POS (9) +#define NFC_2_1_CONFIG1_PPB_MSK (0x3 << 9) +#define NFC_2_1_CONFIG1_FP_INT_POS (11) +#define NFC_2_1_CONFIG1_FP_INT_MSK (0x1 << 11) + +#define NFC_2_1_UNLOCK_START_0_REG_OFF (0x20) +#define NFC_2_1_UNLOCK_END_0_REG_OFF (0x22) +#define NFC_2_1_UNLOCK_START_1_REG_OFF (0x24) +#define NFC_2_1_UNLOCK_END_1_REG_OFF (0x26) +#define NFC_2_1_UNLOCK_START_2_REG_OFF (0x28) +#define NFC_2_1_UNLOCK_END_2_REG_OFF (0x2A) +#define NFC_2_1_UNLOCK_START_3_REG_OFF (0x2C) +#define NFC_2_1_UNLOCK_END_3_REG_OFF (0x2E) + +/* +* Macro definitions for version 3.X NFCs. +*/ + +/* +* Macro definitions for version 3.1 NFCs. +*/ + +#define NFC_3_1_FLASH_ADDR_CMD_REG_OFF (0x00) +#define NFC_3_1_CONFIG1_REG_OFF (0x04) +#define NFC_3_1_ECC_STATUS_RESULT_REG_OFF (0x08) +#define NFC_3_1_LAUNCH_NFC_REG_OFF (0x0C) + +#define NFC_3_1_WRPROT_REG_OFF (0x00) +#define NFC_3_1_WRPROT_UNLOCK_BLK_ADD0_REG_OFF (0x04) +#define NFC_3_1_CONFIG2_REG_OFF (0x14) +#define NFC_3_1_IPC_REG_OFF (0x18) + +/* +* Macro definitions for version 3.2 NFCs. +*/ + +#define NFC_3_2_CMD_REG_OFF (0x00) + +#define NFC_3_2_ADD0_REG_OFF (0x04) +#define NFC_3_2_ADD1_REG_OFF (0x08) +#define NFC_3_2_ADD2_REG_OFF (0x0C) +#define NFC_3_2_ADD3_REG_OFF (0x10) +#define NFC_3_2_ADD4_REG_OFF (0x14) +#define NFC_3_2_ADD5_REG_OFF (0x18) +#define NFC_3_2_ADD6_REG_OFF (0x1C) +#define NFC_3_2_ADD7_REG_OFF (0x20) +#define NFC_3_2_ADD8_REG_OFF (0x24) +#define NFC_3_2_ADD9_REG_OFF (0x28) +#define NFC_3_2_ADD10_REG_OFF (0x2C) +#define NFC_3_2_ADD11_REG_OFF (0x30) + +#define NFC_3_2_CONFIG1_REG_OFF (0x34) +#define NFC_3_2_CONFIG1_SP_EN_POS (0) +#define NFC_3_2_CONFIG1_SP_EN_MSK (0x1 << 0) +#define NFC_3_2_CONFIG1_NF_CE_POS (1) +#define NFC_3_2_CONFIG1_NF_CE_MSK (0x1 << 1) +#define NFC_3_2_CONFIG1_RST_POS (2) +#define NFC_3_2_CONFIG1_RST_MSK (0x1 << 2) +#define NFC_3_2_CONFIG1_RBA_POS (4) +#define NFC_3_2_CONFIG1_RBA_MSK (0x7 << 4) +#define NFC_3_2_CONFIG1_ITER_POS (8) +#define NFC_3_2_CONFIG1_ITER_MSK (0xf << 8) +#define NFC_3_2_CONFIG1_CS_POS (12) +#define NFC_3_2_CONFIG1_CS_MSK (0x7 << 12) +#define NFC_3_2_CONFIG1_STATUS_POS (16) +#define NFC_3_2_CONFIG1_STATUS_MSK (0xFFFF<<16) + +#define NFC_3_2_ECC_STATUS_REG_OFF (0x38) +#define NFC_3_2_ECC_STATUS_NOBER1_POS (0) +#define NFC_3_2_ECC_STATUS_NOBER1_MSK (0xF << 0) +#define NFC_3_2_ECC_STATUS_NOBER2_POS (4) +#define NFC_3_2_ECC_STATUS_NOBER2_MSK (0xF << 4) +#define NFC_3_2_ECC_STATUS_NOBER3_POS (8) +#define NFC_3_2_ECC_STATUS_NOBER3_MSK (0xF << 8) +#define NFC_3_2_ECC_STATUS_NOBER4_POS (12) +#define NFC_3_2_ECC_STATUS_NOBER4_MSK (0xF << 12) +#define NFC_3_2_ECC_STATUS_NOBER5_POS (16) +#define NFC_3_2_ECC_STATUS_NOBER5_MSK (0xF << 16) +#define NFC_3_2_ECC_STATUS_NOBER6_POS (20) +#define NFC_3_2_ECC_STATUS_NOBER6_MSK (0xF << 20) +#define NFC_3_2_ECC_STATUS_NOBER7_POS (24) +#define NFC_3_2_ECC_STATUS_NOBER7_MSK (0xF << 24) +#define NFC_3_2_ECC_STATUS_NOBER8_POS (28) +#define NFC_3_2_ECC_STATUS_NOBER8_MSK (0xF << 28) + + +#define NFC_3_2_STATUS_SUM_REG_OFF (0x3C) +#define NFC_3_2_STATUS_SUM_NAND_SUM_POS (0x0) +#define NFC_3_2_STATUS_SUM_NAND_SUM_MSK (0xFF << 0) +#define NFC_3_2_STATUS_SUM_ECC_SUM_POS (8) +#define NFC_3_2_STATUS_SUM_ECC_SUM_MSK (0xFF << 8) + +#define NFC_3_2_LAUNCH_REG_OFF (0x40) +#define NFC_3_2_LAUNCH_FCMD_POS (0) +#define NFC_3_2_LAUNCH_FCMD_MSK (0x1 << 0) +#define NFC_3_2_LAUNCH_FADD_POS (1) +#define NFC_3_2_LAUNCH_FADD_MSK (0x1 << 1) +#define NFC_3_2_LAUNCH_FDI_POS (2) +#define NFC_3_2_LAUNCH_FDI_MSK (0x1 << 2) +#define NFC_3_2_LAUNCH_FDO_POS (3) +#define NFC_3_2_LAUNCH_FDO_MSK (0x7 << 3) +#define NFC_3_2_LAUNCH_AUTO_PROG_POS (6) +#define NFC_3_2_LAUNCH_AUTO_PROG_MSK (0x1 << 6) +#define NFC_3_2_LAUNCH_AUTO_READ_POS (7) +#define NFC_3_2_LAUNCH_AUTO_READ_MSK (0x1 << 7) +#define NFC_3_2_LAUNCH_AUTO_ERASE_POS (9) +#define NFC_3_2_LAUNCH_AUTO_ERASE_MSK (0x1 << 9) +#define NFC_3_2_LAUNCH_COPY_BACK0_POS (10) +#define NFC_3_2_LAUNCH_COPY_BACK0_MSK (0x1 << 10) +#define NFC_3_2_LAUNCH_COPY_BACK1_POS (11) +#define NFC_3_2_LAUNCH_COPY_BACK1_MSK (0x1 << 11) +#define NFC_3_2_LAUNCH_AUTO_STATUS_POS (12) +#define NFC_3_2_LAUNCH_AUTO_STATUS_MSK (0x1 << 12) + +#define NFC_3_2_WRPROT_REG_OFF (0x00) +#define NFC_3_2_WRPROT_WPC_POS (0) +#define NFC_3_2_WRPROT_WPC_MSK (0x7 << 0) +#define NFC_3_2_WRPROT_CS2L_POS (3) +#define NFC_3_2_WRPROT_CS2L_MSK (0x7 << 3) +#define NFC_3_2_WRPROT_BLS_POS (6) +#define NFC_3_2_WRPROT_BLS_MSK (0x3 << 6) +#define NFC_3_2_WRPROT_LTS0_POS (8) +#define NFC_3_2_WRPROT_LTS0_MSK (0x1 << 8) +#define NFC_3_2_WRPROT_LS0_POS (9) +#define NFC_3_2_WRPROT_LS0_MSK (0x1 << 9) +#define NFC_3_2_WRPROT_US0_POS (10) +#define NFC_3_2_WRPROT_US0_MSK (0x1 << 10) +#define NFC_3_2_WRPROT_LTS1_POS (11) +#define NFC_3_2_WRPROT_LTS1_MSK (0x1 << 11) +#define NFC_3_2_WRPROT_LS1_POS (12) +#define NFC_3_2_WRPROT_LS1_MSK (0x1 << 12) +#define NFC_3_2_WRPROT_US1_POS (13) +#define NFC_3_2_WRPROT_US1_MSK (0x1 << 13) +#define NFC_3_2_WRPROT_LTS2_POS (14) +#define NFC_3_2_WRPROT_LTS2_MSK (0x1 << 14) +#define NFC_3_2_WRPROT_LS2_POS (15) +#define NFC_3_2_WRPROT_LS2_MSK (0x1 << 15) +#define NFC_3_2_WRPROT_US2_POS (16) +#define NFC_3_2_WRPROT_US2_MSK (0x1 << 16) +#define NFC_3_2_WRPROT_LTS3_POS (17) +#define NFC_3_2_WRPROT_LTS3_MSK (0x1 << 17) +#define NFC_3_2_WRPROT_LS3_POS (18) +#define NFC_3_2_WRPROT_LS3_MSK (0x1 << 18) +#define NFC_3_2_WRPROT_US3_POS (19) +#define NFC_3_2_WRPROT_US3_MSK (0x1 << 19) +#define NFC_3_2_WRPROT_LTS4_POS (20) +#define NFC_3_2_WRPROT_LTS4_MSK (0x1 << 20) +#define NFC_3_2_WRPROT_LS4_POS (21) +#define NFC_3_2_WRPROT_LS4_MSK (0x1 << 21) +#define NFC_3_2_WRPROT_US4_POS (22) +#define NFC_3_2_WRPROT_US4_MSK (0x1 << 22) +#define NFC_3_2_WRPROT_LTS5_POS (23) +#define NFC_3_2_WRPROT_LTS5_MSK (0x1 << 23) +#define NFC_3_2_WRPROT_LS5_POS (24) +#define NFC_3_2_WRPROT_LS5_MSK (0x1 << 24) +#define NFC_3_2_WRPROT_US5_POS (25) +#define NFC_3_2_WRPROT_US5_MSK (0x1 << 25) +#define NFC_3_2_WRPROT_LTS6_POS (26) +#define NFC_3_2_WRPROT_LTS6_MSK (0x1 << 26) +#define NFC_3_2_WRPROT_LS6_POS (27) +#define NFC_3_2_WRPROT_LS6_MSK (0x1 << 27) +#define NFC_3_2_WRPROT_US6_POS (28) +#define NFC_3_2_WRPROT_US6_MSK (0x1 << 28) +#define NFC_3_2_WRPROT_LTS7_POS (29) +#define NFC_3_2_WRPROT_LTS7_MSK (0x1 << 29) +#define NFC_3_2_WRPROT_LS7_POS (30) +#define NFC_3_2_WRPROT_LS7_MSK (0x1 << 30) +#define NFC_3_2_WRPROT_US7_POS (31) +#define NFC_3_2_WRPROT_US7_MSK (0x1 << 31) + +#define NFC_3_2_UNLOCK_BLK_ADD0_REG_OFF (0x04) +#define NFC_3_2_UNLOCK_BLK_ADD0_USBA0_POS (0) +#define NFC_3_2_UNLOCK_BLK_ADD0_USBA0_MSK (0xFFFF << 0) +#define NFC_3_2_UNLOCK_BLK_ADD0_UEBA0_POS (16) +#define NFC_3_2_UNLOCK_BLK_ADD0_UEBA0_MSK (0xFFFF<<16) + +#define NFC_3_2_UNLOCK_BLK_ADD1_REG_OFF (0x08) +#define NFC_3_2_UNLOCK_BLK_ADD1_USBA1_POS (0) +#define NFC_3_2_UNLOCK_BLK_ADD1_USBA1_MSK (0xFFFF << 0) +#define NFC_3_2_UNLOCK_BLK_ADD1_UEBA1_POS (16) +#define NFC_3_2_UNLOCK_BLK_ADD1_UEBA1_MSK (0xFFFF<<16) + +#define NFC_3_2_UNLOCK_BLK_ADD2_REG_OFF (0x0C) +#define NFC_3_2_UNLOCK_BLK_ADD2_USBA2_POS (0) +#define NFC_3_2_UNLOCK_BLK_ADD2_USBA2_MSK (0xFFFF << 0) +#define NFC_3_2_UNLOCK_BLK_ADD2_UEBA2_POS (16) +#define NFC_3_2_UNLOCK_BLK_ADD2_UEBA2_MSK (0xFFFF<<16) + +#define NFC_3_2_UNLOCK_BLK_ADD3_REG_OFF (0x10) +#define NFC_3_2_UNLOCK_BLK_ADD3_USBA3_POS (0) +#define NFC_3_2_UNLOCK_BLK_ADD3_USBA3_MSK (0xFFFF << 0) +#define NFC_3_2_UNLOCK_BLK_ADD3_UEBA3_POS (16) +#define NFC_3_2_UNLOCK_BLK_ADD3_UEBA3_MSK (0xFFFF<<16) + +#define NFC_3_2_UNLOCK_BLK_ADD4_REG_OFF (0x14) +#define NFC_3_2_UNLOCK_BLK_ADD4_USBA4_POS (0) +#define NFC_3_2_UNLOCK_BLK_ADD4_USBA4_MSK (0xFFFF << 0) +#define NFC_3_2_UNLOCK_BLK_ADD4_UEBA4_POS (16) +#define NFC_3_2_UNLOCK_BLK_ADD4_UEBA4_MSK (0xFFFF<<16) + +#define NFC_3_2_UNLOCK_BLK_ADD5_REG_OFF (0x18) +#define NFC_3_2_UNLOCK_BLK_ADD5_USBA5_POS (0) +#define NFC_3_2_UNLOCK_BLK_ADD5_USBA5_MSK (0xFFFF << 0) +#define NFC_3_2_UNLOCK_BLK_ADD5_UEBA5_POS (16) +#define NFC_3_2_UNLOCK_BLK_ADD5_UEBA5_MSK (0xFFFF<<16) + +#define NFC_3_2_UNLOCK_BLK_ADD6_REG_OFF (0x1C) +#define NFC_3_2_UNLOCK_BLK_ADD6_USBA6_POS (0) +#define NFC_3_2_UNLOCK_BLK_ADD6_USBA6_MSK (0xFFFF << 0) +#define NFC_3_2_UNLOCK_BLK_ADD6_UEBA6_POS (16) +#define NFC_3_2_UNLOCK_BLK_ADD6_UEBA6_MSK (0xFFFF<<16) + +#define NFC_3_2_UNLOCK_BLK_ADD7_REG_OFF (0x20) +#define NFC_3_2_UNLOCK_BLK_ADD7_USBA7_POS (0) +#define NFC_3_2_UNLOCK_BLK_ADD7_USBA7_MSK (0xFFFF << 0) +#define NFC_3_2_UNLOCK_BLK_ADD7_UEBA7_POS (16) +#define NFC_3_2_UNLOCK_BLK_ADD7_UEBA7_MSK (0xFFFF<<16) + +#define NFC_3_2_CONFIG2_REG_OFF (0x24) +#define NFC_3_2_CONFIG2_PS_POS (0) +#define NFC_3_2_CONFIG2_PS_MSK (0x3 << 0) +#define NFC_3_2_CONFIG2_SYM_POS (2) +#define NFC_3_2_CONFIG2_SYM_MSK (0x1 << 2) +#define NFC_3_2_CONFIG2_ECC_EN_POS (3) +#define NFC_3_2_CONFIG2_ECC_EN_MSK (0x1 << 3) +#define NFC_3_2_CONFIG2_CMD_PHASES_POS (4) +#define NFC_3_2_CONFIG2_CMD_PHASES_MSK (0x1 << 4) +#define NFC_3_2_CONFIG2_ADDR_PHASES0_POS (5) +#define NFC_3_2_CONFIG2_ADDR_PHASES0_MSK (0x1 << 5) +#define NFC_3_2_CONFIG2_ECC_MODE_POS (6) +#define NFC_3_2_CONFIG2_ECC_MODE_MSK (0x1 << 6) +#define NFC_3_2_CONFIG2_PPB_POS (7) +#define NFC_3_2_CONFIG2_PPB_MSK (0x3 << 7) +#define NFC_3_2_CONFIG2_EDC_POS (9) +#define NFC_3_2_CONFIG2_EDC_MSK (0x7 << 9) +#define NFC_3_2_CONFIG2_ADDR_PHASES1_POS (12) +#define NFC_3_2_CONFIG2_ADDR_PHASES1_MSK (0x3 << 12) +#define NFC_3_2_CONFIG2_AUTO_DONE_MSK_POS (14) +#define NFC_3_2_CONFIG2_AUTO_DONE_MSK_MSK (0x1 << 14) +#define NFC_3_2_CONFIG2_INT_MSK_POS (15) +#define NFC_3_2_CONFIG2_INT_MSK_MSK (0x1 << 15) +#define NFC_3_2_CONFIG2_SPAS_POS (16) +#define NFC_3_2_CONFIG2_SPAS_MSK (0xFF << 16) +#define NFC_3_2_CONFIG2_ST_CMD_POS (24) +#define NFC_3_2_CONFIG2_ST_CMD_MSK (0xFF << 24) + +#define NFC_3_2_CONFIG3_REG_OFF (0x28) +#define NFC_3_2_CONFIG3_ADD_OP_POS (0) +#define NFC_3_2_CONFIG3_ADD_OP_MSK (0x3 << 0) +#define NFC_3_2_CONFIG3_TOO_POS (2) +#define NFC_3_2_CONFIG3_TOO_MSK (0x1 << 2) +#define NFC_3_2_CONFIG3_FW_POS (3) +#define NFC_3_2_CONFIG3_FW_MSK (0x1 << 3) +#define NFC_3_2_CONFIG3_SB2R_POS (4) +#define NFC_3_2_CONFIG3_SB2R_MSK (0x7 << 4) +#define NFC_3_2_CONFIG3_NF_BIG_POS (7) +#define NFC_3_2_CONFIG3_NF_BIG_MSK (0x1 << 7) +#define NFC_3_2_CONFIG3_SBB_POS (8) +#define NFC_3_2_CONFIG3_SBB_MSK (0x7 << 8) +#define NFC_3_2_CONFIG3_DMA_MODE_POS (11) +#define NFC_3_2_CONFIG3_DMA_MODE_MSK (0x1 << 11) +#define NFC_3_2_CONFIG3_NUM_OF_DEVICES_POS (12) +#define NFC_3_2_CONFIG3_NUM_OF_DEVICES_MSK (0x7 << 12) +#define NFC_3_2_CONFIG3_RBB_MODE_POS (15) +#define NFC_3_2_CONFIG3_RBB_MODE_MSK (0x1 << 15) +#define NFC_3_2_CONFIG3_FMP_POS (16) +#define NFC_3_2_CONFIG3_FMP_MSK (0xF << 16) +#define NFC_3_2_CONFIG3_NO_SDMA_POS (20) +#define NFC_3_2_CONFIG3_NO_SDMA_MSK (0x1 << 20) + +#define NFC_3_2_IPC_REG_OFF (0x2C) +#define NFC_3_2_IPC_CREQ_POS (0) +#define NFC_3_2_IPC_CREQ_MSK (0x1 << 0) +#define NFC_3_2_IPC_CACK_POS (1) +#define NFC_3_2_IPC_CACK_MSK (0x1 << 1) +#define NFC_3_2_IPC_DMA_STATUS_POS (26) +#define NFC_3_2_IPC_DMA_STATUS_MSK (0x3 << 26) +#define NFC_3_2_IPC_RB_B_POS (28) +#define NFC_3_2_IPC_RB_B_MSK (0x1 << 28) +#define NFC_3_2_IPC_LPS_POS (29) +#define NFC_3_2_IPC_LPS_MSK (0x1 << 29) +#define NFC_3_2_IPC_AUTO_PROG_DONE_POS (30) +#define NFC_3_2_IPC_AUTO_PROG_DONE_MSK (0x1 << 30) +#define NFC_3_2_IPC_INT_POS (31) +#define NFC_3_2_IPC_INT_MSK (0x1 << 31) + +#define NFC_3_2_AXI_ERR_ADD_REG_OFF (0x30) + +/** + * enum override - Choices for overrides. + * + * Some functions of this driver can be overriden at run time. This is a + * convenient enumerated type for all such options. + */ + +enum override { + NEVER = -1, + DRIVER_CHOICE = 0, + ALWAYS = 1, +}; + +/** + * struct physical_geometry - Physical geometry description. + * + * This structure describes the physical geometry of the medium. + * + * @chip_count: The number of chips in the medium. + * @chip_size: The size, in bytes, of a single chip (excluding the + * out-of-band bytes). + * @block_size: The size, in bytes, of a single block (excluding the + * out-of-band bytes). + * @page_data_size: The size, in bytes, of the data area in a page (excluding + * the out-of-band bytes). + * @page_oob_size: The size, in bytes, of the out-of-band area in a page. + */ + +struct physical_geometry { + unsigned int chip_count; + uint64_t chip_size; + unsigned int block_size; + unsigned int page_data_size; + unsigned int page_oob_size; +}; + +/** + * struct nfc_geometry - NFC geometry description. + * + * This structure describes the NFC's view of the medium geometry, which may be + * different from the physical geometry (for example, we treat pages that are + * physically 2K+112 as if they are 2K+64). + * + * @page_data_size: The size of the data area in a page (excluding the + * out-of-band bytes). This is almost certain to be the same + * as the physical data size. + * @page_oob_size: The size of the out-of-band area in a page. This may be + * different from the physical OOB size. + * @ecc_algorithm: The name of the ECC algorithm (e.g., "Reed-Solomon" or + * "BCH"). + * @ecc_strength: A number that describes the strength of the ECC algorithm. + * For example, various i.MX SoC's support ECC-1, ECC-4 or + * ECC-8 of the Reed-Solomon ECC algorithm. + * @buffer_count: The number of main/spare buffers used with this geometry. + * @spare_buf_size: The number of bytes held in each spare buffer. + * @spare_buf_spill: The number of extra bytes held in the last spare buffer. + * @mtd_layout: The MTD layout that best matches the geometry described by + * the rest of this structure. The logical layer might not use + * this structure, especially when interleaving. + */ + +struct nfc_geometry { + const unsigned int page_data_size; + const unsigned int page_oob_size; + const char *ecc_algorithm; + const int ecc_strength; + const unsigned int buffer_count; + const unsigned int spare_buf_size; + const unsigned int spare_buf_spill; + struct nand_ecclayout mtd_layout; +}; + +/** + * struct logical_geometry - Logical geometry description. + * + * This structure describes the logical geometry we expose to MTD. This geometry + * may be different from the physical or NFC geometries, especially when + * interleaving. + * + * @chip_count: The number of chips in the medium. + * @chip_size: The size, in bytes, of a single chip (excluding the + * out-of-band bytes). + * @usable_size: The size, in bytes, of the medium that MTD can actually + * use. This may be less than the chip size multiplied by the + * number of chips. + * @block_size: The size, in bytes, of a single block (excluding the + * out-of-band bytes). + * @page_data_size: The size of the data area in a page (excluding the + * out-of-band bytes). + * @page_oob_size: The size of the out-of-band area in a page. + */ + +struct logical_geometry { + unsigned int chip_count; + uint32_t chip_size; + uint32_t usable_size; + unsigned int block_size; + unsigned int page_data_size; + unsigned int page_oob_size; + struct nand_ecclayout *mtd_layout; +}; + +/** + * struct imx_nfc_data - i.MX NFC per-device data. + * + * Note that the "device" managed by this driver represents the NAND Flash + * controller *and* the NAND Flash medium behind it. Thus, the per-device data + * structure has information about the controller, the chips to which it is + * connected, and properties of the medium as a whole. + * + * @dev: A pointer to the owning struct device. + * @pdev: A pointer to the owning struct platform_device. + * @pdata: A pointer to the device's platform data. + * @buffers: A pointer to the NFC buffers. + * @primary_regs: A pointer to the NFC primary registers. + * @secondary_regs: A pointer to the NFC secondary registers. + * @clock: A pointer to the NFC struct clk. + * @interrupt: The NFC interrupt number. + * @physical_geometry: A description of the medium's physical geometry. + * @nfc: A pointer to the NFC HAL. + * @nfc_geometry: A description of the medium geometry as viewed by the + * NFC. + * @done: The struct completion we use to handle interrupts. + * @logical_geometry: A description of the logical geometry exposed to MTD. + * @interrupt_override: Can override how the driver uses interrupts when + * waiting for the NFC. + * @auto_op_override: Can override whether the driver uses automatic NFC + * operations. + * @inject_ecc_error: Indicates that the driver should inject an ECC error in + * the next read operation that uses ECC. User space + * programs can set this value through the sysfs node of + * the same name. If this value is less than zero, the + * driver will inject an uncorrectable ECC error. If this + * value is greater than zero, the driver will inject that + * number of correctable errors, capped at whatever + * possible maximum currently applies. + * @current_chip: The chip currently selected by the NAND Fash MTD HIL. + * A negative value indicates that no chip is selected. + * We use this field to detect when the HIL begins and + * ends essential transactions. This helps us to know when + * we should turn the NFC clock on or off. + * @command: The last command the HIL tried to send by calling + * cmdfunc(). Later functions use this information to + * adjust their behavior. The sentinel value ~0 indicates + * no command. + * @command_is_new: Indicates the command has just come down to cmdfunc() + * from the HIL and hasn't yet been handled. Other + * functions use this to adjust their behavior. + * @page_address: The current page address of interest. For reads, this + * information arrives in calls to cmdfunc(), but we don't + * actually use it until later. + * @nand: The data structure that represents this NAND Flash + * medium to the MTD NAND Flash system. + * @mtd: The data structure that represents this NAND Flash + * medium to MTD. + * @partitions: A pointer to a set of partitions collected from one of + * several possible sources (e.g., the boot loader, the + * kernel command line, etc.). See the global variable + * partition_source_types for the list of partition + * sources we examine. If this member is NULL, then no + * partitions were discovered. + * @partition_count: The number of discovered partitions. + */ + +struct imx_nfc_data { + + /* System Interface */ + struct device *dev; + struct platform_device *pdev; + + /* Platform Configuration */ + struct imx_nfc_platform_data *pdata; + void *buffers; + void *primary_regs; + void *secondary_regs; + struct clk *clock; + unsigned int interrupt; + + /* Flash Hardware */ + struct physical_geometry physical_geometry; + + /* NFC HAL and NFC Utilities */ + struct nfc_hal *nfc; + struct nfc_geometry *nfc_geometry; + struct completion done; + + /* Medium Abstraction Layer */ + struct logical_geometry logical_geometry; + enum override interrupt_override; + enum override auto_op_override; + int inject_ecc_error; + + /* MTD Interface Layer */ + int current_chip; + unsigned int command; + int command_is_new; + int page_address; + + /* NAND Flash MTD */ + struct nand_chip nand; + + /* MTD */ + struct mtd_info mtd; + struct mtd_partition *partitions; + unsigned int partition_count; + +}; + +/** + * struct nfc_hal - i.MX NFC HAL + * + * This structure embodies an abstract interface to the underlying NFC hardware. + * + * @major_version: The major version number of the NFC to which this + * structure applies. + * @minor_version: The minor version number of the NFC to which this + * structure applies. + * @max_chip_count: The maximum number of chips the NFC can possibly + * support. This may *not* be the actual number of chips + * currently connected. This value is constant for NFC's + * of a given version. + * @max_buffer_count: The number of main/spare buffers available in the NFC's + * memory. This value is constant for NFC's of a given + * version. + * @spare_buf_stride: The stride, in bytes, from the beginning of one spare + * buffer to the beginning of the next one. This value is + * constant for NFC's of a given version. + * @has_secondary_regs: Indicates if the NFC has a secondary register set that + * must be mapped in. + * @can_be_symmetric: Indicates if the NFC supports a "symmetric" clock. When + * the clock is "symmetric," the hardware waits one NFC + * clock for every read/write cycle. When the clock is + * "asymmetric," the hardware waits two NFC clocks for + * every read/write cycle. + * @init: Initializes the NFC and any version-specific data + * structures. This function will be called after + * everything has been set up for communication with the + * NFC itself, but before the platform has set up off-chip + * communication. Thus, this function must not attempt to + * communicate with the NAND Flash hardware. A non-zero + * return value indicates failure. + * @set_geometry: Based on the physical geometry, this function selects + * an NFC geometry structure and configures the NFC + * hardware to match. A non-zero return value indicates + * failure. + * @exit: Shuts down the NFC and cleans up version-specific data + * structures. This function will be called after the + * platform has shut down off-chip communication but while + * communication with the NFC still works. + * @set_closest_cycle: Configures the hardware to make the NAND Flash bus + * cycle period as close as possible to the given cycle + * period. This function is called during boot up and may + * assume that, at the time it's called, the parent clock + * is running at the highest rate it will ever run. Thus, + * this function need never worry that the NAND Flash bus + * will run faster and potentially make it impossible to + * communicate with the NAND Flash device -- it will only + * run slower. + * @mask_interrupt: Masks the NFC's interrupt. + * @unmask_interrupt: Unmasks the NFC's interrupt. + * @clear_interrupt: Clears the NFC's interrupt. + * @is_interrupting: Returns true if the NFC is interrupting. + * @is_ready: Returns true if all the chips in the medium are ready. + * This member may be set to NULL, which indicates that + * the underlying NFC hardware doesn't expose ready/busy + * signals. + * @set_force_ce: If passed true, forces the hardware chip enable signal + * for the current chip to be asserted always. If passed + * false, causes the chip enable signal to be asserted + * only during I/O. + * @set_ecc: Sets ECC on or off. + * @get_ecc_status: Examines the hardware ECC status and returns: + * == 0 => No errors. + * > 0 => The number of corrected errors. + * < 0 => There were uncorrectable errors. + * @get_symmetric: Gets the current symmetric clock setting. For versions + * that don't support symmetric clocks, this function + * always returns false. + * @set_symmetric: For versions that support symmetric clocks, sets + * whether or not the clock is symmetric. + * @select_chip: Selects the current chip. + * @command_cycle: Sends a command code and then returns immediately + * *without* waiting for the NFC to finish. + * @write_cycle: Applies a single write cycle to the current chip, + * sending the given byte, and waiting for the NFC to + * finish. + * @read_cycle: Applies a single read cycle to the current chip and + * returns the result, necessarily waiting for the NFC to + * finish. The width of the result is the same as the + * width of the Flash bus. + * @read_page: Applies read cycles to the current chip to read an + * entire page into the NFC. Note that ECC is enabled or + * disabled with the set_ecc function pointer (see above). + * This function waits for the NFC to finish before + * returning. + * @send_page: Applies write cycles to send an entire page from the + * NFC to the current chip. Note that ECC is enabled or + * disabled with the set_ecc function pointer (see above). + * This function waits for the NFC to finish before + * returning. + * @start_auto_read: Starts an automatic read operation. A NULL pointer + * indicates automatic read operations aren't available + * with this NFC version. + * @wait_for_auto_read: Blocks until an automatic read operation is ready for + * the CPU to copy a page out of the NFC. + * @resume_auto_read: Resumes an automatic read operation after the CPU has + * copied a page out. + * @start_auto_write: Starts an automatic write operation. A NULL pointer + * indicates automatic write operations aren't available + * with this NFC version. + * @wait_for_auto_write: Blocks until an automatic write operation is ready for + * the CPU to copy a page into the NFC. + * @start_auto_erase: Starts an automatic erase operation. A NULL pointer + * indicates automatic erase operations aren't available + * with this NFC version. + */ + +struct nfc_hal { + const unsigned int major_version; + const unsigned int minor_version; + const unsigned int max_chip_count; + const unsigned int max_buffer_count; + const unsigned int spare_buf_stride; + const int has_secondary_regs; + const int can_be_symmetric; + int (*init) (struct imx_nfc_data *); + int (*set_geometry) (struct imx_nfc_data *); + void (*exit) (struct imx_nfc_data *); + int (*set_closest_cycle) (struct imx_nfc_data *, unsigned ns); + void (*mask_interrupt) (struct imx_nfc_data *); + void (*unmask_interrupt) (struct imx_nfc_data *); + void (*clear_interrupt) (struct imx_nfc_data *); + int (*is_interrupting) (struct imx_nfc_data *); + int (*is_ready) (struct imx_nfc_data *); + void (*set_force_ce) (struct imx_nfc_data *, int on); + void (*set_ecc) (struct imx_nfc_data *, int on); + int (*get_ecc_status) (struct imx_nfc_data *); + int (*get_symmetric) (struct imx_nfc_data *); + void (*set_symmetric) (struct imx_nfc_data *, int on); + void (*select_chip) (struct imx_nfc_data *, int chip); + void (*command_cycle) (struct imx_nfc_data *, unsigned cmd); + void (*write_cycle) (struct imx_nfc_data *, unsigned byte); + unsigned (*read_cycle) (struct imx_nfc_data *); + void (*read_page) (struct imx_nfc_data *); + void (*send_page) (struct imx_nfc_data *); + int (*start_auto_read) (struct imx_nfc_data *, + unsigned start, unsigned count, unsigned column, unsigned page); + int (*wait_for_auto_read) (struct imx_nfc_data *); + int (*resume_auto_read) (struct imx_nfc_data *); + int (*start_auto_write) (struct imx_nfc_data *, + unsigned start, unsigned count, unsigned column, unsigned page); + int (*wait_for_auto_write)(struct imx_nfc_data *); + int (*start_auto_erase) (struct imx_nfc_data *, + unsigned start, unsigned count, unsigned page); +}; + +/* + * This variable controls whether or not probing is enabled. If false, then + * the driver will refuse to probe. The "enable" module parameter controls the + * value of this variable. + */ + +static int imx_nfc_module_enable = true; + +#ifdef EVENT_REPORTING + +/* + * This variable controls whether the driver reports event information by + * printing to the console. The "report_events" module parameter controls the + * value of this variable. + */ + +static int imx_nfc_module_report_events; /* implicitly initialized false*/ + +#endif + +/* + * This variable potentially overrides the driver's choice to interleave. The + * "interleave_override" module parameter controls the value of this variable. + */ + +static enum override imx_nfc_module_interleave_override = DRIVER_CHOICE; + +/* + * When set, this variable forces the driver to use the bytewise copy functions + * to get data in and out of the NFC. This is intended for testing, not typical + * use. + */ + +static int imx_nfc_module_force_bytewise_copy; /* implicitly initialized false*/ + +/* + * The list of algorithms we use to get partition information from the + * environment. + */ + +#ifdef CONFIG_MTD_PARTITIONS +static const char *partition_source_types[] = { "cmdlinepart", NULL }; +#endif + +/* + * The following structures describe the NFC geometries we support. + * + * Notice that pieces of some structure definitions are commented out and edited + * because various parts of the MTD system can't handle the way our hardware + * formats the out-of-band area. + * + * Here are the problems: + * + * - struct nand_ecclayout expects no more than 64 ECC bytes. + * + * The eccpos member of struct nand_ecclayout can't hold more than 64 ECC + * byte positions. Some of our formats have more so, unedited, they won't + * even compile. We comment out all ECC byte positions after the 64th one. + * + * - struct nand_ecclayout expects no more than 8 free spans. + * + * The oobfree member of struct nand_ecclayout can't hold more than 8 free + * spans. Some of our formats have more so, unedited, they won't even + * compile. We comment out all free spans after the eighth one. + * + * - The MEMGETOOBSEL command in the mtdchar driver. + * + * The mtdchar ioctl command MEMGETOOBSEL checks the number of ECC bytes + * against the length of the eccpos array in struct nand_oobinfo + * (see include/mtd/mtd-abi.h). This array can handle up to 32 ECC bytes, + * but some of our formats have more. + * + * To make this work, we cap the value assigned to eccbytes at 32. + * + * Notice that struct nand_oobinfo, used by mtdchar, is *different* from the + * struct nand_ecclayout that MTD uses internally. The latter structure + * can accomodate up to 64 ECC byte positions. Thus, we declare up to 64 + * ECC byte positions here, even if the advertised number of ECC bytes is + * less. + * + * This command is obsolete and, if no one used it, we wouldn't care about + * this problem. Unfortunately The nandwrite program uses it, and everyone + * expects nandwrite to work (it's how everyone usually lays down their + * JFFS2 file systems). + */ + +static struct nfc_geometry nfc_geometry_512_16_RS_ECC1 = { + .page_data_size = 512, + .page_oob_size = 16, + .ecc_algorithm = "Reed-Solomon", + .ecc_strength = 1, + .buffer_count = 1, + .spare_buf_size = 16, + .spare_buf_spill = 0, + .mtd_layout = { + .eccbytes = 5, + .eccpos = {6, 7, 8, 9, 10}, + .oobavail = 11, + .oobfree = { {0, 6}, {11, 5} }, + } +}; + +static struct nfc_geometry nfc_geometry_512_16_RS_ECC4 = { + .page_data_size = 512, + .page_oob_size = 16, + .ecc_algorithm = "Reed-Solomon", + .ecc_strength = 4, + .buffer_count = 1, + .spare_buf_size = 16, + .spare_buf_spill = 0, + .mtd_layout = { + .eccbytes = 9, + .eccpos = {7, 8, 9, 10, 11, 12, 13, 14, 15}, + .oobavail = 7, + .oobfree = { {0, 7} }, + } +}; + +static struct nfc_geometry nfc_geometry_512_16_BCH_ECC4 = { + .page_data_size = 512, + .page_oob_size = 16, + .ecc_algorithm = "BCH", + .ecc_strength = 4, + .buffer_count = 1, + .spare_buf_size = 16, + .spare_buf_spill = 0, + .mtd_layout = { + .eccbytes = 8, + .eccpos = {8, 9, 10, 11, 12, 13, 14, 15}, + .oobavail = 8, + .oobfree = { {0, 8} }, + } +}; + +static struct nfc_geometry nfc_geometry_2K_64_RS_ECC4 = { + .page_data_size = 2048, + .page_oob_size = 64, + .ecc_algorithm = "Reed-Solomon", + .ecc_strength = 4, + .buffer_count = 4, + .spare_buf_size = 16, + .spare_buf_spill = 0, + .mtd_layout = { + .eccbytes = 32 /*9 * 4*/, /* See notes above. */ + .eccpos = { + + (0*16)+7 , (0*16)+8 , (0*16)+9 , (0*16)+10, (0*16)+11, + (0*16)+12, (0*16)+13, (0*16)+14, (0*16)+15, + + (1*16)+7 , (1*16)+8 , (1*16)+9 , (1*16)+10, (1*16)+11, + (1*16)+12, (1*16)+13, (1*16)+14, (1*16)+15, + + (2*16)+7 , (2*16)+8 , (2*16)+9 , (2*16)+10, (2*16)+11, + (2*16)+12, (2*16)+13, (2*16)+14, (2*16)+15, + + (3*16)+7 , (3*16)+8 , (3*16)+9 , (3*16)+10, (3*16)+11, + (3*16)+12, (3*16)+13, (3*16)+14, (3*16)+15, + + }, + .oobavail = 7 * 4, + .oobfree = { + {(0*16)+0, 7}, + {(1*16)+0, 7}, + {(2*16)+0, 7}, + {(3*16)+0, 7}, + }, + } +}; + +static struct nfc_geometry nfc_geometry_2K_64_BCH_ECC4 = { + .page_data_size = 2048, + .page_oob_size = 64, + .ecc_algorithm = "BCH", + .ecc_strength = 4, + .buffer_count = 4, + .spare_buf_size = 16, + .spare_buf_spill = 0, + .mtd_layout = { + .eccbytes = 8 * 4, + .eccpos = { + + (0*16)+8 , (0*16)+9 , (0*16)+10, (0*16)+11, + (0*16)+12, (0*16)+13, (0*16)+14, (0*16)+15, + + (1*16)+8 , (1*16)+9 , (1*16)+10, (1*16)+11, + (1*16)+12, (1*16)+13, (1*16)+14, (1*16)+15, + + (2*16)+8 , (2*16)+9 , (2*16)+10, (2*16)+11, + (2*16)+12, (2*16)+13, (2*16)+14, (2*16)+15, + + (3*16)+8 , (3*16)+9 , (3*16)+10, (3*16)+11, + (3*16)+12, (3*16)+13, (3*16)+14, (3*16)+15, + + }, + .oobavail = 8 * 4, + .oobfree = { + {(0*16)+0, 8}, + {(1*16)+0, 8}, + {(2*16)+0, 8}, + {(3*16)+0, 8}, + }, + } +}; + +static struct nfc_geometry nfc_geometry_4K_128_BCH_ECC4 = { + .page_data_size = 4096, + .page_oob_size = 128, + .ecc_algorithm = "BCH", + .ecc_strength = 4, + .buffer_count = 8, + .spare_buf_size = 16, + .spare_buf_spill = 0, + .mtd_layout = { + .eccbytes = 8 * 8, + .eccpos = { + + (0*16)+8 , (0*16)+9 , (0*16)+10, (0*16)+11, + (0*16)+12, (0*16)+13, (0*16)+14, (0*16)+15, + + (1*16)+8 , (1*16)+9 , (1*16)+10, (1*16)+11, + (1*16)+12, (1*16)+13, (1*16)+14, (1*16)+15, + + (2*16)+8 , (2*16)+9 , (2*16)+10, (2*16)+11, + (2*16)+12, (2*16)+13, (2*16)+14, (2*16)+15, + + (3*16)+8 , (3*16)+9 , (3*16)+10, (3*16)+11, + (3*16)+12, (3*16)+13, (3*16)+14, (3*16)+15, + + (4*16)+8 , (4*16)+9 , (4*16)+10, (4*16)+11, + (4*16)+12, (4*16)+13, (4*16)+14, (4*16)+15, + + (5*16)+8 , (5*16)+9 , (5*16)+10, (5*16)+11, + (5*16)+12, (5*16)+13, (5*16)+14, (5*16)+15, + + (6*16)+8 , (6*16)+9 , (6*16)+10, (6*16)+11, + (6*16)+12, (6*16)+13, (6*16)+14, (6*16)+15, + + (7*16)+8 , (7*16)+9 , (7*16)+10, (7*16)+11, + (7*16)+12, (7*16)+13, (7*16)+14, (7*16)+15, + + }, + .oobavail = 8 * 8, + .oobfree = { + {(0*16)+0, 8}, + {(1*16)+0, 8}, + {(2*16)+0, 8}, + {(3*16)+0, 8}, + {(4*16)+0, 8}, + {(5*16)+0, 8}, + {(6*16)+0, 8}, + {(7*16)+0, 8}, + }, + } +}; + +static struct nfc_geometry nfc_geometry_4K_218_BCH_ECC8 = { + .page_data_size = 4096, + .page_oob_size = 218, + .ecc_algorithm = "BCH", + .ecc_strength = 8, + .buffer_count = 8, + .spare_buf_size = 26, + .spare_buf_spill = 10, + .mtd_layout = { + .eccbytes = 32 /*10 * 8*/, /* See notes above. */ + .eccpos = { + + (0*26)+12, (0*26)+13, (0*26)+14, (0*26)+15, (0*26)+16, + (0*26)+17, (0*26)+18, (0*26)+19, (0*26)+20, (0*26)+21, + + (1*26)+12, (1*26)+13, (1*26)+14, (1*26)+15, (1*26)+16, + (1*26)+17, (1*26)+18, (1*26)+19, (1*26)+20, (1*26)+21, + + (2*26)+12, (2*26)+13, (2*26)+14, (2*26)+15, (2*26)+16, + (2*26)+17, (2*26)+18, (2*26)+19, (2*26)+20, (2*26)+21, + + (3*26)+12, (3*26)+13, (3*26)+14, (3*26)+15, (3*26)+16, + (3*26)+17, (3*26)+18, (3*26)+19, (3*26)+20, (3*26)+21, + + (4*26)+12, (4*26)+13, (4*26)+14, (4*26)+15, (4*26)+16, + (4*26)+17, (4*26)+18, (4*26)+19, (4*26)+20, (4*26)+21, + + (5*26)+12, (5*26)+13, (5*26)+14, (5*26)+15, (5*26)+16, + (5*26)+17, (5*26)+18, (5*26)+19, (5*26)+20, (5*26)+21, + + (6*26)+12, (6*26)+13, (6*26)+14, (6*26)+15, + /* See notes above. + (6*26)+16, + (6*26)+17, (6*26)+18, (6*26)+19, (6*26)+20, (6*26)+21, + + (7*26)+12, (7*26)+13, (7*26)+14, (7*26)+15, (7*26)+16, + (7*26)+17, (7*26)+18, (7*26)+19, (7*26)+20, (7*26)+21, + */ + + }, + .oobavail = 96 /*(16 * 8) + 10*/, /* See notes above. */ + .oobfree = { + {(0*26)+0, 12}, {(0*26)+22, 4}, + {(1*26)+0, 12}, {(1*26)+22, 4}, + {(2*26)+0, 12}, {(2*26)+22, 4}, + {(3*26)+0, 48}, /* See notes above. */ + /* See notes above. + {(3*26)+0, 12}, {(3*26)+22, 4}, + {(4*26)+0, 12}, {(4*26)+22, 4}, + {(5*26)+0, 12}, {(5*26)+22, 4}, + {(6*26)+0, 12}, {(6*26)+22, 4}, + {(7*26)+0, 12}, {(7*26)+22, 4 + 10}, + */ + }, + } +}; + +/* + * When the logical geometry differs from the NFC geometry (e.g., + * interleaving), we synthesize a layout rather than use the one that comes with + * the NFC geometry. See mal_set_logical_geometry(). + */ + +static struct nand_ecclayout synthetic_layout; + +/* + * These structures describe how the BBT code will find block marks in the OOB + * area of a page. Don't be confused by the fact that this is the same type used + * to describe bad block tables. Some of the same information is needed, so the + * designers use the same structure for two conceptually distinct functions. + */ + +static uint8_t block_mark_pattern[] = { 0xff, 0xff }; + +static struct nand_bbt_descr small_page_block_mark_descriptor = { + .options = NAND_BBT_SCAN2NDPAGE, + .offs = 5, + .len = 1, + .pattern = block_mark_pattern, +}; + +static struct nand_bbt_descr large_page_block_mark_descriptor = { + .options = NAND_BBT_SCAN2NDPAGE, + .offs = 0, + .len = 2, + .pattern = block_mark_pattern, +}; + +/* + * Bad block table descriptors for the main and mirror tables. + */ + +static uint8_t bbt_main_pattern[] = { 'B', 'b', 't', '0' }; +static uint8_t bbt_mirror_pattern[] = { '1', 't', 'b', 'B' }; + +static struct nand_bbt_descr bbt_main_descriptor = { + .options = + NAND_BBT_LASTBLOCK | + NAND_BBT_CREATE | + NAND_BBT_WRITE | + NAND_BBT_2BIT | + NAND_BBT_VERSION | + NAND_BBT_PERCHIP, + .offs = 0, + .len = 4, + .veroffs = 4, + .maxblocks = 4, + .pattern = bbt_main_pattern, +}; + +static struct nand_bbt_descr bbt_mirror_descriptor = { + .options = + NAND_BBT_LASTBLOCK | + NAND_BBT_CREATE | + NAND_BBT_WRITE | + NAND_BBT_2BIT | + NAND_BBT_VERSION | + NAND_BBT_PERCHIP, + .offs = 0, + .len = 4, + .veroffs = 4, + .maxblocks = 4, + .pattern = bbt_mirror_pattern, +}; + +#ifdef EVENT_REPORTING + +/** + * struct event - A single record in the event trace. + * + * @time: The time at which the event occurred. + * @nesting: Indicates function call nesting. + * @description: A description of the event. + */ + +struct event { + ktime_t time; + unsigned int nesting; + char *description; +}; + +/** + * The event trace. + * + * @overhead: The delay to take a time stamp and nothing else. + * @nesting: The current nesting level. + * @overflow: Indicates the trace overflowed. + * @next: Index of the next event to write. + * @events: The array of events. + */ + +#define MAX_EVENT_COUNT (200) + +static struct { + ktime_t overhead; + int nesting; + int overflow; + unsigned int next; + struct event events[MAX_EVENT_COUNT]; +} event_trace; + +/** + * reset_event_trace() - Resets the event trace. + */ +static void reset_event_trace(void) +{ + event_trace.nesting = 0; + event_trace.overflow = false; + event_trace.next = 0; +} + +/** + * add_event() - Adds an event to the event trace. + * + * @description: A description of the event. + * @delta: A delta to the nesting level for this event [-1, 0, 1]. + */ +static inline void add_event(char *description, int delta) +{ + struct event *event; + + if (!imx_nfc_module_report_events) + return; + + if (event_trace.overflow) + return; + + if (event_trace.next >= MAX_EVENT_COUNT) { + event_trace.overflow = true; + return; + } + + event = event_trace.events + event_trace.next; + + event->time = ktime_get(); + + event->description = description; + + if (!delta) + event->nesting = event_trace.nesting; + else if (delta < 0) { + event->nesting = event_trace.nesting - 1; + event_trace.nesting -= 2; + } else { + event->nesting = event_trace.nesting + 1; + event_trace.nesting += 2; + } + + if (event_trace.nesting < 0) + event_trace.nesting = 0; + + event_trace.next++; + +} + +/** + * add_state_event_l() - Adds an event to display some state. + * + * @address: The address to examine. + * @mask: A mask to apply to the contents of the given address. + * @clear: An event message to add if the result is zero. + * @not_zero: An event message to add if the result is not zero. + */ +static void add_state_event_l(void *address, uint32_t mask, + char *zero, char *not_zero) +{ + int state; + state = !!(__raw_readl(address) & mask); + if (state) + add_event(not_zero, 0); + else + add_event(zero, 0); +} + +/** + * start_event_trace() - Starts an event trace and adds the first event. + * + * @description: A description of the first event. + */ +static void start_event_trace(char *description) +{ + + ktime_t t0; + ktime_t t1; + + if (!imx_nfc_module_report_events) + return; + + reset_event_trace(); + + t0 = ktime_get(); + t1 = ktime_get(); + + event_trace.overhead = ktime_sub(t1, t0); + + add_event(description, 1); + +} + +/** + * dump_event_trace() - Dumps the event trace. + */ +static void dump_event_trace(void) +{ + unsigned int i; + time_t seconds; + long nanoseconds; + char line[100]; + int o; + struct event *first_event; + struct event *last_event; + struct event *matching_event; + struct event *event; + ktime_t delta; + + /* Check if event reporting is turned off. */ + + if (!imx_nfc_module_report_events) + return; + + /* Print important facts about this event trace. */ + + printk(KERN_DEBUG "\n+--------------\n"); + + printk(KERN_DEBUG "| Overhead : [%d:%d]\n", + event_trace.overhead.tv.sec, + event_trace.overhead.tv.nsec); + + if (!event_trace.next) { + printk(KERN_DEBUG "| No Events\n"); + return; + } + + first_event = event_trace.events; + last_event = event_trace.events + (event_trace.next - 1); + + delta = ktime_sub(last_event->time, first_event->time); + printk(KERN_DEBUG "| Elapsed Time: [%d:%d]\n", + delta.tv.sec, delta.tv.nsec); + + if (event_trace.overflow) + printk(KERN_DEBUG "| Overflow!\n"); + + /* Print the events in this history. */ + + for (i = 0, event = event_trace.events; + i < event_trace.next; i++, event++) { + + /* Get the delta between this event and the previous event. */ + + if (!i) { + seconds = 0; + nanoseconds = 0; + } else { + delta = ktime_sub(event[0].time, event[-1].time); + seconds = delta.tv.sec; + nanoseconds = delta.tv.nsec; + } + + /* Print the current event. */ + + o = 0; + + o = snprintf(line, sizeof(line) - o, "| [%ld:% 10ld]%*s %s", + seconds, nanoseconds, + event->nesting, "", + event->description); + /* Check if this is the last event in a nested series. */ + + if (i && (event[0].nesting < event[-1].nesting)) { + + for (matching_event = event - 1;; matching_event--) { + + if (matching_event < event_trace.events) { + matching_event = 0; + break; + } + + if (matching_event->nesting == event->nesting) + break; + + } + + if (matching_event) { + delta = ktime_sub(event->time, + matching_event->time); + o += snprintf(line + o, sizeof(line) - o, + " <%d:%d]", delta.tv.sec, + delta.tv.nsec); + } + + } + + /* Check if this is the first event in a nested series. */ + + if ((i < event_trace.next - 1) && + (event[0].nesting < event[1].nesting)) { + + for (matching_event = event + 1;; matching_event++) { + + if (matching_event >= + (event_trace.events+event_trace.next)) { + matching_event = 0; + break; + } + + if (matching_event->nesting == event->nesting) + break; + + } + + if (matching_event) { + delta = ktime_sub(matching_event->time, + event->time); + o += snprintf(line + o, sizeof(line) - o, + " [%d:%d>", delta.tv.sec, + delta.tv.nsec); + } + + } + + printk(KERN_DEBUG "%s\n", line); + + } + + printk(KERN_DEBUG "+--------------\n"); + +} + +/** + * stop_event_trace() - Stops an event trace. + * + * @description: A description of the last event. + */ +static void stop_event_trace(char *description) +{ + struct event *event; + + if (!imx_nfc_module_report_events) + return; + + /* + * We want the end of the trace, no matter what happens. If the trace + * has already overflowed, or is about to, just jam this event into the + * last spot. Otherwise, add this event like any other. + */ + + if (event_trace.overflow || (event_trace.next >= MAX_EVENT_COUNT)) { + event = event_trace.events + (MAX_EVENT_COUNT - 1); + event->time = ktime_get(); + event->description = description; + event->nesting = 0; + } else { + add_event(description, -1); + } + + dump_event_trace(); + reset_event_trace(); + +} + +#else /* EVENT_REPORTING */ + +#define start_event_trace(description) do {} while (0) +#define add_event(description, delta) do {} while (0) +#define add_state_event_l(address, mask, zero, not_zero) do {} while (0) +#define stop_event_trace(description) do {} while (0) +#define dump_event_trace() do {} while (0) + +#endif /* EVENT_REPORTING */ + +/** + * unimplemented() - Announces intentionally unimplemented features. + * + * @this: Per-device data. + * @msg: A message about the unimplemented feature. + */ +static inline void unimplemented(struct imx_nfc_data *this, const char * msg) +{ + dev_err(this->dev, "Intentionally unimplemented: %s", msg); +} + +/** + * raw_read_mask_w() - Reads masked bits in a 16-bit hardware register. + */ +static inline uint16_t raw_read_mask_w(uint16_t mask, void *address) +{ + return __raw_readw(address) & mask; +} + +/** + * raw_set_mask_w() - Sets bits in a 16-bit hardware register. + */ +static inline void raw_set_mask_w(uint16_t mask, void *address) +{ + __raw_writew(__raw_readw(address) | mask, address); +} + +/** + * raw_clr_mask_w() - Clears bits in a 16-bit hardware register. + */ +static inline void raw_clr_mask_w(uint16_t mask, void *address) +{ + __raw_writew(__raw_readw(address) & (~mask), address); +} + +/** + * raw_read_mask_l() - Reads masked bits in a 32-bit hardware register. + */ +static inline uint32_t raw_read_mask_l(uint32_t mask, void *address) +{ + return __raw_readl(address) & mask; +} + +/** + * raw_set_mask_l() - Sets bits in a 32-bit hardware register. + */ +static inline void raw_set_mask_l(uint32_t mask, void *address) +{ + __raw_writel(__raw_readl(address) | mask, address); +} + +/** + * raw_clr_mask_l() - Clears bits in a 32-bit hardware register. + */ +static inline void raw_clr_mask_l(uint32_t mask, void *address) +{ + __raw_writel(__raw_readl(address) & (~mask), address); +} + +/** + * is_large_page_chip() - Returns true for large page media. + * + * @this: Per-device data. + */ +static inline int is_large_page_chip(struct imx_nfc_data *this) +{ + return (this->physical_geometry.page_data_size > 512); +} + +/** + * is_small_page_chip() - Returns true for small page media. + * + * @this: Per-device data. + */ +static inline int is_small_page_chip(struct imx_nfc_data *this) +{ + return !is_large_page_chip(this); +} + +/** + * get_cycle_in_ns() - Returns the given device's cycle period, in ns. + * + * @this: Per-device data. + */ +static inline unsigned get_cycle_in_ns(struct imx_nfc_data *this) +{ + unsigned long cycle_in_ns; + + cycle_in_ns = 1000000000 / clk_get_rate(this->clock); + + if (!this->nfc->get_symmetric(this)) + cycle_in_ns *= 2; + + return cycle_in_ns; + +} + +/** + * nfc_util_set_best_cycle() - Sets the closest possible NAND Flash bus cycle. + * + * This function computes the clock setup that will best approximate the given + * target Flash bus cycle period. + * + * For some NFC versions, we can make the clock "symmetric." When the clock + * is "symmetric," the hardware waits one NFC clock for every read/write cycle. + * When the clock is "asymmetric," the hardware waits two NFC clocks for every + * read/write cycle. Thus, making the clock asymmetric essentially divides the + * NFC clock by two. + * + * We compute the target frequency that matches the given target period. We then + * discover the closest available match with that frequency and the closest + * available match with double that frequency (for use with an asymmetric + * clock). We implement the best choice of original clock and symmetric or + * asymmetric setting, preferring symmetric clocks. + * + * @this: Per-device data. + * @ns: The target cycle period, in nanoseconds. + * @no_asym: Disallow making the clock asymmetric. + * @no_sym: Disallow making the clock symmetric. + */ +static int nfc_util_set_best_cycle(struct imx_nfc_data *this, + unsigned int ns, int no_asym, int no_sym) +{ + unsigned long target_hz; + long symmetric_hz; + long symmetric_delta_hz; + long asymmetric_hz; + long asymmetric_delta_hz; + unsigned long best_hz; + int best_symmetry_setting; + struct device *dev = this->dev; + + /* The target cycle period must be greater than zero. */ + + if (!ns) + return -EINVAL; + + /* Compute the target frequency. */ + + target_hz = 1000000000 / ns; + + /* Find out how close we can get with a symmetric clock. */ + + if (!no_sym && this->nfc->can_be_symmetric) + symmetric_hz = clk_round_rate(this->clock, target_hz); + else + symmetric_hz = -EINVAL; + + /* Find out how close we can get with an asymmetric clock. */ + + if (!no_asym) + asymmetric_hz = clk_round_rate(this->clock, target_hz * 2); + else + asymmetric_hz = -EINVAL; + + /* Does anything work at all? */ + + if ((symmetric_hz == -EINVAL) && (asymmetric_hz == -EINVAL)) { + dev_err(dev, "Can't support Flash bus cycle of %uns\n", ns); + return -EINVAL; + } + + /* Discover the best match. */ + + if ((symmetric_hz != -EINVAL) && (asymmetric_hz != -EINVAL)) { + + symmetric_delta_hz = target_hz - symmetric_hz; + asymmetric_delta_hz = target_hz - (asymmetric_hz / 2); + + if (symmetric_delta_hz <= asymmetric_delta_hz) + best_symmetry_setting = true; + else + best_symmetry_setting = false; + + } else if (symmetric_hz != -EINVAL) { + best_symmetry_setting = true; + } else { + best_symmetry_setting = false; + } + + best_hz = best_symmetry_setting ? symmetric_hz : asymmetric_hz; + + /* Implement the best match. */ + + this->nfc->set_symmetric(this, best_symmetry_setting); + + return clk_set_rate(this->clock, best_hz); + +} + +/** + * nfc_util_wait_for_the_nfc() - Waits for the NFC to finish an operation. + * + * @this: Per-device data. + * @use_irq: Indicates that we should wait for an interrupt rather than polling + * and delaying. + */ +static void nfc_util_wait_for_the_nfc(struct imx_nfc_data *this, int use_irq) +{ + unsigned spin_count; + struct device *dev = this->dev; + + /* Apply the override, if any. */ + + switch (this->interrupt_override) { + + case NEVER: + use_irq = false; + break; + + case DRIVER_CHOICE: + break; + + case ALWAYS: + use_irq = true; + break; + + } + + /* Check if we're using interrupts. */ + + if (use_irq) { + + /* + * If control arrives here, the caller wants to use interrupts. + * Presumably, this operation is known to take a very long time. + */ + + if (this->nfc->is_interrupting(this)) { + add_event("Waiting for the NFC (early interrupt)", 1); + this->nfc->clear_interrupt(this); + } else { + add_event("Waiting for the NFC (interrupt)", 1); + this->nfc->unmask_interrupt(this); + wait_for_completion(&this->done); + } + + add_event("NFC done", -1); + + } else { + + /* + * If control arrives here, the caller doesn't want to use + * interrupts. Presumably, this operation is too quick to + * justify the overhead. Leave the interrupt masked, and loop + * until the interrupt bit lights up, or we time out. + * + * We spin for a maximum of about 2ms before declaring a time + * out. No operation we could possibly spin on should take that + * long. + */ + + spin_count = 2000; + + add_event("Waiting for the NFC (polling)", 1); + + for (; spin_count > 0; spin_count--) { + + if (this->nfc->is_interrupting(this)) { + this->nfc->clear_interrupt(this); + add_event("NFC done", -1); + return; + } + + udelay(1); + + } + + /* Timed out. */ + + add_event("Timed out", -1); + + dev_err(dev, "[wait_for_the_nfc] ===== Time Out =====\n"); + dump_event_trace(); + + } + +} + +/** + * nfc_util_bytewise_copy_from_nfc_mem() - Copies bytes from the NFC memory. + * + * @from: A pointer to the source memory. + * @to: A pointer to the destination memory. + * @size: The number of bytes to copy. + */ +static void nfc_util_bytewise_copy_from_nfc_mem(const void *from, + void *to, size_t n) +{ + unsigned int i; + const uint8_t *f = from; + uint8_t *t = to; + uint16_t *p; + uint16_t x; + + for (i = 0; i < n; i++, f++, t++) { + + p = (uint16_t *) (((unsigned long) f) & ~((unsigned long) 1)); + + x = __raw_readw(p); + + if (((unsigned long) f) & 0x1) + *t = (x >> 8) & 0xff; + else + *t = (x >> 0) & 0xff; + + } + +} + +/** + * nfc_util_bytewise_copy_to_nfc_mem() - Copies bytes to the NFC memory. + * + * @from: A pointer to the source memory. + * @to: A pointer to the destination memory. + * @size: The number of bytes to copy. + */ +static void nfc_util_bytewise_copy_to_nfc_mem(const void *from, + void *to, size_t n) +{ + unsigned int i; + const uint8_t *f = from; + uint8_t *t = to; + uint16_t *p; + uint16_t x; + + for (i = 0; i < n; i++, f++, t++) { + + p = (uint16_t *) (((unsigned long) t) & ~((unsigned long) 1)); + + x = __raw_readw(p); + + if (((unsigned long) t) & 0x1) + ((uint8_t *)(&x))[1] = *f; + else + ((uint8_t *)(&x))[0] = *f; + + __raw_writew(x, p); + + } + +} + +/** + * nfc_util_copy_from_nfc_mem() - Copies from the NFC memory to main memory. + * + * @from: A pointer to the source memory. + * @to: A pointer to the destination memory. + * @size: The number of bytes to copy. + */ +static void nfc_util_copy_from_nfc_mem(const void *from, void *to, size_t n) +{ + unsigned int chunk_count; + + /* + * Check if we're testing bytewise copies. + */ + + if (imx_nfc_module_force_bytewise_copy) + goto force_bytewise_copy; + + /* + * We'd like to use memcpy to get data out of the NFC but, because that + * memory responds only to 16- and 32-byte reads, we can only do so + * safely if both the start and end of both the source and destination + * are perfectly aligned on 4-byte boundaries. + */ + + if (!(((unsigned long) from) & 0x3) && !(((unsigned long) to) & 0x3)) { + + /* + * If control arrives here, both the source and destination are + * aligned on 4-byte boundaries. Compute the number of whole, + * 4-byte chunks we can move. + */ + + chunk_count = n / 4; + + /* + * Move all the chunks we can, and then update the pointers and + * byte count to show what's left. + */ + + if (chunk_count) { + memcpy(to, from, chunk_count * 4); + from += chunk_count * 4; + to += chunk_count * 4; + n -= chunk_count * 4; + } + + } + + /* + * Move what's left. + */ + +force_bytewise_copy: + + nfc_util_bytewise_copy_from_nfc_mem(from, to, n); + +} + +/** + * nfc_util_copy_to_nfc_mem() - Copies from main memory to the NFC memory. + * + * @from: A pointer to the source memory. + * @to: A pointer to the destination memory. + * @size: The number of bytes to copy. + */ +static void nfc_util_copy_to_nfc_mem(const void *from, void *to, size_t n) +{ + unsigned int chunk_count; + + /* + * Check if we're testing bytewise copies. + */ + + if (imx_nfc_module_force_bytewise_copy) + goto force_bytewise_copy; + + /* + * We'd like to use memcpy to get data into the NFC but, because that + * memory responds only to 16- and 32-byte writes, we can only do so + * safely if both the start and end of both the source and destination + * are perfectly aligned on 4-byte boundaries. + */ + + if (!(((unsigned long) from) & 0x3) && !(((unsigned long) to) & 0x3)) { + + /* + * If control arrives here, both the source and destination are + * aligned on 4-byte boundaries. Compute the number of whole, + * 4-byte chunks we can move. + */ + + chunk_count = n / 4; + + /* + * Move all the chunks we can, and then update the pointers and + * byte count to show what's left. + */ + + if (chunk_count) { + memcpy(to, from, chunk_count * 4); + from += chunk_count * 4; + to += chunk_count * 4; + n -= chunk_count * 4; + } + + } + + /* + * Move what's left. + */ + +force_bytewise_copy: + + nfc_util_bytewise_copy_to_nfc_mem(from, to, n); + +} + +/** + * nfc_util_copy_from_the_nfc() - Copies bytes out of the NFC. + * + * This function makes the data in the NFC look like a contiguous, model page. + * + * @this: Per-device data. + * @start: The index of the starting byte in the NFC. + * @buf: A pointer to the destination buffer. + * @len: The number of bytes to copy out. + */ +static void nfc_util_copy_from_the_nfc(struct imx_nfc_data *this, + unsigned int start, uint8_t *buf, unsigned int len) +{ + unsigned int i; + unsigned int count; + unsigned int offset; + unsigned int data_size; + unsigned int oob_size; + unsigned int total_size; + void *spare_base; + unsigned int first_spare; + void *from; + struct nfc_geometry *geometry = this->nfc_geometry; + + /* + * During initialization, the HIL will attempt to read ID bytes. For + * some NFC hardware versions, the ID bytes are deposited in the NFC + * memory, so this function will be called to deliver them. At that + * point, we won't know the NFC geometry. That's OK because we're only + * going to be reading a byte at a time. + * + * If we don't yet know the NFC geometry, just plug in some values that + * make things work for now. + */ + + if (unlikely(!geometry)) { + data_size = NFC_MAIN_BUF_SIZE; + oob_size = 0; + } else { + data_size = geometry->page_data_size; + oob_size = geometry->page_oob_size; + } + + total_size = data_size + oob_size; + + /* Validate. */ + + if ((start >= total_size) || ((start + len) > total_size)) { + dev_err(this->dev, "Bad copy from NFC memory: [%u, %u]\n", + start, len); + return; + } + + /* Check if we're copying anything at all. */ + + if (!len) + return; + + /* Check if anything comes from the main area. */ + + if (start < data_size) { + + /* Compute the bytes to copy from the main area. */ + + count = min(len, data_size - start); + + /* Copy. */ + + nfc_util_copy_from_nfc_mem(this->buffers + start, buf, count); + + buf += count; + start += count; + len -= count; + + } + + /* Check if we're done. */ + + if (!len) + return; + + /* Compute the base address of the spare buffers. */ + + spare_base = this->buffers + + (this->nfc->max_buffer_count * NFC_MAIN_BUF_SIZE); + + /* Discover in which spare buffer the copying begins. */ + + first_spare = (start - data_size) / geometry->spare_buf_size; + + /* Check if anything comes from the regular spare buffer area. */ + + if (first_spare < geometry->buffer_count) { + + /* Start copying from spare buffers. */ + + for (i = first_spare; i < geometry->buffer_count; i++) { + + /* Compute the offset into this spare area. */ + + offset = start - + (data_size + (geometry->spare_buf_size * i)); + + /* Compute the address of that offset. */ + + from = spare_base + offset + + (this->nfc->spare_buf_stride * i); + + /* Compute the bytes to copy from this spare area. */ + + count = min(len, geometry->spare_buf_size - offset); + + /* Copy. */ + + nfc_util_copy_from_nfc_mem(from, buf, count); + + buf += count; + start += count; + len -= count; + + } + + } + + /* Check if we're done. */ + + if (!len) + return; + + /* Compute the offset into the extra spare area. */ + + offset = start - + (data_size + (geometry->spare_buf_size*geometry->buffer_count)); + + /* Compute the address of that offset. */ + + from = spare_base + offset + + (this->nfc->spare_buf_stride * geometry->buffer_count); + + /* Compute the bytes to copy from the extra spare area. */ + + count = min(len, geometry->spare_buf_spill - offset); + + /* Copy. */ + + nfc_util_copy_from_nfc_mem(from, buf, count); + +} + +/** + * nfc_util_copy_to_the_nfc() - Copies bytes into the NFC memory. + * + * This function makes the data in the NFC look like a contiguous, model page. + * + * @this: Per-device data. + * @buf: A pointer to the source buffer. + * @start: The index of the starting byte in the NFC memory. + * @len: The number of bytes to copy in. + */ +static void nfc_util_copy_to_the_nfc(struct imx_nfc_data *this, + const uint8_t *buf, unsigned int start, unsigned int len) +{ + unsigned int i; + unsigned int count; + unsigned int offset; + unsigned int data_size; + unsigned int oob_size; + unsigned int total_size; + void *spare_base; + unsigned int first_spare; + void *to; + struct nfc_geometry *geometry = this->nfc_geometry; + + /* Establish some important facts. */ + + data_size = geometry->page_data_size; + oob_size = geometry->page_oob_size; + total_size = data_size + oob_size; + + /* Validate. */ + + if ((start >= total_size) || ((start + len) > total_size)) { + dev_err(this->dev, "Bad copy to NFC memory: [%u, %u]\n", + start, len); + return; + } + + /* Check if we're copying anything at all. */ + + if (!len) + return; + + /* Check if anything goes to the main area. */ + + if (start < data_size) { + + /* Compute the bytes to copy to the main area. */ + + count = min(len, data_size - start); + + /* Copy. */ + + nfc_util_copy_to_nfc_mem(buf, this->buffers + start, count); + + buf += count; + start += count; + len -= count; + + } + + /* Check if we're done. */ + + if (!len) + return; + + /* Compute the base address of the spare buffers. */ + + spare_base = this->buffers + + (this->nfc->max_buffer_count * NFC_MAIN_BUF_SIZE); + + /* Discover in which spare buffer the copying begins. */ + + first_spare = (start - data_size) / geometry->spare_buf_size; + + /* Check if anything goes to the regular spare buffer area. */ + + if (first_spare < geometry->buffer_count) { + + /* Start copying to spare buffers. */ + + for (i = first_spare; i < geometry->buffer_count; i++) { + + /* Compute the offset into this spare area. */ + + offset = start - + (data_size + (geometry->spare_buf_size * i)); + + /* Compute the address of that offset. */ + + to = spare_base + offset + + (this->nfc->spare_buf_stride * i); + + /* Compute the bytes to copy to this spare area. */ + + count = min(len, geometry->spare_buf_size - offset); + + /* Copy. */ + + nfc_util_copy_to_nfc_mem(buf, to, count); + + buf += count; + start += count; + len -= count; + + } + + } + + /* Check if we're done. */ + + if (!len) + return; + + /* Compute the offset into the extra spare area. */ + + offset = start - + (data_size + (geometry->spare_buf_size*geometry->buffer_count)); + + /* Compute the address of that offset. */ + + to = spare_base + offset + + (this->nfc->spare_buf_stride * geometry->buffer_count); + + /* Compute the bytes to copy to the extra spare area. */ + + count = min(len, geometry->spare_buf_spill - offset); + + /* Copy. */ + + nfc_util_copy_to_nfc_mem(buf, to, count); + +} + +/** + * nfc_util_isr() - i.MX NFC ISR. + * + * @irq: The arriving interrupt number. + * @context: A cookie for this ISR. + */ +static irqreturn_t nfc_util_isr(int irq, void *cookie) +{ + struct imx_nfc_data *this = cookie; + this->nfc->mask_interrupt(this); + this->nfc->clear_interrupt(this); + complete(&this->done); + return IRQ_HANDLED; +} + +/** + * nfc_util_send_cmd() - Sends a command to the current chip, without waiting. + * + * @this: Per-device data. + * @command: The command code. + */ + +static void nfc_util_send_cmd(struct imx_nfc_data *this, unsigned int command) +{ + + add_event("Entering nfc_util_send_cmd", 1); + + this->nfc->command_cycle(this, command); + + add_event("Exiting nfc_util_send_cmd", -1); + +} + +/** + * nfc_util_send_cmd_and_addrs() - Sends a cmd and addrs to the current chip. + * + * This function conveniently combines sending a command, and then sending + * optional addresses, waiting for the NFC to finish will all steps. + * + * @this: Per-device data. + * @command: The command code. + * @column: The column address to send, or -1 if no column address applies. + * @page: The page address to send, or -1 if no page address applies. + */ + +static void nfc_util_send_cmd_and_addrs(struct imx_nfc_data *this, + unsigned command, int column, int page) +{ + uint32_t page_mask; + + add_event("Entering nfc_util_send_cmd_and_addrs", 1); + + /* Send the command.*/ + + add_event("Sending the command...", 0); + + nfc_util_send_cmd(this, command); + + nfc_util_wait_for_the_nfc(this, false); + + /* Send the addresses. */ + + add_event("Sending the addresses...", 0); + + if (column != -1) { + + this->nfc->write_cycle(this, (column >> 0) & 0xff); + + if (is_large_page_chip(this)) + this->nfc->write_cycle(this, (column >> 8) & 0xff); + + } + + if (page != -1) { + + page_mask = this->nand.pagemask; + + do { + this->nfc->write_cycle(this, page & 0xff); + page_mask >>= 8; + page >>= 8; + } while (page_mask != 0); + + } + + add_event("Exiting nfc_util_send_cmd_and_addrs", -1); + +} + +/** + * nfc_2_x_exit() - Version-specific shut down. + * + * @this: Per-device data. + */ +static void nfc_2_x_exit(struct imx_nfc_data *this) +{ +} + +/** + * nfc_2_x_clear_interrupt() - Clears an interrupt. + * + * @this: Per-device data. + */ +static void nfc_2_x_clear_interrupt(struct imx_nfc_data *this) +{ + void *base = this->primary_regs; + raw_clr_mask_w(NFC_2_X_CONFIG2_INT_MSK, base + NFC_2_X_CONFIG2_REG_OFF); +} + +/** + * nfc_2_x_is_interrupting() - Returns the interrupt bit status. + * + * @this: Per-device data. + */ +static int nfc_2_x_is_interrupting(struct imx_nfc_data *this) +{ + void *base = this->primary_regs; + return raw_read_mask_w(NFC_2_X_CONFIG2_INT_MSK, + base + NFC_2_X_CONFIG2_REG_OFF); +} + +/** + * nfc_2_x_command_cycle() - Sends a command. + * + * @this: Per-device data. + * @command: The command code. + */ +static void nfc_2_x_command_cycle(struct imx_nfc_data *this, unsigned command) +{ + void *base = this->primary_regs; + + /* Write the command we want to send. */ + + __raw_writew(command, base + NFC_2_X_FLASH_CMD_REG_OFF); + + /* Launch a command cycle. */ + + __raw_writew(NFC_2_X_CONFIG2_FCMD_MSK, base + NFC_2_X_CONFIG2_REG_OFF); + +} + +/** + * nfc_2_x_write_cycle() - Writes a single byte. + * + * @this: Per-device data. + * @byte: The byte. + */ +static void nfc_2_x_write_cycle(struct imx_nfc_data *this, unsigned int byte) +{ + void *base = this->primary_regs; + + /* Give the NFC the byte we want to write. */ + + __raw_writew(byte, base + NFC_2_X_FLASH_ADDR_REG_OFF); + + /* Launch an address cycle. + * + * This is *sort* of a hack, but not really. The intent of the NFC + * design is for this operation to send an address byte. In fact, the + * NFC neither knows nor cares what we're sending. It justs runs a write + * cycle. + */ + + __raw_writew(NFC_2_X_CONFIG2_FADD_MSK, base + NFC_2_X_CONFIG2_REG_OFF); + + /* Wait for the NFC to finish. */ + + nfc_util_wait_for_the_nfc(this, false); + +} + +/** + * nfc_2_0_init() - Version-specific hardware initialization. + * + * @this: Per-device data. + */ +static int nfc_2_0_init(struct imx_nfc_data *this) +{ + void *base = this->primary_regs; + + /* Initialize the interrupt machinery. */ + + this->nfc->mask_interrupt(this); + this->nfc->clear_interrupt(this); + + /* Unlock the NFC memory. */ + + __raw_writew(0x2, base + NFC_2_X_CONFIG_REG_OFF); + + /* Set the unlocked block range to cover the entire medium. */ + + __raw_writew(0 , base + NFC_2_0_UNLOCK_START_REG_OFF); + __raw_writew(~0, base + NFC_2_0_UNLOCK_END_REG_OFF); + + /* Unlock all blocks. */ + + __raw_writew(0x4, base + NFC_2_X_WR_PROT_REG_OFF); + + /* Return success. */ + + return 0; + +} + +/** + * nfc_2_0_mask_interrupt() - Masks interrupts. + * + * @this: Per-device data. + */ +static void nfc_2_0_mask_interrupt(struct imx_nfc_data *this) +{ + void *base = this->primary_regs; + raw_set_mask_w(NFC_2_0_CONFIG1_INT_MSK_MSK, + base + NFC_2_0_CONFIG1_REG_OFF); +} + +/** + * nfc_2_0_unmask_interrupt() - Unmasks interrupts. + * + * @this: Per-device data. + */ +static void nfc_2_0_unmask_interrupt(struct imx_nfc_data *this) +{ + void *base = this->primary_regs; + raw_clr_mask_w(NFC_2_0_CONFIG1_INT_MSK_MSK, + base + NFC_2_0_CONFIG1_REG_OFF); +} + +/** + * nfc_2_0_set_ecc() - Turns ECC on or off. + * + * @this: Per-device data. + * @on: Indicates if ECC should be on or off. + */ +static void nfc_2_0_set_ecc(struct imx_nfc_data *this, int on) +{ + void *base = this->primary_regs; + + if (on) + raw_set_mask_w(NFC_2_0_CONFIG1_ECC_EN_MSK, + base + NFC_2_0_CONFIG1_REG_OFF); + else + raw_clr_mask_w(NFC_2_0_CONFIG1_ECC_EN_MSK, + base + NFC_2_0_CONFIG1_REG_OFF); + +} + +/** + * nfc_2_0_get_ecc_status() - Reports ECC errors. + * + * @this: Per-device data. + */ +static int nfc_2_0_get_ecc_status(struct imx_nfc_data *this) +{ + unsigned int i; + void *base = this->primary_regs; + uint16_t status_reg; + unsigned int buffer_status[4]; + int status; + + /* Get the entire status register. */ + + status_reg = __raw_readw(base + NFC_2_0_ECC_STATUS_REG_OFF); + + /* Pick out the status for each buffer. */ + + buffer_status[0] = (status_reg & NFC_2_0_ECC_STATUS_NOSER1_MSK) + >> NFC_2_0_ECC_STATUS_NOSER1_POS; + + buffer_status[1] = (status_reg & NFC_2_0_ECC_STATUS_NOSER2_MSK) + >> NFC_2_0_ECC_STATUS_NOSER2_POS; + + buffer_status[2] = (status_reg & NFC_2_0_ECC_STATUS_NOSER3_MSK) + >> NFC_2_0_ECC_STATUS_NOSER3_POS; + + buffer_status[3] = (status_reg & NFC_2_0_ECC_STATUS_NOSER4_MSK) + >> NFC_2_0_ECC_STATUS_NOSER4_POS; + + /* Loop through the buffers we're actually using. */ + + status = 0; + + for (i = 0; i < this->nfc_geometry->buffer_count; i++) { + + if (buffer_status[i] > this->nfc_geometry->ecc_strength) { + status = -1; + break; + } + + status += buffer_status[i]; + + } + + /* Return the final result. */ + + return status; + +} + +/** + * nfc_2_0_get_symmetric() - Indicates if the clock is symmetric. + * + * @this: Per-device data. + */ +static int nfc_2_0_get_symmetric(struct imx_nfc_data *this) +{ + void *base = this->primary_regs; + + return !!raw_read_mask_w(NFC_2_0_CONFIG1_ONE_CYLE_MSK, + base + NFC_2_0_CONFIG1_REG_OFF); + +} + +/** + * nfc_2_0_set_symmetric() - Turns symmetric clock mode on or off. + * + * @this: Per-device data. + */ +static void nfc_2_0_set_symmetric(struct imx_nfc_data *this, int on) +{ + void *base = this->primary_regs; + + if (on) + raw_set_mask_w(NFC_2_0_CONFIG1_ONE_CYLE_MSK, + base + NFC_2_0_CONFIG1_REG_OFF); + else + raw_clr_mask_w(NFC_2_0_CONFIG1_ONE_CYLE_MSK, + base + NFC_2_0_CONFIG1_REG_OFF); + +} + +/** + * nfc_2_0_set_geometry() - Configures for the medium geometry. + * + * @this: Per-device data. + */ +static int nfc_2_0_set_geometry(struct imx_nfc_data *this) +{ + struct physical_geometry *physical = &this->physical_geometry; + + /* Select an NFC geometry. */ + + switch (physical->page_data_size) { + + case 512: + this->nfc_geometry = &nfc_geometry_512_16_RS_ECC4; + break; + + case 2048: + this->nfc_geometry = &nfc_geometry_2K_64_RS_ECC4; + break; + + default: + dev_err(this->dev, "NFC can't handle page size: %u", + physical->page_data_size); + return !0; + break; + + } + + /* + * This NFC version receives page size information from a register + * that's external to the NFC. We must rely on platform-specific code + * to set this register for us. + */ + + return this->pdata->set_page_size(physical->page_data_size); + +} + +/** + * nfc_2_0_select_chip() - Selects the current chip. + * + * @this: Per-device data. + * @chip: The chip number to select, or -1 to select no chip. + */ +static void nfc_2_0_select_chip(struct imx_nfc_data *this, int chip) +{ +} + +/** + * nfc_2_0_read_cycle() - Applies a single read cycle to the current chip. + * + * @this: Per-device data. + */ +static unsigned int nfc_2_0_read_cycle(struct imx_nfc_data *this) +{ + uint8_t byte; + unsigned int result; + void *base = this->primary_regs; + + /* Read into main buffer 0. */ + + __raw_writew(0x0, base + NFC_2_0_BUF_ADDR_REG_OFF); + + /* Launch a "Data Out" operation. */ + + __raw_writew(0x4 << NFC_2_X_CONFIG2_FDO_POS, + base + NFC_2_X_CONFIG2_REG_OFF); + + /* Wait for the NFC to finish. */ + + nfc_util_wait_for_the_nfc(this, false); + + /* Get the result from the NFC memory. */ + + nfc_util_copy_from_the_nfc(this, 0, &byte, 1); + result = byte; + + /* Return the results. */ + + return result; + +} + +/** + * nfc_2_0_read_page() - Reads a page from the current chip into the NFC. + * + * @this: Per-device data. + */ +static void nfc_2_0_read_page(struct imx_nfc_data *this) +{ + unsigned int i; + void *base = this->primary_regs; + + /* Loop over the number of buffers in use. */ + + for (i = 0; i < this->nfc_geometry->buffer_count; i++) { + + /* Make the NFC read into the current buffer. */ + + __raw_writew(i << NFC_2_0_BUF_ADDR_RBA_POS, + base + NFC_2_0_BUF_ADDR_REG_OFF); + + /* Launch a page data out operation. */ + + __raw_writew(0x1 << NFC_2_X_CONFIG2_FDO_POS, + base + NFC_2_X_CONFIG2_REG_OFF); + + /* Wait for the NFC to finish. */ + + nfc_util_wait_for_the_nfc(this, true); + + } + +} + +/** + * nfc_2_0_send_page() - Sends a page from the NFC to the current chip. + * + * @this: Per-device data. + */ +static void nfc_2_0_send_page(struct imx_nfc_data *this) +{ + unsigned int i; + void *base = this->primary_regs; + + /* Loop over the number of buffers in use. */ + + for (i = 0; i < this->nfc_geometry->buffer_count; i++) { + + /* Make the NFC send from the current buffer. */ + + __raw_writew(i << NFC_2_0_BUF_ADDR_RBA_POS, + base + NFC_2_0_BUF_ADDR_REG_OFF); + + /* Launch a page data in operation. */ + + __raw_writew(0x1 << NFC_2_X_CONFIG2_FDI_POS, + base + NFC_2_X_CONFIG2_REG_OFF); + + /* Wait for the NFC to finish. */ + + nfc_util_wait_for_the_nfc(this, true); + + } + +} + +/** + * nfc_3_2_init() - Hardware initialization. + * + * @this: Per-device data. + */ +static int nfc_3_2_init(struct imx_nfc_data *this) +{ + int error; + unsigned int no_sdma; + unsigned int fmp; + unsigned int rbb_mode; + unsigned int num_of_devices; + unsigned int dma_mode; + unsigned int sbb; + unsigned int nf_big; + unsigned int sb2r; + unsigned int fw; + unsigned int too; + unsigned int add_op; + uint32_t config3; + void *primary_base = this->primary_regs; + void *secondary_base = this->secondary_regs; + + /* Initialize the interrupt machinery. */ + + this->nfc->mask_interrupt(this); + this->nfc->clear_interrupt(this); + + /* Set up the clock. */ + + error = this->nfc->set_closest_cycle(this, + this->pdata->target_cycle_in_ns); + + if (error) + return !0; + + /* We never read the spare area alone. */ + + raw_clr_mask_l(NFC_3_2_CONFIG1_SP_EN_MSK, + primary_base + NFC_3_2_CONFIG1_REG_OFF); + + /* Tell the NFC the "Read Status" command code. */ + + raw_clr_mask_l(NFC_3_2_CONFIG2_ST_CMD_MSK, + secondary_base + NFC_3_2_CONFIG2_REG_OFF); + + raw_set_mask_l(NAND_CMD_STATUS << NFC_3_2_CONFIG2_ST_CMD_POS, + secondary_base + NFC_3_2_CONFIG2_REG_OFF); + + /* + * According to erratum ENGcm09051, the CONFIG3 register doesn't reset + * correctly, so we need to re-build the entire register just in case. + */ + + /* + * Set the NO_SDMA bit to tell the NFC that we are NOT using SDMA. If + * you clear this bit (to indicates you *are* using SDMA), but you + * don't actually set up SDMA, the NFC has been observed to crash the + * hardware when it asserts its DMA request signals. In the future, we + * *may* use SDMA, but it's not worth the effort at this writing. + */ + + no_sdma = 0x1; + + /* + * Set the default FIFO Mode Protection (128 bytes). FMP doesn't work if + * the NO_SDMA bit is set. + */ + + fmp = 0x2; + + /* + * The rbb_mode bit determines how the NFC figures out whether chips are + * ready during automatic operations only (this has no effect on atomic + * operations). The two choices are either to monitor the ready/busy + * signals, or to read the status register. We monitor the ready/busy + * signals. + */ + + rbb_mode = 0x1; + + /* + * We don't yet know how many devices are connected. We'll find out in + * out in nfc_3_2_set_geometry(). + */ + + num_of_devices = 0; + + /* Set the default DMA mode. */ + + dma_mode = 0x0; + + /* Set the default status busy bit. */ + + sbb = 0x6; + + /* Little-endian (the default). */ + + nf_big = 0x0; + + /* Set the default (standard) status bit to record. */ + + sb2r = 0x0; + + /* We support only 8-bit Flash bus width. */ + + fw = 0x1; + + /* We don't support "two-on-one." */ + + too = 0x0; + + /* Set the addressing option. */ + + add_op = 0x3; + + /* Set the CONFIG3 register. */ + + config3 = 0; + + config3 |= no_sdma << NFC_3_2_CONFIG3_NO_SDMA_POS; + config3 |= fmp << NFC_3_2_CONFIG3_FMP_POS; + config3 |= rbb_mode << NFC_3_2_CONFIG3_RBB_MODE_POS; + config3 |= num_of_devices << NFC_3_2_CONFIG3_NUM_OF_DEVICES_POS; + config3 |= dma_mode << NFC_3_2_CONFIG3_DMA_MODE_POS; + config3 |= sbb << NFC_3_2_CONFIG3_SBB_POS; + config3 |= nf_big << NFC_3_2_CONFIG3_NF_BIG_POS; + config3 |= sb2r << NFC_3_2_CONFIG3_SB2R_POS; + config3 |= fw << NFC_3_2_CONFIG3_FW_POS; + config3 |= too << NFC_3_2_CONFIG3_TOO_POS; + config3 |= add_op << NFC_3_2_CONFIG3_ADD_OP_POS; + + __raw_writel(config3, secondary_base + NFC_3_2_CONFIG3_REG_OFF); + + /* Return success. */ + + return 0; + +} + +/** + * nfc_3_2_set_geometry() - Configures for the medium geometry. + * + * @this: Per-device data. + */ +static int nfc_3_2_set_geometry(struct imx_nfc_data *this) +{ + unsigned int ps; + unsigned int cmd_phases; + unsigned int pages_per_chip; + unsigned int addr_phases0; + unsigned int addr_phases1; + unsigned int pages_per_block; + unsigned int ecc_mode; + unsigned int ppb; + unsigned int spas; + unsigned int mask; + uint32_t config2; + unsigned int num_of_devices; + uint32_t config3; + unsigned int x; + unsigned int chip; + struct physical_geometry *physical = &this->physical_geometry; + void *secondary_base = this->secondary_regs; + + /* + * Select an NFC geometry based on the physical geometry and the + * capabilities of this NFC. + */ + + switch (physical->page_data_size) { + + case 512: + this->nfc_geometry = &nfc_geometry_512_16_BCH_ECC4; + ps = 0; + break; + + case 2048: + this->nfc_geometry = &nfc_geometry_2K_64_BCH_ECC4; + ps = 1; + break; + + case 4096: + + switch (this->physical_geometry.page_oob_size) { + + case 128: + this->nfc_geometry = &nfc_geometry_4K_128_BCH_ECC4; + break; + + case 218: + this->nfc_geometry = &nfc_geometry_4K_218_BCH_ECC8; + break; + + default: + dev_err(this->dev, + "NFC can't handle page geometry: %u+%u", + physical->page_data_size, + physical->page_oob_size); + return !0; + break; + + } + + ps = 2; + + break; + + default: + dev_err(this->dev, "NFC can't handle page size: %u", + physical->page_data_size); + return !0; + break; + + } + + /* Compute the ECC mode. */ + + switch (this->nfc_geometry->ecc_strength) { + + case 4: + ecc_mode = 0; + break; + + case 8: + ecc_mode = 1; + break; + + default: + dev_err(this->dev, "NFC can't handle ECC strength: %u", + this->nfc_geometry->ecc_strength); + return !0; + break; + + } + + /* Compute the pages per block. */ + + pages_per_block = physical->block_size / physical->page_data_size; + + switch (pages_per_block) { + case 32: + ppb = 0; + break; + case 64: + ppb = 1; + break; + case 128: + ppb = 2; + break; + case 256: + ppb = 3; + break; + default: + dev_err(this->dev, "NFC can't handle pages per block: %d", + pages_per_block); + return !0; + break; + } + + /* + * The hardware needs to know the physical size of the spare area, in + * units of half-words (16 bits). This may be different from the amount + * of the spare area we actually expose to MTD. For example, for for + * 2K+112, we only expose 64 spare bytes, but the hardware needs to know + * the real facts. + */ + + spas = this->physical_geometry.page_oob_size >> 1; + + /* + * The number of command phases needed to read a page is directly + * dependent on whether this is a small page or large page device. Large + * page devices need more address phases, terminated by a second command + * phase. + */ + + cmd_phases = is_large_page_chip(this) ? 1 : 0; + + /* + * The num_adr_phases1 field contains the number of phases needed to + * transmit addresses for read and program operations. This is the sum + * of the number of phases for a page address and the number of phases + * for a column address. + * + * The number of phases for a page address is the number of bytes needed + * to contain a page address. + * + * The number of phases for a column address is the number of bytes + * needed to contain a column address. + * + * After computing the sum, we subtract three because a value of zero in + * this field indicates three address phases, and this is the minimum + * number of phases the hardware can comprehend. + * + * We compute the number of phases based on the *physical* geometry, not + * the NFC geometry. For example, even if we are treating a very large + * device as if it contains fewer pages than it actually does, the + * hardware still needs the additional address phases. + */ + + pages_per_chip = + physical->chip_size >> (fls(physical->page_data_size) - 1); + + addr_phases1 = (fls(pages_per_chip) >> 3) + 1; + + addr_phases1 += (fls(physical->page_data_size) >> 3) + 1; + + addr_phases1 -= 3; + + /* + * The num_adr_phases0 field contains the number of phases needed to + * transmit a page address for an erase operation. That is, this is + * the value of addr_phases1, less the number of phases for the column + * address. + * + * The hardware expresses this phase count as one or two cycles less + * than the count indicated by add_phases1 (see the reference manual). + */ + + addr_phases0 = is_large_page_chip(this) ? 1 : 0; + + /* Set the CONFIG2 register. */ + + mask = + NFC_3_2_CONFIG2_PS_MSK | + NFC_3_2_CONFIG2_CMD_PHASES_MSK | + NFC_3_2_CONFIG2_ADDR_PHASES0_MSK | + NFC_3_2_CONFIG2_ECC_MODE_MSK | + NFC_3_2_CONFIG2_PPB_MSK | + NFC_3_2_CONFIG2_ADDR_PHASES1_MSK | + NFC_3_2_CONFIG2_SPAS_MSK ; + + config2 = __raw_readl(secondary_base + NFC_3_2_CONFIG2_REG_OFF); + + config2 &= ~mask; + + config2 |= ps << NFC_3_2_CONFIG2_PS_POS; + config2 |= cmd_phases << NFC_3_2_CONFIG2_CMD_PHASES_POS; + config2 |= addr_phases0 << NFC_3_2_CONFIG2_ADDR_PHASES0_POS; + config2 |= ecc_mode << NFC_3_2_CONFIG2_ECC_MODE_POS; + config2 |= ppb << NFC_3_2_CONFIG2_PPB_POS; + config2 |= addr_phases1 << NFC_3_2_CONFIG2_ADDR_PHASES1_POS; + config2 |= spas << NFC_3_2_CONFIG2_SPAS_POS; + + config2 = __raw_writel(config2, + secondary_base + NFC_3_2_CONFIG2_REG_OFF); + + /* + * Compute the num_of_devices field. + * + * It's very important to set this field correctly. This controls the + * set of ready/busy lines to which the NFC listens with automatic + * transactions. If this number is too large, the NFC will listen to + * ready/busy signals that are electrically floating, or it will try to + * read the status registers of chips that don't exist. Conversely, if + * the number is too small, the NFC could believe an operation is + * finished when some chips are still busy. + */ + + num_of_devices = physical->chip_count - 1; + + /* Set the CONFIG3 register. */ + + mask = NFC_3_2_CONFIG3_NUM_OF_DEVICES_MSK; + + config3 = __raw_readl(secondary_base + NFC_3_2_CONFIG3_REG_OFF); + + config3 &= ~mask; + + config3 |= num_of_devices << NFC_3_2_CONFIG3_NUM_OF_DEVICES_POS; + + __raw_writel(config3, secondary_base + NFC_3_2_CONFIG3_REG_OFF); + + /* + * Check if the physical chip count is a power of 2. If not, then + * automatic operations aren't available. This is because we use an + * addressing option (see the ADD_OP field of CONFIG3) that requires + * a number of chips that is a power of 2. + */ + + if (ffs(physical->chip_count) != fls(physical->chip_count)) { + this->nfc->start_auto_read = 0; + this->nfc->start_auto_write = 0; + this->nfc->start_auto_erase = 0; + } + + /* Unlock the NFC RAM. */ + + x = __raw_readl(secondary_base + NFC_3_2_WRPROT_REG_OFF); + x &= ~NFC_3_2_WRPROT_BLS_MSK; + x |= 0x2 << NFC_3_2_WRPROT_BLS_POS; + __raw_writel(x, secondary_base + NFC_3_2_WRPROT_REG_OFF); + + /* Loop over chip selects, setting the unlocked ranges. */ + + for (chip = 0; chip < this->nfc->max_chip_count; chip++) { + + /* Set the unlocked range to cover the entire chip.*/ + + __raw_writel(0xffff0000, secondary_base + + NFC_3_2_UNLOCK_BLK_ADD0_REG_OFF + (chip * 4)); + + /* Unlock. */ + + x = __raw_readl(secondary_base + NFC_3_2_WRPROT_REG_OFF); + x &= ~(NFC_3_2_WRPROT_CS2L_MSK | NFC_3_2_WRPROT_WPC_MSK); + x |= chip << NFC_3_2_WRPROT_CS2L_POS; + x |= 0x4 << NFC_3_2_WRPROT_WPC_POS ; + __raw_writel(x, secondary_base + NFC_3_2_WRPROT_REG_OFF); + + } + + /* Return success. */ + + return 0; + +} + +/** + * nfc_3_2_exit() - Hardware cleanup. + * + * @this: Per-device data. + */ +static void nfc_3_2_exit(struct imx_nfc_data *this) +{ +} + +/** + * nfc_3_2_set_closest_cycle() - Version-specific hardware cleanup. + * + * @this: Per-device data. + */ +static int nfc_3_2_set_closest_cycle(struct imx_nfc_data *this, unsigned ns) +{ + struct clk *parent_clock; + unsigned long parent_clock_rate_in_hz; + unsigned long sym_low_clock_rate_in_hz; + unsigned long asym_low_clock_rate_in_hz; + unsigned int sym_high_cycle_in_ns; + unsigned int asym_high_cycle_in_ns; + + /* + * According to ENGcm09121: + * + * - If the NFC is set to SYMMETRIC mode, the NFC clock divider must + * divide the EMI Slow Clock by NO MORE THAN 4. + * + * - If the NFC is set for ASYMMETRIC mode, the NFC clock divider must + * divide the EMI Slow Clock by NO MORE THAN 3. + * + * We need to compute the corresponding cycle time constraints. Start + * by getting information about the parent clock. + */ + + parent_clock = clk_get_parent(this->clock); + parent_clock_rate_in_hz = clk_get_rate(parent_clock); + + /* Compute the limit frequencies. */ + + sym_low_clock_rate_in_hz = parent_clock_rate_in_hz / 4; + asym_low_clock_rate_in_hz = parent_clock_rate_in_hz / 3; + + /* Compute the corresponding limit cycle periods. */ + + sym_high_cycle_in_ns = 1000000000 / sym_low_clock_rate_in_hz; + asym_high_cycle_in_ns = (1000000000 / asym_low_clock_rate_in_hz) * 2; + + /* Attempt to implement the given cycle. */ + + return nfc_util_set_best_cycle(this, ns, + ns > asym_high_cycle_in_ns, ns > sym_high_cycle_in_ns); + +} + +/** + * nfc_3_2_mask_interrupt() - Masks interrupts. + * + * @this: Per-device data. + */ +static void nfc_3_2_mask_interrupt(struct imx_nfc_data *this) +{ + void *secondary_base = this->secondary_regs; + raw_set_mask_l(NFC_3_2_CONFIG2_INT_MSK_MSK, + secondary_base + NFC_3_2_CONFIG2_REG_OFF); +} + +/** + * nfc_3_2_unmask_interrupt() - Unmasks interrupts. + * + * @this: Per-device data. + */ +static void nfc_3_2_unmask_interrupt(struct imx_nfc_data *this) +{ + void *secondary_base = this->secondary_regs; + raw_clr_mask_l(NFC_3_2_CONFIG2_INT_MSK_MSK, + secondary_base + NFC_3_2_CONFIG2_REG_OFF); +} + +/** + * nfc_3_2_clear_interrupt() - Clears an interrupt. + * + * @this: Per-device data. + */ +static void nfc_3_2_clear_interrupt(struct imx_nfc_data *this) +{ + int done; + void *secondary_base = this->secondary_regs; + + /* Request IP bus interface access. */ + + raw_set_mask_l(NFC_3_2_IPC_CREQ_MSK, + secondary_base + NFC_3_2_IPC_REG_OFF); + + /* Wait for access. */ + + do + done = !!raw_read_mask_l(NFC_3_2_IPC_CACK_MSK, + secondary_base + NFC_3_2_IPC_REG_OFF); + while (!done); + + /* Clear the interrupt. */ + + raw_clr_mask_l(NFC_3_2_IPC_INT_MSK, + secondary_base + NFC_3_2_IPC_REG_OFF); + + /* Release the IP bus interface. */ + + raw_clr_mask_l(NFC_3_2_IPC_CREQ_MSK, + secondary_base + NFC_3_2_IPC_REG_OFF); + +} + +/** + * nfc_3_2_is_interrupting() - Returns the interrupt bit status. + * + * @this: Per-device data. + */ +static int nfc_3_2_is_interrupting(struct imx_nfc_data *this) +{ + void *secondary_base = this->secondary_regs; + return !!raw_read_mask_l(NFC_3_2_IPC_INT_MSK, + secondary_base + NFC_3_2_IPC_REG_OFF); +} + +/** + * nfc_3_2_is_ready() - Returns the ready/busy status. + * + * @this: Per-device data. + */ +static int nfc_3_2_is_ready(struct imx_nfc_data *this) +{ + void *secondary_base = this->secondary_regs; + return !!raw_read_mask_l(NFC_3_2_IPC_RB_B_MSK, + secondary_base + NFC_3_2_IPC_REG_OFF); +} + +/** + * nfc_3_2_set_force_ce() - Can force CE to be asserted always. + * + * @this: Per-device data. + * @on: Indicates if the hardware CE signal should be asserted always. + */ +static void nfc_3_2_set_force_ce(struct imx_nfc_data *this, int on) +{ + void *primary_base = this->primary_regs; + + if (on) + raw_set_mask_l(NFC_3_2_CONFIG1_NF_CE_MSK, + primary_base + NFC_3_2_CONFIG1_REG_OFF); + else + raw_clr_mask_l(NFC_3_2_CONFIG1_NF_CE_MSK, + primary_base + NFC_3_2_CONFIG1_REG_OFF); + +} + +/** + * nfc_3_2_set_ecc() - Turns ECC on or off. + * + * @this: Per-device data. + * @on: Indicates if ECC should be on or off. + */ +static void nfc_3_2_set_ecc(struct imx_nfc_data *this, int on) +{ + void *secondary_base = this->secondary_regs; + + if (on) + raw_set_mask_l(NFC_3_2_CONFIG2_ECC_EN_MSK, + secondary_base + NFC_3_2_CONFIG2_REG_OFF); + else + raw_clr_mask_l(NFC_3_2_CONFIG2_ECC_EN_MSK, + secondary_base + NFC_3_2_CONFIG2_REG_OFF); + +} + +/** + * nfc_3_2_get_ecc_status() - Reports ECC errors. + * + * @this: Per-device data. + */ +static int nfc_3_2_get_ecc_status(struct imx_nfc_data *this) +{ + unsigned int i; + void *base = this->primary_regs; + uint16_t status_reg; + unsigned int buffer_status[8]; + int status; + + /* Get the entire status register. */ + + status_reg = __raw_readw(base + NFC_3_2_ECC_STATUS_REG_OFF); + + /* Pick out the status for each buffer. */ + + buffer_status[0] = (status_reg & NFC_3_2_ECC_STATUS_NOBER1_MSK) + >> NFC_3_2_ECC_STATUS_NOBER1_POS; + + buffer_status[1] = (status_reg & NFC_3_2_ECC_STATUS_NOBER2_MSK) + >> NFC_3_2_ECC_STATUS_NOBER2_POS; + + buffer_status[2] = (status_reg & NFC_3_2_ECC_STATUS_NOBER3_MSK) + >> NFC_3_2_ECC_STATUS_NOBER3_POS; + + buffer_status[3] = (status_reg & NFC_3_2_ECC_STATUS_NOBER4_MSK) + >> NFC_3_2_ECC_STATUS_NOBER4_POS; + + buffer_status[4] = (status_reg & NFC_3_2_ECC_STATUS_NOBER5_MSK) + >> NFC_3_2_ECC_STATUS_NOBER5_POS; + + buffer_status[5] = (status_reg & NFC_3_2_ECC_STATUS_NOBER6_MSK) + >> NFC_3_2_ECC_STATUS_NOBER6_POS; + + buffer_status[6] = (status_reg & NFC_3_2_ECC_STATUS_NOBER7_MSK) + >> NFC_3_2_ECC_STATUS_NOBER7_POS; + + buffer_status[7] = (status_reg & NFC_3_2_ECC_STATUS_NOBER8_MSK) + >> NFC_3_2_ECC_STATUS_NOBER8_POS; + + /* Loop through the buffers we're actually using. */ + + status = 0; + + for (i = 0; i < this->nfc_geometry->buffer_count; i++) { + + if (buffer_status[i] > this->nfc_geometry->ecc_strength) { + status = -1; + break; + } + + status += buffer_status[i]; + + } + + /* Return the final result. */ + + return status; + +} + +/** + * nfc_3_2_get_symmetric() - Indicates if the clock is symmetric. + * + * @this: Per-device data. + */ +static int nfc_3_2_get_symmetric(struct imx_nfc_data *this) +{ + void *secondary_base = this->secondary_regs; + + return !!raw_read_mask_w(NFC_3_2_CONFIG2_SYM_MSK, + secondary_base + NFC_3_2_CONFIG2_REG_OFF); + +} + +/** + * nfc_3_2_set_symmetric() - Turns symmetric clock mode on or off. + * + * @this: Per-device data. + */ +static void nfc_3_2_set_symmetric(struct imx_nfc_data *this, int on) +{ + void *secondary_base = this->secondary_regs; + + if (on) + raw_set_mask_l(NFC_3_2_CONFIG2_SYM_MSK, + secondary_base + NFC_3_2_CONFIG2_REG_OFF); + else + raw_clr_mask_l(NFC_3_2_CONFIG2_SYM_MSK, + secondary_base + NFC_3_2_CONFIG2_REG_OFF); + +} + +/** + * nfc_3_2_select_chip() - Selects the current chip. + * + * @this: Per-device data. + * @chip: The chip number to select, or -1 to select no chip. + */ +static void nfc_3_2_select_chip(struct imx_nfc_data *this, int chip) +{ + unsigned long x; + void *primary_base = this->primary_regs; + + if (chip < 0) + return; + + x = __raw_readl(primary_base + NFC_3_2_CONFIG1_REG_OFF); + + x &= ~NFC_3_2_CONFIG1_CS_MSK; + + x |= (chip << NFC_3_2_CONFIG1_CS_POS) & NFC_3_2_CONFIG1_CS_MSK; + + __raw_writel(x, primary_base + NFC_3_2_CONFIG1_REG_OFF); + +} + +/** + * nfc_3_2_command_cycle() - Sends a command. + * + * @this: Per-device data. + * @command: The command code. + */ +static void nfc_3_2_command_cycle(struct imx_nfc_data *this, unsigned command) +{ + void *primary_base = this->primary_regs; + + /* Write the command we want to send. */ + + __raw_writel(command, primary_base + NFC_3_2_CMD_REG_OFF); + + /* Launch a command cycle. */ + + __raw_writel(NFC_3_2_LAUNCH_FCMD_MSK, + primary_base + NFC_3_2_LAUNCH_REG_OFF); + +} + +/** + * nfc_3_2_write_cycle() - writes a single byte. + * + * @this: Per-device data. + * @byte: The byte. + */ +static void nfc_3_2_write_cycle(struct imx_nfc_data *this, unsigned int byte) +{ + void *primary_base = this->primary_regs; + + /* Give the NFC the byte we want to write. */ + + __raw_writel(byte, primary_base + NFC_3_2_ADD0_REG_OFF); + + /* Launch an address cycle. + * + * This is *sort* of a hack, but not really. The intent of the NFC + * design is for this operation to send an address byte. In fact, the + * NFC neither knows nor cares what we're sending. It justs runs a write + * cycle. + */ + + __raw_writel(NFC_3_2_LAUNCH_FADD_MSK, + primary_base + NFC_3_2_LAUNCH_REG_OFF); + + /* Wait for the NFC to finish. */ + + nfc_util_wait_for_the_nfc(this, false); + +} + +/** + * nfc_3_2_read_cycle() - Applies a single read cycle to the current chip. + * + * @this: Per-device data. + */ +static unsigned int nfc_3_2_read_cycle(struct imx_nfc_data *this) +{ + unsigned int result; + void *primary_base = this->primary_regs; + + /* Launch a "Data Out" operation. */ + + __raw_writel(0x4 << NFC_3_2_LAUNCH_FDO_POS, + primary_base + NFC_3_2_LAUNCH_REG_OFF); + + /* Wait for the NFC to finish. */ + + nfc_util_wait_for_the_nfc(this, false); + + /* Get the result. */ + + result = __raw_readl(primary_base + NFC_3_2_CONFIG1_REG_OFF) + >> NFC_3_2_CONFIG1_STATUS_POS; + result &= 0xff; + + /* Return the result. */ + + return result; + +} + +/** + * nfc_3_2_read_page() - Reads a page into the NFC memory. + * + * @this: Per-device data. + */ +static void nfc_3_2_read_page(struct imx_nfc_data *this) +{ + void *primary_base = this->primary_regs; + + /* Start reading into buffer 0. */ + + raw_clr_mask_l(NFC_3_2_CONFIG1_RBA_MSK, + primary_base + NFC_3_2_CONFIG1_REG_OFF); + + /* Launch a page data out operation. */ + + __raw_writel(0x1 << NFC_3_2_LAUNCH_FDO_POS, + primary_base + NFC_3_2_LAUNCH_REG_OFF); + + /* Wait for the NFC to finish. */ + + nfc_util_wait_for_the_nfc(this, true); + +} + +/** + * nfc_3_2_send_page() - Sends a page from the NFC to the current chip. + * + * @this: Per-device data. + */ +static void nfc_3_2_send_page(struct imx_nfc_data *this) +{ + void *primary_base = this->primary_regs; + + /* Start sending from buffer 0. */ + + raw_clr_mask_l(NFC_3_2_CONFIG1_RBA_MSK, + primary_base + NFC_3_2_CONFIG1_REG_OFF); + + /* Launch a page data in operation. */ + + __raw_writel(NFC_3_2_LAUNCH_FDI_MSK, + primary_base + NFC_3_2_LAUNCH_REG_OFF); + + /* Wait for the NFC to finish. */ + + nfc_util_wait_for_the_nfc(this, true); + +} + +/** + * nfc_3_2_add_state_events() - Adds events to display important state. + * + * @this: Per-device data. + */ +static void nfc_3_2_add_state_events(struct imx_nfc_data *this) +{ +#ifdef EVENT_REPORTING + void *secondary_base = this->secondary_regs; + + add_state_event_l + ( + secondary_base + NFC_3_2_IPC_REG_OFF, + NFC_3_2_IPC_INT_MSK, + " Interrupt : 0", + " Interrupt : X" + ); + + add_state_event_l + ( + secondary_base + NFC_3_2_IPC_REG_OFF, + NFC_3_2_IPC_AUTO_PROG_DONE_MSK, + " auto_prog_done: 0", + " auto_prog_done: X" + ); + + add_state_event_l + ( + secondary_base + NFC_3_2_IPC_REG_OFF, + NFC_3_2_IPC_RB_B_MSK, + " Medium : Busy", + " Medium : Ready" + ); +#endif +} + +/** + * nfc_3_2_get_auto_loop_params() - Gets automatic operation loop parameters. + * + * This function and the corresponding "setter" enable the automatic operations + * to keep some state as they iterate over chips. + * + * The most "obvious" way to save state would be to allocate a private data + * structure and hang it off the owning struct nfc_hal. On the other hand, + * writing the code to allocate the memory and then release it when the NFC + * shuts down is annoying - and we have some perfectly good memory in the NFC + * hardware that we can use. Since we only use two commands at a time, we can + * stash our loop limits and loop index in the top 16 bits of the NAND_CMD + * register. To paraphrase the reference manual: + * + * + * NAND_CMD + * + * |<-- 4 bits -->|<-- 4 bits -->|<-- 8 bits -->| + * +----------------+---------------+--------------------------------+ + * | First | Last | Loop Index | + * +----------------+---------------+--------------------------------+ + * | NAND COMMAND1 | NAND COMMAND0 | + * +--------------------------------+--------------------------------+ + * |<-- 16 bits -->|<-- 16 bits -->| + * + * + * @this: Per-device data. + * @first: A pointer to a variable that will receive the first chip number. + * @last: A pointer to a variable that will receive the last chip number. + * @index: A pointer to a variable that will receive the current chip number. + */ +static void nfc_3_2_get_auto_loop_params(struct imx_nfc_data *this, + unsigned *first, unsigned *last, unsigned *index) +{ + uint32_t x; + void *primary_base = this->primary_regs; + + x = __raw_readl(primary_base + NFC_3_2_CMD_REG_OFF); + + *first = (x >> 28) & 0x0f; + *last = (x >> 24) & 0x0f; + *index = (x >> 16) & 0xff; + +} + +/** + * nfc_3_2_set_auto_loop_params() - Sets automatic operation loop parameters. + * + * See nfc_3_2_get_auto_loop_params() for detailed information about these + * functions. + * + * @this: Per-device data. + * @first: The first chip number. + * @last: The last chip number. + * @index: The current chip number. + */ +static void nfc_3_2_set_auto_loop_params(struct imx_nfc_data *this, + unsigned first, unsigned last, unsigned index) +{ + uint32_t x; + void *primary_base = this->primary_regs; + + x = __raw_readl(primary_base + NFC_3_2_CMD_REG_OFF); + + x &= 0x0000ffff; + x |= (first & 0x0f) << 28; + x |= (last & 0x0f) << 24; + x |= (index & 0xff) << 16; + + __raw_writel(x, primary_base + NFC_3_2_CMD_REG_OFF); + +} + +/** + * nfc_3_2_get_auto_addresses() - Gets automatic operation addresses. + * + * @this: Per-device data. + * @group: The address group number. + * @chip: A pointer to a variable that will receive the chip number. + * @column: A pointer to a variable that will receive the column address. + * A NULL pointer indicates there is no column address. + * @page: A pointer to a variable that will receive the page address. + */ +static void nfc_3_2_get_auto_addresses(struct imx_nfc_data *this, + unsigned group, unsigned *chip, unsigned *column, unsigned *page) +{ + uint32_t x; + unsigned int chip_count; + unsigned int cs_width; + unsigned int cs_mask; + unsigned int page_lsbs; + unsigned int page_msbs; + uint32_t *low; + uint16_t *high; + void *primary_base = this->primary_regs; + void *secondary_base = this->secondary_regs; + + /* + * The width of the chip select field depends on the number of connected + * chips. + * + * Notice that these computations work only if the number of chips is a + * power of 2. In fact, that is a fundamental limitation for using + * automatic operations. + */ + + x = __raw_readl(secondary_base + NFC_3_2_CONFIG3_REG_OFF); + + chip_count = + (x & NFC_3_2_CONFIG3_NUM_OF_DEVICES_MSK) >> + NFC_3_2_CONFIG3_NUM_OF_DEVICES_POS; + chip_count++; + + cs_width = ffs(chip_count) - 1; + cs_mask = chip_count - 1; + + /* Construct pointers to the pieces of the given address group. */ + + low = primary_base + NFC_3_2_ADD0_REG_OFF; + low += group; + + high = primary_base + NFC_3_2_ADD8_REG_OFF; + high += group; + + /* Check if there's a column address. */ + + if (column) { + + /* + * The low 32 bits of the address group look like this: + * + * 16 - n n + * | <- bits ->|<->|<- 16 bits ->| + * +-------------+---+----------------+ + * | Page LSBs |CS | Column | + * +-------------+---+----------------+ + */ + + x = __raw_readl(low); + + *column = x & 0xffff; + *chip = (x >> 16) & cs_mask; + page_lsbs = x >> (16 + cs_width); + + /* The high 16 bits contain the MSB's of the page address. */ + + page_msbs = __raw_readw(high); + + *page = (page_msbs << (16 - cs_width)) | page_lsbs; + + } else { + + /* + * The low 32 bits of the address group look like this: + * + * n + * | <- (32 - n) bits ->|<->| + * +-----------------------------+---+ + * | Page LSBs |CS | + * +-----------------------------+---+ + */ + + x = __raw_readl(low); + + *chip = x & cs_mask; + page_lsbs = x >> cs_width; + + /* The high 16 bits contain the MSB's of the page address. */ + + page_msbs = __raw_readw(high); + + *page = (page_msbs << (32 - cs_width)) | page_lsbs; + + } + +} + +/** + * nfc_3_2_set_auto_addresses() - Sets automatic operation addresses. + * + * @this: Per-device data. + * @group: The address group number. + * @chip: The chip number. + * @column: The column address. The sentinel value ~0 indicates that there is + * no column address. + * @page: The page address. + */ +static void nfc_3_2_set_auto_addresses(struct imx_nfc_data *this, + unsigned group, unsigned chip, unsigned column, unsigned page) +{ + uint32_t x; + unsigned chip_count; + unsigned int cs_width; + unsigned int cs_mask; + uint32_t *low; + uint16_t *high; + void *primary_base = this->primary_regs; + void *secondary_base = this->secondary_regs; + + /* + * The width of the chip select field depends on the number of connected + * chips. + * + * Notice that these computations work only if the number of chips is a + * power of 2. In fact, that is a fundamental limitation for using + * automatic operations. + */ + + x = __raw_readl(secondary_base + NFC_3_2_CONFIG3_REG_OFF); + + chip_count = + (x & NFC_3_2_CONFIG3_NUM_OF_DEVICES_MSK) >> + NFC_3_2_CONFIG3_NUM_OF_DEVICES_POS; + chip_count++; + + cs_width = ffs(chip_count) - 1; + cs_mask = chip_count - 1; + + /* Construct pointers to the pieces of the given address group. */ + + low = primary_base + NFC_3_2_ADD0_REG_OFF; + low += group; + + high = primary_base + NFC_3_2_ADD8_REG_OFF; + high += group; + + /* Check if we have a column address. */ + + if (column != ~0) { + + /* + * The low 32 bits of the address group look like this: + * + * 16 - n n + * | <- bits ->|<->|<- 16 bits ->| + * +-------------+---+----------------+ + * | Page LSBs |CS | Column | + * +-------------+---+----------------+ + */ + + x = 0; + x |= column & 0xffff; + x |= (chip & cs_mask) << 16; + x |= page << (16 + cs_width); + + __raw_writel(x, low); + + /* The high 16 bits contain the MSB's of the page address. */ + + x = (page >> (16 - cs_width)) & 0xffff; + + __raw_writew(x, high); + + } else { + + /* + * The low 32 bits of the address group look like this: + * + * n + * | <- (32 - n) bits ->|<->| + * +-----------------------------+---+ + * | Page LSBs |CS | + * +-----------------------------+---+ + */ + + x = 0; + x |= chip & cs_mask; + x |= page << cs_width; + + __raw_writel(x, low); + + /* The high 16 bits contain the MSB's of the page address. */ + + x = (page >> (32 - cs_width)) & 0xffff; + + __raw_writew(x, high); + + } + +} + +/** + * nfc_3_2_start_auto_read() - Starts an automatic read. + * + * This function returns 0 if everything went well. + * + * @this: Per-device data. + * @start: The first physical chip number on which to operate. + * @count: The number of physical chips on which to operate. + * @column: The column address. + * @page: The page address. + */ +static int nfc_3_2_start_auto_read(struct imx_nfc_data *this, + unsigned start, unsigned count, unsigned column, unsigned page) +{ + uint32_t x; + int return_value = 0; + void *primary_base = this->primary_regs; + + add_event("Entering nfc_3_2_start_auto_read", 1); + + /* Check for nonsense. */ + + if ((start > 7) || (!count) || (count > 8)) { + return_value = !0; + goto exit; + } + + /* Set state. */ + + nfc_3_2_set_auto_loop_params(this, start, start + count - 1, start); + nfc_3_2_set_auto_addresses(this, 0, start, column, page); + + /* Set up for ONE iteration at a time. */ + + raw_clr_mask_l(NFC_3_2_CONFIG1_ITER_MSK, + primary_base + NFC_3_2_CONFIG1_REG_OFF); + + /* Reset to buffer 0. */ + + raw_clr_mask_l(NFC_3_2_CONFIG1_RBA_MSK, + primary_base + NFC_3_2_CONFIG1_REG_OFF); + + /* + * Set up the commands. Note that the number of command phases was + * configured in the set_geometry() function so, even though we're + * giving both commands here, they won't necessarily both be used. + */ + + x = __raw_readl(primary_base + NFC_3_2_CMD_REG_OFF); + + x &= 0xffff0000; + x |= NAND_CMD_READ0 << 0; + x |= NAND_CMD_READSTART << 8; + + __raw_writel(x, primary_base + NFC_3_2_CMD_REG_OFF); + + /* Launch the operation. */ + + add_event("Launching", 0); + + __raw_writel(NFC_3_2_LAUNCH_AUTO_READ_MSK, + primary_base + NFC_3_2_LAUNCH_REG_OFF); + +exit: /* Return. */ + + add_event("Exiting nfc_3_2_start_auto_read", -1); + + return return_value; + +} + +/** + * nfc_3_2_wait_for_auto_read() - Waits until auto read is ready for the CPU. + * + * This function returns 0 if everything went well. + * + * @this: Per-device data. + */ +static int nfc_3_2_wait_for_auto_read(struct imx_nfc_data *this) +{ + unsigned int first; + unsigned int last; + unsigned int index; + int return_value = 0; + + add_event("Entering nfc_3_2_wait_for_auto_read", 1); + + /* Get state. */ + + nfc_3_2_get_auto_loop_params(this, &first, &last, &index); + + /* This function should be called for every chip. */ + + if ((index < first) || (index > last)) { + return_value = !0; + goto exit; + } + + /* Wait for the NFC to completely finish and interrupt. */ + + nfc_util_wait_for_the_nfc(this, true); + +exit: /* Return. */ + + add_event("Exiting nfc_3_2_wait_for_auto_read", -1); + + return return_value; + +} + +/** + * nfc_3_2_resume_auto_read() - Resumes auto read after CPU intervention. + * + * This function returns 0 if everything went well. + * + * @this: Per-device data. + */ +static int nfc_3_2_resume_auto_read(struct imx_nfc_data *this) +{ + unsigned int first; + unsigned int last; + unsigned int index; + unsigned int chip; + unsigned int column; + unsigned int page; + int return_value = 0; + void *primary_base = this->primary_regs; + + add_event("Entering nfc_3_2_resume_auto_read", 1); + + /* Get state. */ + + nfc_3_2_get_auto_loop_params(this, &first, &last, &index); + nfc_3_2_get_auto_addresses(this, 0, &chip, &column, &page); + + /* This function should be called for every chip, except the last. */ + + if ((index < first) || (index >= last)) { + return_value = !0; + goto exit; + } + + /* Move to the next chip. */ + + index++; + + /* Update state. */ + + nfc_3_2_set_auto_loop_params(this, first, last, index); + nfc_3_2_set_auto_addresses(this, 0, index, column, page); + + /* Reset to buffer 0. */ + + raw_clr_mask_l(NFC_3_2_CONFIG1_RBA_MSK, + primary_base + NFC_3_2_CONFIG1_REG_OFF); + + /* Launch the operation. */ + + add_event("Launching", 0); + + __raw_writel(NFC_3_2_LAUNCH_AUTO_READ_MSK, + primary_base + NFC_3_2_LAUNCH_REG_OFF); + +exit: /* Return. */ + + add_event("Exiting nfc_3_2_resume_auto_read", -1); + + return return_value; + +} + +/** + * nfc_3_2_start_auto_write() - Starts an automatic write. + * + * This function returns 0 if everything went well. + * + * @this: Per-device data. + * @start: The first physical chip number on which to operate. + * @count: The number of physical chips on which to operate. + * @column: The column address. + * @page: The page address. + */ +static int nfc_3_2_start_auto_write(struct imx_nfc_data *this, + unsigned start, unsigned count, unsigned column, unsigned page) +{ + uint32_t x; + int return_value = 0; + void *primary_base = this->primary_regs; + void *secondary_base = this->secondary_regs; + + add_event("Entering nfc_3_2_start_auto_write", 1); + + /* Check for nonsense. */ + + if ((start > 7) || (!count) || (count > 8)) { + return_value = !0; + goto exit; + } + + /* Set state. */ + + nfc_3_2_set_auto_loop_params(this, start, start + count - 1, start); + nfc_3_2_set_auto_addresses(this, 0, start, column, page); + + /* Set up for ONE iteration at a time. */ + + raw_clr_mask_l(NFC_3_2_CONFIG1_ITER_MSK, + primary_base + NFC_3_2_CONFIG1_REG_OFF); + + /* Set up the commands. */ + + x = __raw_readl(primary_base + NFC_3_2_CMD_REG_OFF); + + x &= 0xffff0000; + x |= NAND_CMD_SEQIN << 0; + x |= NAND_CMD_PAGEPROG << 8; + + __raw_writel(x, primary_base + NFC_3_2_CMD_REG_OFF); + + /* Clear the auto_prog_done bit. */ + + raw_clr_mask_l(NFC_3_2_IPC_AUTO_PROG_DONE_MSK, + secondary_base + NFC_3_2_IPC_REG_OFF); + +exit: /* Return. */ + + add_event("Exiting nfc_3_2_start_auto_write", -1); + + return return_value; + +} + +/** + * nfc_3_2_wait_for_auto_write() - Waits for auto write to be writey for the CPU. + * + * This function returns 0 if everything went well. + * + * @this: Per-device data. + */ +static int nfc_3_2_wait_for_auto_write(struct imx_nfc_data *this) +{ + unsigned int first; + unsigned int last; + unsigned int index; + unsigned int chip; + unsigned int column; + unsigned int page; + uint32_t x; + int interrupt; + int transmitted; + int ready; + int return_value = 0; + void *primary_base = this->primary_regs; + void *secondary_base = this->secondary_regs; + + add_event("Entering nfc_3_2_wait_for_auto_write", 1); + + /* Get state. */ + + nfc_3_2_get_auto_loop_params(this, &first, &last, &index); + nfc_3_2_get_auto_addresses(this, 0, &chip, &column, &page); + + /* This function should be called for every chip. */ + + if ((index < first) || (index > last)) { + return_value = !0; + goto exit; + } + + /* Reset to buffer 0. */ + + raw_clr_mask_l(NFC_3_2_CONFIG1_RBA_MSK, + primary_base + NFC_3_2_CONFIG1_REG_OFF); + + /* Launch the operation. */ + + nfc_3_2_add_state_events(this); + + add_event("Launching", 0); + + __raw_writel(NFC_3_2_LAUNCH_AUTO_PROG_MSK, + primary_base + NFC_3_2_LAUNCH_REG_OFF); + + nfc_3_2_add_state_events(this); + + /* Wait for the NFC to transmit the page. */ + + add_event("Spinning while the NFC transmits the page...", 0); + + do + transmitted = !!raw_read_mask_l(NFC_3_2_IPC_AUTO_PROG_DONE_MSK, + secondary_base + NFC_3_2_IPC_REG_OFF); + while (!transmitted); + + /* + * When control arrives here, the auto_prog_done bit is set. This + * indicates the NFC has finished transmitting the current page. The CPU + * is now free to write the next page into the NFC's memory. The Flash + * hardware is still busy programming the page into its storage array. + * + * Clear the auto_prog_done bit. This is analogous to acknowledging an + * interrupt. + */ + + nfc_3_2_add_state_events(this); + + add_event("Acknowledging the page...", 0); + + raw_clr_mask_l(NFC_3_2_IPC_AUTO_PROG_DONE_MSK, + secondary_base + NFC_3_2_IPC_REG_OFF); + + nfc_3_2_add_state_events(this); + + /* + * If this is *not* the last iteration, move to the next chip and return + * to the caller so he can put the next page in the NFC buffer. + */ + + if (index < last) { + + add_event("Moving to the next chip...", 0); + + index++; + + nfc_3_2_set_auto_loop_params(this, first, last, index); + nfc_3_2_set_auto_addresses(this, 0, index, column, page); + + goto exit; + + } + + /* + * If control arrives here, this is the last iteration, so it's time to + * close out the entire operation. We need to wait for the medium to be + * ready and then acknowledge the final interrupt. + * + * Because of the way the NFC hardware works, the code here requires a + * bit of explanation. The most important rule is: + * + * During automatic operations, the NFC sets its + * interrupt bit *whenever* it sees the ready/busy + * signal transition from "Busy" to "Ready". + * + * Recall that the ready/busy signals from all the chips in the medium + * are "wire-anded." Thus, the NFC will only see that the medium is + * ready if *all* chips are ready. + * + * Because of variability in NAND Flash timing, the medium *may* have + * become ready during previous iterations, which means the interrupt + * bit *may* be set at this moment. This is a "left-over" interrupt, and + * can complicate our logic. + * + * The two bits of state that interest us here are the interrupt bit + * and the ready/busy bit. It boils down to the following truth table: + * + * | Interrupt | Ready/Busy | Description + * +------------+------------+--------------- + * | | | Busy medium and no left-over interrupt. + * | 0 | 0 | The final interrupt will arrive in the + * | | | future. + * +------------+------------+--------------- + * | | | Ready medium and no left-over interrupt. + * | 0 | 1 | There will be no final interrupt. This + * | | | case should be impossible. + * +------------+------------+--------------- + * | | | Busy medium and left-over interrupt. + * | 1 | 0 | The final interrupt will arrive in the + * | | | future. This is the hard case. + * +------------+------------+--------------- + * | | | Ready medium and left-over interrupt. + * | 1 | 1 | The final interrupt has already + * | | | arrived. Acknowledge it and exit. + * +------------+------------+--------------- + * + * Case #3 is a small problem. If we clear the interrupt, we may or may + * not have another interrupt following. + */ + + /* Sample the IPC register. */ + + x = __raw_readl(secondary_base + NFC_3_2_IPC_REG_OFF); + + interrupt = !!(x & NFC_3_2_IPC_INT_MSK); + ready = !!(x & NFC_3_2_IPC_RB_B_MSK); + + /* Check for the easy cases. */ + + if (!interrupt && !ready) { + add_event("Waiting for the final interrupt..." , 0); + nfc_util_wait_for_the_nfc(this, true); + goto exit; + } else if (!interrupt && ready) { + add_event("Done." , 0); + goto exit; + } else if (interrupt && ready) { + add_event("Acknowledging the final interrupt..." , 0); + nfc_util_wait_for_the_nfc(this, false); + goto exit; + + } + + /* + * If control arrives here, we hit case #3. Begin by acknowledging the + * interrupt we have right now. + */ + + add_event("Clearing the left-over interrupt..." , 0); + nfc_util_wait_for_the_nfc(this, false); + + /* + * Check the ready/busy bit again. If the medium is still busy, then + * we're going to get one more interrupt. + */ + + ready = !!raw_read_mask_l(NFC_3_2_IPC_RB_B_MSK, + secondary_base + NFC_3_2_IPC_REG_OFF); + + if (!ready) { + add_event("Waiting for the final interrupt..." , 0); + nfc_util_wait_for_the_nfc(this, true); + } + +exit: /* Return. */ + + add_event("Exiting nfc_3_2_wait_for_auto_write", -1); + + return return_value; + +} + +/** + * nfc_3_2_start_auto_erase() - Starts an automatic erase. + * + * This function returns 0 if everything went well. + * + * @this: Per-device data. + * @start: The first physical chip number on which to operate. + * @count: The number of physical chips on which to operate. + * @page: The page address. + */ +static int nfc_3_2_start_auto_erase(struct imx_nfc_data *this, + unsigned start, unsigned count, unsigned page) +{ + uint32_t x; + unsigned i; + int return_value = 0; + void *primary_base = this->primary_regs; + + add_event("Entering nfc_3_2_start_auto_erase", 1); + + /* Check for nonsense. */ + + if ((start > 7) || (!count) || (count > 8)) { + return_value = !0; + goto exit; + } + + /* Set up the commands. */ + + x = __raw_readl(primary_base + NFC_3_2_CMD_REG_OFF); + + x &= 0xffff0000; + x |= NAND_CMD_ERASE1 << 0; + x |= NAND_CMD_ERASE2 << 8; + + __raw_writel(x, primary_base + NFC_3_2_CMD_REG_OFF); + + /* Set the iterations. */ + + x = __raw_readl(primary_base + NFC_3_2_CONFIG1_REG_OFF); + + x &= ~NFC_3_2_CONFIG1_ITER_MSK; + x |= ((count - 1) << NFC_3_2_CONFIG1_ITER_POS) & + NFC_3_2_CONFIG1_ITER_MSK; + + __raw_writel(x, primary_base + NFC_3_2_CONFIG1_REG_OFF); + + /* Loop over chips, setting up the address groups. */ + + for (i = 0; i < count; i++) + nfc_3_2_set_auto_addresses(this, i, start + i, ~0, page); + + /* Launch the operation. */ + + add_event("Launching", 0); + + __raw_writel(NFC_3_2_LAUNCH_AUTO_ERASE_MSK, + primary_base + NFC_3_2_LAUNCH_REG_OFF); + +exit: /* Return. */ + + add_event("Exiting nfc_3_2_start_auto_erase", -1); + + return return_value; + +} + +/* + * At this point, we've defined all the version-specific primitives. We're now + * ready to construct the NFC HAL structures for every version. + */ + +struct nfc_hal nfc_1_0_hal = { + .major_version = 1, + .minor_version = 0, + .max_chip_count = 1, + .max_buffer_count = 4, + .spare_buf_stride = 16, + .has_secondary_regs = 0, + .can_be_symmetric = 0, + }; + +struct nfc_hal nfc_2_0_hal = { + .major_version = 2, + .minor_version = 0, + .max_chip_count = 1, + .max_buffer_count = 4, + .spare_buf_stride = 16, + .has_secondary_regs = false, + .can_be_symmetric = true, + .init = nfc_2_0_init, + .set_geometry = nfc_2_0_set_geometry, + .exit = nfc_2_x_exit, + .mask_interrupt = nfc_2_0_mask_interrupt, + .unmask_interrupt = nfc_2_0_unmask_interrupt, + .clear_interrupt = nfc_2_x_clear_interrupt, + .is_interrupting = nfc_2_x_is_interrupting, + .is_ready = 0, /* Ready/Busy not exposed. */ + .set_ecc = nfc_2_0_set_ecc, + .get_ecc_status = nfc_2_0_get_ecc_status, + .get_symmetric = nfc_2_0_get_symmetric, + .set_symmetric = nfc_2_0_set_symmetric, + .select_chip = nfc_2_0_select_chip, + .command_cycle = nfc_2_x_command_cycle, + .write_cycle = nfc_2_x_write_cycle, + .read_cycle = nfc_2_0_read_cycle, + .read_page = nfc_2_0_read_page, + .send_page = nfc_2_0_send_page, + .start_auto_read = 0, /* Not supported. */ + .wait_for_auto_read = 0, /* Not supported. */ + .resume_auto_read = 0, /* Not supported. */ + .start_auto_write = 0, /* Not supported. */ + .wait_for_auto_write = 0, /* Not supported. */ + .start_auto_erase = 0, /* Not supported. */ + }; + +struct nfc_hal nfc_2_1_hal = { + .major_version = 2, + .minor_version = 1, + .max_chip_count = 4, + .max_buffer_count = 8, + .spare_buf_stride = 64, + .has_secondary_regs = 0, + .can_be_symmetric = !0, + }; + +struct nfc_hal nfc_3_1_hal = { + .major_version = 3, + .minor_version = 1, + .max_chip_count = 4, + .max_buffer_count = 8, + .spare_buf_stride = 64, + .has_secondary_regs = !0, + .can_be_symmetric = !0, + }; + +struct nfc_hal nfc_3_2_hal = { + .major_version = 3, + .minor_version = 2, + .max_chip_count = 8, + .max_buffer_count = 8, + .spare_buf_stride = 64, + .has_secondary_regs = true, + .can_be_symmetric = true, + .init = nfc_3_2_init, + .set_geometry = nfc_3_2_set_geometry, + .exit = nfc_3_2_exit, + .set_closest_cycle = nfc_3_2_set_closest_cycle, + .mask_interrupt = nfc_3_2_mask_interrupt, + .unmask_interrupt = nfc_3_2_unmask_interrupt, + .clear_interrupt = nfc_3_2_clear_interrupt, + .is_interrupting = nfc_3_2_is_interrupting, + .is_ready = nfc_3_2_is_ready, + .set_force_ce = nfc_3_2_set_force_ce, + .set_ecc = nfc_3_2_set_ecc, + .get_ecc_status = nfc_3_2_get_ecc_status, + .get_symmetric = nfc_3_2_get_symmetric, + .set_symmetric = nfc_3_2_set_symmetric, + .select_chip = nfc_3_2_select_chip, + .command_cycle = nfc_3_2_command_cycle, + .write_cycle = nfc_3_2_write_cycle, + .read_cycle = nfc_3_2_read_cycle, + .read_page = nfc_3_2_read_page, + .send_page = nfc_3_2_send_page, + .start_auto_read = nfc_3_2_start_auto_read, + .wait_for_auto_read = nfc_3_2_wait_for_auto_read, + .resume_auto_read = nfc_3_2_resume_auto_read, + .start_auto_write = nfc_3_2_start_auto_write, + .wait_for_auto_write = nfc_3_2_wait_for_auto_write, + .start_auto_erase = nfc_3_2_start_auto_erase, + }; + +/* + * This array has a pointer to every NFC HAL structure. The probing process will + * find the one that matches the version given by the platform. + */ + +struct nfc_hal *(nfc_hals[]) = { + &nfc_1_0_hal, + &nfc_2_0_hal, + &nfc_2_1_hal, + &nfc_3_1_hal, + &nfc_3_2_hal, +}; + +/** + * mal_init() - Initialize the Medium Abstraction Layer. + * + * @this: Per-device data. + */ +static void mal_init(struct imx_nfc_data *this) +{ + this->interrupt_override = DRIVER_CHOICE; + this->auto_op_override = DRIVER_CHOICE; + this->inject_ecc_error = 0; +} + +/** + * mal_set_physical_geometry() - Set up the physical medium geometry. + * + * This function retrieves the physical geometry information discovered by + * nand_scan(), corrects it, and records it in the per-device data structure. + * + * @this: Per-device data. + */ +static int mal_set_physical_geometry(struct imx_nfc_data *this) +{ + struct mtd_info *mtd = &this->mtd; + struct nand_chip *nand = &this->nand; + struct device *dev = this->dev; + uint8_t manufacturer_id; + uint8_t device_id; + unsigned int block_size_in_pages; + unsigned int chip_size_in_blocks; + unsigned int chip_size_in_pages; + uint64_t medium_size_in_bytes; + struct physical_geometry *physical = &this->physical_geometry; + + /* + * Begin by transcribing exactly what the MTD code discovered. If there + * are any mistakes, we'll fix them in a moment. + */ + + physical->chip_count = nand->numchips; + physical->chip_size = nand->chipsize; + physical->block_size = mtd->erasesize; + physical->page_data_size = mtd->writesize; + physical->page_oob_size = mtd->oobsize; + + /* Read some of the ID bytes from the first NAND Flash chip. */ + + nand->select_chip(mtd, 0); + + nfc_util_send_cmd_and_addrs(this, NAND_CMD_READID, 0x00, -1); + + manufacturer_id = nand->read_byte(mtd); + device_id = nand->read_byte(mtd); + + /* + * Most manufacturers sell 4K page devices with 218 out-of-band bytes + * per page to accomodate ECC-8. + * + * Samsung and Hynix claim their parts have better reliability, so they + * only need ECC-4 and they have only 128 out-of-band bytes. + * + * The MTD code pays no attention to the manufacturer ID (something that + * eventually will have to change), so it believes that all 4K pages + * have 218 out-of-band bytes. + * + * We correct that mistake here. + */ + + if (physical->page_data_size == 4096) { + if ((manufacturer_id == NAND_MFR_SAMSUNG) || + (manufacturer_id == NAND_MFR_HYNIX)) { + physical->page_oob_size = 128; + } + } + + /* Compute some interesting facts. */ + + block_size_in_pages = + physical->block_size / physical->page_data_size; + chip_size_in_pages = + physical->chip_size >> (fls(physical->page_data_size) - 1); + chip_size_in_blocks = + physical->chip_size >> (fls(physical->block_size) - 1); + medium_size_in_bytes = + physical->chip_size * physical->chip_count; + + /* Report. */ + + dev_dbg(dev, "-----------------\n"); + dev_dbg(dev, "Physical Geometry\n"); + dev_dbg(dev, "-----------------\n"); + dev_dbg(dev, "Chip Count : %d\n", physical->chip_count); + dev_dbg(dev, "Page Data Size in Bytes: %u (0x%x)\n", + physical->page_data_size, physical->page_data_size); + dev_dbg(dev, "Page OOB Size in Bytes : %u\n", + physical->page_oob_size); + dev_dbg(dev, "Block Size in Bytes : %u (0x%x)\n", + physical->block_size, physical->block_size); + dev_dbg(dev, "Block Size in Pages : %u (0x%x)\n", + block_size_in_pages, block_size_in_pages); + dev_dbg(dev, "Chip Size in Bytes : %llu (0x%llx)\n", + physical->chip_size, physical->chip_size); + dev_dbg(dev, "Chip Size in Pages : %u (0x%x)\n", + chip_size_in_pages, chip_size_in_pages); + dev_dbg(dev, "Chip Size in Blocks : %u (0x%x)\n", + chip_size_in_blocks, chip_size_in_blocks); + dev_dbg(dev, "Medium Size in Bytes : %llu (0x%llx)\n", + medium_size_in_bytes, medium_size_in_bytes); + + /* Return success. */ + + return 0; + +} + +/** + * mal_set_nfc_geometry() - Set up the NFC geometry. + * + * This function calls the NFC HAL to select an NFC geometry that is compatible + * with the medium's physical geometry. + * + * @this: Per-device data. + */ +static int mal_set_nfc_geometry(struct imx_nfc_data *this) +{ + struct device *dev = this->dev; + struct nfc_geometry *nfc; + + /* Set the NFC geometry. */ + + if (this->nfc->set_geometry(this)) + return !0; + + /* Get a pointer to the new NFC geometry information. */ + + nfc = this->nfc_geometry; + + /* Report. */ + + dev_dbg(dev, "------------\n"); + dev_dbg(dev, "NFC Geometry\n"); + dev_dbg(dev, "------------\n"); + dev_dbg(dev, "Page Data Size in Bytes: %u (0x%x)\n", + nfc->page_data_size, nfc->page_data_size); + dev_dbg(dev, "Page OOB Size in Bytes : %u\n", nfc->page_oob_size); + dev_dbg(dev, "ECC Algorithm : %s\n", nfc->ecc_algorithm); + dev_dbg(dev, "ECC Strength : %d\n", nfc->ecc_strength); + dev_dbg(dev, "Buffer Count : %u\n", nfc->buffer_count); + dev_dbg(dev, "Spare Buffer Size : %u\n", nfc->spare_buf_size); + dev_dbg(dev, "Spare Buffer Spillover : %u\n", nfc->spare_buf_spill); + dev_dbg(dev, "Auto Read Available : %s\n", + this->nfc->start_auto_read ? "Yes" : "No"); + dev_dbg(dev, "Auto Write Available : %s\n", + this->nfc->start_auto_write ? "Yes" : "No"); + dev_dbg(dev, "Auto Erase Available : %s\n", + this->nfc->start_auto_erase ? "Yes" : "No"); + + /* Return success. */ + + return 0; + +} + +/** + * mal_set_logical_geometry() - Set up the logical medium geometry. + * + * This function constructs the logical geometry that we will expose to MTD, + * based on the physical and NFC geometries, and whether or not interleaving is + * on. + * + * @this: Per-device data. + */ +static int mal_set_logical_geometry(struct imx_nfc_data *this) +{ + const uint32_t max_medium_size_in_bytes = ~0; + int we_are_interleaving; + uint64_t physical_medium_size_in_bytes; + unsigned int usable_blocks; + unsigned int block_size_in_pages; + unsigned int chip_size_in_blocks; + unsigned int chip_size_in_pages; + unsigned int usable_medium_size_in_pages; + unsigned int usable_medium_size_in_blocks; + struct physical_geometry *physical = &this->physical_geometry; + struct nfc_geometry *nfc = this->nfc_geometry; + struct logical_geometry *logical = &this->logical_geometry; + struct device *dev = this->dev; + + /* Figure out if we're interleaving. */ + + we_are_interleaving = this->pdata->interleave; + + switch (imx_nfc_module_interleave_override) { + + case NEVER: + we_are_interleaving = false; + break; + + case DRIVER_CHOICE: + break; + + case ALWAYS: + we_are_interleaving = true; + break; + + } + + /* Compute the physical size of the medium. */ + + physical_medium_size_in_bytes = + physical->chip_count * physical->chip_size; + + /* Compute the logical geometry. */ + + if (!we_are_interleaving) { + + /* + * At this writing, MTD uses unsigned 32-bit variables to + * represent the size of the medium. If the physical medium is + * larger than that, the logical medium must be smaller. Here, + * we compute the total number of physical blocks in the medium + * that we can actually use. + */ + + if (physical_medium_size_in_bytes <= max_medium_size_in_bytes) { + usable_blocks = + physical_medium_size_in_bytes >> + (ffs(physical->block_size) - 1); + } else { + usable_blocks = + max_medium_size_in_bytes / physical->block_size; + } + + /* Set up the logical geometry. + * + * Notice that the usable medium size is not necessarily the + * same as the chip size multiplied by the number of physical + * chips. We can't afford to touch the physical chip size + * because the NAND Flash MTD code *requires* it to be a power + * of 2. + */ + + logical->chip_count = physical->chip_count; + logical->chip_size = physical->chip_size; + logical->usable_size = usable_blocks * physical->block_size; + logical->block_size = physical->block_size; + logical->page_data_size = nfc->page_data_size; + + /* Use the MTD layout that best matches the NFC geometry. */ + + logical->mtd_layout = &nfc->mtd_layout; + logical->page_oob_size = nfc->mtd_layout.eccbytes + + nfc->mtd_layout.oobavail; + + } else { + + /* + * If control arrives here, we are interleaving. Specifically, + * we are "horizontally concatenating" the pages in all the + * physical chips. + * + * - A logical page will be the size of a physical page + * multiplied by the number of physical chips. + * + * - A logical block will have the same number of pages as a + * physical block but, since the logical page size is larger, + * the logical block size is larger. + * + * - The entire medium will appear to be a single chip. + * + * At this writing, MTD uses unsigned 32-bit variables to + * represent the size of the medium. If the physical medium is + * larger than that, the logical medium must be smaller. + * + * The NAND Flash MTD code represents the size of a single chip + * as an unsigned 32-bit value. It also *requires* that the size + * of a chip be a power of two. Thus, the largest possible chip + * size is 2GiB. + * + * When interleaving, the entire medium appears to be one chip. + * Thus, when interleaving, the largest possible medium size is + * 2GiB. + */ + + if (physical_medium_size_in_bytes <= max_medium_size_in_bytes) { + logical->chip_size = + 0x1 << (fls(physical_medium_size_in_bytes) - 1); + } else { + logical->chip_size = + 0x1 << (fls(max_medium_size_in_bytes) - 1); + } + + /* + * If control arrives here, we're interleaving. The logical + * geometry is very different from the physical geometry. + */ + + logical->chip_count = 1; + logical->usable_size = logical->chip_size; + logical->block_size = + physical->block_size * physical->chip_count; + logical->page_data_size = + nfc->page_data_size * physical->chip_count; + + /* + * Since the logical geometry doesn't match the physical + * geometry, we can't use the MTD layout that matches the + * NFC geometry. We synthesize one here. + * + * Our "logical" OOB will be the concatenation of the first 5 + * bytes of the "physical" OOB of every chip. This has some + * important properties: + * + * - This will make the block mark of every physical chip + * visible (even for small page chips, which put their block + * mark in the 5th OOB byte). + * + * - None of the NFC controllers put ECC in the first 5 OOB + * bytes, so this layout exposes no ECC. + */ + + logical->page_oob_size = 5 * physical->chip_count; + + synthetic_layout.eccbytes = 0; + synthetic_layout.oobavail = 5 * physical->chip_count; + synthetic_layout.oobfree[0].offset = 0; + synthetic_layout.oobfree[0].length = synthetic_layout.oobavail; + + /* Install the synthetic layout. */ + + logical->mtd_layout = &synthetic_layout; + + } + + /* Compute some interesting facts. */ + + block_size_in_pages = logical->block_size / logical->page_data_size; + chip_size_in_pages = logical->chip_size / logical->page_data_size; + chip_size_in_blocks = logical->chip_size / logical->block_size; + usable_medium_size_in_pages = + logical->usable_size / logical->page_data_size; + usable_medium_size_in_blocks = + logical->usable_size / logical->block_size; + + /* Report. */ + + dev_dbg(dev, "----------------\n"); + dev_dbg(dev, "Logical Geometry\n"); + dev_dbg(dev, "----------------\n"); + dev_dbg(dev, "Chip Count : %d\n", logical->chip_count); + dev_dbg(dev, "Page Data Size in Bytes: %u (0x%x)\n", + logical->page_data_size, logical->page_data_size); + dev_dbg(dev, "Page OOB Size in Bytes : %u\n", + logical->page_oob_size); + dev_dbg(dev, "Block Size in Bytes : %u (0x%x)\n", + logical->block_size, logical->block_size); + dev_dbg(dev, "Block Size in Pages : %u (0x%x)\n", + block_size_in_pages, block_size_in_pages); + dev_dbg(dev, "Chip Size in Bytes : %u (0x%x)\n", + logical->chip_size, logical->chip_size); + dev_dbg(dev, "Chip Size in Pages : %u (0x%x)\n", + chip_size_in_pages, chip_size_in_pages); + dev_dbg(dev, "Chip Size in Blocks : %u (0x%x)\n", + chip_size_in_blocks, chip_size_in_blocks); + dev_dbg(dev, "Physical Size in Bytes : %llu (0x%llx)\n", + physical_medium_size_in_bytes, physical_medium_size_in_bytes); + dev_dbg(dev, "Usable Size in Bytes : %u (0x%x)\n", + logical->usable_size, logical->usable_size); + dev_dbg(dev, "Usable Size in Pages : %u (0x%x)\n", + usable_medium_size_in_pages, usable_medium_size_in_pages); + dev_dbg(dev, "Usable Size in Blocks : %u (0x%x)\n", + usable_medium_size_in_blocks, usable_medium_size_in_blocks); + + /* Return success. */ + + return 0; + +} + +/** + * mal_set_mtd_geometry() - Set up the MTD geometry. + * + * This function adjusts the owning MTD data structures to match the logical + * geometry we've chosen. + * + * @this: Per-device data. + */ +static int mal_set_mtd_geometry(struct imx_nfc_data *this) +{ + struct logical_geometry *logical = &this->logical_geometry; + struct mtd_info *mtd = &this->mtd; + struct nand_chip *nand = &this->nand; + + /* Configure the struct mtd_info. */ + + mtd->size = logical->usable_size; + mtd->erasesize = logical->block_size; + mtd->writesize = logical->page_data_size; + mtd->ecclayout = logical->mtd_layout; + mtd->oobavail = mtd->ecclayout->oobavail; + mtd->oobsize = mtd->ecclayout->oobavail + mtd->ecclayout->eccbytes; + mtd->subpage_sft = 0; /* We don't support sub-page writing. */ + + /* Configure the struct nand_chip. */ + + nand->numchips = logical->chip_count; + nand->chipsize = logical->chip_size; + nand->page_shift = ffs(logical->page_data_size) - 1; + nand->pagemask = (nand->chipsize >> nand->page_shift) - 1; + nand->subpagesize = mtd->writesize >> mtd->subpage_sft; + nand->phys_erase_shift = ffs(logical->block_size) - 1; + nand->bbt_erase_shift = nand->phys_erase_shift; + nand->chip_shift = ffs(logical->chip_size) - 1; + nand->oob_poi = nand->buffers->databuf+logical->page_data_size; + nand->ecc.layout = logical->mtd_layout; + + /* Set up the pattern that describes block marks. */ + + if (is_small_page_chip(this)) + nand->badblock_pattern = &small_page_block_mark_descriptor; + else + nand->badblock_pattern = &large_page_block_mark_descriptor; + + /* Return success. */ + + return 0; +} + +/** + * mal_set_geometry() - Set up the medium geometry. + * + * @this: Per-device data. + */ +static int mal_set_geometry(struct imx_nfc_data *this) +{ + + /* Set up the various layers of geometry, in this specific order. */ + + if (mal_set_physical_geometry(this)) + return !0; + + if (mal_set_nfc_geometry(this)) + return !0; + + if (mal_set_logical_geometry(this)) + return !0; + + if (mal_set_mtd_geometry(this)) + return !0; + + /* Return success. */ + + return 0; + +} + +/** + * mal_reset() - Resets the given chip. + * + * This is the fully-generalized reset operation, including support for + * interleaving. All reset operations funnel through here. + * + * @this: Per-device data. + * @chip: The logical chip of interest. + */ +static void mal_reset(struct imx_nfc_data *this, unsigned chip) +{ + int we_are_interleaving; + unsigned int start; + unsigned int end; + unsigned int i; + struct physical_geometry *physical = &this->physical_geometry; + struct logical_geometry *logical = &this->logical_geometry; + + add_event("Entering mal_get_status", 1); + + /* Establish some important facts. */ + + we_are_interleaving = logical->chip_count != physical->chip_count; + + /* Choose the loop bounds. */ + + if (we_are_interleaving) { + start = 0; + end = physical->chip_count; + } else { + start = chip; + end = start + 1; + } + + /* Loop over physical chips. */ + + add_event("Looping over physical chips...", 0); + + for (i = start; i < end; i++) { + + /* Select the current chip. */ + + this->nfc->select_chip(this, i); + + /* Reset the current chip. */ + + add_event("Resetting...", 0); + + nfc_util_send_cmd(this, NAND_CMD_RESET); + nfc_util_wait_for_the_nfc(this, false); + + } + + add_event("Exiting mal_get_status", -1); + +} + +/** + * mal_get_status() - Abstracted status retrieval. + * + * For media with a single chip, or concatenated chips, the HIL explicitly + * addresses a single chip at a time and wants the status from that chip only. + * + * For interleaved media, we must combine the individual chip states. At this + * writing, the NAND MTD system knows about the following bits in status + * registers: + * + * +------------------------+-------+---------+ + * | | | Combine | + * | Macro | Value | With | + * +------------------------+-------+---------+ + * | NAND_STATUS_FAIL | 0x01 | OR | + * | NAND_STATUS_FAIL_N1 | 0x02 | OR | + * | NAND_STATUS_TRUE_READY | 0x20 | AND | + * | NAND_STATUS_READY | 0x40 | AND | + * | NAND_STATUS_WP | 0x80 | AND | + * +------------------------+-------+---------+ + * + * @this: Per-device data. + * @chip: The logical chip of interest. + */ +static uint8_t mal_get_status(struct imx_nfc_data *this, unsigned chip) +{ + int we_are_interleaving; + unsigned int start; + unsigned int end; + unsigned int i; + unsigned int x; + unsigned int or_mask; + unsigned int and_mask; + uint8_t status; + struct physical_geometry *physical = &this->physical_geometry; + struct logical_geometry *logical = &this->logical_geometry; + + add_event("Entering mal_get_status", 1); + + /* Establish some important facts. */ + + we_are_interleaving = logical->chip_count != physical->chip_count; + + /* Compute the masks we need. */ + + or_mask = NAND_STATUS_FAIL | NAND_STATUS_FAIL_N1; + and_mask = NAND_STATUS_TRUE_READY | NAND_STATUS_READY | NAND_STATUS_WP; + + /* Assume the chip is successful, ready and writeable. */ + + status = and_mask & ~or_mask; + + /* Choose the loop bounds. */ + + if (we_are_interleaving) { + start = 0; + end = physical->chip_count; + } else { + start = chip; + end = start + 1; + } + + /* Loop over physical chips. */ + + add_event("Looping over physical chips...", 0); + + for (i = start; i < end; i++) { + + /* Select the current chip. */ + + this->nfc->select_chip(this, i); + + /* Get the current chip's status. */ + + add_event("Sending the command...", 0); + + nfc_util_send_cmd(this, NAND_CMD_STATUS); + nfc_util_wait_for_the_nfc(this, false); + + add_event("Reading the status...", 0); + + x = this->nfc->read_cycle(this); + + /* Fold this chip's status into the combined status. */ + + status |= (x & or_mask); + status &= (x & and_mask) | or_mask; + + } + + add_event("Exiting mal_get_status", -1); + + return status; + +} + +/** + * mal_read_a_page() - Abstracted page read. + * + * This function returns the ECC status for the entire read operation. A + * positive return value indicates the number of errors that were corrected + * (symbol errors for Reed-Solomon hardware engines, bit errors for BCH hardware + * engines). A negative return value indicates that the ECC engine failed to + * correct all errors and the data is corrupted. A zero return value indicates + * there were no errors at all. + * + * @this: Per-device data. + * @use_ecc: Indicates if we're to use ECC. + * @chip: The logical chip of interest. + * @page: The logical page number to read. + * @data: A pointer to the destination data buffer. If this pointer is null, + * that indicates the caller doesn't want the data. + * @oob: A pointer to the destination OOB buffer. If this pointer is null, + * that indicates the caller doesn't want the OOB. + */ +static int mal_read_a_page(struct imx_nfc_data *this, int use_ecc, + unsigned chip, unsigned page, uint8_t *data, uint8_t *oob) +{ + int we_are_interleaving; + int use_automatic_op; + unsigned int start; + unsigned int end; + unsigned int current_chip; + unsigned int oob_bytes_to_copy; + unsigned int data_bytes_to_copy; + int status; + unsigned int worst_case_ecc_status; + int return_value = 0; + struct physical_geometry *physical = &this->physical_geometry; + struct nfc_geometry *nfc = this->nfc_geometry; + struct logical_geometry *logical = &this->logical_geometry; + + add_event("Entering mal_read_a_page", 1); + + /* Establish some important facts. */ + + we_are_interleaving = logical->chip_count != physical->chip_count; + use_automatic_op = !!this->nfc->start_auto_read; + + /* Apply the automatic operation override, if any. */ + + switch (this->auto_op_override) { + + case NEVER: + use_automatic_op = false; + break; + + case DRIVER_CHOICE: + break; + + case ALWAYS: + if (this->nfc->start_auto_read) + use_automatic_op = true; + break; + + } + + /* Set up ECC. */ + + this->nfc->set_ecc(this, use_ecc); + + /* Check if we're interleaving and set up the loop iterations. */ + + if (we_are_interleaving) { + + start = 0; + end = physical->chip_count; + + data_bytes_to_copy = + this->logical_geometry.page_data_size / + this->physical_geometry.chip_count; + oob_bytes_to_copy = + this->logical_geometry.page_oob_size / + this->physical_geometry.chip_count; + + } else { + + start = chip; + end = start + 1; + + data_bytes_to_copy = this->logical_geometry.page_data_size; + oob_bytes_to_copy = this->logical_geometry.page_oob_size; + + } + + /* If we're using the automatic operation, start it now. */ + + if (use_automatic_op) { + add_event("Starting the automatic operation...", 0); + this->nfc->start_auto_read(this, start, end - start, 0, page); + } + + /* Loop over physical chips. */ + + add_event("Looping over physical chips...", 0); + + for (current_chip = start; current_chip < end; current_chip++) { + + /* Check if we're using the automatic operation. */ + + if (use_automatic_op) { + + add_event("Waiting...", 0); + this->nfc->wait_for_auto_read(this); + + } else { + + /* Select the current chip. */ + + this->nfc->select_chip(this, current_chip); + + /* Set up the chip. */ + + add_event("Sending the command and addresses...", 0); + + nfc_util_send_cmd_and_addrs(this, + NAND_CMD_READ0, 0, page); + + if (is_large_page_chip(this)) { + add_event("Sending the final command...", 0); + nfc_util_send_cmd(this, NAND_CMD_READSTART); + } + + /* Wait till the page is ready. */ + + add_event("Waiting for the page to arrive...", 0); + + nfc_util_wait_for_the_nfc(this, true); + + /* Read the page. */ + + add_event("Reading the page...", 0); + + this->nfc->read_page(this); + + } + + /* Copy a page out of the NFC. */ + + add_event("Copying from the NFC...", 0); + + if (oob) { + nfc_util_copy_from_the_nfc(this, + nfc->page_data_size, oob, oob_bytes_to_copy); + oob += oob_bytes_to_copy; + } + + if (data) { + nfc_util_copy_from_the_nfc(this, + 0, data, data_bytes_to_copy); + data += data_bytes_to_copy; + } + + /* + * If we're using ECC, and we haven't already seen an ECC + * failure, continue to gather ECC status. Note that, if we + * *do* see an ECC failure, we continue to read because the + * client might want the data for forensic purposes. + */ + + if (use_ecc && (return_value >= 0)) { + + add_event("Getting ECC status...", 0); + + status = this->nfc->get_ecc_status(this); + + if (status >= 0) + return_value += status; + else + return_value = -1; + + } + + /* Check if we're using the automatic operation. */ + + if (use_automatic_op) { + + /* + * If this is not the last iteration, resume the + * automatic operation. + */ + + if (current_chip < (end - 1)) { + add_event("Resuming...", 0); + this->nfc->resume_auto_read(this); + } + + } + + } + + /* Check if we're supposed to inject an ECC error. */ + + if (use_ecc && this->inject_ecc_error) { + + /* Inject the appropriate error. */ + + if (this->inject_ecc_error < 0) { + + add_event("Injecting an uncorrectable error...", 0); + + return_value = -1; + + } else { + + add_event("Injecting correctable errors...", 0); + + worst_case_ecc_status = + physical->chip_count * + nfc->buffer_count * + nfc->ecc_strength; + + if (this->inject_ecc_error > worst_case_ecc_status) + return_value = worst_case_ecc_status; + else + return_value = this->inject_ecc_error; + + } + + /* Stop injecting further errors. */ + + this->inject_ecc_error = 0; + + } + + /* Return. */ + + add_event("Exiting mal_read_a_page", -1); + + return return_value; + +} + +/** + * mal_write_a_page() - Abstracted page write. + * + * This function returns zero if the operation succeeded, or -EIO if the + * operation failed. + * + * @this: Per-device data. + * @use_ecc: Indicates if we're to use ECC. + * @chip: The logical chip of interest. + * @page: The logical page number to write. + * @data: A pointer to the source data buffer. + * @oob: A pointer to the source OOB buffer. + */ +static int mal_write_a_page(struct imx_nfc_data *this, int use_ecc, + unsigned chip, unsigned page, const uint8_t *data, const uint8_t *oob) +{ + int we_are_interleaving; + int use_automatic_op; + unsigned int start; + unsigned int end; + unsigned int current_chip; + unsigned int oob_bytes_to_copy; + unsigned int data_bytes_to_copy; + int return_value = 0; + struct physical_geometry *physical = &this->physical_geometry; + struct nfc_geometry *nfc = this->nfc_geometry; + struct logical_geometry *logical = &this->logical_geometry; + + add_event("Entering mal_write_a_page", 1); + + /* Establish some important facts. */ + + we_are_interleaving = logical->chip_count != physical->chip_count; + use_automatic_op = !!this->nfc->start_auto_write; + + /* Apply the automatic operation override, if any. */ + + switch (this->auto_op_override) { + + case NEVER: + use_automatic_op = false; + break; + + case DRIVER_CHOICE: + break; + + case ALWAYS: + if (this->nfc->start_auto_write) + use_automatic_op = true; + break; + + } + + /* Set up ECC. */ + + this->nfc->set_ecc(this, use_ecc); + + /* Check if we're interleaving and set up the loop iterations. */ + + if (we_are_interleaving) { + + start = 0; + end = physical->chip_count; + + data_bytes_to_copy = + this->logical_geometry.page_data_size / + this->physical_geometry.chip_count; + oob_bytes_to_copy = + this->logical_geometry.page_oob_size / + this->physical_geometry.chip_count; + + } else { + + start = chip; + end = start + 1; + + data_bytes_to_copy = this->logical_geometry.page_data_size; + oob_bytes_to_copy = this->logical_geometry.page_oob_size; + + } + + /* If we're using the automatic operation, start the hardware now. */ + + if (use_automatic_op) { + add_event("Starting the automatic operation...", 0); + this->nfc->start_auto_write(this, start, end - start, 0, page); + } + + /* Loop over physical chips. */ + + add_event("Looping over physical chips...", 0); + + for (current_chip = start; current_chip < end; current_chip++) { + + /* Copy a page into the NFC. */ + + add_event("Copying to the NFC...", 0); + + nfc_util_copy_to_the_nfc(this, oob, nfc->page_data_size, + oob_bytes_to_copy); + oob += oob_bytes_to_copy; + + nfc_util_copy_to_the_nfc(this, data, 0, data_bytes_to_copy); + + data += data_bytes_to_copy; + + /* Check if we're using the automatic operation. */ + + if (use_automatic_op) { + + /* Wait for the write operation to finish. */ + + add_event("Waiting...", 0); + + this->nfc->wait_for_auto_write(this); + + } else { + + /* Select the current chip. */ + + this->nfc->select_chip(this, current_chip); + + /* Set up the chip. */ + + add_event("Sending the command and addresses...", 0); + + nfc_util_send_cmd_and_addrs(this, + NAND_CMD_SEQIN, 0, page); + + /* Send the page. */ + + add_event("Sending the page...", 0); + + this->nfc->send_page(this); + + /* Start programming the page. */ + + add_event("Programming the page...", 0); + + nfc_util_send_cmd(this, NAND_CMD_PAGEPROG); + + /* Wait until the page is finished. */ + + add_event("Waiting...", 0); + + nfc_util_wait_for_the_nfc(this, true); + + } + + } + + /* Get status. */ + + add_event("Gathering status...", 0); + + if (mal_get_status(this, chip) & NAND_STATUS_FAIL) { + add_event("Bad status", 0); + return_value = -EIO; + } else { + add_event("Good status", 0); + } + + /* Return. */ + + add_event("Exiting mal_write_a_page", -1); + + return return_value; + +} + +/** + * mal_erase_a_block() - Abstract block erase operation. + * + * Note that this function does *not* wait for the operation to finish. The + * caller is expected to call waitfunc() at some later time. + * + * @this: Per-device data. + * @chip: The logical chip of interest. + * @page: A logical page address that identifies the block to erase. + */ +static void mal_erase_a_block(struct imx_nfc_data *this, + unsigned chip, unsigned page) +{ + int we_are_interleaving; + int use_automatic_op; + unsigned int start; + unsigned int end; + unsigned int i; + struct physical_geometry *physical = &this->physical_geometry; + struct logical_geometry *logical = &this->logical_geometry; + + add_event("Entering mal_erase_a_block", 1); + + /* Establish some important facts. */ + + we_are_interleaving = logical->chip_count != physical->chip_count; + use_automatic_op = !!this->nfc->start_auto_erase; + + /* Apply the automatic operation override, if any. */ + + switch (this->auto_op_override) { + + case NEVER: + use_automatic_op = false; + break; + + case DRIVER_CHOICE: + break; + + case ALWAYS: + if (this->nfc->start_auto_erase) + use_automatic_op = true; + break; + + } + + /* Choose the loop bounds. */ + + if (we_are_interleaving) { + start = 0; + end = physical->chip_count; + } else { + start = chip; + end = start + 1; + } + + /* Check if we're using the automatic operation. */ + + if (use_automatic_op) { + + /* + * Start the operation. Note that we don't wait for it to + * finish because the HIL will call our waitfunc(). + */ + + add_event("Starting the automatic operation...", 0); + + this->nfc->start_auto_erase(this, start, end - start, page); + + } else { + + /* Loop over physical chips. */ + + add_event("Looping over physical chips...", 0); + + for (i = start; i < end; i++) { + + /* Select the current chip. */ + + this->nfc->select_chip(this, i); + + /* Set up the chip. */ + + nfc_util_send_cmd_and_addrs(this, + NAND_CMD_ERASE1, -1, page); + + /* Start the erase. */ + + nfc_util_send_cmd(this, NAND_CMD_ERASE2); + + /* + * If this is the last time through the loop, break out + * now so we don't try to wait (the HIL will call our + * waitfunc() for the final wait). + */ + + if (i >= (end - 1)) + break; + + /* Wait for the erase on the current chip to finish. */ + + nfc_util_wait_for_the_nfc(this, true); + + } + + } + + add_event("Exiting mal_erase_a_block", -1); + +} + +/** + * mal_is_block_bad() - Abstract bad block check. + * + * @this: Per-device data. + * @chip: The logical chip of interest. + * @page: The logical page number to read. + */ + #if 0 + +/* TODO: Finish this function and plug it in. */ + +static int mal_is_block_bad(struct imx_nfc_data *this, + unsigned chip, unsigned page) +{ + int we_are_interleaving; + unsigned int start; + unsigned int end; + unsigned int i; + uint8_t *p; + int return_value = 0; + struct nand_chip *nand = &this->nand; + struct physical_geometry *physical = &this->physical_geometry; + struct logical_geometry *logical = &this->logical_geometry; + + /* Figure out if we're interleaving. */ + + we_are_interleaving = logical->chip_count != physical->chip_count; + + /* + * We're about to use the NAND Flash MTD layer's buffer, so invalidate + * the page cache. + */ + + this->nand.pagebuf = -1; + + /* + * Read the OOB of the given page, using the NAND Flash MTD's buffer. + * + * Notice that ECC is off, which it *must* be when scanning block marks. + */ + + mal_read_a_page(this, false, + this->current_chip, this->page_address, 0, nand->oob_poi); + + /* Choose the loop bounds. */ + + if (we_are_interleaving) { + start = 0; + end = physical->chip_count; + } else { + start = chip; + end = start + 1; + } + + /* Start scanning at the beginning of the OOB data. */ + + p = nand->oob_poi; + + /* Loop over physical chips. */ + + add_event("Looping over physical chips...", 0); + + for (i = start; i < end; i++, p += 5) { + + /* Examine the OOB for this chip. */ + + if (p[nand->badblockpos] != 0xff) { + return_value = !0; + break; + } + + } + + /* Return. */ + + return return_value; + +} +#endif + +/** + * mil_init() - Initializes the MTD Interface Layer. + * + * @this: Per-device data. + */ +static void mil_init(struct imx_nfc_data *this) +{ + this->current_chip = -1; /* No chip is selected yet. */ + this->command_is_new = false; /* No command yet. */ +} + +/** + * mil_cmd_ctrl() - MTD Interface cmd_ctrl() + * + * @mtd: A pointer to the owning MTD. + * @dat: The data signals to present to the chip. + * @ctrl: The control signals to present to the chip. + */ +static void mil_cmd_ctrl(struct mtd_info *mtd, int dat, unsigned int ctrl) +{ + struct nand_chip *nand = mtd->priv; + struct imx_nfc_data *this = nand->priv; + unimplemented(this, __func__); +} + +/** + * mil_dev_ready() - MTD Interface dev_ready() + * + * @mtd: A pointer to the owning MTD. + */ +static int mil_dev_ready(struct mtd_info *mtd) +{ + struct nand_chip *nand = mtd->priv; + struct imx_nfc_data *this = nand->priv; + + DEBUG(MTD_DEBUG_LEVEL2, "[imx_nfc dev_ready]\n"); + + add_event("Entering mil_dev_ready", 1); + + if (this->nfc->is_ready(this)) { + add_event("Exiting mil_dev_ready - Returning ready", -1); + return !0; + } else { + add_event("Exiting mil_dev_ready - Returning busy", -1); + return 0; + } + +} + +/** + * mil_select_chip() - MTD Interface select_chip() + * + * @mtd: A pointer to the owning MTD. + * @chip: The chip number to select, or -1 to select no chip. + */ +static void mil_select_chip(struct mtd_info *mtd, int chip) +{ + struct nand_chip *nand = mtd->priv; + struct imx_nfc_data *this = nand->priv; + + DEBUG(MTD_DEBUG_LEVEL2, "[imx_nfc select_chip] chip: %d\n", chip); + + /* Figure out what kind of transition this is. */ + + if ((this->current_chip < 0) && (chip >= 0)) { + start_event_trace("Entering mil_select_chip"); + if (this->pdata->force_ce) + this->nfc->set_force_ce(this, true); + clk_enable(this->clock); + add_event("Exiting mil_select_chip", -1); + } else if ((this->current_chip >= 0) && (chip < 0)) { + add_event("Entering mil_select_chip", 1); + if (this->pdata->force_ce) + this->nfc->set_force_ce(this, false); + clk_disable(this->clock); + stop_event_trace("Exiting mil_select_chip"); + } else { + add_event("Entering mil_select_chip", 1); + add_event("Exiting mil_select_chip", -1); + } + + this->current_chip = chip; + +} + +/** + * mil_cmdfunc() - MTD Interface cmdfunc() + * + * This function handles NAND Flash command codes from the HIL. Since only the + * HIL calls this function (none of the reference implementations we use do), it + * needs to handle very few command codes. + * + * @mtd: A pointer to the owning MTD. + * @command: The command code. + * @column: The column address associated with this command code, or -1 if no + * column address applies. + * @page: The page address associated with this command code, or -1 if no + * page address applies. + */ +static void mil_cmdfunc(struct mtd_info *mtd, + unsigned command, int column, int page) +{ + struct nand_chip *nand = mtd->priv; + struct imx_nfc_data *this = nand->priv; + + DEBUG(MTD_DEBUG_LEVEL2, "[imx_nfc cmdfunc] command: 0x%02x, " + "column: 0x%04x, page: 0x%06x\n", command, column, page); + + add_event("Entering mil_cmdfunc", 1); + + /* Record the command and the fact that it hasn't yet been sent. */ + + this->command = command; + this->command_is_new = true; + + /* + * Process the command code. + * + * Note the default case to trap unrecognized codes. Thus, every command + * we support must have a case here, even if we don't have to do any + * pre-processing work. If the HIL changes and starts sending commands + * we haven't explicitly implemented, this will warn us. + */ + + switch (command) { + + case NAND_CMD_READ0: + add_event("NAND_CMD_READ0", 0); + /* + * After calling this function to send the command and + * addresses, the HIL will call ecc.read_page() or + * ecc.read_page_raw() to collect the data. + * + * The column address from the HIL is always zero. The only + * information we need to keep from this call is the page + * address. + */ + this->page_address = page; + break; + + case NAND_CMD_STATUS: + add_event("NAND_CMD_STATUS", 0); + /* + * After calling this function to send the command, the HIL + * will call read_byte() once to collect the status. + */ + break; + + case NAND_CMD_READID: + add_event("NAND_CMD_READID", 0); + /* + * After calling this function to send the command, the HIL + * will call read_byte() repeatedly to collect ID bytes. + */ + break; + + case NAND_CMD_RESET: + add_event("NAND_CMD_RESET", 0); + mal_reset(this, this->current_chip); + break; + + default: + dev_emerg(this->dev, "Unsupported NAND Flash command code: " + "0x%02x\n", command); + BUG(); + break; + + } + + add_event("Exiting mil_cmdfunc", -1); + +} + +/** + * mil_waitfunc() - MTD Interface waifunc() + * + * This function blocks until the current chip is ready and then returns the + * contents of the chip's status register. The HIL only calls this function + * after starting an erase operation. + * + * @mtd: A pointer to the owning MTD. + * @nand: A pointer to the owning NAND Flash MTD. + */ +static int mil_waitfunc(struct mtd_info *mtd, struct nand_chip *nand) +{ + int status; + struct imx_nfc_data *this = nand->priv; + + DEBUG(MTD_DEBUG_LEVEL2, "[imx_nfc waitfunc]\n"); + + add_event("Entering mil_waitfunc", 1); + + /* Wait for the NFC to finish. */ + + nfc_util_wait_for_the_nfc(this, true); + + /* Get the status. */ + + status = mal_get_status(this, this->current_chip); + + add_event("Exiting mil_waitfunc", -1); + + return status; + +} + +/** + * mil_read_byte() - MTD Interface read_byte(). + * + * @mtd: A pointer to the owning MTD. + */ +static uint8_t mil_read_byte(struct mtd_info *mtd) +{ + uint8_t byte = 0; + struct nand_chip *nand = mtd->priv; + struct imx_nfc_data *this = nand->priv; + + add_event("Entering mil_read_byte", 1); + + /* + * The command sent by the HIL before it called this function determines + * how we get the byte we're going to return. + */ + + switch (this->command) { + + case NAND_CMD_STATUS: + add_event("NAND_CMD_STATUS", 0); + byte = mal_get_status(this, this->current_chip); + break; + + case NAND_CMD_READID: + add_event("NAND_CMD_READID", 0); + + /* + * Check if the command is new. If so, then the HIL just + * recently called cmdfunc(), so the current chip isn't selected + * and the command hasn't been sent to the chip. + */ + + if (this->command_is_new) { + add_event("Sending the \"Read ID\" command...", 0); + this->nfc->select_chip(this, this->current_chip); + nfc_util_send_cmd_and_addrs(this, + NAND_CMD_READID, 0, -1); + this->command_is_new = false; + } + + /* Read the ID byte. */ + + add_event("Reading the ID byte...", 0); + + byte = this->nfc->read_cycle(this); + + break; + + default: + dev_emerg(this->dev, "Unsupported NAND Flash command code: " + "0x%02x\n", this->command); + BUG(); + break; + + } + + DEBUG(MTD_DEBUG_LEVEL2, + "[imx_nfc read_byte] Returning: 0x%02x\n", byte); + + add_event("Exiting mil_read_byte", -1); + + return byte; + +} + +/** + * mil_read_word() - MTD Interface read_word(). + * + * @mtd: A pointer to the owning MTD. + */ +static uint16_t mil_read_word(struct mtd_info *mtd) +{ + struct nand_chip *nand = mtd->priv; + struct imx_nfc_data *this = nand->priv; + unimplemented(this, __func__); + return 0; +} + +/** + * mil_read_buf() - MTD Interface read_buf(). + * + * @mtd: A pointer to the owning MTD. + * @buf: The destination buffer. + * @len: The number of bytes to read. + */ +static void mil_read_buf(struct mtd_info *mtd, uint8_t * buf, int len) +{ + struct nand_chip *nand = mtd->priv; + struct imx_nfc_data *this = nand->priv; + unimplemented(this, __func__); +} + +/** + * mil_write_buf() - MTD Interface write_buf(). + * + * @mtd: A pointer to the owning MTD. + * @buf: The source buffer. + * @len: The number of bytes to read. + */ +static void mil_write_buf(struct mtd_info *mtd, const uint8_t * buf, int len) +{ + struct nand_chip *nand = mtd->priv; + struct imx_nfc_data *this = nand->priv; + unimplemented(this, __func__); +} + +/** + * mil_verify_buf() - MTD Interface verify_buf(). + * + * @mtd: A pointer to the owning MTD. + * @buf: The destination buffer. + * @len: The number of bytes to read. + */ +static int mil_verify_buf(struct mtd_info *mtd, const uint8_t *buf, int len) +{ + struct nand_chip *nand = mtd->priv; + struct imx_nfc_data *this = nand->priv; + unimplemented(this, __func__); + return 0; +} + +/** + * mil_ecc_hwctl() - MTD Interface ecc.hwctl(). + * + * @mtd: A pointer to the owning MTD. + * @mode: The ECC mode. + */ +static void mil_ecc_hwctl(struct mtd_info *mtd, int mode) +{ + struct nand_chip *nand = mtd->priv; + struct imx_nfc_data *this = nand->priv; + unimplemented(this, __func__); +} + +/** + * mil_ecc_calculate() - MTD Interface ecc.calculate(). + * + * @mtd: A pointer to the owning MTD. + * @dat: A pointer to the source data. + * @ecc_code: A pointer to a buffer that will receive the resulting ECC. + */ +static int mil_ecc_calculate(struct mtd_info *mtd, + const uint8_t *dat, uint8_t *ecc_code) +{ + struct nand_chip *nand = mtd->priv; + struct imx_nfc_data *this = nand->priv; + unimplemented(this, __func__); + return 0; +} + +/** + * mil_ecc_correct() - MTD Interface ecc.correct(). + * + * @mtd: A pointer to the owning MTD. + * @dat: A pointer to the source data. + * @read_ecc: A pointer to the ECC that was read from the medium. + * @calc_ecc: A pointer to the ECC that was calculated for the source data. + */ +static int mil_ecc_correct(struct mtd_info *mtd, + uint8_t *dat, uint8_t *read_ecc, uint8_t *calc_ecc) +{ + struct nand_chip *nand = mtd->priv; + struct imx_nfc_data *this = nand->priv; + unimplemented(this, __func__); + return 0; +} + +/** + * mil_ecc_read_page() - MTD Interface ecc.read_page(). + * + * @mtd: A pointer to the owning MTD. + * @nand: A pointer to the owning NAND Flash MTD. + * @buf: A pointer to the destination buffer. + */ +static int mil_ecc_read_page(struct mtd_info *mtd, + struct nand_chip *nand, uint8_t *buf) +{ + int ecc_status; + struct imx_nfc_data *this = nand->priv; + + DEBUG(MTD_DEBUG_LEVEL2, "[imx_nfc ecc_read_page]\n"); + + add_event("Entering mil_ecc_read_page", 1); + + /* Read the page. */ + + ecc_status = + mal_read_a_page(this, true, this->current_chip, + this->page_address, buf, nand->oob_poi); + + /* Propagate ECC information. */ + + if (ecc_status < 0) { + add_event("ECC Failure", 0); + mtd->ecc_stats.failed++; + } else if (ecc_status > 0) { + add_event("ECC Corrections", 0); + mtd->ecc_stats.corrected += ecc_status; + } + + add_event("Exiting mil_ecc_read_page", -1); + + return 0; + +} + +/** + * mil_ecc_read_page_raw() - MTD Interface ecc.read_page_raw(). + * + * @mtd: A pointer to the owning MTD. + * @nand: A pointer to the owning NAND Flash MTD. + * @buf: A pointer to the destination buffer. + */ +static int mil_ecc_read_page_raw(struct mtd_info *mtd, + struct nand_chip *nand, uint8_t *buf) +{ + struct imx_nfc_data *this = nand->priv; + + DEBUG(MTD_DEBUG_LEVEL2, "[imx_nfc ecc_read_page_raw]\n"); + + add_event("Entering mil_ecc_read_page_raw", 1); + + mal_read_a_page(this, false, this->current_chip, + this->page_address, buf, nand->oob_poi); + + add_event("Exiting mil_ecc_read_page_raw", -1); + + return 0; + +} + +/** + * mil_ecc_write_page() - MTD Interface ecc.write_page(). + * + * @mtd: A pointer to the owning MTD. + * @nand: A pointer to the owning NAND Flash MTD. + * @buf: A pointer to the source buffer. + */ +static void mil_ecc_write_page(struct mtd_info *mtd, + struct nand_chip *nand, const uint8_t *buf) +{ + struct imx_nfc_data *this = nand->priv; + unimplemented(this, __func__); +} + +/** + * mil_ecc_write_page_raw() - MTD Interface ecc.write_page_raw(). + * + * @mtd: A pointer to the owning MTD. + * @nand: A pointer to the owning NAND Flash MTD. + * @buf: A pointer to the source buffer. + */ +static void mil_ecc_write_page_raw(struct mtd_info *mtd, + struct nand_chip *nand, const uint8_t *buf) +{ + struct imx_nfc_data *this = nand->priv; + unimplemented(this, __func__); +} + +/** + * mil_write_page() - MTD Interface ecc.write_page(). + * + * @mtd: A pointer to the owning MTD. + * @nand: A pointer to the owning NAND Flash MTD. + * @buf: A pointer to the source buffer. + * @page: The page number to write. + * @cached: Indicates cached programming (ignored). + * @raw: Indicates not to use ECC. + */ +static int mil_write_page(struct mtd_info *mtd, + struct nand_chip *nand, const uint8_t *buf, + int page, int cached, int raw) +{ + int return_value; + struct imx_nfc_data *this = nand->priv; + + DEBUG(MTD_DEBUG_LEVEL2, "[imx_nfc write_page]\n"); + + add_event("Entering mil_write_page", 1); + + return_value = mal_write_a_page(this, !raw, + this->current_chip, page, buf, nand->oob_poi); + + add_event("Exiting mil_write_page", -1); + + return return_value; + +} + +/** + * mil_ecc_read_oob() - MTD Interface read_oob(). + * + * @mtd: A pointer to the owning MTD. + * @nand: A pointer to the owning NAND Flash MTD. + * @page: The page number to read. + * @sndcmd: Indicates this function should send a command to the chip before + * reading the out-of-band bytes. This is only false for small page + * chips that support auto-increment. + */ +static int mil_ecc_read_oob(struct mtd_info *mtd, struct nand_chip *nand, + int page, int sndcmd) +{ + struct imx_nfc_data *this = nand->priv; + + DEBUG(MTD_DEBUG_LEVEL2, "[imx_nfc ecc_read_oob] " + "page: 0x%06x, sndcmd: %s\n", page, sndcmd ? "Yes" : "No"); + + add_event("Entering mil_ecc_read_oob", 1); + + mal_read_a_page(this, false, + this->current_chip, page, 0, nand->oob_poi); + + add_event("Exiting mil_ecc_read_oob", -1); + + /* + * Return true, indicating that the next call to this function must send + * a command. + */ + + return true; + +} + +/** + * mil_ecc_write_oob() - MTD Interface write_oob(). + * + * @mtd: A pointer to the owning MTD. + * @nand: A pointer to the owning NAND Flash MTD. + * @page: The page number to write. + */ +static int mil_ecc_write_oob(struct mtd_info *mtd, + struct nand_chip *nand, int page) +{ + struct imx_nfc_data *this = nand->priv; + + DEBUG(MTD_DEBUG_LEVEL2, "[imx_nfc ecc_write_oob] page: 0x%06x\n", page); + + /* + * There are fundamental incompatibilities between the i.MX NFC and the + * NAND Flash MTD model that make it essentially impossible to write the + * out-of-band bytes. + */ + + dev_emerg(this->dev, "This driver doesn't support writing the OOB\n"); + WARN_ON(1); + + /* Return status. */ + + return -EIO; + +} + +/** + * mil_erase_cmd() - MTD Interface erase_cmd(). + * + * We set the erase_cmd pointer in struct nand_chip to point to this function. + * Thus, the HIL will call here for all erase operations. + * + * Strictly speaking, since the erase_cmd pointer is marked "Internal," we + * shouldn't be doing this. However, the only reason the HIL uses that pointer + * is to install a different function for erasing conventional NAND Flash or AND + * Flash. Since AND Flash is obsolete and we don't support it, this isn't + * important. + * + * Furthermore, to cleanly implement interleaving (which is critical to speeding + * up erase operations), we want to "hook into" the operation at the highest + * semantic level possible. If we don't hook this function, then the only way + * we'll know that an erase is happening is when the HIL calls cmdfunc() with + * an erase command. Implementing interleaving at that level is roughly a + * billion times less desirable. + * + * This function does *not* wait for the operation to finish. The HIL will call + * waitfunc() later to wait for the operation to finish. + * + * @mtd: A pointer to the owning MTD. + * @page: A page address that identifies the block to erase. + */ +static void mil_erase_cmd(struct mtd_info *mtd, int page) +{ + struct nand_chip *nand = mtd->priv; + struct imx_nfc_data *this = nand->priv; + + DEBUG(MTD_DEBUG_LEVEL2, "[imx_nfc erase_cmd] page: 0x%06x\n", page); + + add_event("Entering mil_erase_cmd", 1); + + mal_erase_a_block(this, this->current_chip, page); + + add_event("Exiting mil_erase_cmd", -1); + +} + +/** + * mil_block_bad() - MTD Interface block_bad(). + * + * @mtd: A pointer to the owning MTD. + * @ofs: The offset of the block of interest, from the start of the medium. + * @getchip: Indicates this function must acquire the MTD before using it. + */ +#if 0 + +/* TODO: Finish this function and plug it in. */ + +static int mil_block_bad(struct mtd_info *mtd, loff_t ofs, int getchip) +{ + unsigned int chip; + unsigned int page; + int return_value; + struct nand_chip *nand = mtd->priv; + struct imx_nfc_data *this = nand->priv; + + DEBUG(MTD_DEBUG_LEVEL2, "[imx_nfc block_bad] page: 0x%06x\n", page); + + add_event("Entering mil_block_bad", 1); + + /* Compute the logical chip number that contains the given offset. */ + + chip = (unsigned int) (ofs >> nand->chip_shift); + + /* Compute the logical page address within the logical chip. */ + + page = ((unsigned int) (ofs >> nand->page_shift)) & nand->pagemask; + + /* Check if the block is bad. */ + + return_value = mal_is_block_bad(this, chip, page); + + if (return_value) + add_event("Bad block", 0); + + /* Return. */ + + add_event("Exiting mil_block_bad", -1); + + return return_value; + +} +#endif + +/** + * mil_scan_bbt() - MTD Interface scan_bbt(). + * + * The HIL calls this function once, when it initializes the NAND Flash MTD. + * + * Nominally, the purpose of this function is to look for or create the bad + * block table. In fact, since the HIL calls this function at the very end of + * the initialization process started by nand_scan(), and the HIL doesn't have a + * more formal mechanism, everyone "hooks" this function to continue the + * initialization process. + * + * At this point, the physical NAND Flash chips have been identified and + * counted, so we know the physical geometry. This enables us to make some + * important configuration decisions. + * + * The return value of this function propogates directly back to this driver's + * call to nand_scan(). Anything other than zero will cause this driver to + * tear everything down and declare failure. + * + * @mtd: A pointer to the owning MTD. + */ +static int mil_scan_bbt(struct mtd_info *mtd) +{ + struct nand_chip *nand = mtd->priv; + struct imx_nfc_data *this = nand->priv; + + DEBUG(MTD_DEBUG_LEVEL2, "[imx_nfc scan_bbt] \n"); + + add_event("Entering mil_scan_bbt", 1); + + /* + * We replace the erase_cmd() function that the MTD NAND Flash system + * has installed with our own. See mil_erase_cmd() for the reasons. + */ + + nand->erase_cmd = mil_erase_cmd; + + /* + * Tell MTD users that the out-of-band area can't be written. + * + * This flag is not part of the standard kernel source tree. It comes + * from a patch that touches both MTD and JFFS2. + * + * The problem is that, without this patch, JFFS2 believes it can write + * the data area and the out-of-band area separately. This is wrong for + * two reasons: + * + * 1) Our NFC distributes out-of-band bytes throughout the page, + * intermingled with the data, and covered by the same ECC. + * Thus, it's not possible to write the out-of-band bytes and + * data bytes separately. + * + * 2) Large page (MLC) Flash chips don't support partial page + * writes. You must write the entire page at a time. Thus, even + * if our NFC didn't force you to write out-of-band and data + * bytes together, it would *still* be a bad idea to do + * otherwise. + */ + + mtd->flags &= ~MTD_OOB_WRITEABLE; + + /* Set up geometry. */ + + mal_set_geometry(this); + + /* We use the reference implementation for bad block management. */ + + add_event("Exiting mil_scan_bbt", -1); + + return nand_scan_bbt(mtd, nand->badblock_pattern); + +} + +/** + * parse_bool_param() - Parses the value of a boolean parameter string. + * + * @s: The string to parse. + */ +static int parse_bool_param(const char *s) +{ + + if (!strcmp(s, "1") || !strcmp(s, "on") || + !strcmp(s, "yes") || !strcmp(s, "true")) { + return 1; + } else if (!strcmp(s, "0") || !strcmp(s, "off") || + !strcmp(s, "no") || !strcmp(s, "false")) { + return 0; + } else { + return -1; + } + +} + +/** + * set_module_enable() - Controls whether this driver is enabled. + * + * Note that this state can be controlled from the command line. Disabling this + * driver is sometimes useful for debugging. + * + * @s: The new value of the parameter. + * @kp: The owning kernel parameter. + */ +static int set_module_enable(const char *s, struct kernel_param *kp) +{ + + switch (parse_bool_param(s)) { + + case 1: + imx_nfc_module_enable = true; + break; + + case 0: + imx_nfc_module_enable = false; + break; + + default: + return -EINVAL; + break; + + } + + return 0; + +} + +/** + * get_module_enable() - Indicates whether this driver is enabled. + * + * @p: A pointer to a (small) buffer that will receive the response. + * @kp: The owning kernel parameter. + */ +static int get_module_enable(char *p, struct kernel_param *kp) +{ + p[0] = imx_nfc_module_enable ? '1' : '0'; + p[1] = 0; + return 1; +} + +#ifdef EVENT_REPORTING + +/** + * set_module_report_events() - Controls whether this driver reports events. + * + * @s: The new value of the parameter. + * @kp: The owning kernel parameter. + */ +static int set_module_report_events(const char *s, struct kernel_param *kp) +{ + + switch (parse_bool_param(s)) { + + case 1: + imx_nfc_module_report_events = true; + break; + + case 0: + imx_nfc_module_report_events = false; + reset_event_trace(); + break; + + default: + return -EINVAL; + break; + + } + + return 0; + +} + +/** + * get_module_report_events() - Indicates whether the driver reports events. + * + * @p: A pointer to a (small) buffer that will receive the response. + * @kp: The owning kernel parameter. + */ +static int get_module_report_events(char *p, struct kernel_param *kp) +{ + p[0] = imx_nfc_module_report_events ? '1' : '0'; + p[1] = 0; + return 1; +} + +/** + * set_module_dump_events() - Forces the driver to dump current events. + * + * @s: The new value of the parameter. + * @kp: The owning kernel parameter. + */ +static int set_module_dump_events(const char *s, struct kernel_param *kp) +{ + dump_event_trace(); + return 0; +} + +#endif /*EVENT_REPORTING*/ + +/** + * set_module_interleave_override() - Controls the interleave override. + * + * @s: The new value of the parameter. + * @kp: The owning kernel parameter. + */ +static int set_module_interleave_override(const char *s, + struct kernel_param *kp) +{ + + if (!strcmp(s, "-1")) + imx_nfc_module_interleave_override = NEVER; + else if (!strcmp(s, "0")) + imx_nfc_module_interleave_override = DRIVER_CHOICE; + else if (!strcmp(s, "1")) + imx_nfc_module_interleave_override = ALWAYS; + else + return -EINVAL; + + return 0; + +} + +/** + * get_module_interleave_override() - Indicates the interleave override state. + * + * @p: A pointer to a (small) buffer that will receive the response. + * @kp: The owning kernel parameter. + */ +static int get_module_interleave_override(char *p, struct kernel_param *kp) +{ + return sprintf(p, "%d", imx_nfc_module_interleave_override); +} + +/** + * set_force_bytewise_copy() - Controls forced bytewise copy from/to the NFC. + * + * @s: The new value of the parameter. + * @kp: The owning kernel parameter. + */ +static int set_module_force_bytewise_copy(const char *s, + struct kernel_param *kp) +{ + + switch (parse_bool_param(s)) { + + case 1: + imx_nfc_module_force_bytewise_copy = true; + break; + + case 0: + imx_nfc_module_force_bytewise_copy = false; + break; + + default: + return -EINVAL; + break; + + } + + return 0; + +} + +/** + * get_force_bytewise_copy() - Indicates whether bytewise copy is being forced. + * + * @p: A pointer to a (small) buffer that will receive the response. + * @kp: The owning kernel parameter. + */ +static int get_module_force_bytewise_copy(char *p, struct kernel_param *kp) +{ + p[0] = imx_nfc_module_force_bytewise_copy ? '1' : '0'; + p[1] = 0; + return 1; +} + +/* Module attributes that appear in sysfs. */ + +module_param_call(enable, set_module_enable, get_module_enable, 0, 0444); +MODULE_PARM_DESC(enable, "enables/disables probing"); + +#ifdef EVENT_REPORTING +module_param_call(report_events, + set_module_report_events, get_module_report_events, 0, 0644); +MODULE_PARM_DESC(report_events, "enables/disables event reporting"); + +module_param_call(dump_events, set_module_dump_events, 0, 0, 0644); +MODULE_PARM_DESC(dump_events, "forces current event dump"); +#endif + +module_param_call(interleave_override, set_module_interleave_override, + get_module_interleave_override, 0, 0444); +MODULE_PARM_DESC(interleave_override, "overrides interleaving choice"); + +module_param_call(force_bytewise_copy, set_module_force_bytewise_copy, + get_module_force_bytewise_copy, 0, 0644); +MODULE_PARM_DESC(force_bytewise_copy, "forces bytewise copy from/to NFC"); + +/** + * show_device_platform_info() - Shows the device's platform information. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer that will receive a representation of the attribute. + */ +static ssize_t show_device_platform_info(struct device *dev, + struct device_attribute *attr, char *buf) +{ + int o = 0; + unsigned int i; + void *buffer_base; + void *primary_base; + void *secondary_base; + unsigned int interrupt_number; + struct resource *r; + struct imx_nfc_data *this = dev_get_drvdata(dev); + struct platform_device *pdev = this->pdev; + struct imx_nfc_platform_data *pdata = this->pdata; + struct mtd_partition *partition; + + r = platform_get_resource_byname(pdev, IORESOURCE_MEM, + IMX_NFC_BUFFERS_ADDR_RES_NAME); + + buffer_base = (void *) r->start; + + r = platform_get_resource_byname(pdev, IORESOURCE_MEM, + IMX_NFC_PRIMARY_REGS_ADDR_RES_NAME); + + primary_base = (void *) r->start; + + r = platform_get_resource_byname(pdev, IORESOURCE_MEM, + IMX_NFC_SECONDARY_REGS_ADDR_RES_NAME); + + secondary_base = (void *) r->start; + + r = platform_get_resource_byname(pdev, IORESOURCE_IRQ, + IMX_NFC_INTERRUPT_RES_NAME); + + interrupt_number = r->start; + + o += sprintf(buf, + "NFC Major Version : %u\n" + "NFC Minor Version : %u\n" + "Force CE : %s\n" + "Target Cycle in ns : %u\n" + "Clock Name : %s\n" + "Interleave : %s\n" + "Buffer Base : 0x%p\n" + "Primary Registers Base : 0x%p\n" + "Secondary Registers Base: 0x%p\n" + "Interrupt Number : %u\n" + , + pdata->nfc_major_version, + pdata->nfc_minor_version, + pdata->force_ce ? "Yes" : "No", + pdata->target_cycle_in_ns, + pdata->clock_name, + pdata->interleave ? "Yes" : "No", + buffer_base, + primary_base, + secondary_base, + interrupt_number + ); + + #ifdef CONFIG_MTD_PARTITIONS + + o += sprintf(buf + o, + "Partition Count : %u\n" + , + pdata->partition_count + ); + + /* Loop over partitions. */ + + for (i = 0; i < pdata->partition_count; i++) { + + partition = pdata->partitions + i; + + o += sprintf(buf+o, " [%d]\n", i); + o += sprintf(buf+o, " Name : %s\n", partition->name); + + switch (partition->offset) { + + case MTDPART_OFS_NXTBLK: + o += sprintf(buf+o, " Offset: " + "MTDPART_OFS_NXTBLK\n"); + break; + case MTDPART_OFS_APPEND: + o += sprintf(buf+o, " Offset: " + "MTDPART_OFS_APPEND\n"); + break; + default: + o += sprintf(buf+o, " Offset: %u (%u MiB)\n", + partition->offset, + partition->offset / (1024 * 1024)); + break; + + } + + if (partition->size == MTDPART_SIZ_FULL) { + o += sprintf(buf+o, " Size : " + "MTDPART_SIZ_FULL\n"); + } else { + o += sprintf(buf+o, " Size : %u (%u MiB)\n", + partition->size, + partition->size / (1024 * 1024)); + } + + } + + #endif + + return o; + +} + +/** + * show_device_physical_geometry() - Shows the physical Flash device geometry. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer that will receive a representation of the attribute. + */ +static ssize_t show_device_physical_geometry(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct imx_nfc_data *this = dev_get_drvdata(dev); + struct physical_geometry *physical = &this->physical_geometry; + + return sprintf(buf, + "Chip Count : %u\n" + "Chip Size in Bytes : %llu\n" + "Block Size in Bytes : %u\n" + "Page Data Size in Bytes: %u\n" + "Page OOB Size in Bytes : %u\n" + , + physical->chip_count, + physical->chip_size, + physical->block_size, + physical->page_data_size, + physical->page_oob_size + ); + +} + +/** + * show_device_nfc_info() - Shows the NFC-specific information. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer that will receive a representation of the attribute. + */ +static ssize_t show_device_nfc_info(struct device *dev, + struct device_attribute *attr, char *buf) +{ + unsigned long parent_clock_rate_in_hz; + unsigned long clock_rate_in_hz; + struct clk *parent_clock; + struct imx_nfc_data *this = dev_get_drvdata(dev); + struct nfc_hal *nfc = this->nfc; + + parent_clock = clk_get_parent(this->clock); + parent_clock_rate_in_hz = clk_get_rate(parent_clock); + clock_rate_in_hz = clk_get_rate(this->clock); + + return sprintf(buf, + "Major Version : %u\n" + "Minor Version : %u\n" + "Max Chip Count : %u\n" + "Max Buffer Count : %u\n" + "Spare Buffer Stride : %u\n" + "Has Secondary Registers : %s\n" + "Can Be Symmetric : %s\n" + "Exposes Ready/Busy : %s\n" + "Parent Clock Rate in Hz : %lu\n" + "Clock Rate in Hz : %lu\n" + "Symmetric Clock : %s\n" + , + nfc->major_version, + nfc->minor_version, + nfc->max_chip_count, + nfc->max_buffer_count, + nfc->spare_buf_stride, + nfc->has_secondary_regs ? "Yes" : "No", + nfc->can_be_symmetric ? "Yes" : "No", + nfc->is_ready ? "Yes" : "No", + parent_clock_rate_in_hz, + clock_rate_in_hz, + this->nfc->get_symmetric(this) ? "Yes" : "No" + ); + +} + +/** + * show_device_nfc_geometry() - Shows the NFC view of the device geometry. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer that will receive a representation of the attribute. + */ +static ssize_t show_device_nfc_geometry(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct imx_nfc_data *this = dev_get_drvdata(dev); + + return sprintf(buf, + "Page Data Size in Bytes : %u\n" + "Page OOB Size in Bytes : %u\n" + "ECC Algorithm : %s\n" + "ECC Strength : %u\n" + "Buffers in Use : %u\n" + "Spare Buffer Size in Use: %u\n" + "Spare Buffer Spillover : %u\n" + , + this->nfc_geometry->page_data_size, + this->nfc_geometry->page_oob_size, + this->nfc_geometry->ecc_algorithm, + this->nfc_geometry->ecc_strength, + this->nfc_geometry->buffer_count, + this->nfc_geometry->spare_buf_size, + this->nfc_geometry->spare_buf_spill + ); + +} + +/** + * show_device_logical_geometry() - Shows the logical device geometry. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer that will receive a representation of the attribute. + */ +static ssize_t show_device_logical_geometry(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct imx_nfc_data *this = dev_get_drvdata(dev); + struct logical_geometry *logical = &this->logical_geometry; + + return sprintf(buf, + "Chip Count : %u\n" + "Chip Size in Bytes : %u\n" + "Usable Size in Bytes : %u\n" + "Block Size in Bytes : %u\n" + "Page Data Size in Bytes: %u\n" + "Page OOB Size in Bytes : %u\n" + , + logical->chip_count, + logical->chip_size, + logical->usable_size, + logical->block_size, + logical->page_data_size, + logical->page_oob_size + ); + +} + +/** + * show_device_mtd_nand_info() - Shows the device's MTD NAND-specific info. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer that will receive a representation of the attribute. + */ +static ssize_t show_device_mtd_nand_info(struct device *dev, + struct device_attribute *attr, char *buf) +{ + int o = 0; + unsigned int i; + unsigned int j; + static const unsigned int columns = 8; + struct imx_nfc_data *this = dev_get_drvdata(dev); + struct nand_chip *nand = &this->nand; + + o += sprintf(buf + o, + "Options : 0x%08x\n" + "Chip Count : %u\n" + "Chip Size : %lu\n" + "Minimum Writable Size: %u\n" + "Page Shift : %u\n" + "Page Mask : 0x%x\n" + "Block Shift : %u\n" + "BBT Block Shift : %u\n" + "Chip Shift : %u\n" + "Block Mark Offset : %u\n" + "Cached Page Number : %d\n" + , + nand->options, + nand->numchips, + nand->chipsize, + nand->subpagesize, + nand->page_shift, + nand->pagemask, + nand->phys_erase_shift, + nand->bbt_erase_shift, + nand->chip_shift, + nand->badblockpos, + nand->pagebuf + ); + + o += sprintf(buf + o, + "ECC Byte Count : %u\n" + , + nand->ecc.layout->eccbytes + ); + + /* Loop over rows. */ + + for (i = 0; (i * columns) < nand->ecc.layout->eccbytes; i++) { + + /* Loop over columns within rows. */ + + for (j = 0; j < columns; j++) { + + if (((i * columns) + j) >= nand->ecc.layout->eccbytes) + break; + + o += sprintf(buf + o, " %3u", + nand->ecc.layout->eccpos[(i * columns) + j]); + + } + + o += sprintf(buf + o, "\n"); + + } + + o += sprintf(buf + o, + "OOB Available Bytes : %u\n" + , + nand->ecc.layout->oobavail + ); + + j = 0; + + for (i = 0; j < nand->ecc.layout->oobavail; i++) { + + j += nand->ecc.layout->oobfree[i].length; + + o += sprintf(buf + o, + " [%3u, %2u]\n" + , + nand->ecc.layout->oobfree[i].offset, + nand->ecc.layout->oobfree[i].length + ); + + } + + return o; + +} + +/** + * show_device_mtd_info() - Shows the device's MTD-specific information. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer that will receive a representation of the attribute. + */ +static ssize_t show_device_mtd_info(struct device *dev, + struct device_attribute *attr, char *buf) +{ + int o = 0; + unsigned int i; + unsigned int j; + static const unsigned int columns = 8; + struct imx_nfc_data *this = dev_get_drvdata(dev); + struct mtd_info *mtd = &this->mtd; + + o += sprintf(buf + o, + "Name : %s\n" + "Type : %u\n" + "Flags : 0x%08x\n" + "Size in Bytes : %u\n" + "Erase Region Count : %d\n" + "Erase Size in Bytes: %u\n" + "Write Size in Bytes: %u\n" + "OOB Size in Bytes : %u\n" + "Errors Corrected : %u\n" + "Failed Reads : %u\n" + "Bad Block Count : %u\n" + "BBT Block Count : %u\n" + , + mtd->name, + mtd->type, + mtd->flags, + mtd->size, + mtd->numeraseregions, + mtd->erasesize, + mtd->writesize, + mtd->oobsize, + mtd->ecc_stats.corrected, + mtd->ecc_stats.failed, + mtd->ecc_stats.badblocks, + mtd->ecc_stats.bbtblocks + ); + + o += sprintf(buf + o, + "ECC Byte Count : %u\n" + , + mtd->ecclayout->eccbytes + ); + + /* Loop over rows. */ + + for (i = 0; (i * columns) < mtd->ecclayout->eccbytes; i++) { + + /* Loop over columns within rows. */ + + for (j = 0; j < columns; j++) { + + if (((i * columns) + j) >= mtd->ecclayout->eccbytes) + break; + + o += sprintf(buf + o, " %3u", + mtd->ecclayout->eccpos[(i * columns) + j]); + + } + + o += sprintf(buf + o, "\n"); + + } + + o += sprintf(buf + o, + "OOB Available Bytes: %u\n" + , + mtd->ecclayout->oobavail + ); + + j = 0; + + for (i = 0; j < mtd->ecclayout->oobavail; i++) { + + j += mtd->ecclayout->oobfree[i].length; + + o += sprintf(buf + o, + " [%3u, %2u]\n" + , + mtd->ecclayout->oobfree[i].offset, + mtd->ecclayout->oobfree[i].length + ); + + } + + return o; + +} + +/** + * show_device_bbt_pages() - Shows the pages in which BBT's appear. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer that will receive a representation of the attribute. + */ +static ssize_t show_device_bbt_pages(struct device *dev, + struct device_attribute *attr, char *buf) +{ + int o = 0; + unsigned int i; + struct imx_nfc_data *this = dev_get_drvdata(dev); + struct nand_chip *nand = &this->nand; + + /* Loop over main BBT pages. */ + + if (nand->bbt_td) + for (i = 0; i < NAND_MAX_CHIPS; i++) + o += sprintf(buf + o, "%d: 0x%08x\n", + i, nand->bbt_td->pages[i]); + + /* Loop over mirror BBT pages. */ + + if (nand->bbt_md) + for (i = 0; i < NAND_MAX_CHIPS; i++) + o += sprintf(buf + o, "%d: 0x%08x\n", + i, nand->bbt_md->pages[i]); + + return o; + +} + +/** + * show_device_cycle_in_ns() - Shows the device's cycle in ns. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer that will receive a representation of the attribute. + */ +static ssize_t show_device_cycle_in_ns(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct imx_nfc_data *this = dev_get_drvdata(dev); + return sprintf(buf, "%u\n", get_cycle_in_ns(this)); +} + +/** + * store_device_cycle_in_ns() - Sets the device's cycle in ns. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer containing a new attribute value. + * @size: The size of the buffer. + */ +static ssize_t store_device_cycle_in_ns(struct device *dev, + struct device_attribute *attr, const char *buf, size_t size) +{ + int error; + unsigned long new_cycle_in_ns; + struct imx_nfc_data *this = dev_get_drvdata(dev); + + /* Look for nonsense. */ + + if (!size) + return -EINVAL; + + /* Try to understand the new cycle period. */ + + if (strict_strtoul(buf, 0, &new_cycle_in_ns)) + return -EINVAL; + + /* Try to implement the new cycle period. */ + + error = this->nfc->set_closest_cycle(this, new_cycle_in_ns); + + if (error) + return -EINVAL; + + /* Return success. */ + + return size; + +} + +/** + * show_device_interrupt_override() - Shows the device's interrupt override. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer that will receive a representation of the attribute. + */ +static ssize_t show_device_interrupt_override(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct imx_nfc_data *this = dev_get_drvdata(dev); + + switch (this->interrupt_override) { + + case NEVER: + return sprintf(buf, "-1\n"); + break; + + case DRIVER_CHOICE: + return sprintf(buf, "0\n"); + break; + + case ALWAYS: + return sprintf(buf, "1\n"); + break; + + default: + return sprintf(buf, "?\n"); + break; + + } + +} + +/** + * store_device_interrupt_override() - Sets the device's interrupt override. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer containing a new attribute value. + * @size: The size of the buffer. + */ +static ssize_t store_device_interrupt_override(struct device *dev, + struct device_attribute *attr, const char *buf, size_t size) +{ + struct imx_nfc_data *this = dev_get_drvdata(dev); + + if (!strcmp(buf, "-1")) + this->interrupt_override = NEVER; + else if (!strcmp(buf, "0")) + this->interrupt_override = DRIVER_CHOICE; + else if (!strcmp(buf, "1")) + this->interrupt_override = ALWAYS; + else + return -EINVAL; + + return size; + +} + +/** + * show_device_auto_op_override() - Shows the device's automatic op override. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer that will receive a representation of the attribute. + */ +static ssize_t show_device_auto_op_override(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct imx_nfc_data *this = dev_get_drvdata(dev); + + switch (this->auto_op_override) { + + case NEVER: + return sprintf(buf, "-1\n"); + break; + + case DRIVER_CHOICE: + return sprintf(buf, "0\n"); + break; + + case ALWAYS: + return sprintf(buf, "1\n"); + break; + + default: + return sprintf(buf, "?\n"); + break; + + } + +} + +/** + * store_device_auto_op_override() - Sets the device's automatic op override. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer containing a new attribute value. + * @size: The size of the buffer. + */ +static ssize_t store_device_auto_op_override(struct device *dev, + struct device_attribute *attr, const char *buf, size_t size) +{ + struct imx_nfc_data *this = dev_get_drvdata(dev); + + if (!strcmp(buf, "-1")) + this->auto_op_override = NEVER; + else if (!strcmp(buf, "0")) + this->auto_op_override = DRIVER_CHOICE; + else if (!strcmp(buf, "1")) + this->auto_op_override = ALWAYS; + else + return -EINVAL; + + return size; + +} + +/** + * show_device_inject_ecc_error() - Shows the device's error injection flag. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer that will receive a representation of the attribute. + */ +static ssize_t show_device_inject_ecc_error(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct imx_nfc_data *this = dev_get_drvdata(dev); + + return sprintf(buf, "%d\n", this->inject_ecc_error); + +} + +/** + * store_device_inject_ecc_error() - Sets the device's error injection flag. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer containing a new attribute value. + * @size: The size of the buffer. + */ +static ssize_t store_device_inject_ecc_error(struct device *dev, + struct device_attribute *attr, const char *buf, size_t size) +{ + unsigned long new_inject_ecc_error; + struct imx_nfc_data *this = dev_get_drvdata(dev); + + /* Look for nonsense. */ + + if (!size) + return -EINVAL; + + /* Try to understand the new cycle period. */ + + if (strict_strtol(buf, 0, &new_inject_ecc_error)) + return -EINVAL; + + /* Store the value. */ + + this->inject_ecc_error = new_inject_ecc_error; + + /* Return success. */ + + return size; + +} + +/** + * store_device_invalidate_page_cache() - Invalidates the device's page cache. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer containing a new attribute value. + * @size: The size of the buffer. + */ +static ssize_t store_device_invalidate_page_cache(struct device *dev, + struct device_attribute *attr, const char *buf, size_t size) +{ + struct imx_nfc_data *this = dev_get_drvdata(dev); + + /* Invalidate the page cache. */ + + this->nand.pagebuf = -1; + + /* Return success. */ + + return size; + +} + +/* Device attributes that appear in sysfs. */ + +static DEVICE_ATTR(platform_info , 0444, show_device_platform_info , 0); +static DEVICE_ATTR(physical_geometry, 0444, show_device_physical_geometry, 0); +static DEVICE_ATTR(nfc_info , 0444, show_device_nfc_info , 0); +static DEVICE_ATTR(nfc_geometry , 0444, show_device_nfc_geometry , 0); +static DEVICE_ATTR(logical_geometry , 0444, show_device_logical_geometry , 0); +static DEVICE_ATTR(mtd_nand_info , 0444, show_device_mtd_nand_info , 0); +static DEVICE_ATTR(mtd_info , 0444, show_device_mtd_info , 0); +static DEVICE_ATTR(bbt_pages , 0444, show_device_bbt_pages , 0); + +static DEVICE_ATTR(cycle_in_ns, 0644, + show_device_cycle_in_ns, store_device_cycle_in_ns); + +static DEVICE_ATTR(interrupt_override, 0644, + show_device_interrupt_override, store_device_interrupt_override); + +static DEVICE_ATTR(auto_op_override, 0644, + show_device_auto_op_override, store_device_auto_op_override); + +static DEVICE_ATTR(inject_ecc_error, 0644, + show_device_inject_ecc_error, store_device_inject_ecc_error); + +static DEVICE_ATTR(invalidate_page_cache, 0644, + 0, store_device_invalidate_page_cache); + +static struct device_attribute *device_attributes[] = { + &dev_attr_platform_info, + &dev_attr_physical_geometry, + &dev_attr_nfc_info, + &dev_attr_nfc_geometry, + &dev_attr_logical_geometry, + &dev_attr_mtd_nand_info, + &dev_attr_mtd_info, + &dev_attr_bbt_pages, + &dev_attr_cycle_in_ns, + &dev_attr_interrupt_override, + &dev_attr_auto_op_override, + &dev_attr_inject_ecc_error, + &dev_attr_invalidate_page_cache, +}; + +/** + * validate_the_platform() - Validates information about the platform. + * + * Note that this function doesn't validate the NFC version. That's done when + * the probing process attempts to configure for the specific hardware version. + * + * @pdev: A pointer to the platform device. + */ +static int validate_the_platform(struct platform_device *pdev) +{ + struct device *dev = &pdev->dev; + struct imx_nfc_platform_data *pdata = pdev->dev.platform_data; + + /* Validate the clock name. */ + + if (!pdata->clock_name) { + dev_err(dev, "No clock name\n"); + return -ENXIO; + } + + /* Validate the partitions. */ + + if ((pdata->partitions && (!pdata->partition_count)) || + (!pdata->partitions && (pdata->partition_count))) { + dev_err(dev, "Bad partition data\n"); + return -ENXIO; + } + + /* Return success */ + + return 0; + +} + +/** + * set_up_the_nfc_hal() - Sets up for the specific NFC hardware HAL. + * + * @this: Per-device data. + */ +static int set_up_the_nfc_hal(struct imx_nfc_data *this) +{ + unsigned int i; + struct nfc_hal *p; + struct imx_nfc_platform_data *pdata = this->pdata; + + for (i = 0; i < ARRAY_SIZE(nfc_hals); i++) { + + p = nfc_hals[i]; + + /* + * Restrict to 3.2 until others are fully implemented. + * + * TODO: Remove this. + */ + + if ((p->major_version != 3) && (p->minor_version != 2)) + continue; + + if ((p->major_version == pdata->nfc_major_version) && + (p->minor_version == pdata->nfc_minor_version)) { + this->nfc = p; + return 0; + break; + } + + } + + dev_err(this->dev, "Unkown NFC version %d.%d\n", + pdata->nfc_major_version, pdata->nfc_minor_version); + + return !0; + +} + +/** + * acquire_resources() - Tries to acquire resources. + * + * @this: Per-device data. + */ +static int acquire_resources(struct imx_nfc_data *this) +{ + + int error = 0; + struct platform_device *pdev = this->pdev; + struct device *dev = this->dev; + struct imx_nfc_platform_data *pdata = this->pdata; + struct resource *r; + + /* Find the buffers and map them. */ + + r = platform_get_resource_byname(pdev, IORESOURCE_MEM, + IMX_NFC_BUFFERS_ADDR_RES_NAME); + + if (!r) { + dev_err(dev, "Can't get '%s'\n", IMX_NFC_BUFFERS_ADDR_RES_NAME); + error = -ENXIO; + goto exit_buffers; + } + + this->buffers = ioremap(r->start, r->end - r->start + 1); + + if (!this->buffers) { + dev_err(dev, "Can't remap buffers\n"); + error = -EIO; + goto exit_buffers; + } + + /* Find the primary registers and map them. */ + + r = platform_get_resource_byname(pdev, IORESOURCE_MEM, + IMX_NFC_PRIMARY_REGS_ADDR_RES_NAME); + + if (!r) { + dev_err(dev, "Can't get '%s'\n", + IMX_NFC_PRIMARY_REGS_ADDR_RES_NAME); + error = -ENXIO; + goto exit_primary_registers; + } + + this->primary_regs = ioremap(r->start, r->end - r->start + 1); + + if (!this->primary_regs) { + dev_err(dev, "Can't remap the primary registers\n"); + error = -EIO; + goto exit_primary_registers; + } + + /* Check for secondary registers. */ + + r = platform_get_resource_byname(pdev, IORESOURCE_MEM, + IMX_NFC_SECONDARY_REGS_ADDR_RES_NAME); + + if (r && !this->nfc->has_secondary_regs) { + + dev_err(dev, "Resource '%s' should not be present\n", + IMX_NFC_SECONDARY_REGS_ADDR_RES_NAME); + error = -ENXIO; + goto exit_secondary_registers; + + } + + if (this->nfc->has_secondary_regs) { + + if (!r) { + dev_err(dev, "Can't get '%s'\n", + IMX_NFC_SECONDARY_REGS_ADDR_RES_NAME); + error = -ENXIO; + goto exit_secondary_registers; + } + + this->secondary_regs = ioremap(r->start, r->end - r->start + 1); + + if (!this->secondary_regs) { + dev_err(dev, + "Can't remap the secondary registers\n"); + error = -EIO; + goto exit_secondary_registers; + } + + } + + /* Find out what our interrupt is and try to own it. */ + + r = platform_get_resource_byname(pdev, IORESOURCE_IRQ, + IMX_NFC_INTERRUPT_RES_NAME); + + if (!r) { + dev_err(dev, "Can't get '%s'\n", IMX_NFC_INTERRUPT_RES_NAME); + error = -ENXIO; + goto exit_irq; + } + + this->interrupt = r->start; + + error = request_irq(this->interrupt, + nfc_util_isr, 0, this->dev->bus_id, this); + + if (error) { + dev_err(dev, "Can't own interrupt %d\n", this->interrupt); + goto exit_irq; + } + + /* Find out the name of our clock and try to own it. */ + + this->clock = clk_get(dev, pdata->clock_name); + + if (this->clock == ERR_PTR(-ENOENT)) { + dev_err(dev, "Can't get clock '%s'\n", pdata->clock_name); + error = -ENXIO; + goto exit_clock; + } + + /* Return success. */ + + return 0; + + /* Error return paths begin here. */ + +exit_clock: + free_irq(this->interrupt, this); +exit_irq: + if (this->secondary_regs) + iounmap(this->secondary_regs); +exit_secondary_registers: + iounmap(this->primary_regs); +exit_primary_registers: + iounmap(this->buffers); +exit_buffers: + return error; + +} + +/** + * release_resources() - Releases resources. + * + * @this: Per-device data. + */ +static void release_resources(struct imx_nfc_data *this) +{ + + /* Release our clock. */ + + clk_disable(this->clock); + clk_put(this->clock); + + /* Release our interrupt. */ + + free_irq(this->interrupt, this); + + /* Release mapped memory. */ + + iounmap(this->buffers); + iounmap(this->primary_regs); + if (this->secondary_regs) + iounmap(this->secondary_regs); + +} + +/** + * register_with_mtd() - Registers this medium with MTD. + * + * @this: Per-device data. + */ +static int register_with_mtd(struct imx_nfc_data *this) +{ + int error = 0; + struct mtd_info *mtd = &this->mtd; + struct nand_chip *nand = &this->nand; + struct device *dev = this->dev; + struct imx_nfc_platform_data *pdata = this->pdata; + + /* Link the MTD structures together, along with our own data. */ + + mtd->priv = nand; + nand->priv = this; + + /* Prepare the MTD structure. */ + + mtd->owner = THIS_MODULE; + + /* + * Signal Control Functions + */ + + nand->cmd_ctrl = mil_cmd_ctrl; + + /* + * Chip Control Functions + * + * Not all of our NFC hardware versions expose Ready/Busy signals. For + * versions that don't, the is_ready function pointer will be NULL. In + * those cases, we leave the dev_ready member unassigned, which will + * cause the HIL to use a reference implementation's algorithm to + * discover when the hardware is ready. + */ + + nand->select_chip = mil_select_chip; + nand->cmdfunc = mil_cmdfunc; + nand->waitfunc = mil_waitfunc; + + if (this->nfc->is_ready) + nand->dev_ready = mil_dev_ready; + + /* + * Low-level I/O Functions + */ + + nand->read_byte = mil_read_byte; + nand->read_word = mil_read_word; + nand->read_buf = mil_read_buf; + nand->write_buf = mil_write_buf; + nand->verify_buf = mil_verify_buf; + + /* + * ECC Control Functions + */ + + nand->ecc.hwctl = mil_ecc_hwctl; + nand->ecc.calculate = mil_ecc_calculate; + nand->ecc.correct = mil_ecc_correct; + + /* + * ECC-Aware I/O Functions + */ + + nand->ecc.read_page = mil_ecc_read_page; + nand->ecc.read_page_raw = mil_ecc_read_page_raw; + nand->ecc.write_page = mil_ecc_write_page; + nand->ecc.write_page_raw = mil_ecc_write_page_raw; + + /* + * High-level I/O Functions + */ + + nand->write_page = mil_write_page; + nand->ecc.read_oob = mil_ecc_read_oob; + nand->ecc.write_oob = mil_ecc_write_oob; + + /* + * Bad Block Marking Functions + * + * We want to use the reference block_bad and block_markbad + * implementations, so we don't assign those members. + */ + + nand->scan_bbt = mil_scan_bbt; + + /* + * Error Recovery Functions + * + * We don't fill in the errstat function pointer because it's optional + * and we don't have a need for it. + */ + + /* + * Device Attributes + * + * We don't fill in the chip_delay member because we don't have a need + * for it. + * + * We support only 8-bit Flash bus width. + */ + + /* + * ECC Attributes + * + * Members that aren't set here are configured by a version-specific + * set_geometry() function. + */ + + nand->ecc.mode = NAND_ECC_HW; + nand->ecc.size = NFC_MAIN_BUF_SIZE; + nand->ecc.prepad = 0; + nand->ecc.postpad = 0; + + /* + * Bad Block Management Attributes + * + * We don't fill in the following attributes: + * + * badblockpos + * bbt + * badblock_pattern + * bbt_erase_shift + * + * These attributes aren't hardware-specific, and the HIL makes fine + * choices without our help. + */ + + nand->options |= NAND_USE_FLASH_BBT; + nand->bbt_td = &bbt_main_descriptor; + nand->bbt_md = &bbt_mirror_descriptor; + + /* + * Device Control + * + * We don't fill in the controller attribute. In principle, we could set + * up a structure to represent the controller. However, since it's + * vanishingly improbable that we'll have more than one medium behind + * the controller, it's not worth the effort. We let the HIL handle it. + */ + + /* + * Memory-mapped I/O + * + * We don't fill in the following attributes: + * + * IO_ADDR_R + * IO_ADDR_W + * + * None of these are necessary because we don't have a memory-mapped + * implementation. + */ + + /* + * Install a "fake" ECC layout. + * + * We'll be calling nand_scan() to do the final MTD setup. If we haven't + * already chosen an ECC layout, then nand_scan() will choose one based + * on the part geometry it discovers. Unfortunately, it doesn't make + * good choices. It would be best if we could install the correct ECC + * layout now, before we call nand_scan(). We can't do that because we + * don't know the medium geometry yet. Here, we install a "fake" ECC + * layout just to stop nand_scan() from trying to pick on for itself. + * Later, in imx_nfc_scan_bbt(), when we know the medium geometry, we'll + * install the correct choice. + * + * Of course, this tactic depends critically on nand_scan() not using + * the fake layout before we can install a good one. This is in fact the + * case. + */ + + nand->ecc.layout = &nfc_geometry_512_16_RS_ECC1.mtd_layout; + + /* + * Ask the NAND Flash system to scan for chips. + * + * This will fill in reference implementations for all the members of + * the MTD structures that we didn't set, and will make the medium fully + * usable. + */ + + error = nand_scan(mtd, this->nfc->max_chip_count); + + if (error) { + dev_err(dev, "Chip scan failed\n"); + error = -ENXIO; + goto exit_scan; + } + + /* Register the MTD that represents the entire medium. */ + + mtd->name = "NAND Flash Medium"; + + add_mtd_device(mtd); + + /* Check if we're doing partitions and register MTD's accordingly. */ + + #ifdef CONFIG_MTD_PARTITIONS + + /* + * Look for partition information. If we find some, install + * them. Otherwise, use the partitions handed to us by the + * platform. + */ + + this->partition_count = + parse_mtd_partitions(mtd, partition_source_types, + &this->partitions, 0); + + if ((this->partition_count <= 0) && (pdata->partitions)) { + this->partition_count = pdata->partition_count; + this->partitions = pdata->partitions; + } + + if (this->partitions) + add_mtd_partitions(mtd, this->partitions, + this->partition_count); + + #endif + + /* Return success. */ + + return 0; + + /* Error return paths begin here. */ + +exit_scan: + return error; + +} + +/** + * unregister_with_mtd() - Unregisters this medium with MTD. + * + * @this: Per-device data. + */ +static void unregister_with_mtd(struct imx_nfc_data *this) +{ + + /* Get MTD to let go. */ + + nand_release(&this->mtd); + +} + +/** + * manage_sysfs_files() - Creates/removes sysfs files for this device. + * + * @this: Per-device data. + */ +static void manage_sysfs_files(struct imx_nfc_data *this, int create) +{ + int error; + unsigned int i; + struct device_attribute **attr; + + for (i = 0, attr = device_attributes; + i < ARRAY_SIZE(device_attributes); i++, attr++) { + + if (create) { + error = device_create_file(this->dev, *attr); + if (error) { + while (--attr >= device_attributes) + device_remove_file(this->dev, *attr); + return; + } + } else { + device_remove_file(this->dev, *attr); + } + + } + +} + +/** + * imx_nfc_probe() - Probes for a device and, if possible, takes ownership. + * + * @pdev: A pointer to the platform device. + */ +static int imx_nfc_probe(struct platform_device *pdev) +{ + int error = 0; + char *symmetric_clock; + struct clk *parent_clock; + unsigned long parent_clock_rate_in_hz; + unsigned long parent_clock_rate_in_mhz; + unsigned long nfc_clock_rate_in_hz; + unsigned long nfc_clock_rate_in_mhz; + unsigned long clock_divisor; + unsigned long cycle_in_ns; + struct device *dev = &pdev->dev; + struct imx_nfc_platform_data *pdata = pdev->dev.platform_data; + struct imx_nfc_data *this = 0; + + /* Say hello. */ + + dev_info(dev, "Probing...\n"); + + /* Check if we're enabled. */ + + if (!imx_nfc_module_enable) { + dev_info(dev, "Disabled\n"); + return -ENXIO; + } + + /* Validate the platform device data. */ + + error = validate_the_platform(pdev); + + if (error) + goto exit_validate_platform; + + /* Allocate memory for the per-device data. */ + + this = kzalloc(sizeof(*this), GFP_KERNEL); + + if (!this) { + dev_err(dev, "Failed to allocate per-device memory\n"); + error = -ENOMEM; + goto exit_allocate_this; + } + + /* Link our per-device data to the owning device. */ + + platform_set_drvdata(pdev, this); + + /* Fill in the convenience pointers in our per-device data. */ + + this->pdev = pdev; + this->dev = &pdev->dev; + this->pdata = pdata; + + /* Initialize the interrupt service pathway. */ + + init_completion(&this->done); + + /* Set up the NFC HAL. */ + + error = set_up_the_nfc_hal(this); + + if (error) + goto exit_set_up_nfc_hal; + + /* Attempt to acquire the resources we need. */ + + error = acquire_resources(this); + + if (error) + goto exit_acquire_resources; + + /* Initialize the NFC HAL. */ + + if (this->nfc->init(this)) { + error = -ENXIO; + goto exit_nfc_init; + } + + /* Tell the platform we're bringing this device up. */ + + if (pdata->init) + error = pdata->init(); + + if (error) + goto exit_platform_init; + + /* Report. */ + + parent_clock = clk_get_parent(this->clock); + parent_clock_rate_in_hz = clk_get_rate(parent_clock); + parent_clock_rate_in_mhz = parent_clock_rate_in_hz / 1000000; + nfc_clock_rate_in_hz = clk_get_rate(this->clock); + nfc_clock_rate_in_mhz = nfc_clock_rate_in_hz / 1000000; + + clock_divisor = parent_clock_rate_in_hz / nfc_clock_rate_in_hz; + symmetric_clock = this->nfc->get_symmetric(this) ? "Yes" : "No"; + cycle_in_ns = get_cycle_in_ns(this); + + dev_dbg(dev, "-------------\n"); + dev_dbg(dev, "Configuration\n"); + dev_dbg(dev, "-------------\n"); + dev_dbg(dev, "NFC Version : %d.%d\n" , this->nfc->major_version, + this->nfc->minor_version); + dev_dbg(dev, "Buffers : 0x%p\n" , this->buffers); + dev_dbg(dev, "Primary Regs : 0x%p\n" , this->primary_regs); + dev_dbg(dev, "Secondary Regs : 0x%p\n" , this->secondary_regs); + dev_dbg(dev, "Interrupt : %u\n" , this->interrupt); + dev_dbg(dev, "Clock Name : %s\n" , pdata->clock_name); + dev_dbg(dev, "Parent Clock Rate: %lu Hz (%lu MHz)\n", + parent_clock_rate_in_hz, + parent_clock_rate_in_mhz); + dev_dbg(dev, "Clock Divisor : %lu\n", clock_divisor); + dev_dbg(dev, "NFC Clock Rate : %lu Hz (%lu MHz)\n", + nfc_clock_rate_in_hz, + nfc_clock_rate_in_mhz); + dev_dbg(dev, "Symmetric Clock : %s\n" , symmetric_clock); + dev_dbg(dev, "Actual Cycle : %lu ns\n" , cycle_in_ns); + dev_dbg(dev, "Target Cycle : %u ns\n" , pdata->target_cycle_in_ns); + + /* Initialize the Medium Abstraction Layer. */ + + mal_init(this); + + /* Initialize the MTD Interface Layer. */ + + mil_init(this); + + /* Register this medium with MTD. */ + + error = register_with_mtd(this); + + if (error) + goto exit_mtd_registration; + + /* Create sysfs entries for this device. */ + + manage_sysfs_files(this, true); + + /* Return success. */ + + return 0; + + /* Error return paths begin here. */ + +exit_mtd_registration: + if (pdata->exit) + pdata->exit(); +exit_platform_init: + this->nfc->exit(this); +exit_nfc_init: +exit_acquire_resources: +exit_set_up_nfc_hal: + platform_set_drvdata(pdev, NULL); + kfree(this); +exit_allocate_this: +exit_validate_platform: + return error; + +} + +/** + * imx_nfc_remove() - Dissociates this driver from the given device. + * + * @pdev: A pointer to the device. + */ +static int __exit imx_nfc_remove(struct platform_device *pdev) +{ + struct imx_nfc_data *this = platform_get_drvdata(pdev); + + /* Remove sysfs entries for this device. */ + + manage_sysfs_files(this, false); + + /* Unregister with the NAND Flash MTD system. */ + + unregister_with_mtd(this); + + /* Tell the platform we're shutting down this device. */ + + if (this->pdata->exit) + this->pdata->exit(); + + /* Shut down the NFC. */ + + this->nfc->exit(this); + + /* Release our resources. */ + + release_resources(this); + + /* Unlink our per-device data from the platform device. */ + + platform_set_drvdata(pdev, NULL); + + /* Free our per-device data. */ + + kfree(this); + + /* Return success. */ + + return 0; +} + +#ifdef CONFIG_PM + +/** + * suspend() - Puts the NFC in a low power state. + * + * Refer to Documentation/driver-model/driver.txt for more information. + * + * @pdev: A pointer to the device. + * @state: The new power state. + */ + +static int imx_nfc_suspend(struct platform_device *pdev, pm_message_t state) +{ + int error = 0; + struct imx_nfc_data *this = platform_get_drvdata(pdev); + struct mtd_info *mtd = &this->mtd; + struct device *dev = &this->pdev->dev; + + dev_dbg(dev, "Suspending...\n"); + + /* Suspend MTD's use of this device. */ + + error = mtd->suspend(mtd); + + /* Suspend the actual hardware. */ + + clk_disable(this->clock); + + return error; + +} + +/** + * resume() - Brings the NFC back from a low power state. + * + * Refer to Documentation/driver-model/driver.txt for more information. + * + * @pdev: A pointer to the device. + */ +static int imx_nfc_resume(struct platform_device *pdev) +{ + struct imx_nfc_data *this = platform_get_drvdata(pdev); + struct mtd_info *mtd = &this->mtd; + struct device *dev = &this->pdev->dev; + + dev_dbg(dev, "Resuming...\n"); + + /* Resume MTD's use of this device. */ + + mtd->resume(mtd); + + return 0; + +} + +#else + +#define suspend NULL +#define resume NULL + +#endif /* CONFIG_PM */ + +/* + * This structure represents this driver to the platform management system. + */ +static struct platform_driver imx_nfc_driver = { + .driver = { + .name = IMX_NFC_DRIVER_NAME, + }, + .probe = imx_nfc_probe, + .remove = __exit_p(imx_nfc_remove), + .suspend = imx_nfc_suspend, + .resume = imx_nfc_resume, +}; + +/** + * imx_nfc_init() - Initializes this module. + */ +static int __init imx_nfc_init(void) +{ + + pr_info("i.MX NFC driver %s\n", DRIVER_VERSION); + + /* Register this driver with the platform management system. */ + + if (platform_driver_register(&imx_nfc_driver) != 0) { + pr_err("i.MX NFC driver registration failed\n"); + return -ENODEV; + } + + return 0; + +} + +/** + * imx_nfc_exit() - Deactivates this module. + */ +static void __exit imx_nfc_exit(void) +{ + pr_debug("i.MX NFC driver exiting...\n"); + platform_driver_unregister(&imx_nfc_driver); +} + +module_init(imx_nfc_init); +module_exit(imx_nfc_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("i.MX NAND Flash Controller Driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/mtd/nand/mxc_nand.c b/drivers/mtd/nand/mxc_nand.c index 88785032322a..66f38d598e13 100644 --- a/drivers/mtd/nand/mxc_nand.c +++ b/drivers/mtd/nand/mxc_nand.c @@ -1,5 +1,5 @@ /* - * Copyright 2004-2007 Freescale Semiconductor, Inc. All Rights Reserved. + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. * Copyright 2008 Sascha Hauer, kernel@pengutronix.de * * This program is free software; you can redistribute it and/or @@ -30,6 +30,7 @@ #include #include #include +#include #include #include diff --git a/drivers/mtd/nand/mxc_nd.c b/drivers/mtd/nand/mxc_nd.c new file mode 100644 index 000000000000..7344bafa77fa --- /dev/null +++ b/drivers/mtd/nand/mxc_nd.c @@ -0,0 +1,1413 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "mxc_nd.h" + +#define DVR_VER "2.1" + +struct mxc_mtd_s { + struct mtd_info mtd; + struct nand_chip nand; + struct mtd_partition *parts; + struct device *dev; +}; + +static struct mxc_mtd_s *mxc_nand_data; + +/* + * Define delays in microsec for NAND device operations + */ +#define TROP_US_DELAY 2000 +/* + * Macros to get half word and bit positions of ECC + */ +#define COLPOS(x) ((x) >> 4) +#define BITPOS(x) ((x) & 0xf) + +/* Define single bit Error positions in Main & Spare area */ +#define MAIN_SINGLEBIT_ERROR 0x4 +#define SPARE_SINGLEBIT_ERROR 0x1 + +struct nand_info { + bool bSpareOnly; + bool bStatusRequest; + u16 colAddr; +}; + +static struct nand_info g_nandfc_info; + +#ifdef CONFIG_MTD_NAND_MXC_SWECC +static int hardware_ecc; +#else +static int hardware_ecc = 1; +#endif + +#ifndef CONFIG_MTD_NAND_MXC_ECC_CORRECTION_OPTION2 +static int Ecc_disabled; +#endif + +static int is2k_Pagesize; + +static struct clk *nfc_clk; + +/* + * OOB placement block for use with hardware ecc generation + */ +static struct nand_ecclayout nand_hw_eccoob_8 = { + .eccbytes = 5, + .eccpos = {6, 7, 8, 9, 10}, + .oobfree = {{0, 5}, {11, 5} } +}; + +static struct nand_ecclayout nand_hw_eccoob_16 = { + .eccbytes = 5, + .eccpos = {6, 7, 8, 9, 10}, + .oobfree = {{0, 6}, {12, 4} } +}; + +static struct nand_ecclayout nand_hw_eccoob_2k = { + .eccbytes = 20, + .eccpos = {6, 7, 8, 9, 10, 22, 23, 24, 25, 26, + 38, 39, 40, 41, 42, 54, 55, 56, 57, 58}, + .oobfree = { + {.offset = 0, + .length = 5}, + + {.offset = 11, + .length = 10}, + + {.offset = 27, + .length = 10}, + + {.offset = 43, + .length = 10}, + + {.offset = 59, + .length = 5} + } +}; + +/*! + * @defgroup NAND_MTD NAND Flash MTD Driver for MXC processors + */ + +/*! + * @file mxc_nd.c + * + * @brief This file contains the hardware specific layer for NAND Flash on + * MXC processor + * + * @ingroup NAND_MTD + */ + +#ifdef CONFIG_MTD_PARTITIONS +static const char *part_probes[] = { "RedBoot", "cmdlinepart", NULL }; +#endif + +static wait_queue_head_t irq_waitq; + +static irqreturn_t mxc_nfc_irq(int irq, void *dev_id) +{ + NFC_CONFIG1 |= NFC_INT_MSK; /* Disable interrupt */ + wake_up(&irq_waitq); + + return IRQ_RETVAL(1); +} + +/*! + * This function polls the NANDFC to wait for the basic operation to complete by + * checking the INT bit of config2 register. + * + * @param maxRetries number of retry attempts (separated by 1 us) + * @param param parameter for debug + * @param useirq True if IRQ should be used rather than polling + */ +static void wait_op_done(int maxRetries, u16 param, bool useirq) +{ + if (useirq) { + if ((NFC_CONFIG2 & NFC_INT) == 0) { + NFC_CONFIG1 &= ~NFC_INT_MSK; /* Enable interrupt */ + wait_event(irq_waitq, NFC_CONFIG2 & NFC_INT); + } + NFC_CONFIG2 &= ~NFC_INT; + } else { + while (maxRetries-- > 0) { + if (NFC_CONFIG2 & NFC_INT) { + NFC_CONFIG2 &= ~NFC_INT; + break; + } + udelay(1); + } + if (maxRetries <= 0) + DEBUG(MTD_DEBUG_LEVEL0, "%s(%d): INT not set\n", + __FUNCTION__, param); + } +} + +/*! + * This function issues the specified command to the NAND device and + * waits for completion. + * + * @param cmd command for NAND Flash + * @param useirq True if IRQ should be used rather than polling + */ +static void send_cmd(u16 cmd, bool useirq) +{ + DEBUG(MTD_DEBUG_LEVEL3, "send_cmd(0x%x, %d)\n", cmd, useirq); + + NFC_FLASH_CMD = (u16) cmd; + NFC_CONFIG2 = NFC_CMD; + + /* Wait for operation to complete */ + wait_op_done(TROP_US_DELAY, cmd, useirq); +} + +/*! + * This function sends an address (or partial address) to the + * NAND device. The address is used to select the source/destination for + * a NAND command. + * + * @param addr address to be written to NFC. + * @param islast True if this is the last address cycle for command + */ +static void send_addr(u16 addr, bool islast) +{ + DEBUG(MTD_DEBUG_LEVEL3, "send_addr(0x%x %d)\n", addr, islast); + + NFC_FLASH_ADDR = addr; + NFC_CONFIG2 = NFC_ADDR; + + /* Wait for operation to complete */ + wait_op_done(TROP_US_DELAY, addr, islast); +} + +/*! + * This function requests the NANDFC to initate the transfer + * of data currently in the NANDFC RAM buffer to the NAND device. + * + * @param buf_id Specify Internal RAM Buffer number (0-3) + * @param bSpareOnly set true if only the spare area is transferred + */ +static void send_prog_page(u8 buf_id, bool bSpareOnly) +{ + DEBUG(MTD_DEBUG_LEVEL3, "send_prog_page (%d)\n", bSpareOnly); + + /* NANDFC buffer 0 is used for page read/write */ + + NFC_BUF_ADDR = buf_id; + + /* Configure spare or page+spare access */ + if (!is2k_Pagesize) { + if (bSpareOnly) { + NFC_CONFIG1 |= NFC_SP_EN; + } else { + NFC_CONFIG1 &= ~(NFC_SP_EN); + } + } + NFC_CONFIG2 = NFC_INPUT; + + /* Wait for operation to complete */ + wait_op_done(TROP_US_DELAY, bSpareOnly, true); +} + +/*! + * This function will correct the single bit ECC error + * + * @param buf_id Specify Internal RAM Buffer number (0-3) + * @param eccpos Ecc byte and bit position + * @param bSpareOnly set to true if only spare area needs correction + */ + +static void mxc_nd_correct_error(u8 buf_id, u16 eccpos, bool bSpareOnly) +{ + u16 col; + u8 pos; + volatile u16 *buf; + + /* Get col & bit position of error + these macros works for both 8 & 16 bits */ + col = COLPOS(eccpos); /* Get half-word position */ + pos = BITPOS(eccpos); /* Get bit position */ + + DEBUG(MTD_DEBUG_LEVEL3, + "mxc_nd_correct_error (col=%d pos=%d)\n", col, pos); + + /* Set the pointer for main / spare area */ + if (!bSpareOnly) { + buf = (volatile u16 *)(MAIN_AREA0 + col + (256 * buf_id)); + } else { + buf = (volatile u16 *)(SPARE_AREA0 + col + (8 * buf_id)); + } + + /* Fix the data */ + *buf ^= (1 << pos); +} + +/*! + * This function will maintains state of single bit Error + * in Main & spare area + * + * @param buf_id Specify Internal RAM Buffer number (0-3) + * @param spare set to true if only spare area needs correction + */ +static void mxc_nd_correct_ecc(u8 buf_id, bool spare) +{ +#ifdef CONFIG_MTD_NAND_MXC_ECC_CORRECTION_OPTION2 + static int lastErrMain, lastErrSpare; /* To maintain single bit + error in previous page */ +#endif + u16 value, ecc_status; + /* Read the ECC result */ + ecc_status = NFC_ECC_STATUS_RESULT; + DEBUG(MTD_DEBUG_LEVEL3, + "mxc_nd_correct_ecc (Ecc status=%x)\n", ecc_status); + +#ifdef CONFIG_MTD_NAND_MXC_ECC_CORRECTION_OPTION2 + /* Check for Error in Mainarea */ + if ((ecc_status & 0xC) == MAIN_SINGLEBIT_ERROR) { + /* Check for error in previous page */ + if (lastErrMain && !spare) { + value = NFC_RSLTMAIN_AREA; + /* Correct single bit error in Mainarea + NFC will not correct the error in + current page */ + mxc_nd_correct_error(buf_id, value, false); + } else { + /* Set if single bit error in current page */ + lastErrMain = 1; + } + } else { + /* Reset if no single bit error in current page */ + lastErrMain = 0; + } + + /* Check for Error in Sparearea */ + if ((ecc_status & 0x3) == SPARE_SINGLEBIT_ERROR) { + /* Check for error in previous page */ + if (lastErrSpare) { + value = NFC_RSLTSPARE_AREA; + /* Correct single bit error in Mainarea + NFC will not correct the error in + current page */ + mxc_nd_correct_error(buf_id, value, true); + } else { + /* Set if single bit error in current page */ + lastErrSpare = 1; + } + } else { + /* Reset if no single bit error in current page */ + lastErrSpare = 0; + } +#else + if (((ecc_status & 0xC) == MAIN_SINGLEBIT_ERROR) + || ((ecc_status & 0x3) == SPARE_SINGLEBIT_ERROR)) { + if (Ecc_disabled) { + if ((ecc_status & 0xC) == MAIN_SINGLEBIT_ERROR) { + value = NFC_RSLTMAIN_AREA; + /* Correct single bit error in Mainarea + NFC will not correct the error in + current page */ + mxc_nd_correct_error(buf_id, value, false); + } + if ((ecc_status & 0x3) == SPARE_SINGLEBIT_ERROR) { + value = NFC_RSLTSPARE_AREA; + /* Correct single bit error in Mainarea + NFC will not correct the error in + current page */ + mxc_nd_correct_error(buf_id, value, true); + } + + } else { + /* Disable ECC */ + NFC_CONFIG1 &= ~(NFC_ECC_EN); + Ecc_disabled = 1; + } + } else if (ecc_status == 0) { + if (Ecc_disabled) { + /* Enable ECC */ + NFC_CONFIG1 |= NFC_ECC_EN; + Ecc_disabled = 0; + } + } else { + /* 2-bit Error Do nothing */ + } +#endif /* CONFIG_MTD_NAND_MXC_ECC_CORRECTION_OPTION2 */ + +} + +/*! + * This function requests the NANDFC to initated the transfer + * of data from the NAND device into in the NANDFC ram buffer. + * + * @param buf_id Specify Internal RAM Buffer number (0-3) + * @param bSpareOnly set true if only the spare area is transferred + */ +static void send_read_page(u8 buf_id, bool bSpareOnly) +{ + DEBUG(MTD_DEBUG_LEVEL3, "send_read_page (%d)\n", bSpareOnly); + + /* NANDFC buffer 0 is used for page read/write */ + NFC_BUF_ADDR = buf_id; + + /* Configure spare or page+spare access */ + if (!is2k_Pagesize) { + if (bSpareOnly) { + NFC_CONFIG1 |= NFC_SP_EN; + } else { + NFC_CONFIG1 &= ~(NFC_SP_EN); + } + } + + NFC_CONFIG2 = NFC_OUTPUT; + + /* Wait for operation to complete */ + wait_op_done(TROP_US_DELAY, bSpareOnly, true); + + /* If there are single bit errors in + two consecutive page reads then + the error is not corrected by the + NFC for the second page. + Correct single bit error in driver */ + + mxc_nd_correct_ecc(buf_id, bSpareOnly); +} + +/*! + * This function requests the NANDFC to perform a read of the + * NAND device ID. + */ +static void send_read_id(void) +{ + struct nand_chip *this = &mxc_nand_data->nand; + + /* NANDFC buffer 0 is used for device ID output */ + NFC_BUF_ADDR = 0x0; + + /* Read ID into main buffer */ + NFC_CONFIG1 &= (~(NFC_SP_EN)); + NFC_CONFIG2 = NFC_ID; + + /* Wait for operation to complete */ + wait_op_done(TROP_US_DELAY, 0, true); + + if (this->options & NAND_BUSWIDTH_16) { + volatile u16 *mainBuf = MAIN_AREA0; + + /* + * Pack the every-other-byte result for 16-bit ID reads + * into every-byte as the generic code expects and various + * chips implement. + */ + + mainBuf[0] = (mainBuf[0] & 0xff) | ((mainBuf[1] & 0xff) << 8); + mainBuf[1] = (mainBuf[2] & 0xff) | ((mainBuf[3] & 0xff) << 8); + mainBuf[2] = (mainBuf[4] & 0xff) | ((mainBuf[5] & 0xff) << 8); + } +} + +/*! + * This function requests the NANDFC to perform a read of the + * NAND device status and returns the current status. + * + * @return device status + */ +static u16 get_dev_status(void) +{ + volatile u16 *mainBuf = MAIN_AREA1; + u32 store; + u16 ret; + /* Issue status request to NAND device */ + + /* store the main area1 first word, later do recovery */ + store = *((u32 *) mainBuf); + /* + * NANDFC buffer 1 is used for device status to prevent + * corruption of read/write buffer on status requests. + */ + NFC_BUF_ADDR = 1; + + /* Read status into main buffer */ + NFC_CONFIG1 &= (~(NFC_SP_EN)); + NFC_CONFIG2 = NFC_STATUS; + + /* Wait for operation to complete */ + wait_op_done(TROP_US_DELAY, 0, true); + + /* Status is placed in first word of main buffer */ + /* get status, then recovery area 1 data */ + ret = mainBuf[0]; + *((u32 *) mainBuf) = store; + + return ret; +} + +/*! + * This functions is used by upper layer to checks if device is ready + * + * @param mtd MTD structure for the NAND Flash + * + * @return 0 if device is busy else 1 + */ +static int mxc_nand_dev_ready(struct mtd_info *mtd) +{ + /* + * NFC handles R/B internally.Therefore,this function + * always returns status as ready. + */ + return 1; +} + +static void mxc_nand_enable_hwecc(struct mtd_info *mtd, int mode) +{ + /* + * If HW ECC is enabled, we turn it on during init. There is + * no need to enable again here. + */ +} + +static int mxc_nand_correct_data(struct mtd_info *mtd, u_char *dat, + u_char *read_ecc, u_char *calc_ecc) +{ + /* + * 1-Bit errors are automatically corrected in HW. No need for + * additional correction. 2-Bit errors cannot be corrected by + * HW ECC, so we need to return failure + */ + u16 ecc_status = NFC_ECC_STATUS_RESULT; + + if (((ecc_status & 0x3) == 2) || ((ecc_status >> 2) == 2)) { + DEBUG(MTD_DEBUG_LEVEL0, + "MXC_NAND: HWECC uncorrectable 2-bit ECC error\n"); + return -1; + } + + return 0; +} + +static int mxc_nand_calculate_ecc(struct mtd_info *mtd, const u_char *dat, + u_char *ecc_code) +{ + /* + * Just return success. HW ECC does not read/write the NFC spare + * buffer. Only the FLASH spare area contains the calcuated ECC. + */ + return 0; +} + +/*! + * This function reads byte from the NAND Flash + * + * @param mtd MTD structure for the NAND Flash + * + * @return data read from the NAND Flash + */ +static u_char mxc_nand_read_byte(struct mtd_info *mtd) +{ + u_char retVal = 0; + u16 col, rdWord; + volatile u16 *mainBuf = MAIN_AREA0; + volatile u16 *spareBuf = SPARE_AREA0; + + /* Check for status request */ + if (g_nandfc_info.bStatusRequest) { + return get_dev_status() & 0xFF; + } + + /* Get column for 16-bit access */ + col = g_nandfc_info.colAddr >> 1; + + /* If we are accessing the spare region */ + if (g_nandfc_info.bSpareOnly) { + rdWord = spareBuf[col]; + } else { + rdWord = mainBuf[col]; + } + + /* Pick upper/lower byte of word from RAM buffer */ + if (g_nandfc_info.colAddr & 0x1) { + retVal = (rdWord >> 8) & 0xFF; + } else { + retVal = rdWord & 0xFF; + } + + /* Update saved column address */ + g_nandfc_info.colAddr++; + + return retVal; +} + +/*! + * This function reads word from the NAND Flash + * + * @param mtd MTD structure for the NAND Flash + * + * @return data read from the NAND Flash + */ +static u16 mxc_nand_read_word(struct mtd_info *mtd) +{ + u16 col; + u16 rdWord, retVal; + volatile u16 *p; + + DEBUG(MTD_DEBUG_LEVEL3, + "mxc_nand_read_word(col = %d)\n", g_nandfc_info.colAddr); + + col = g_nandfc_info.colAddr; + /* Adjust saved column address */ + if (col < mtd->writesize && g_nandfc_info.bSpareOnly) + col += mtd->writesize; + + if (col < mtd->writesize) + p = (MAIN_AREA0) + (col >> 1); + else + p = (SPARE_AREA0) + ((col - mtd->writesize) >> 1); + + if (col & 1) { + rdWord = *p; + retVal = (rdWord >> 8) & 0xff; + rdWord = *(p + 1); + retVal |= (rdWord << 8) & 0xff00; + + } else { + retVal = *p; + + } + + /* Update saved column address */ + g_nandfc_info.colAddr = col + 2; + + return retVal; +} + +/*! + * This function writes data of length \b len to buffer \b buf. The data to be + * written on NAND Flash is first copied to RAMbuffer. After the Data Input + * Operation by the NFC, the data is written to NAND Flash + * + * @param mtd MTD structure for the NAND Flash + * @param buf data to be written to NAND Flash + * @param len number of bytes to be written + */ +static void mxc_nand_write_buf(struct mtd_info *mtd, + const u_char *buf, int len) +{ + int n; + int col; + int i = 0; + + DEBUG(MTD_DEBUG_LEVEL3, + "mxc_nand_write_buf(col = %d, len = %d)\n", g_nandfc_info.colAddr, + len); + + col = g_nandfc_info.colAddr; + + /* Adjust saved column address */ + if (col < mtd->writesize && g_nandfc_info.bSpareOnly) + col += mtd->writesize; + + n = mtd->writesize + mtd->oobsize - col; + n = min(len, n); + + DEBUG(MTD_DEBUG_LEVEL3, + "%s:%d: col = %d, n = %d\n", __FUNCTION__, __LINE__, col, n); + + while (n) { + volatile u32 *p; + if (col < mtd->writesize) + p = (volatile u32 *)((ulong) (MAIN_AREA0) + (col & ~3)); + else + p = (volatile u32 *)((ulong) (SPARE_AREA0) - + mtd->writesize + (col & ~3)); + + DEBUG(MTD_DEBUG_LEVEL3, "%s:%d: p = %p\n", __FUNCTION__, + __LINE__, p); + + if (((col | (int)&buf[i]) & 3) || n < 16) { + u32 data = 0; + + if (col & 3 || n < 4) + data = *p; + + switch (col & 3) { + case 0: + if (n) { + data = (data & 0xffffff00) | + (buf[i++] << 0); + n--; + col++; + } + case 1: + if (n) { + data = (data & 0xffff00ff) | + (buf[i++] << 8); + n--; + col++; + } + case 2: + if (n) { + data = (data & 0xff00ffff) | + (buf[i++] << 16); + n--; + col++; + } + case 3: + if (n) { + data = (data & 0x00ffffff) | + (buf[i++] << 24); + n--; + col++; + } + } + + *p = data; + } else { + int m = mtd->writesize - col; + + if (col >= mtd->writesize) + m += mtd->oobsize; + + m = min(n, m) & ~3; + + DEBUG(MTD_DEBUG_LEVEL3, + "%s:%d: n = %d, m = %d, i = %d, col = %d\n", + __FUNCTION__, __LINE__, n, m, i, col); + + memcpy((void *)(p), &buf[i], m); + col += m; + i += m; + n -= m; + } + } + /* Update saved column address */ + g_nandfc_info.colAddr = col; + +} + +/*! + * This function id is used to read the data buffer from the NAND Flash. To + * read the data from NAND Flash first the data output cycle is initiated by + * the NFC, which copies the data to RAMbuffer. This data of length \b len is + * then copied to buffer \b buf. + * + * @param mtd MTD structure for the NAND Flash + * @param buf data to be read from NAND Flash + * @param len number of bytes to be read + */ +static void mxc_nand_read_buf(struct mtd_info *mtd, u_char * buf, int len) +{ + + int n; + int col; + int i = 0; + + DEBUG(MTD_DEBUG_LEVEL3, + "mxc_nand_read_buf(col = %d, len = %d)\n", g_nandfc_info.colAddr, + len); + + col = g_nandfc_info.colAddr; + /* Adjust saved column address */ + if (col < mtd->writesize && g_nandfc_info.bSpareOnly) + col += mtd->writesize; + + n = mtd->writesize + mtd->oobsize - col; + n = min(len, n); + + while (n) { + volatile u32 *p; + + if (col < mtd->writesize) + p = (volatile u32 *)((ulong) (MAIN_AREA0) + (col & ~3)); + else + p = (volatile u32 *)((ulong) (SPARE_AREA0) - + mtd->writesize + (col & ~3)); + + if (((col | (int)&buf[i]) & 3) || n < 16) { + u32 data; + + data = *p; + switch (col & 3) { + case 0: + if (n) { + buf[i++] = (u8) (data); + n--; + col++; + } + case 1: + if (n) { + buf[i++] = (u8) (data >> 8); + n--; + col++; + } + case 2: + if (n) { + buf[i++] = (u8) (data >> 16); + n--; + col++; + } + case 3: + if (n) { + buf[i++] = (u8) (data >> 24); + n--; + col++; + } + } + } else { + int m = mtd->writesize - col; + + if (col >= mtd->writesize) + m += mtd->oobsize; + + m = min(n, m) & ~3; + memcpy(&buf[i], (void *)(p), m); + col += m; + i += m; + n -= m; + } + } + /* Update saved column address */ + g_nandfc_info.colAddr = col; + +} + +/*! + * This function is used by the upper layer to verify the data in NAND Flash + * with the data in the \b buf. + * + * @param mtd MTD structure for the NAND Flash + * @param buf data to be verified + * @param len length of the data to be verified + * + * @return -EFAULT if error else 0 + * + */ +static int +mxc_nand_verify_buf(struct mtd_info *mtd, const u_char * buf, int len) +{ + return -EFAULT; +} + +/*! + * This function is used by upper layer for select and deselect of the NAND + * chip + * + * @param mtd MTD structure for the NAND Flash + * @param chip val indicating select or deselect + */ +static void mxc_nand_select_chip(struct mtd_info *mtd, int chip) +{ +#ifdef CONFIG_MTD_NAND_MXC_FORCE_CE + if (chip > 0) { + DEBUG(MTD_DEBUG_LEVEL0, + "ERROR: Illegal chip select (chip = %d)\n", chip); + return; + } + + if (chip == -1) { + NFC_CONFIG1 &= (~(NFC_CE)); + return; + } + + NFC_CONFIG1 |= NFC_CE; +#endif + + switch (chip) { + case -1: + /* Disable the NFC clock */ + clk_disable(nfc_clk); + break; + case 0: + /* Enable the NFC clock */ + clk_enable(nfc_clk); + break; + + default: + break; + } +} + +/*! + * This function is used by the upper layer to write command to NAND Flash for + * different operations to be carried out on NAND Flash + * + * @param mtd MTD structure for the NAND Flash + * @param command command for NAND Flash + * @param column column offset for the page read + * @param page_addr page to be read from NAND Flash + */ +static void mxc_nand_command(struct mtd_info *mtd, unsigned command, + int column, int page_addr) +{ + bool useirq = true; + + DEBUG(MTD_DEBUG_LEVEL3, + "mxc_nand_command (cmd = 0x%x, col = 0x%x, page = 0x%x)\n", + command, column, page_addr); + + /* + * Reset command state information + */ + g_nandfc_info.bStatusRequest = false; + + /* Reset column address to 0 */ + g_nandfc_info.colAddr = 0; + + /* + * Command pre-processing step + */ + switch (command) { + + case NAND_CMD_STATUS: + g_nandfc_info.bStatusRequest = true; + break; + + case NAND_CMD_READ0: + g_nandfc_info.colAddr = column; + g_nandfc_info.bSpareOnly = false; + useirq = false; + break; + + case NAND_CMD_READOOB: + g_nandfc_info.colAddr = column; + g_nandfc_info.bSpareOnly = true; + useirq = false; + if (is2k_Pagesize) + command = NAND_CMD_READ0; /* only READ0 is valid */ + break; + + case NAND_CMD_SEQIN: + if (column >= mtd->writesize) { + if (is2k_Pagesize) { + /** + * FIXME: before send SEQIN command for write OOB, + * We must read one page out. + * For K9F1GXX has no READ1 command to set current HW + * pointer to spare area, we must write the whole page including OOB together. + */ + /* call itself to read a page */ + mxc_nand_command(mtd, NAND_CMD_READ0, 0, + page_addr); + } + g_nandfc_info.colAddr = column - mtd->writesize; + g_nandfc_info.bSpareOnly = true; + /* Set program pointer to spare region */ + if (!is2k_Pagesize) + send_cmd(NAND_CMD_READOOB, false); + } else { + g_nandfc_info.bSpareOnly = false; + g_nandfc_info.colAddr = column; + /* Set program pointer to page start */ + if (!is2k_Pagesize) + send_cmd(NAND_CMD_READ0, false); + } + useirq = false; + break; + + case NAND_CMD_PAGEPROG: +#ifndef CONFIG_MTD_NAND_MXC_ECC_CORRECTION_OPTION2 + if (Ecc_disabled) { + /* Enable Ecc for page writes */ + NFC_CONFIG1 |= NFC_ECC_EN; + } +#endif + + send_prog_page(0, g_nandfc_info.bSpareOnly); + + if (is2k_Pagesize) { + /* data in 4 areas datas */ + send_prog_page(1, g_nandfc_info.bSpareOnly); + send_prog_page(2, g_nandfc_info.bSpareOnly); + send_prog_page(3, g_nandfc_info.bSpareOnly); + } + + break; + + case NAND_CMD_ERASE1: + useirq = false; + break; + } + + /* + * Write out the command to the device. + */ + send_cmd(command, useirq); + + /* + * Write out column address, if necessary + */ + if (column != -1) { + /* + * MXC NANDFC can only perform full page+spare or + * spare-only read/write. When the upper layers + * layers perform a read/write buf operation, + * we will used the saved column adress to index into + * the full page. + */ + send_addr(0, page_addr == -1); + if (is2k_Pagesize) + /* another col addr cycle for 2k page */ + send_addr(0, false); + } + + /* + * Write out page address, if necessary + */ + if (page_addr != -1) { + send_addr((page_addr & 0xff), false); /* paddr_0 - p_addr_7 */ + + if (is2k_Pagesize) { + /* One more address cycle for higher density devices */ + if (mtd->size >= 0x10000000) { + /* paddr_8 - paddr_15 */ + send_addr((page_addr >> 8) & 0xff, false); + send_addr((page_addr >> 16) & 0xff, true); + } else + /* paddr_8 - paddr_15 */ + send_addr((page_addr >> 8) & 0xff, true); + } else { + /* One more address cycle for higher density devices */ + if (mtd->size >= 0x4000000) { + /* paddr_8 - paddr_15 */ + send_addr((page_addr >> 8) & 0xff, false); + send_addr((page_addr >> 16) & 0xff, true); + } else + /* paddr_8 - paddr_15 */ + send_addr((page_addr >> 8) & 0xff, true); + } + } + + /* + * Command post-processing step + */ + switch (command) { + + case NAND_CMD_RESET: + break; + + case NAND_CMD_READOOB: + case NAND_CMD_READ0: + if (is2k_Pagesize) { + /* send read confirm command */ + send_cmd(NAND_CMD_READSTART, true); + /* read for each AREA */ + send_read_page(0, g_nandfc_info.bSpareOnly); + send_read_page(1, g_nandfc_info.bSpareOnly); + send_read_page(2, g_nandfc_info.bSpareOnly); + send_read_page(3, g_nandfc_info.bSpareOnly); + } else { + send_read_page(0, g_nandfc_info.bSpareOnly); + } + break; + + case NAND_CMD_READID: + send_read_id(); + break; + + case NAND_CMD_PAGEPROG: +#ifndef CONFIG_MTD_NAND_MXC_ECC_CORRECTION_OPTION2 + if (Ecc_disabled) { + /* Disble Ecc after page writes */ + NFC_CONFIG1 &= ~(NFC_ECC_EN); + } +#endif + break; + + case NAND_CMD_STATUS: + break; + + case NAND_CMD_ERASE2: + break; + } +} + +/* Define some generic bad / good block scan pattern which are used + * while scanning a device for factory marked good / bad blocks. */ +static uint8_t scan_ff_pattern[] = { 0xff, 0xff }; + +static struct nand_bbt_descr smallpage_memorybased = { + .options = NAND_BBT_SCAN2NDPAGE, + .offs = 5, + .len = 1, + .pattern = scan_ff_pattern +}; + +static struct nand_bbt_descr largepage_memorybased = { + .options = 0, + .offs = 0, + .len = 2, + .pattern = scan_ff_pattern +}; + +/* Generic flash bbt decriptors +*/ +static uint8_t bbt_pattern[] = { 'B', 'b', 't', '0' }; +static uint8_t mirror_pattern[] = { '1', 't', 'b', 'B' }; + +static struct nand_bbt_descr bbt_main_descr = { + .options = NAND_BBT_LASTBLOCK | NAND_BBT_CREATE | NAND_BBT_WRITE + | NAND_BBT_2BIT | NAND_BBT_VERSION | NAND_BBT_PERCHIP, + .offs = 0, + .len = 4, + .veroffs = 4, + .maxblocks = 4, + .pattern = bbt_pattern +}; + +static struct nand_bbt_descr bbt_mirror_descr = { + .options = NAND_BBT_LASTBLOCK | NAND_BBT_CREATE | NAND_BBT_WRITE + | NAND_BBT_2BIT | NAND_BBT_VERSION | NAND_BBT_PERCHIP, + .offs = 0, + .len = 4, + .veroffs = 4, + .maxblocks = 4, + .pattern = mirror_pattern +}; + +static int mxc_nand_scan_bbt(struct mtd_info *mtd) +{ + struct nand_chip *this = mtd->priv; + + /* Config before scanning */ + /* Do not rely on NFMS_BIT, set/clear NFMS bit based on mtd->writesize */ + if (mtd->writesize == 2048) { + NFMS |= (1 << NFMS_BIT); + is2k_Pagesize = 1; + } else { + if ((NFMS >> NFMS_BIT) & 0x1) { /* This case strangly happened on MXC91321 P1.2.2 */ + printk(KERN_INFO + "Oops... NFMS Bit set for 512B Page, resetting it. [RCSR: 0x%08x]\n", + NFMS); + NFMS &= ~(1 << NFMS_BIT); + } + is2k_Pagesize = 0; + } + + if (is2k_Pagesize) + this->ecc.layout = &nand_hw_eccoob_2k; + + /* jffs2 not write oob */ + mtd->flags &= ~MTD_OOB_WRITEABLE; + + /* use flash based bbt */ + this->bbt_td = &bbt_main_descr; + this->bbt_md = &bbt_mirror_descr; + + /* update flash based bbt */ + this->options |= NAND_USE_FLASH_BBT; + + if (!this->badblock_pattern) { + if (mtd->writesize == 2048) + this->badblock_pattern = &smallpage_memorybased; + else + this->badblock_pattern = (mtd->writesize > 512) ? + &largepage_memorybased : &smallpage_memorybased; + } + /* Build bad block table */ + return nand_scan_bbt(mtd, this->badblock_pattern); +} + +#ifdef CONFIG_MXC_NAND_LOW_LEVEL_ERASE +static void mxc_low_erase(struct mtd_info *mtd) +{ + + struct nand_chip *this = mtd->priv; + unsigned int page_addr, addr; + u_char status; + + DEBUG(MTD_DEBUG_LEVEL0, "MXC_ND : mxc_low_erase:Erasing NAND\n"); + for (addr = 0; addr < this->chipsize; addr += mtd->erasesize) { + page_addr = addr / mtd->writesize; + mxc_nand_command(mtd, NAND_CMD_ERASE1, -1, page_addr); + mxc_nand_command(mtd, NAND_CMD_ERASE2, -1, -1); + mxc_nand_command(mtd, NAND_CMD_STATUS, -1, -1); + status = mxc_nand_read_byte(mtd); + if (status & NAND_STATUS_FAIL) { + printk(KERN_ERR + "ERASE FAILED(block = %d,status = 0x%x)\n", + addr / mtd->erasesize, status); + } + } + +} +#endif +/*! + * This function is called during the driver binding process. + * + * @param pdev the device structure used to store device specific + * information that is used by the suspend, resume and + * remove functions + * + * @return The function always returns 0. + */ +static int __init mxcnd_probe(struct platform_device *pdev) +{ + struct nand_chip *this; + struct mtd_info *mtd; + struct flash_platform_data *flash = pdev->dev.platform_data; + int nr_parts = 0; + + int err = 0; + /* Allocate memory for MTD device structure and private data */ + mxc_nand_data = kzalloc(sizeof(struct mxc_mtd_s), GFP_KERNEL); + if (!mxc_nand_data) { + printk(KERN_ERR "%s: failed to allocate mtd_info\n", + __FUNCTION__); + err = -ENOMEM; + goto out; + } + memset((char *)&g_nandfc_info, 0, sizeof(g_nandfc_info)); + + mxc_nand_data->dev = &pdev->dev; + /* structures must be linked */ + this = &mxc_nand_data->nand; + mtd = &mxc_nand_data->mtd; + mtd->priv = this; + mtd->owner = THIS_MODULE; + + /* 50 us command delay time */ + this->chip_delay = 5; + + this->priv = mxc_nand_data; + this->dev_ready = mxc_nand_dev_ready; + this->cmdfunc = mxc_nand_command; + this->select_chip = mxc_nand_select_chip; + this->read_byte = mxc_nand_read_byte; + this->read_word = mxc_nand_read_word; + this->write_buf = mxc_nand_write_buf; + this->read_buf = mxc_nand_read_buf; + this->verify_buf = mxc_nand_verify_buf; + this->scan_bbt = mxc_nand_scan_bbt; + + nfc_clk = clk_get(&pdev->dev, "nfc_clk"); + clk_enable(nfc_clk); + + NFC_CONFIG1 |= NFC_INT_MSK; + init_waitqueue_head(&irq_waitq); + err = request_irq(MXC_INT_NANDFC, mxc_nfc_irq, 0, "mxc_nd", NULL); + if (err) { + goto out_1; + } + + if (hardware_ecc) { + this->ecc.calculate = mxc_nand_calculate_ecc; + this->ecc.hwctl = mxc_nand_enable_hwecc; + this->ecc.correct = mxc_nand_correct_data; + this->ecc.mode = NAND_ECC_HW; + this->ecc.size = 512; + this->ecc.bytes = 3; + this->ecc.layout = &nand_hw_eccoob_8; + NFC_CONFIG1 |= NFC_ECC_EN; + } else { + this->ecc.mode = NAND_ECC_SOFT; + } + + /* Reset NAND */ + this->cmdfunc(mtd, NAND_CMD_RESET, -1, -1); + + /* preset operation */ + /* Unlock the internal RAM Buffer */ + NFC_CONFIG = 0x2; + + /* Blocks to be unlocked */ + NFC_UNLOCKSTART_BLKADDR = 0x0; + NFC_UNLOCKEND_BLKADDR = 0x4000; + + /* Unlock Block Command for given address range */ + NFC_WRPROT = 0x4; + + /* NAND bus width determines access funtions used by upper layer */ + if (flash->width == 2) { + this->options |= NAND_BUSWIDTH_16; + this->ecc.layout = &nand_hw_eccoob_16; + } else { + this->options |= 0; + } + + is2k_Pagesize = 0; + + /* Scan to find existence of the device */ + if (nand_scan(mtd, 1)) { + DEBUG(MTD_DEBUG_LEVEL0, + "MXC_ND: Unable to find any NAND device.\n"); + err = -ENXIO; + goto out_1; + } + + /* Register the partitions */ +#ifdef CONFIG_MTD_PARTITIONS + nr_parts = + parse_mtd_partitions(mtd, part_probes, &mxc_nand_data->parts, 0); + if (nr_parts > 0) + add_mtd_partitions(mtd, mxc_nand_data->parts, nr_parts); + else if (flash->parts) + add_mtd_partitions(mtd, flash->parts, flash->nr_parts); + else +#endif + { + pr_info("Registering %s as whole device\n", mtd->name); + add_mtd_device(mtd); + } +#ifdef CONFIG_MXC_NAND_LOW_LEVEL_ERASE + /* Erase all the blocks of a NAND */ + mxc_low_erase(mtd); +#endif + + platform_set_drvdata(pdev, mtd); + return 0; + + out_1: + kfree(mxc_nand_data); + out: + return err; + +} + + /*! + * Dissociates the driver from the device. + * + * @param pdev the device structure used to give information on which + * + * @return The function always returns 0. + */ + +static int __exit mxcnd_remove(struct platform_device *pdev) +{ + struct mtd_info *mtd = platform_get_drvdata(pdev); + + clk_put(nfc_clk); + platform_set_drvdata(pdev, NULL); + + if (mxc_nand_data) { + nand_release(mtd); + free_irq(MXC_INT_NANDFC, NULL); + kfree(mxc_nand_data); + } + + return 0; +} + +#ifdef CONFIG_PM +/*! + * This function is called to put the NAND in a low power state. Refer to the + * document driver-model/driver.txt in the kernel source tree for more + * information. + * + * @param pdev the device information structure + * + * @param state the power state the device is entering + * + * @return The function returns 0 on success and -1 on failure + */ + +static int mxcnd_suspend(struct platform_device *pdev, pm_message_t state) +{ + struct mtd_info *info = platform_get_drvdata(pdev); + int ret = 0; + + DEBUG(MTD_DEBUG_LEVEL0, "MXC_ND : NAND suspend\n"); + if (info) + ret = info->suspend(info); + + /* Disable the NFC clock */ + clk_disable(nfc_clk); + + return ret; +} + +/*! + * This function is called to bring the NAND back from a low power state. Refer + * to the document driver-model/driver.txt in the kernel source tree for more + * information. + * + * @param pdev the device information structure + * + * @return The function returns 0 on success and -1 on failure + */ +static int mxcnd_resume(struct platform_device *pdev) +{ + struct mtd_info *info = platform_get_drvdata(pdev); + int ret = 0; + + DEBUG(MTD_DEBUG_LEVEL0, "MXC_ND : NAND resume\n"); + /* Enable the NFC clock */ + clk_enable(nfc_clk); + + if (info) { + info->resume(info); + } + + return ret; +} + +#else +#define mxcnd_suspend NULL +#define mxcnd_resume NULL +#endif /* CONFIG_PM */ + +/*! + * This structure contains pointers to the power management callback functions. + */ +static struct platform_driver mxcnd_driver = { + .driver = { + .name = "mxc_nand_flash", + }, + .probe = mxcnd_probe, + .remove = __exit_p(mxcnd_remove), + .suspend = mxcnd_suspend, + .resume = mxcnd_resume, +}; + +/*! + * Main initialization routine + * @return 0 if successful; non-zero otherwise + */ +static int __init mxc_nd_init(void) +{ + /* Register the device driver structure. */ + pr_info("MXC MTD nand Driver %s\n", DVR_VER); + if (platform_driver_register(&mxcnd_driver) != 0) { + printk(KERN_ERR "Driver register failed for mxcnd_driver\n"); + return -ENODEV; + } + return 0; +} + +/*! + * Clean up routine + */ +static void __exit mxc_nd_cleanup(void) +{ + /* Unregister the device structure */ + platform_driver_unregister(&mxcnd_driver); +} + +module_init(mxc_nd_init); +module_exit(mxc_nd_cleanup); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MXC NAND MTD driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/mtd/nand/mxc_nd.h b/drivers/mtd/nand/mxc_nd.h new file mode 100644 index 000000000000..a2a257c3897c --- /dev/null +++ b/drivers/mtd/nand/mxc_nd.h @@ -0,0 +1,112 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mxc_nd.h + * + * @brief This file contains the NAND Flash Controller register information. + * + * + * @ingroup NAND_MTD + */ + +#ifndef __MXC_ND_H__ +#define __MXC_ND_H__ + +#include + +/* + * Addresses for NFC registers + */ +#define NFC_BUF_SIZE (*((volatile u16 *)IO_ADDRESS(NFC_BASE_ADDR + 0xE00))) +#define NFC_BUF_ADDR (*((volatile u16 *)IO_ADDRESS(NFC_BASE_ADDR + 0xE04))) +#define NFC_FLASH_ADDR (*((volatile u16 *)IO_ADDRESS(NFC_BASE_ADDR + 0xE06))) +#define NFC_FLASH_CMD (*((volatile u16 *)IO_ADDRESS(NFC_BASE_ADDR + 0xE08))) +#define NFC_CONFIG (*((volatile u16 *)IO_ADDRESS(NFC_BASE_ADDR + 0xE0A))) +#define NFC_ECC_STATUS_RESULT (*((volatile u16 *)IO_ADDRESS(NFC_BASE_ADDR + 0xE0C))) +#define NFC_RSLTMAIN_AREA (*((volatile u16 *)IO_ADDRESS(NFC_BASE_ADDR + 0xE0E))) +#define NFC_RSLTSPARE_AREA (*((volatile u16 *)IO_ADDRESS(NFC_BASE_ADDR + 0xE10))) +#define NFC_WRPROT (*((volatile u16 *)IO_ADDRESS(NFC_BASE_ADDR + 0xE12))) +#define NFC_UNLOCKSTART_BLKADDR (*((volatile u16 *)IO_ADDRESS(NFC_BASE_ADDR + 0xE14))) +#define NFC_UNLOCKEND_BLKADDR (*((volatile u16 *)IO_ADDRESS(NFC_BASE_ADDR + 0xE16))) +#define NFC_NF_WRPRST (*((volatile u16 *)IO_ADDRESS(NFC_BASE_ADDR + 0xE18))) +#define NFC_CONFIG1 (*((volatile u16 *)IO_ADDRESS(NFC_BASE_ADDR + 0xE1A))) +#define NFC_CONFIG2 (*((volatile u16 *)IO_ADDRESS(NFC_BASE_ADDR + 0xE1C))) + +/*! + * Addresses for NFC RAM BUFFER Main area 0 + */ +#define MAIN_AREA0 (volatile u16 *)IO_ADDRESS(NFC_BASE_ADDR + 0x000) +#define MAIN_AREA1 (volatile u16 *)IO_ADDRESS(NFC_BASE_ADDR + 0x200) +#define MAIN_AREA2 (volatile u16 *)IO_ADDRESS(NFC_BASE_ADDR + 0x400) +#define MAIN_AREA3 (volatile u16 *)IO_ADDRESS(NFC_BASE_ADDR + 0x600) + +/*! + * Addresses for NFC SPARE BUFFER Spare area 0 + */ +#define SPARE_AREA0 (volatile u16 *)IO_ADDRESS(NFC_BASE_ADDR + 0x800) +#define SPARE_AREA1 (volatile u16 *)IO_ADDRESS(NFC_BASE_ADDR + 0x810) +#define SPARE_AREA2 (volatile u16 *)IO_ADDRESS(NFC_BASE_ADDR + 0x820) +#define SPARE_AREA3 (volatile u16 *)IO_ADDRESS(NFC_BASE_ADDR + 0x830) + +/*! + * Set INT to 0, FCMD to 1, rest to 0 in NFC_CONFIG2 Register for Command + * operation + */ +#define NFC_CMD 0x1 + +/*! + * Set INT to 0, FADD to 1, rest to 0 in NFC_CONFIG2 Register for Address + * operation + */ +#define NFC_ADDR 0x2 + +/*! + * Set INT to 0, FDI to 1, rest to 0 in NFC_CONFIG2 Register for Input + * operation + */ +#define NFC_INPUT 0x4 + +/*! + * Set INT to 0, FDO to 001, rest to 0 in NFC_CONFIG2 Register for Data Output + * operation + */ +#define NFC_OUTPUT 0x8 + +/*! + * Set INT to 0, FD0 to 010, rest to 0 in NFC_CONFIG2 Register for Read ID + * operation + */ +#define NFC_ID 0x10 + +/*! + * Set INT to 0, FDO to 100, rest to 0 in NFC_CONFIG2 Register for Read Status + * operation + */ +#define NFC_STATUS 0x20 + +/*! + * Set INT to 1, rest to 0 in NFC_CONFIG2 Register for Read Status + * operation + */ +#define NFC_INT 0x8000 + +#define NFC_SP_EN (1 << 2) +#define NFC_ECC_EN (1 << 3) +#define NFC_INT_MSK (1 << 4) +#define NFC_BIG (1 << 5) +#define NFC_RST (1 << 6) +#define NFC_CE (1 << 7) +#define NFC_ONE_CYCLE (1 << 8) + +#endif /* MXCND_H */ diff --git a/drivers/mtd/nand/mxc_nd2.c b/drivers/mtd/nand/mxc_nd2.c new file mode 100644 index 000000000000..2f7bebff6a61 --- /dev/null +++ b/drivers/mtd/nand/mxc_nd2.c @@ -0,0 +1,1628 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "mxc_nd2.h" +#include "nand_device_info.h" + +#define DVR_VER "3.0" + +/* Global address Variables */ +static void __iomem *nfc_axi_base, *nfc_ip_base; +static int nfc_irq; + +struct mxc_mtd_s { + struct mtd_info mtd; + struct nand_chip nand; + struct mtd_partition *parts; + struct device *dev; + int disable_bi_swap; /* disable bi swap */ +}; + +static struct mxc_mtd_s *mxc_nand_data; + +/* + * Define delay timeout value + */ +#define TROP_US_DELAY (1000 * 1000) + +struct nand_info { + bool bStatusRequest; + u16 colAddr; +}; + +static struct nand_info g_nandfc_info; + +#ifdef CONFIG_MTD_NAND_MXC_SWECC +static int hardware_ecc; +#else +static int hardware_ecc = 1; +#endif + +static u8 num_of_interleave = 1; + +static u8 *data_buf; +static u8 *oob_buf; + +static int g_page_mask; + +static struct clk *nfc_clk; + +/* + * OOB placement block for use with hardware ecc generation + */ +static struct nand_ecclayout nand_hw_eccoob_512 = { + .eccbytes = 9, + .eccpos = {7, 8, 9, 10, 11, 12, 13, 14, 15}, + .oobavail = 4, + .oobfree = {{0, 4} } +}; + +static struct nand_ecclayout nand_hw_eccoob_2k = { + .eccbytes = 9, + .eccpos = {7, 8, 9, 10, 11, 12, 13, 14, 15}, + .oobavail = 4, + .oobfree = {{2, 4} } +}; + +static struct nand_ecclayout nand_hw_eccoob_4k = { + .eccbytes = 9, + .eccpos = {7, 8, 9, 10, 11, 12, 13, 14, 15}, + .oobavail = 4, + .oobfree = {{2, 4} } +}; + +/*! + * @defgroup NAND_MTD NAND Flash MTD Driver for MXC processors + */ + +/*! + * @file mxc_nd2.c + * + * @brief This file contains the hardware specific layer for NAND Flash on + * MXC processor + * + * @ingroup NAND_MTD + */ + +#ifdef CONFIG_MTD_PARTITIONS +static const char *part_probes[] = { "RedBoot", "cmdlinepart", NULL }; +#endif + +static wait_queue_head_t irq_waitq; + +static irqreturn_t mxc_nfc_irq(int irq, void *dev_id) +{ + /* Disable Interuupt */ + raw_write(raw_read(REG_NFC_INTRRUPT) | NFC_INT_MSK, REG_NFC_INTRRUPT); + wake_up(&irq_waitq); + + return IRQ_HANDLED; +} + +static void mxc_nand_bi_swap(struct mtd_info *mtd) +{ + u16 ma, sa, nma, nsa; + + if (!IS_LARGE_PAGE_NAND) + return; + + /* Disable bi swap if the user set disable_bi_swap at sys entry */ + if (mxc_nand_data->disable_bi_swap) + return; + + ma = __raw_readw(BAD_BLK_MARKER_MAIN); + sa = __raw_readw(BAD_BLK_MARKER_SP); + + nma = (ma & 0xFF00) | (sa >> 8); + nsa = (sa & 0x00FF) | (ma << 8); + + __raw_writew(nma, BAD_BLK_MARKER_MAIN); + __raw_writew(nsa, BAD_BLK_MARKER_SP); +} + +static void nfc_memcpy(void *dest, void *src, int len) +{ + u8 *d = dest; + u8 *s = src; + + while (len > 0) { + if (len >= 4) { + *(u32 *)d = *(u32 *)s; + d += 4; + s += 4; + len -= 4; + } else { + *(u16 *)d = *(u16 *)s; + len -= 2; + break; + } + } + + if (len) + BUG(); +} + +/* + * Functions to transfer data to/from spare erea. + */ +static void +copy_spare(struct mtd_info *mtd, void *pbuf, void *pspare, int len, bool bfrom) +{ + u16 i, j; + u16 m = mtd->oobsize; + u16 n = mtd->writesize >> 9; + u8 *d = (u8 *) pbuf; + u8 *s = (u8 *) pspare; + u16 t = SPARE_LEN; + + m /= num_of_interleave; + n /= num_of_interleave; + + j = (m / n >> 1) << 1; + + if (bfrom) { + for (i = 0; i < n - 1; i++) + nfc_memcpy(&d[i * j], &s[i * t], j); + + /* the last section */ + nfc_memcpy(&d[i * j], &s[i * t], len - i * j); + } else { + for (i = 0; i < n - 1; i++) + nfc_memcpy(&s[i * t], &d[i * j], j); + + /* the last section */ + nfc_memcpy(&s[i * t], &d[i * j], len - i * j); + } +} + +/*! + * This function polls the NFC to wait for the basic operation to complete by + * checking the INT bit of config2 register. + * + * @param maxRetries number of retry attempts (separated by 1 us) + * @param useirq True if IRQ should be used rather than polling + */ +static void wait_op_done(int maxRetries, bool useirq) +{ + if (useirq) { + if ((raw_read(REG_NFC_OPS_STAT) & NFC_OPS_STAT) == 0) { + /* enable interrupt */ + raw_write(raw_read(REG_NFC_INTRRUPT) & ~NFC_INT_MSK, + REG_NFC_INTRRUPT); + if (!wait_event_timeout(irq_waitq, + (raw_read(REG_NFC_OPS_STAT) & NFC_OPS_STAT), + msecs_to_jiffies(TROP_US_DELAY / 1000)) > 0) { + /* disable interrupt */ + raw_write(raw_read(REG_NFC_INTRRUPT) + | NFC_INT_MSK, REG_NFC_INTRRUPT); + + printk(KERN_WARNING "%s(%d): INT not set\n", + __func__, __LINE__); + return; + } + } + WRITE_NFC_IP_REG((raw_read(REG_NFC_OPS_STAT) & + ~NFC_OPS_STAT), REG_NFC_OPS_STAT); + } else { + while (1) { + maxRetries--; + if (raw_read(REG_NFC_OPS_STAT) & NFC_OPS_STAT) { + WRITE_NFC_IP_REG((raw_read(REG_NFC_OPS_STAT) & + ~NFC_OPS_STAT), + REG_NFC_OPS_STAT); + break; + } + udelay(1); + if (maxRetries <= 0) { + printk(KERN_WARNING "%s(%d): INT not set\n", + __func__, __LINE__); + break; + } + } + } +} + +static inline void send_atomic_cmd(u16 cmd, bool useirq) +{ + /* fill command */ + raw_write(cmd, REG_NFC_FLASH_CMD); + + /* send out command */ + raw_write(NFC_CMD, REG_NFC_OPS); + + /* Wait for operation to complete */ + wait_op_done(TROP_US_DELAY, useirq); +} + +static void mxc_do_addr_cycle(struct mtd_info *mtd, int column, int page_addr); +static int mxc_check_ecc_status(struct mtd_info *mtd); + +#ifdef NFC_AUTO_MODE_ENABLE +/*! + * This function handle the interleave related work + * @param mtd mtd info + * @param cmd command + */ +static void auto_cmd_interleave(struct mtd_info *mtd, u16 cmd) +{ + u32 i, page_addr, ncs; + u32 j = num_of_interleave; + struct nand_chip *this = mtd->priv; + u32 addr_low = raw_read(NFC_FLASH_ADDR0); + u32 addr_high = raw_read(NFC_FLASH_ADDR8); + u8 *dbuf = data_buf; + u8 *obuf = oob_buf; + u32 dlen = mtd->writesize / j; + u32 olen = mtd->oobsize / j; + + /* adjust the addr value + * since ADD_OP mode is 01 + */ + if (cmd == NAND_CMD_ERASE2) + page_addr = addr_low; + else + page_addr = addr_low >> 16 | addr_high << 16; + + ncs = page_addr >> (this->chip_shift - this->page_shift); + + if (j > 1) { + page_addr *= j; + } else { + page_addr *= this->numchips; + page_addr += ncs; + } + + switch (cmd) { + case NAND_CMD_PAGEPROG: + for (i = 0; i < j; i++) { + /* reset addr cycle */ + mxc_do_addr_cycle(mtd, 0, page_addr++); + + /* data transfer */ + memcpy(MAIN_AREA0, dbuf, dlen); + copy_spare(mtd, obuf, SPARE_AREA0, olen, false); + mxc_nand_bi_swap(mtd); + + /* update the value */ + dbuf += dlen; + obuf += olen; + + NFC_SET_RBA(0); + raw_write(NFC_AUTO_PROG, REG_NFC_OPS); + + /* wait auto_prog_done bit set */ + while (!(raw_read(REG_NFC_OPS_STAT) & NFC_OP_DONE)) + ; + } + + wait_op_done(TROP_US_DELAY, true); + while (!(raw_read(REG_NFC_OPS_STAT) & NFC_RB)); + + break; + case NAND_CMD_READSTART: + for (i = 0; i < j; i++) { + /* reset addr cycle */ + mxc_do_addr_cycle(mtd, 0, page_addr++); + + NFC_SET_RBA(0); + raw_write(NFC_AUTO_READ, REG_NFC_OPS); + wait_op_done(TROP_US_DELAY, true); + + /* check ecc error */ + mxc_check_ecc_status(mtd); + + /* data transfer */ + mxc_nand_bi_swap(mtd); + memcpy(dbuf, MAIN_AREA0, dlen); + copy_spare(mtd, obuf, SPARE_AREA0, olen, true); + + /* update the value */ + dbuf += dlen; + obuf += olen; + } + break; + case NAND_CMD_ERASE2: + for (i = 0; i < j; i++) { + mxc_do_addr_cycle(mtd, -1, page_addr++); + raw_write(NFC_AUTO_ERASE, REG_NFC_OPS); + wait_op_done(TROP_US_DELAY, true); + } + break; + case NAND_CMD_RESET: + for (i = 0; i < j; i++) { + if (j > 1) + NFC_SET_NFC_ACTIVE_CS(i); + send_atomic_cmd(cmd, false); + } + break; + default: + break; + } +} +#endif + +static void send_addr(u16 addr, bool useirq); + +/*! + * This function issues the specified command to the NAND device and + * waits for completion. + * + * @param cmd command for NAND Flash + * @param useirq True if IRQ should be used rather than polling + */ +static void send_cmd(struct mtd_info *mtd, u16 cmd, bool useirq) +{ + DEBUG(MTD_DEBUG_LEVEL3, "send_cmd(0x%x, %d)\n", cmd, useirq); + +#ifdef NFC_AUTO_MODE_ENABLE + switch (cmd) { + case NAND_CMD_READ0: + case NAND_CMD_READOOB: + raw_write(NAND_CMD_READ0, REG_NFC_FLASH_CMD); + break; + case NAND_CMD_SEQIN: + case NAND_CMD_ERASE1: + raw_write(cmd, REG_NFC_FLASH_CMD); + break; + case NAND_CMD_PAGEPROG: + case NAND_CMD_ERASE2: + case NAND_CMD_READSTART: + raw_write(raw_read(REG_NFC_FLASH_CMD) | cmd << NFC_CMD_1_SHIFT, + REG_NFC_FLASH_CMD); + auto_cmd_interleave(mtd, cmd); + break; + case NAND_CMD_READID: + send_atomic_cmd(cmd, useirq); + send_addr(0, false); + break; + case NAND_CMD_RESET: + auto_cmd_interleave(mtd, cmd); + break; + case NAND_CMD_STATUS: + send_atomic_cmd(cmd, useirq); + break; + default: + break; + } +#else + send_atomic_cmd(cmd, useirq); +#endif +} + +/*! + * This function sends an address (or partial address) to the + * NAND device. The address is used to select the source/destination for + * a NAND command. + * + * @param addr address to be written to NFC. + * @param useirq True if IRQ should be used rather than polling + */ +static void send_addr(u16 addr, bool useirq) +{ + DEBUG(MTD_DEBUG_LEVEL3, "send_addr(0x%x %d)\n", addr, useirq); + + /* fill address */ + raw_write((addr << NFC_FLASH_ADDR_SHIFT), REG_NFC_FLASH_ADDR); + + /* send out address */ + raw_write(NFC_ADDR, REG_NFC_OPS); + + /* Wait for operation to complete */ + wait_op_done(TROP_US_DELAY, useirq); +} + +/*! + * This function requests the NFC to initate the transfer + * of data currently in the NFC RAM buffer to the NAND device. + * + * @param buf_id Specify Internal RAM Buffer number + */ +static void send_prog_page(u8 buf_id) +{ +#ifndef NFC_AUTO_MODE_ENABLE + DEBUG(MTD_DEBUG_LEVEL3, "%s\n", __FUNCTION__); + + /* set ram buffer id */ + NFC_SET_RBA(buf_id); + + /* transfer data from NFC ram to nand */ + raw_write(NFC_INPUT, REG_NFC_OPS); + + /* Wait for operation to complete */ + wait_op_done(TROP_US_DELAY, true); +#endif +} + +/*! + * This function requests the NFC to initated the transfer + * of data from the NAND device into in the NFC ram buffer. + * + * @param buf_id Specify Internal RAM Buffer number + */ +static void send_read_page(u8 buf_id) +{ +#ifndef NFC_AUTO_MODE_ENABLE + DEBUG(MTD_DEBUG_LEVEL3, "%s(%d)\n", __FUNCTION__, buf_id); + + /* set ram buffer id */ + NFC_SET_RBA(buf_id); + + /* transfer data from nand to NFC ram */ + raw_write(NFC_OUTPUT, REG_NFC_OPS); + + /* Wait for operation to complete */ + wait_op_done(TROP_US_DELAY, true); +#endif +} + +/*! + * This function requests the NFC to perform a read of the + * NAND device ID. + */ +static void send_read_id(void) +{ + /* Set RBA bits for BUFFER0 */ + NFC_SET_RBA(0); + + /* Read ID into main buffer */ + raw_write(NFC_ID, REG_NFC_OPS); + + /* Wait for operation to complete */ + wait_op_done(TROP_US_DELAY, false); + +} + +#ifdef NFC_AUTO_MODE_ENABLE +static inline void read_dev_status(u16 *status) +{ + u32 mask = 0xFF << 16; + + /* use atomic mode to read status instead + of using auto mode,auto-mode has issues + and the status is not correct. + */ + raw_write(NFC_STATUS, REG_NFC_OPS); + + wait_op_done(TROP_US_DELAY, true); + + *status = (raw_read(NFC_CONFIG1) & mask) >> 16; + +} +#endif + +/*! + * This function requests the NFC to perform a read of the + * NAND device status and returns the current status. + * + * @return device status + */ +static u16 get_dev_status(void) +{ +#ifdef NFC_AUTO_MODE_ENABLE + int i; + u16 status = 0; + for (i = 0; i < num_of_interleave; i++) { + + /* set ative cs */ + NFC_SET_NFC_ACTIVE_CS(i); + + /* FIXME, NFC Auto erase may have + * problem, have to pollingit until + * the nand get idle, otherwise + * it may get error + */ + read_dev_status(&status); + if (status & NAND_STATUS_FAIL) + break; + } + + return status; +#else + volatile u16 *mainBuf = MAIN_AREA1; + u8 val = 1; + u16 ret; + + /* Set ram buffer id */ + NFC_SET_RBA(val); + + /* Read status into main buffer */ + raw_write(NFC_STATUS, REG_NFC_OPS); + + /* Wait for operation to complete */ + wait_op_done(TROP_US_DELAY, true); + + /* Status is placed in first word of main buffer */ + /* get status, then recovery area 1 data */ + ret = *mainBuf; + + return ret; +#endif +} + +static void mxc_nand_enable_hwecc(struct mtd_info *mtd, int mode) +{ + raw_write((raw_read(REG_NFC_ECC_EN) | NFC_ECC_EN), REG_NFC_ECC_EN); + return; +} + +/* + * Function to record the ECC corrected/uncorrected errors resulted + * after a page read. This NFC detects and corrects upto to 4 symbols + * of 9-bits each. + */ +static int mxc_check_ecc_status(struct mtd_info *mtd) +{ + u32 ecc_stat, err; + int no_subpages = 1; + int ret = 0; + u8 ecc_bit_mask = 0xf; + + no_subpages = mtd->writesize >> 9; + + no_subpages /= num_of_interleave; + + ecc_stat = GET_NFC_ECC_STATUS(); + do { + err = ecc_stat & ecc_bit_mask; + if (err == ecc_bit_mask) { + mtd->ecc_stats.failed++; + printk(KERN_WARNING "UnCorrectable RS-ECC Error\n"); + return -1; + } else { + ret += err; + } + ecc_stat >>= 4; + } while (--no_subpages); + + pr_debug("Correctable ECC Error(%d)\n", ret); + + return ret; +} + +/* + * Function to correct the detected errors. This NFC corrects all the errors + * detected. So this function just return 0. + */ +static int mxc_nand_correct_data(struct mtd_info *mtd, u_char *dat, + u_char *read_ecc, u_char *calc_ecc) +{ + return 0; +} + +/* + * Function to calculate the ECC for the data to be stored in the Nand device. + * This NFC has a hardware RS(511,503) ECC engine together with the RS ECC + * CONTROL blocks are responsible for detection and correction of up to + * 8 symbols of 9 bits each in 528 byte page. + * So this function is just return 0. + */ + +static int mxc_nand_calculate_ecc(struct mtd_info *mtd, const u_char *dat, + u_char *ecc_code) +{ + return 0; +} + +/*! + * This function id is used to read the data buffer from the NAND Flash. To + * read the data from NAND Flash first the data output cycle is initiated by + * the NFC, which copies the data to RAMbuffer. This data of length \b len is + * then copied to buffer \b buf. + * + * @param mtd MTD structure for the NAND Flash + * @param buf data to be read from NAND Flash + * @param len number of bytes to be read + */ +static void mxc_nand_read_buf(struct mtd_info *mtd, u_char * buf, int len) +{ + u16 col = g_nandfc_info.colAddr; + + if (mtd->writesize) { + + int j = mtd->writesize - col; + int n = mtd->oobsize + j; + + n = min(n, len); + + if (j > 0) { + if (n > j) { + memcpy(buf, &data_buf[col], j); + memcpy(buf + j, &oob_buf[0], n - j); + } else { + memcpy(buf, &data_buf[col], n); + } + } else { + col -= mtd->writesize; + memcpy(buf, &oob_buf[col], len); + } + + /* update */ + g_nandfc_info.colAddr += n; + + } else { + /* At flash identify phase, + * mtd->writesize has not been + * set correctly, it should + * be zero.And len will less 2 + */ + memcpy(buf, &data_buf[col], len); + + /* update */ + g_nandfc_info.colAddr += len; + } + +} + +/*! + * This function reads byte from the NAND Flash + * + * @param mtd MTD structure for the NAND Flash + * + * @return data read from the NAND Flash + */ +static uint8_t mxc_nand_read_byte(struct mtd_info *mtd) +{ + uint8_t ret; + + /* Check for status request */ + if (g_nandfc_info.bStatusRequest) { + return get_dev_status() & 0xFF; + } + + mxc_nand_read_buf(mtd, &ret, 1); + + return ret; +} + +/*! + * This function reads word from the NAND Flash + * + * @param mtd MTD structure for the NAND Flash + * + * @return data read from the NAND Flash + */ +static u16 mxc_nand_read_word(struct mtd_info *mtd) +{ + u16 ret; + + mxc_nand_read_buf(mtd, (uint8_t *) &ret, sizeof(u16)); + + return ret; +} + +/*! + * This function reads byte from the NAND Flash + * + * @param mtd MTD structure for the NAND Flash + * + * @return data read from the NAND Flash + */ +static u_char mxc_nand_read_byte16(struct mtd_info *mtd) +{ + /* Check for status request */ + if (g_nandfc_info.bStatusRequest) { + return get_dev_status() & 0xFF; + } + + return mxc_nand_read_word(mtd) & 0xFF; +} + +/*! + * This function writes data of length \b len from buffer \b buf to the NAND + * internal RAM buffer's MAIN area 0. + * + * @param mtd MTD structure for the NAND Flash + * @param buf data to be written to NAND Flash + * @param len number of bytes to be written + */ +static void mxc_nand_write_buf(struct mtd_info *mtd, + const u_char *buf, int len) +{ + u16 col = g_nandfc_info.colAddr; + int j = mtd->writesize - col; + int n = mtd->oobsize + j; + + n = min(n, len); + + if (j > 0) { + if (n > j) { + memcpy(&data_buf[col], buf, j); + memcpy(&oob_buf[0], buf + j, n - j); + } else { + memcpy(&data_buf[col], buf, n); + } + } else { + col -= mtd->writesize; + memcpy(&oob_buf[col], buf, len); + } + + /* update */ + g_nandfc_info.colAddr += n; +} + +/*! + * This function is used by the upper layer to verify the data in NAND Flash + * with the data in the \b buf. + * + * @param mtd MTD structure for the NAND Flash + * @param buf data to be verified + * @param len length of the data to be verified + * + * @return -EFAULT if error else 0 + * + */ +static int mxc_nand_verify_buf(struct mtd_info *mtd, const u_char * buf, + int len) +{ + u_char *s = data_buf; + + const u_char *p = buf; + + for (; len > 0; len--) { + if (*p++ != *s++) + return -EFAULT; + } + + return 0; +} + +/*! + * This function is used by upper layer for select and deselect of the NAND + * chip + * + * @param mtd MTD structure for the NAND Flash + * @param chip val indicating select or deselect + */ +static void mxc_nand_select_chip(struct mtd_info *mtd, int chip) +{ + + switch (chip) { + case -1: + /* Disable the NFC clock */ + clk_disable(nfc_clk); + break; + case 0 ... 7: + /* Enable the NFC clock */ + clk_enable(nfc_clk); + + NFC_SET_NFC_ACTIVE_CS(chip); + break; + + default: + break; + } +} + +/* + * Function to perform the address cycles. + */ +static void mxc_do_addr_cycle(struct mtd_info *mtd, int column, int page_addr) +{ +#ifdef NFC_AUTO_MODE_ENABLE + + if (page_addr != -1 && column != -1) { + u32 mask = 0xFFFF; + /* the column address */ + raw_write(column & mask, NFC_FLASH_ADDR0); + raw_write((raw_read(NFC_FLASH_ADDR0) | + ((page_addr & mask) << 16)), NFC_FLASH_ADDR0); + /* the row address */ + raw_write(((raw_read(NFC_FLASH_ADDR8) & (mask << 16)) | + ((page_addr & (mask << 16)) >> 16)), + NFC_FLASH_ADDR8); + } else if (page_addr != -1) { + raw_write(page_addr, NFC_FLASH_ADDR0); + raw_write(0, NFC_FLASH_ADDR8); + } + + DEBUG(MTD_DEBUG_LEVEL3, + "AutoMode:the ADDR REGS value is (0x%x, 0x%x)\n", + raw_read(NFC_FLASH_ADDR0), raw_read(NFC_FLASH_ADDR8)); +#else + + u32 page_mask = g_page_mask; + + if (column != -1) { + send_addr(column & 0xFF, true); + if (IS_2K_PAGE_NAND) { + /* another col addr cycle for 2k page */ + send_addr((column >> 8) & 0xF, true); + } else if (IS_4K_PAGE_NAND) { + /* another col addr cycle for 4k page */ + send_addr((column >> 8) & 0x1F, true); + } + } + if (page_addr != -1) { + do { + send_addr((page_addr & 0xff), true); + page_mask >>= 8; + page_addr >>= 8; + } while (page_mask != 0); + } +#endif +} + +/*! + * This function is used by the upper layer to write command to NAND Flash for + * different operations to be carried out on NAND Flash + * + * @param mtd MTD structure for the NAND Flash + * @param command command for NAND Flash + * @param column column offset for the page read + * @param page_addr page to be read from NAND Flash + */ +static void mxc_nand_command(struct mtd_info *mtd, unsigned command, + int column, int page_addr) +{ + bool useirq = true; + + DEBUG(MTD_DEBUG_LEVEL3, + "mxc_nand_command (cmd = 0x%x, col = 0x%x, page = 0x%x)\n", + command, column, page_addr); + /* + * Reset command state information + */ + g_nandfc_info.bStatusRequest = false; + + /* + * Command pre-processing step + */ + switch (command) { + case NAND_CMD_STATUS: + g_nandfc_info.colAddr = 0; + g_nandfc_info.bStatusRequest = true; + break; + + case NAND_CMD_READ0: + g_nandfc_info.colAddr = column; + break; + + case NAND_CMD_READOOB: + g_nandfc_info.colAddr = column; + command = NAND_CMD_READ0; + break; + + case NAND_CMD_SEQIN: + if (column != 0) { + + /* FIXME: before send SEQIN command for + * partial write,We need read one page out. + * FSL NFC does not support partial write + * It alway send out 512+ecc+512+ecc ... + * for large page nand flash. But for small + * page nand flash, it did support SPARE + * ONLY operation. But to make driver + * simple. We take the same as large page,read + * whole page out and update. As for MLC nand + * NOP(num of operation) = 1. Partial written + * on one programed page is not allowed! We + * can't limit it on the driver, it need the + * upper layer applicaiton take care it + */ + + mxc_nand_command(mtd, NAND_CMD_READ0, 0, page_addr); + } + + g_nandfc_info.colAddr = column; + column = 0; + + break; + + case NAND_CMD_PAGEPROG: +#ifndef NFC_AUTO_MODE_ENABLE + /* FIXME:the NFC interal buffer + * access has some limitation, it + * does not allow byte access. To + * make the code simple and ease use + * not every time check the address + * alignment.Use the temp buffer + * to accomadate the data.since We + * know data_buf will be at leat 4 + * byte alignment, so we can use + * memcpy safely + */ + nfc_memcpy(MAIN_AREA0, data_buf, mtd->writesize); + copy_spare(mtd, oob_buf, SPARE_AREA0, mtd->oobsize, false); + mxc_nand_bi_swap(mtd); +#endif + + if (IS_LARGE_PAGE_NAND) + PROG_PAGE(); + else + send_prog_page(0); + + break; + + case NAND_CMD_ERASE1: + break; + case NAND_CMD_ERASE2: + break; + } + + /* + * Write out the command to the device. + */ + send_cmd(mtd, command, useirq); + + mxc_do_addr_cycle(mtd, column, page_addr); + + /* + * Command post-processing step + */ + switch (command) { + + case NAND_CMD_READOOB: + case NAND_CMD_READ0: + if (IS_LARGE_PAGE_NAND) { + /* send read confirm command */ + send_cmd(mtd, NAND_CMD_READSTART, true); + /* read for each AREA */ + READ_PAGE(); + } else { + send_read_page(0); + } + +#ifndef NFC_AUTO_MODE_ENABLE + /* FIXME, the NFC interal buffer + * access has some limitation, it + * does not allow byte access. To + * make the code simple and ease use + * not every time check the address + * alignment.Use the temp buffer + * to accomadate the data.since We + * know data_buf will be at leat 4 + * byte alignment, so we can use + * memcpy safely + */ + mxc_nand_bi_swap(mtd); + nfc_memcpy(data_buf, MAIN_AREA0, mtd->writesize); + copy_spare(mtd, oob_buf, SPARE_AREA0, mtd->oobsize, true); +#endif + + break; + + case NAND_CMD_READID: + send_read_id(); + g_nandfc_info.colAddr = column; + nfc_memcpy(data_buf, MAIN_AREA0, 2048); + + break; + } +} + +static int mxc_nand_read_oob(struct mtd_info *mtd, + struct nand_chip *chip, int page, int sndcmd) +{ + if (sndcmd) { + + chip->cmdfunc(mtd, NAND_CMD_READ0, 0x00, page); + sndcmd = 0; + } + + memcpy(chip->oob_poi, oob_buf, mtd->oobsize); + + return sndcmd; +} + +static int mxc_nand_read_page(struct mtd_info *mtd, struct nand_chip *chip, + uint8_t *buf, int page) +{ + +#ifndef NFC_AUTO_MODE_ENABLE + mxc_check_ecc_status(mtd); +#endif + + memcpy(buf, data_buf, mtd->writesize); + memcpy(chip->oob_poi, oob_buf, mtd->oobsize); + + return 0; +} + +static void mxc_nand_write_page(struct mtd_info *mtd, struct nand_chip *chip, + const uint8_t *buf) +{ + memcpy(data_buf, buf, mtd->writesize); + memcpy(oob_buf, chip->oob_poi, mtd->oobsize); + +} + +/* Define some generic bad / good block scan pattern which are used + * while scanning a device for factory marked good / bad blocks. */ +static uint8_t scan_ff_pattern[] = { 0xff, 0xff }; + +static struct nand_bbt_descr smallpage_memorybased = { + .options = NAND_BBT_SCAN2NDPAGE, + .offs = 5, + .len = 1, + .pattern = scan_ff_pattern +}; + +static struct nand_bbt_descr largepage_memorybased = { + .options = 0, + .offs = 0, + .len = 2, + .pattern = scan_ff_pattern +}; + +/* Generic flash bbt decriptors +*/ +static uint8_t bbt_pattern[] = { 'B', 'b', 't', '0' }; +static uint8_t mirror_pattern[] = { '1', 't', 'b', 'B' }; + +static struct nand_bbt_descr bbt_main_descr = { + .options = NAND_BBT_LASTBLOCK | NAND_BBT_CREATE | NAND_BBT_WRITE + | NAND_BBT_2BIT | NAND_BBT_VERSION, + .offs = 0, + .len = 4, + .veroffs = 4, + .maxblocks = 4, + .pattern = bbt_pattern +}; + +static struct nand_bbt_descr bbt_mirror_descr = { + .options = NAND_BBT_LASTBLOCK | NAND_BBT_CREATE | NAND_BBT_WRITE + | NAND_BBT_2BIT | NAND_BBT_VERSION, + .offs = 0, + .len = 4, + .veroffs = 4, + .maxblocks = 4, + .pattern = mirror_pattern +}; + +static int mxc_nand_scan_bbt(struct mtd_info *mtd) +{ + struct nand_chip *this = mtd->priv; + + g_page_mask = this->pagemask; + + if (IS_2K_PAGE_NAND) { + NFC_SET_NFMS(1 << NFMS_NF_PG_SZ); + this->ecc.layout = &nand_hw_eccoob_2k; + } else if (IS_4K_PAGE_NAND) { + NFC_SET_NFMS(1 << NFMS_NF_PG_SZ); + this->ecc.layout = &nand_hw_eccoob_4k; + } else { + this->ecc.layout = &nand_hw_eccoob_512; + } + + /* propagate ecc.layout to mtd_info */ + mtd->ecclayout = this->ecc.layout; + + /* jffs2 not write oob */ + mtd->flags &= ~MTD_OOB_WRITEABLE; + + /* fix up the offset */ + largepage_memorybased.offs = BAD_BLK_MARKER_OOB_OFFS; + + /* keep compatible for bbt table with old soc */ + if (cpu_is_mx53()) { + bbt_mirror_descr.offs = BAD_BLK_MARKER_OOB_OFFS + 2; + bbt_main_descr.offs = BAD_BLK_MARKER_OOB_OFFS + 2; + } + + /* use flash based bbt */ + this->bbt_td = &bbt_main_descr; + this->bbt_md = &bbt_mirror_descr; + + /* update flash based bbt */ + this->options |= NAND_USE_FLASH_BBT; + + if (!this->badblock_pattern) { + this->badblock_pattern = (mtd->writesize > 512) ? + &largepage_memorybased : &smallpage_memorybased; + } + + /* Build bad block table */ + return nand_scan_bbt(mtd, this->badblock_pattern); +} + +static int mxc_get_resources(struct platform_device *pdev) +{ + struct resource *r; + int error = 0; + +#define MXC_NFC_NO_IP_REG \ + (cpu_is_mx25() || cpu_is_mx31() || cpu_is_mx32() || cpu_is_mx35()) + + r = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!r) { + error = -ENXIO; + goto out_0; + } + nfc_axi_base = ioremap(r->start, resource_size(r)); + + if (!MXC_NFC_NO_IP_REG) { + r = platform_get_resource(pdev, IORESOURCE_MEM, 1); + if (!r) { + error = -ENXIO; + goto out_1; + } + } + nfc_ip_base = ioremap(r->start, resource_size(r)); + + r = platform_get_resource(pdev, IORESOURCE_IRQ, 0); + if (!r) { + error = -ENXIO; + goto out_2; + } + nfc_irq = r->start; + + init_waitqueue_head(&irq_waitq); + error = request_irq(nfc_irq, mxc_nfc_irq, 0, "mxc_nd", NULL); + if (error) + goto out_3; + + return 0; +out_3: +out_2: + if (!MXC_NFC_NO_IP_REG) + iounmap(nfc_ip_base); +out_1: + iounmap(nfc_axi_base); +out_0: + return error; +} + +static void mxc_nfc_init(void) +{ + /* Disable interrupt */ + raw_write((raw_read(REG_NFC_INTRRUPT) | NFC_INT_MSK), REG_NFC_INTRRUPT); + + /* disable spare enable */ + raw_write(raw_read(REG_NFC_SP_EN) & ~NFC_SP_EN, REG_NFC_SP_EN); + + /* Unlock the internal RAM Buffer */ + raw_write(NFC_SET_BLS(NFC_BLS_UNLCOKED), REG_NFC_BLS); + + if (!(cpu_is_mx53())) { + /* Blocks to be unlocked */ + UNLOCK_ADDR(0x0, 0xFFFF); + + /* Unlock Block Command for given address range */ + raw_write(NFC_SET_WPC(NFC_WPC_UNLOCK), REG_NFC_WPC); + } + + /* Enable symetric mode by default except mx37TO1.0 */ + if (!(cpu_is_mx37_rev(CHIP_REV_1_0) == 1)) + raw_write(raw_read(REG_NFC_ONE_CYCLE) | + NFC_ONE_CYCLE, REG_NFC_ONE_CYCLE); +} + +static int mxc_alloc_buf(void) +{ + int err = 0; + + data_buf = kzalloc(NAND_MAX_PAGESIZE, GFP_KERNEL); + if (!data_buf) { + printk(KERN_ERR "%s: failed to allocate data_buf\n", __func__); + err = -ENOMEM; + goto out; + } + oob_buf = kzalloc(NAND_MAX_OOBSIZE, GFP_KERNEL); + if (!oob_buf) { + printk(KERN_ERR "%s: failed to allocate oob_buf\n", __func__); + err = -ENOMEM; + goto out; + } + + out: + return err; +} + +static void mxc_free_buf(void) +{ + kfree(data_buf); + kfree(oob_buf); +} + +int nand_scan_mid(struct mtd_info *mtd) +{ + int i; + uint8_t id_bytes[NAND_DEVICE_ID_BYTE_COUNT]; + struct nand_chip *this = mtd->priv; + struct nand_device_info *dev_info; + + if (!IS_LARGE_PAGE_NAND) + return 0; + + /* Read ID bytes from the first NAND Flash chip. */ + this->select_chip(mtd, 0); + + this->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1); + + for (i = 0; i < NAND_DEVICE_ID_BYTE_COUNT; i++) + id_bytes[i] = this->read_byte(mtd); + + /* Get information about this device, based on the ID bytes. */ + dev_info = nand_device_get_info(id_bytes); + + /* Check if we understand this device. */ + if (!dev_info) { + printk(KERN_ERR "Unrecognized NAND Flash device.\n"); + return !0; + } + + /* Correct mtd setting */ + this->chipsize = dev_info->chip_size_in_bytes; + mtd->size = dev_info->chip_size_in_bytes * this->numchips; + mtd->writesize = dev_info->page_total_size_in_bytes & ~0x3ff; + mtd->oobsize = dev_info->page_total_size_in_bytes & 0x3ff; + mtd->erasesize = dev_info->block_size_in_pages * mtd->writesize; + + /* limit to 2G size due to Kernel + * larger 4G space support,need fix + * it later + */ + if ((u32)mtd->size == 0) { + mtd->size = (u32)(1 << 31); + this->numchips = 1; + this->chipsize = mtd->size; + } + + /* Calculate the address shift from the page size */ + this->page_shift = ffs(mtd->writesize) - 1; + /* Convert chipsize to number of pages per chip -1. */ + this->pagemask = (this->chipsize >> this->page_shift) - 1; + + this->bbt_erase_shift = this->phys_erase_shift = + ffs(mtd->erasesize) - 1; + this->chip_shift = ffs(this->chipsize) - 1; + + return 0; +} + +/*! + * show_device_disable_bi_swap() + * Shows the value of the 'disable_bi_swap' flag. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer that will receive a representation of the attribute. + */ +static ssize_t show_device_disable_bi_swap(struct device *dev, + struct device_attribute *attr, char *buf) +{ + return sprintf(buf, "%d\n", mxc_nand_data->disable_bi_swap); +} + +/*! + * store_device_disable_bi_swap() + * Sets the value of the 'disable_bi_swap' flag. + * + * @dev: The device of interest. + * @attr: The attribute of interest. + * @buf: A buffer containing a new attribute value. + * @size: The size of the buffer. + */ +static ssize_t store_device_disable_bi_swap(struct device *dev, + struct device_attribute *attr, const char *buf, size_t size) +{ + const char *p = buf; + unsigned long v; + + /* Try to make sense of what arrived from user space. */ + + if (strict_strtoul(p, 0, &v) < 0) + return size; + + if (v > 0) + v = 1; + mxc_nand_data->disable_bi_swap = v; + return size; + +} + +static DEVICE_ATTR(disable_bi_swap, 0644, + show_device_disable_bi_swap, store_device_disable_bi_swap); +static struct device_attribute *device_attributes[] = { + &dev_attr_disable_bi_swap, +}; +/*! + * manage_sysfs_files() - Creates/removes sysfs files for this device. + * + * @create: create/remove the sys entry. + */ +static void manage_sysfs_files(int create) +{ + struct device *dev = mxc_nand_data->dev; + int error; + unsigned int i; + struct device_attribute **attr; + + for (i = 0, attr = device_attributes; + i < ARRAY_SIZE(device_attributes); i++, attr++) { + + if (create) { + error = device_create_file(dev, *attr); + if (error) { + while (--attr >= device_attributes) + device_remove_file(dev, *attr); + return; + } + } else { + device_remove_file(dev, *attr); + } + } + +} + + +/*! + * This function is called during the driver binding process. + * + * @param pdev the device structure used to store device specific + * information that is used by the suspend, resume and + * remove functions + * + * @return The function always returns 0. + */ +static int __init mxcnd_probe(struct platform_device *pdev) +{ + struct nand_chip *this; + struct mtd_info *mtd; + struct flash_platform_data *flash = pdev->dev.platform_data; + int nr_parts = 0, err = 0; + + /* get the resource */ + err = mxc_get_resources(pdev); + if (err) + goto out; + + /* init the nfc */ + mxc_nfc_init(); + + /* init data buf */ + if (mxc_alloc_buf()) + goto out; + + /* Allocate memory for MTD device structure and private data */ + mxc_nand_data = kzalloc(sizeof(struct mxc_mtd_s), GFP_KERNEL); + if (!mxc_nand_data) { + printk(KERN_ERR "%s: failed to allocate mtd_info\n", + __FUNCTION__); + err = -ENOMEM; + goto out; + } + + memset((char *)&g_nandfc_info, 0, sizeof(g_nandfc_info)); + + mxc_nand_data->dev = &pdev->dev; + /* structures must be linked */ + this = &mxc_nand_data->nand; + mtd = &mxc_nand_data->mtd; + mtd->priv = this; + mtd->owner = THIS_MODULE; + + this->priv = mxc_nand_data; + this->cmdfunc = mxc_nand_command; + this->select_chip = mxc_nand_select_chip; + this->read_byte = mxc_nand_read_byte; + this->read_word = mxc_nand_read_word; + this->write_buf = mxc_nand_write_buf; + this->read_buf = mxc_nand_read_buf; + this->verify_buf = mxc_nand_verify_buf; + this->scan_bbt = mxc_nand_scan_bbt; + + /* NAND bus width determines access funtions used by upper layer */ + if (flash->width == 2) { + this->read_byte = mxc_nand_read_byte16; + this->options |= NAND_BUSWIDTH_16; + NFC_SET_NFMS(1 << NFMS_NF_DWIDTH); + } else { + NFC_SET_NFMS(0); + } + + nfc_clk = clk_get(&pdev->dev, "nfc_clk"); + clk_enable(nfc_clk); + + if (hardware_ecc) { + this->ecc.read_page = mxc_nand_read_page; + this->ecc.write_page = mxc_nand_write_page; + this->ecc.read_oob = mxc_nand_read_oob; + this->ecc.layout = &nand_hw_eccoob_512; + this->ecc.calculate = mxc_nand_calculate_ecc; + this->ecc.hwctl = mxc_nand_enable_hwecc; + this->ecc.correct = mxc_nand_correct_data; + this->ecc.mode = NAND_ECC_HW; + this->ecc.size = 512; + this->ecc.bytes = 9; + raw_write((raw_read(REG_NFC_ECC_EN) | NFC_ECC_EN), + REG_NFC_ECC_EN); + } else { + this->ecc.mode = NAND_ECC_SOFT; + raw_write((raw_read(REG_NFC_ECC_EN) & ~NFC_ECC_EN), + REG_NFC_ECC_EN); + } + + /* config the gpio */ + if (flash->init) + flash->init(); + + /* Reset NAND */ + this->cmdfunc(mtd, NAND_CMD_RESET, -1, -1); + + /* Scan to find existence of the device */ + if (nand_scan_ident(mtd, NFC_GET_MAXCHIP_SP(), NULL) + || nand_scan_mid(mtd) + || nand_scan_tail(mtd)) { + DEBUG(MTD_DEBUG_LEVEL0, + "MXC_ND2: Unable to find any NAND device.\n"); + err = -ENXIO; + goto out_1; + } + + /* Register the partitions */ +#ifdef CONFIG_MTD_PARTITIONS + nr_parts = + parse_mtd_partitions(mtd, part_probes, &mxc_nand_data->parts, 0); + if (nr_parts > 0) + add_mtd_partitions(mtd, mxc_nand_data->parts, nr_parts); + else if (flash->parts) + add_mtd_partitions(mtd, flash->parts, flash->nr_parts); + else +#endif + { + pr_info("Registering %s as whole device\n", mtd->name); + add_mtd_device(mtd); + } + + /* Create sysfs entries for this device. */ + manage_sysfs_files(true); + + platform_set_drvdata(pdev, mtd); + + return 0; + + out_1: + kfree(mxc_nand_data); + out: + return err; + +} + + /*! + * Dissociates the driver from the device. + * + * @param pdev the device structure used to give information on which + * + * @return The function always returns 0. + */ + +static int __exit mxcnd_remove(struct platform_device *pdev) +{ + struct mtd_info *mtd = platform_get_drvdata(pdev); + struct flash_platform_data *flash = pdev->dev.platform_data; + + if (flash->exit) + flash->exit(); + + manage_sysfs_files(false); + mxc_free_buf(); + + clk_disable(nfc_clk); + clk_put(nfc_clk); + platform_set_drvdata(pdev, NULL); + + if (mxc_nand_data) { + nand_release(mtd); + free_irq(nfc_irq, NULL); + kfree(mxc_nand_data); + } + + return 0; +} + +#ifdef CONFIG_PM +/*! + * This function is called to put the NAND in a low power state. Refer to the + * document driver-model/driver.txt in the kernel source tree for more + * information. + * + * @param pdev the device information structure + * + * @param state the power state the device is entering + * + * @return The function returns 0 on success and -1 on failure + */ + +static int mxcnd_suspend(struct platform_device *pdev, pm_message_t state) +{ + DEBUG(MTD_DEBUG_LEVEL0, "MXC_ND2 : NAND suspend\n"); + + /* Disable the NFC clock */ + clk_disable(nfc_clk); + + return 0; +} + +/*! + * This function is called to bring the NAND back from a low power state. Refer + * to the document driver-model/driver.txt in the kernel source tree for more + * information. + * + * @param pdev the device information structure + * + * @return The function returns 0 on success and -1 on failure + */ +static int mxcnd_resume(struct platform_device *pdev) +{ + DEBUG(MTD_DEBUG_LEVEL0, "MXC_ND2 : NAND resume\n"); + + /* Enable the NFC clock */ + clk_enable(nfc_clk); + + return 0; +} + +#else +#define mxcnd_suspend NULL +#define mxcnd_resume NULL +#endif /* CONFIG_PM */ + +/*! + * This structure contains pointers to the power management callback functions. + */ +static struct platform_driver mxcnd_driver = { + .driver = { + .name = "mxc_nandv2_flash", + }, + .probe = mxcnd_probe, + .remove = __exit_p(mxcnd_remove), + .suspend = mxcnd_suspend, + .resume = mxcnd_resume, +}; + +/*! + * Main initialization routine + * @return 0 if successful; non-zero otherwise + */ +static int __init mxc_nd_init(void) +{ + /* Register the device driver structure. */ + pr_info("MXC MTD nand Driver %s\n", DVR_VER); + if (platform_driver_register(&mxcnd_driver) != 0) { + printk(KERN_ERR "Driver register failed for mxcnd_driver\n"); + return -ENODEV; + } + return 0; +} + +/*! + * Clean up routine + */ +static void __exit mxc_nd_cleanup(void) +{ + /* Unregister the device structure */ + platform_driver_unregister(&mxcnd_driver); +} + +module_init(mxc_nd_init); +module_exit(mxc_nd_cleanup); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MXC NAND MTD driver Version 2-5"); +MODULE_LICENSE("GPL"); diff --git a/drivers/mtd/nand/mxc_nd2.h b/drivers/mtd/nand/mxc_nd2.h new file mode 100644 index 000000000000..99b8bfc828df --- /dev/null +++ b/drivers/mtd/nand/mxc_nd2.h @@ -0,0 +1,712 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mxc_nd2.h + * + * @brief This file contains the NAND Flash Controller register information. + * + * + * @ingroup NAND_MTD + */ + +#ifndef __MXC_ND2_H__ +#define __MXC_ND2_H__ + +#include + +#define IS_2K_PAGE_NAND ((mtd->writesize / num_of_interleave) \ + == NAND_PAGESIZE_2KB) +#define IS_4K_PAGE_NAND ((mtd->writesize / num_of_interleave) \ + == NAND_PAGESIZE_4KB) +#define IS_LARGE_PAGE_NAND ((mtd->writesize / num_of_interleave) > 512) + +#define GET_NAND_OOB_SIZE (mtd->oobsize / num_of_interleave) +#define GET_NAND_PAGE_SIZE (mtd->writesize / num_of_interleave) + +#define NAND_PAGESIZE_2KB 2048 +#define NAND_PAGESIZE_4KB 4096 + +/* + * main area for bad block marker is in the last data section + * the spare area for swapped bad block marker is the second + * byte of last spare section + */ +#define NAND_SECTIONS (GET_NAND_PAGE_SIZE >> 9) +#define NAND_OOB_PER_SECTION (((GET_NAND_OOB_SIZE / NAND_SECTIONS) >> 1) << 1) +#define NAND_CHUNKS (GET_NAND_PAGE_SIZE / (512 + NAND_OOB_PER_SECTION)) + +#define BAD_BLK_MARKER_MAIN_OFFS \ + (GET_NAND_PAGE_SIZE - NAND_CHUNKS * NAND_OOB_PER_SECTION) + +#define BAD_BLK_MARKER_SP_OFFS (NAND_CHUNKS * SPARE_LEN) + +#define BAD_BLK_MARKER_OOB_OFFS (NAND_CHUNKS * NAND_OOB_PER_SECTION) + +#define BAD_BLK_MARKER_MAIN \ + ((u32)MAIN_AREA0 + BAD_BLK_MARKER_MAIN_OFFS) + +#define BAD_BLK_MARKER_SP \ + ((u32)SPARE_AREA0 + BAD_BLK_MARKER_SP_OFFS) + +#ifdef CONFIG_ARCH_MXC_HAS_NFC_V3 +/* + * For V3 NFC registers Definition + */ + +#if defined(CONFIG_ARCH_MXC_HAS_NFC_V3_1) /* mx37 */ +#define MXC_INT_NANDFC MXC_INT_EMI +#define NFC_FLASH_ADDR_CMD (nfc_axi_base + 0x1E00) +#define NFC_CONFIG1 (nfc_axi_base + 0x1E04) +#define NFC_ECC_STATUS_RESULT (nfc_axi_base + 0x1E08) +#define LAUNCH_NFC (nfc_axi_base + 0x1E0c) +#define NFC_WRPROT (nfc_ip_base + 0x00) +#define NFC_WRPROT_UNLOCK_BLK_ADD0 (nfc_ip_base + 0x04) +#define NFC_CONFIG2 (nfc_ip_base + 0x14) +#define NFC_IPC (nfc_ip_base + 0x18) +#elif defined(CONFIG_ARCH_MXC_HAS_NFC_V3_2) /* mx51 */ +#define MXC_INT_NANDFC MXC_INT_NFC +#define NFC_AUTO_MODE_ENABLE +#define NFC_FLASH_CMD (nfc_axi_base + 0x1E00) +#define NFC_FLASH_ADDR0 (nfc_axi_base + 0x1E04) +#define NFC_FLASH_ADDR8 (nfc_axi_base + 0x1E24) +#define NFC_CONFIG1 (nfc_axi_base + 0x1E34) +#define NFC_ECC_STATUS_RESULT (nfc_axi_base + 0x1E38) +#define NFC_ECC_STATUS_SUM (nfc_axi_base + 0x1E3C) +#define LAUNCH_NFC (nfc_axi_base + 0x1E40) +#define NFC_WRPROT (nfc_ip_base + 0x00) +#define NFC_WRPROT_UNLOCK_BLK_ADD0 (nfc_ip_base + 0x04) +#define NFC_CONFIG2 (nfc_ip_base + 0x24) +#define NFC_CONFIG3 (nfc_ip_base + 0x28) +#define NFC_IPC (nfc_ip_base + 0x2C) +#define NFC_DELAY_LINE (nfc_ip_base + 0x34) +#else /* skye */ +#define NFC_FLASH_ADDR_CMD (nfc_axi_base + 0xE00) +#define NFC_CONFIG1 (nfc_axi_base + 0xE04) +#define NFC_ECC_STATUS_RESULT (nfc_axi_base + 0xE08) +#define LAUNCH_NFC (nfc_axi_base + 0xE0C) +#define NFC_WRPROT (nfc_ip_base + 0x00) +#define NFC_WRPROT_UNLOCK_BLK_ADD0 (nfc_ip_base + 0x04) +#define NFC_CONFIG2 (nfc_ip_base + 0x14) +#define NFC_IPC (nfc_ip_base + 0x18) +#endif +/*! + * Addresses for NFC RAM BUFFER Main area 0 + */ +#define MAIN_AREA0 ((u16 *)(nfc_axi_base + 0x000)) +#define MAIN_AREA1 ((u16 *)(nfc_axi_base + 0x200)) + +/*! + * Addresses for NFC SPARE BUFFER Spare area 0 + */ +#if defined(CONFIG_ARCH_MXC_HAS_NFC_V3_1) || \ + defined(CONFIG_ARCH_MXC_HAS_NFC_V3_2) +#define SPARE_AREA0 ((u16 *)(nfc_axi_base + 0x1000)) +#define SPARE_LEN 64 +#define SPARE_COUNT 8 +#define SPARE_SIZE (SPARE_LEN * SPARE_COUNT) +#else +#define SPARE_AREA0 ((u16 *)(nfc_axi_base + 0x800)) +#define SPARE_LEN 16 +#define SPARE_COUNT 4 +#define SPARE_SIZE (SPARE_LEN * SPARE_COUNT) +#endif + +#if defined(CONFIG_ARCH_MXC_HAS_NFC_V3_1) || \ + defined(CONFIG_ARCH_MXC_HAS_NFC_V3_2) +#define NFC_SPAS_WIDTH 8 +#define NFC_SPAS_SHIFT 16 + +#define NFC_SET_SPAS(v) \ + raw_write((((raw_read(NFC_CONFIG2) & \ + NFC_FIELD_RESET(NFC_SPAS_WIDTH, NFC_SPAS_SHIFT)) | ((v) << 16))), \ + NFC_CONFIG2) + +#define NFC_SET_ECC_MODE(v) \ +do { \ + if (cpu_is_mx53() > 0) { \ + if ((v) == NFC_SPAS_218 || (v) == NFC_SPAS_112) \ + raw_write(((raw_read(NFC_CONFIG2) & \ + ~(3 << 6)) | \ + NFC_ECC_MODE_16), NFC_CONFIG2); \ + else \ + raw_write(((raw_read(NFC_CONFIG2) & \ + ~(3 << 6)) & \ + NFC_ECC_MODE_4), NFC_CONFIG2); \ + } else if (cpu_is_mx51_rev(CHIP_REV_2_0) > 0) { \ + if ((v) == NFC_SPAS_218 || (v) == NFC_SPAS_112) \ + raw_write(((raw_read(NFC_CONFIG2) & \ + ~(1 << 6)) | \ + NFC_ECC_MODE_8), NFC_CONFIG2); \ + else \ + raw_write(((raw_read(NFC_CONFIG2) & \ + ~(1 << 6)) & \ + NFC_ECC_MODE_4), NFC_CONFIG2); \ + } else { \ + if ((v) == NFC_SPAS_218 || (v) == NFC_SPAS_112) \ + raw_write(((raw_read(NFC_CONFIG2) & \ + ~(1 << 6))), NFC_CONFIG2); \ + else \ + raw_write(((raw_read(NFC_CONFIG2) & \ + ~(1 << 6)) | \ + NFC_ECC_MODE_4), NFC_CONFIG2); \ + } \ +} while (0) + +#define WRITE_NFC_IP_REG(val, reg) \ + do { \ + raw_write(raw_read(NFC_IPC) | NFC_IPC_CREQ, NFC_IPC); \ + while (!(raw_read(NFC_IPC) & NFC_IPC_ACK)) \ + ; \ + raw_write(val, reg); \ + raw_write(raw_read(NFC_IPC) & ~NFC_IPC_CREQ, NFC_IPC); \ + } while (0) + +#else +#define NFC_SET_SPAS(v) +#define NFC_SET_ECC_MODE(v) +#define NFC_SET_NFMS(v) (NFMS |= (v)) + +#define WRITE_NFC_IP_REG(val, reg) \ + raw_write((raw_read(REG_NFC_OPS_STAT) & ~NFC_OPS_STAT), \ + REG_NFC_OPS_STAT) +#endif + +#define GET_NFC_ECC_STATUS() raw_read(REG_NFC_ECC_STATUS_RESULT); + +/*! + * Set 1 to specific operation bit, rest to 0 in LAUNCH_NFC Register for + * Specific operation + */ +#define NFC_CMD 0x1 +#define NFC_ADDR 0x2 +#define NFC_INPUT 0x4 +#define NFC_OUTPUT 0x8 +#define NFC_ID 0x10 +#define NFC_STATUS 0x20 + +#ifdef CONFIG_ARCH_MXC_HAS_NFC_V3_2 /* mx51 */ +#define NFC_AUTO_PROG 0x40 +#define NFC_AUTO_READ 0x80 +#define NFC_AUTO_ERASE 0x200 +#define NFC_COPY_BACK_0 0x400 +#define NFC_COPY_BACK_1 0x800 +#define NFC_AUTO_STATE 0x1000 +#endif + +/* Bit Definitions for NFC_IPC*/ +#define NFC_OPS_STAT (1 << 31) + +#ifdef CONFIG_ARCH_MXC_HAS_NFC_V3_2 /* mx51 */ +#define NFC_OP_DONE (1 << 30) +#define NFC_RB (1 << 28) +#define NFC_PS_WIDTH 2 +#define NFC_PS_SHIFT 0 +#define NFC_PS_512 0 +#define NFC_PS_2K 1 +#define NFC_PS_4K 2 +#else +#define NFC_RB (1 << 29) +#endif + +#define NFC_ONE_CYCLE (1 << 2) + +#ifdef CONFIG_ARCH_MXC_HAS_NFC_V3_2 /* mx51 */ +#define NFC_INT_MSK (1 << 15) +#define NFC_AUTO_PROG_DONE_MSK (1 << 14) +#define NFC_NUM_ADDR_PHASE1_WIDTH 2 +#define NFC_NUM_ADDR_PHASE1_SHIFT 12 + +#define NFC_NUM_ADDR_PHASE0_WIDTH 1 +#define NFC_NUM_ADDR_PHASE0_SHIFT 5 + +#define NFC_ONE_LESS_PHASE1 0 +#define NFC_TWO_LESS_PHASE1 1 + +#define NFC_FLASH_ADDR_SHIFT 0 +#else +#define NFC_INT_MSK (1 << 4) +#define NFC_BIG (1 << 5) +#define NFC_FLASH_ADDR_SHIFT 16 +#endif + +#define NFC_UNLOCK_END_ADDR_SHIFT 16 + +/* Bit definition for NFC_CONFIGRATION_1 */ +#define NFC_SP_EN (1 << 0) +#define NFC_CE (1 << 1) +#define NFC_RST (1 << 2) +#define NFC_ECC_EN (1 << 3) + +#define NFC_FIELD_RESET(width, shift) (~((((1 << (width)) - 1) << (shift)))) + +#define NFC_RBA_SHIFT 4 + +#if defined(CONFIG_ARCH_MXC_HAS_NFC_V3_1) || \ + defined(CONFIG_ARCH_MXC_HAS_NFC_V3_2) /* mx51 */ +#define NFC_RBA_WIDTH 3 +#else +#define NFC_RBA_WIDTH 2 +#endif + +#if defined(CONFIG_ARCH_MXC_HAS_NFC_V3_2) /* mx51 */ +#define NFC_ITERATION_SHIFT 8 +#define NFC_ITERATION_WIDTH 4 +#define NFC_ACTIVE_CS_SHIFT 12 +#define NFC_ACTIVE_CS_WIDTH 3 +/* bit definition for CONFIGRATION3 */ +#define NFC_NO_SDMA (1 << 20) +#define NFC_FMP_SHIFT 16 +#define NFC_FMP_WIDTH 4 +#define NFC_RBB_MODE (1 << 15) +#define NFC_NUM_OF_DEVICES_SHIFT 12 +#define NFC_NUM_OF_DEVICES_WIDTH 4 +#define NFC_DMA_MODE_SHIFT 11 +#define NFC_DMA_MODE_WIDTH 1 +#define NFC_SBB_SHIFT 8 +#define NFC_SBB_WIDTH 3 +#define NFC_BIG (1 << 7) +#define NFC_SB2R_SHIFT 4 +#define NFC_SB2R_WIDTH 3 +#define NFC_FW_SHIFT 3 +#define NFC_FW_WIDTH 1 +#define NFC_TOO (1 << 2) +#define NFC_ADD_OP_SHIFT 0 +#define NFC_ADD_OP_WIDTH 2 +#define NFC_FW_8 1 +#define NFC_FW_16 0 +#define NFC_ST_CMD_SHITF 24 +#define NFC_ST_CMD_WIDTH 8 +#endif + +#define NFC_PPB_32 (0 << 7) +#define NFC_PPB_64 (1 << 7) +#define NFC_PPB_128 (2 << 7) +#define NFC_PPB_256 (3 << 7) +#define NFC_PPB_RESET (~(3 << 7)) + +#if defined(CONFIG_ARCH_MXC_HAS_NFC_V3_2) +#define NFC_BLS_LOCKED (0 << 6) +#define NFC_BLS_LOCKED_DEFAULT (1 << 6) +#define NFC_BLS_UNLCOKED (2 << 6) +#define NFC_BLS_RESET (~(3 << 6)) +#else +#define NFC_BLS_LOCKED (0 << 16) +#define NFC_BLS_LOCKED_DEFAULT (1 << 16) +#define NFC_BLS_UNLCOKED (2 << 16) +#define NFC_BLS_RESET (~(3 << 16)) +#endif + +#define NFC_WPC_LOCK_TIGHT 1 +#define NFC_WPC_LOCK (1 << 1) +#define NFC_WPC_UNLOCK (1 << 2) +#define NFC_WPC_RESET (~(7)) +#if defined(CONFIG_ARCH_MXC_HAS_NFC_V3_1) || \ + defined(CONFIG_ARCH_MXC_HAS_NFC_V3_2) +#define NFC_ECC_MODE_4 (0x0 << 6) +#define NFC_ECC_MODE_8 (0x1 << 6) +#define NFC_ECC_MODE_14 (0x3 << 6) +#define NFC_ECC_MODE_16 (0x3 << 6) +#define NFC_SPAS_16 8 +#define NFC_SPAS_64 32 +#define NFC_SPAS_128 64 +#define NFC_SPAS_112 56 +#define NFC_SPAS_218 109 +#define NFC_IPC_CREQ (1 << 0) +#define NFC_IPC_ACK (1 << 1) +#endif + +#define REG_NFC_OPS_STAT NFC_IPC +#define REG_NFC_INTRRUPT NFC_CONFIG2 +#ifdef CONFIG_ARCH_MXC_HAS_NFC_V3_2 +#define REG_NFC_FLASH_ADDR NFC_FLASH_ADDR0 +#define REG_NFC_FLASH_CMD NFC_FLASH_CMD +#else +#define REG_NFC_FLASH_ADDR NFC_FLASH_ADDR_CMD +#define REG_NFC_FLASH_CMD NFC_FLASH_ADDR_CMD +#endif +#define REG_NFC_OPS LAUNCH_NFC +#define REG_NFC_SET_RBA NFC_CONFIG1 +#define REG_NFC_RB NFC_IPC +#define REG_NFC_ECC_EN NFC_CONFIG2 +#define REG_NFC_ECC_STATUS_RESULT NFC_ECC_STATUS_RESULT +#define REG_NFC_CE NFC_CONFIG1 +#define REG_NFC_RST NFC_CONFIG1 +#define REG_NFC_PPB NFC_CONFIG2 +#define REG_NFC_SP_EN NFC_CONFIG1 +#define REG_NFC_BLS NFC_WRPROT +#define REG_UNLOCK_BLK_ADD0 NFC_WRPROT_UNLOCK_BLK_ADD0 +#define REG_UNLOCK_BLK_ADD1 NFC_WRPROT_UNLOCK_BLK_ADD1 +#define REG_UNLOCK_BLK_ADD2 NFC_WRPROT_UNLOCK_BLK_ADD2 +#define REG_UNLOCK_BLK_ADD3 NFC_WRPROT_UNLOCK_BLK_ADD3 +#define REG_NFC_WPC NFC_WRPROT +#define REG_NFC_ONE_CYCLE NFC_CONFIG2 + +/* NFC V3 Specific MACRO functions definitions */ +#define raw_write(v, a) __raw_writel(v, a) +#define raw_read(a) __raw_readl(a) + +/* Set RBA buffer id*/ +#define NFC_SET_RBA(val) \ + raw_write((raw_read(REG_NFC_SET_RBA) & \ + (NFC_FIELD_RESET(NFC_RBA_WIDTH, NFC_RBA_SHIFT))) | \ + ((val) << NFC_RBA_SHIFT), REG_NFC_SET_RBA); + +#define NFC_SET_PS(val) \ + raw_write((raw_read(NFC_CONFIG2) & \ + (NFC_FIELD_RESET(NFC_PS_WIDTH, NFC_PS_SHIFT))) | \ + ((val) << NFC_PS_SHIFT), NFC_CONFIG2); + +#ifdef CONFIG_ARCH_MXC_HAS_NFC_V3_2 +#define UNLOCK_ADDR(start_addr, end_addr) \ +{ \ + int i = 0; \ + for (; i < NAND_MAX_CHIPS; i++) \ + raw_write(start_addr | \ + (end_addr << NFC_UNLOCK_END_ADDR_SHIFT), \ + REG_UNLOCK_BLK_ADD0 + (i << 2)); \ +} +#define NFC_SET_NFC_ACTIVE_CS(val) \ + raw_write((raw_read(NFC_CONFIG1) & \ + (NFC_FIELD_RESET(NFC_ACTIVE_CS_WIDTH, NFC_ACTIVE_CS_SHIFT))) | \ + ((val) << NFC_ACTIVE_CS_SHIFT), NFC_CONFIG1); + +#define NFC_GET_MAXCHIP_SP() 8 + +#else +#define UNLOCK_ADDR(start_addr, end_addr) \ + raw_write(start_addr | \ + (end_addr << NFC_UNLOCK_END_ADDR_SHIFT), REG_UNLOCK_BLK_ADD0); + +#define NFC_SET_NFC_ACTIVE_CS(val) +#define NFC_GET_MAXCHIP_SP() 1 +#endif + +#define NFC_SET_BLS(val) ((raw_read(REG_NFC_BLS) & NFC_BLS_RESET) | val) +#define NFC_SET_WPC(val) ((raw_read(REG_NFC_WPC) & NFC_WPC_RESET) | val) +#define CHECK_NFC_RB (raw_read(REG_NFC_RB) & NFC_RB) + +#if defined(CONFIG_ARCH_MXC_HAS_NFC_V3_2) +#define NFC_SET_NFC_NUM_ADDR_PHASE1(val) \ + raw_write((raw_read(NFC_CONFIG2) & \ + (NFC_FIELD_RESET(NFC_NUM_ADDR_PHASE1_WIDTH, \ + NFC_NUM_ADDR_PHASE1_SHIFT))) | \ + ((val) << NFC_NUM_ADDR_PHASE1_SHIFT), NFC_CONFIG2); + +#define NFC_SET_NFC_NUM_ADDR_PHASE0(val) \ + raw_write((raw_read(NFC_CONFIG2) & \ + (NFC_FIELD_RESET(NFC_NUM_ADDR_PHASE0_WIDTH, \ + NFC_NUM_ADDR_PHASE0_SHIFT))) | \ + ((val) << NFC_NUM_ADDR_PHASE0_SHIFT), NFC_CONFIG2); + +#define NFC_SET_NFC_ITERATION(val) \ + raw_write((raw_read(NFC_CONFIG1) & \ + (NFC_FIELD_RESET(NFC_ITERATION_WIDTH, NFC_ITERATION_SHIFT))) | \ + ((val) << NFC_ITERATION_SHIFT), NFC_CONFIG1); + +#define NFC_SET_FW(val) \ + raw_write((raw_read(NFC_CONFIG3) & \ + (NFC_FIELD_RESET(NFC_FW_WIDTH, NFC_FW_SHIFT))) | \ + ((val) << NFC_FW_SHIFT), NFC_CONFIG3); + +#define NFC_SET_NUM_OF_DEVICE(val) \ + raw_write((raw_read(NFC_CONFIG3) & \ + (NFC_FIELD_RESET(NFC_NUM_OF_DEVICES_WIDTH, \ + NFC_NUM_OF_DEVICES_SHIFT))) | \ + ((val) << NFC_NUM_OF_DEVICES_SHIFT), NFC_CONFIG3); + +#define NFC_SET_ADD_OP_MODE(val) \ + raw_write((raw_read(NFC_CONFIG3) & \ + (NFC_FIELD_RESET(NFC_ADD_OP_WIDTH, NFC_ADD_OP_SHIFT))) | \ + ((val) << NFC_ADD_OP_SHIFT), NFC_CONFIG3); + +#define NFC_SET_ADD_CS_MODE(val) \ +{ \ + NFC_SET_ADD_OP_MODE(val); \ + NFC_SET_NUM_OF_DEVICE(this->numchips - 1); \ +} + +#define NFC_SET_ST_CMD(val) \ + raw_write((raw_read(NFC_CONFIG2) & \ + (NFC_FIELD_RESET(NFC_ST_CMD_WIDTH, \ + NFC_ST_CMD_SHITF))) | \ + ((val) << NFC_ST_CMD_SHITF), NFC_CONFIG2); + +#define NFMS_NF_DWIDTH 0 +#define NFMS_NF_PG_SZ 1 +#define NFC_CMD_1_SHIFT 8 + +#define NUM_OF_ADDR_CYCLE (fls(g_page_mask) >> 3) +#define SET_NFC_DELAY_LINE(val) raw_write((val), NFC_DELAY_LINE) + +/*should set the fw,ps,spas,ppb*/ +#define NFC_SET_NFMS(v) \ +do { \ + if (!(v)) \ + NFC_SET_FW(NFC_FW_8); \ + if (((v) & (1 << NFMS_NF_DWIDTH))) \ + NFC_SET_FW(NFC_FW_16); \ + if (((v) & (1 << NFMS_NF_PG_SZ))) { \ + if (IS_2K_PAGE_NAND) { \ + NFC_SET_PS(NFC_PS_2K); \ + NFC_SET_NFC_NUM_ADDR_PHASE1(NUM_OF_ADDR_CYCLE); \ + NFC_SET_NFC_NUM_ADDR_PHASE0(NFC_TWO_LESS_PHASE1); \ + } else if (IS_4K_PAGE_NAND) { \ + NFC_SET_PS(NFC_PS_4K); \ + NFC_SET_NFC_NUM_ADDR_PHASE1(NUM_OF_ADDR_CYCLE); \ + NFC_SET_NFC_NUM_ADDR_PHASE0(NFC_TWO_LESS_PHASE1); \ + } else { \ + NFC_SET_PS(NFC_PS_512); \ + NFC_SET_NFC_NUM_ADDR_PHASE1(NUM_OF_ADDR_CYCLE - 1); \ + NFC_SET_NFC_NUM_ADDR_PHASE0(NFC_ONE_LESS_PHASE1); \ + } \ + NFC_SET_ADD_CS_MODE(1); \ + NFC_SET_SPAS(GET_NAND_OOB_SIZE >> 1); \ + NFC_SET_ECC_MODE(GET_NAND_OOB_SIZE >> 1); \ + NFC_SET_ST_CMD(0x70); \ + raw_write(raw_read(NFC_CONFIG3) | NFC_NO_SDMA, NFC_CONFIG3); \ + raw_write(raw_read(NFC_CONFIG3) | NFC_RBB_MODE, NFC_CONFIG3); \ + if (cpu_is_mx51()) \ + SET_NFC_DELAY_LINE(0); \ + } \ +} while (0) +#endif + +#ifdef CONFIG_ARCH_MXC_HAS_NFC_V3_1 +#define NFC_SET_NFMS(v) +#endif + +#define READ_PAGE() send_read_page(0) +#define PROG_PAGE() send_prog_page(0) + +#elif CONFIG_ARCH_MXC_HAS_NFC_V2 + +/* + * For V1/V2 NFC registers Definition + */ + +/* + * Addresses for NFC registers + */ +#ifdef CONFIG_ARCH_MXC_HAS_NFC_V2_1 +#define NFC_REG_BASE (nfc_axi_base + 0x1000) +#else +#define NFC_REG_BASE nfc_axi_base +#endif +#define NFC_BUF_SIZE (NFC_REG_BASE + 0xE00) +#define NFC_BUF_ADDR (NFC_REG_BASE + 0xE04) +#define NFC_FLASH_ADDR (NFC_REG_BASE + 0xE06) +#define NFC_FLASH_CMD (NFC_REG_BASE + 0xE08) +#define NFC_CONFIG (NFC_REG_BASE + 0xE0A) +#ifdef CONFIG_ARCH_MXC_HAS_NFC_V2_1 +#define NFC_ECC_STATUS_RESULT (NFC_REG_BASE + 0xE0C) +#define NFC_ECC_STATUS_RESULT_1 (NFC_REG_BASE + 0xE0C) +#define NFC_ECC_STATUS_RESULT_2 (NFC_REG_BASE + 0xE0E) +#define NFC_SPAS (NFC_REG_BASE + 0xE10) +#else +#define NFC_ECC_STATUS_RESULT (NFC_REG_BASE + 0xE0C) +#define NFC_RSLTMAIN_AREA (NFC_REG_BASE + 0xE0E) +#define NFC_RSLTSPARE_AREA (NFC_REG_BASE + 0xE10) +#endif +#define NFC_WRPROT (NFC_REG_BASE + 0xE12) +#ifdef CONFIG_ARCH_MXC_HAS_NFC_V2_1 +#define NFC_UNLOCKSTART_BLKADDR (NFC_REG_BASE + 0xE20) +#define NFC_UNLOCKEND_BLKADDR (NFC_REG_BASE + 0xE22) +#define NFC_UNLOCKSTART_BLKADDR1 (NFC_REG_BASE + 0xE24) +#define NFC_UNLOCKEND_BLKADDR1 (NFC_REG_BASE + 0xE26) +#define NFC_UNLOCKSTART_BLKADDR2 (NFC_REG_BASE + 0xE28) +#define NFC_UNLOCKEND_BLKADDR2 (NFC_REG_BASE + 0xE2A) +#define NFC_UNLOCKSTART_BLKADDR3 (NFC_REG_BASE + 0xE2C) +#define NFC_UNLOCKEND_BLKADDR3 (NFC_REG_BASE + 0xE2E) +#else +#define NFC_UNLOCKSTART_BLKADDR (NFC_REG_BASE + 0xE14) +#define NFC_UNLOCKEND_BLKADDR (NFC_REG_BASE + 0xE16) +#endif +#define NFC_NF_WRPRST (NFC_REG_BASE + 0xE18) +#define NFC_CONFIG1 (NFC_REG_BASE + 0xE1A) +#define NFC_CONFIG2 (NFC_REG_BASE + 0xE1C) + +/*! + * Addresses for NFC RAM BUFFER Main area 0 + */ +#define MAIN_AREA0 (u16 *)(nfc_axi_base + 0x000) +#define MAIN_AREA1 (u16 *)(nfc_axi_base + 0x200) + +/*! + * Addresses for NFC SPARE BUFFER Spare area 0 + */ +#ifdef CONFIG_ARCH_MXC_HAS_NFC_V2_1 +#define SPARE_AREA0 (u16 *)(nfc_axi_base + 0x1000) +#define SPARE_LEN 64 +#define SPARE_COUNT 8 +#else +#define SPARE_AREA0 (u16 *)(nfc_axi_base + 0x800) +#define SPARE_LEN 16 +#define SPARE_COUNT 4 +#endif +#define SPARE_SIZE (SPARE_LEN * SPARE_COUNT) + +#ifdef CONFIG_ARCH_MXC_HAS_NFC_V2_1 +#define REG_NFC_ECC_MODE NFC_CONFIG1 +#define SPAS_SHIFT (0) +#define REG_NFC_SPAS NFC_SPAS +#define SPAS_MASK (0xFF00) + +#define NFC_SET_SPAS(v) \ + raw_write(((raw_read(REG_NFC_SPAS) & SPAS_MASK) | ((v<> 1); \ + } \ +} while (0) +#else +#define NFC_SET_SPAS(v) +#define NFC_SET_ECC_MODE(v) +#define GET_ECC_STATUS() raw_read(REG_NFC_ECC_STATUS_RESULT); +#define NFC_SET_NFMS(v) (NFMS |= (v)) +#endif + +#define WRITE_NFC_IP_REG(val, reg) \ + raw_write((raw_read(REG_NFC_OPS_STAT) & ~NFC_OPS_STAT), \ + REG_NFC_OPS_STAT) + +#define GET_NFC_ECC_STATUS() raw_read(REG_NFC_ECC_STATUS_RESULT); + +/*! + * Set INT to 0, Set 1 to specific operation bit, rest to 0 in LAUNCH_NFC Register for + * Specific operation + */ +#define NFC_CMD 0x1 +#define NFC_ADDR 0x2 +#define NFC_INPUT 0x4 +#define NFC_OUTPUT 0x8 +#define NFC_ID 0x10 +#define NFC_STATUS 0x20 + +/* Bit Definitions */ +#define NFC_OPS_STAT (1 << 15) +#define NFC_SP_EN (1 << 2) +#define NFC_ECC_EN (1 << 3) +#define NFC_INT_MSK (1 << 4) +#define NFC_BIG (1 << 5) +#define NFC_RST (1 << 6) +#define NFC_CE (1 << 7) +#define NFC_ONE_CYCLE (1 << 8) +#define NFC_BLS_LOCKED 0 +#define NFC_BLS_LOCKED_DEFAULT 1 +#define NFC_BLS_UNLCOKED 2 +#define NFC_WPC_LOCK_TIGHT 1 +#define NFC_WPC_LOCK (1 << 1) +#define NFC_WPC_UNLOCK (1 << 2) +#define NFC_FLASH_ADDR_SHIFT 0 +#define NFC_UNLOCK_END_ADDR_SHIFT 0 + +#ifdef CONFIG_ARCH_MXC_HAS_NFC_V2_1 +#define NFC_ECC_MODE_4 (1<<0) +#define NFC_ECC_MODE_8 (~(1<<0)) +#define NFC_SPAS_16 8 +#define NFC_SPAS_64 32 +#define NFC_SPAS_112 56 +#define NFC_SPAS_128 64 +#define NFC_SPAS_218 109 +#endif +/* NFC Register Mapping */ +#define REG_NFC_OPS_STAT NFC_CONFIG2 +#define REG_NFC_INTRRUPT NFC_CONFIG1 +#define REG_NFC_FLASH_ADDR NFC_FLASH_ADDR +#define REG_NFC_FLASH_CMD NFC_FLASH_CMD +#define REG_NFC_OPS NFC_CONFIG2 +#define REG_NFC_SET_RBA NFC_BUF_ADDR +#define REG_NFC_ECC_EN NFC_CONFIG1 +#define REG_NFC_ECC_STATUS_RESULT NFC_ECC_STATUS_RESULT +#define REG_NFC_CE NFC_CONFIG1 +#define REG_NFC_SP_EN NFC_CONFIG1 +#define REG_NFC_BLS NFC_CONFIG +#define REG_NFC_WPC NFC_WRPROT +#define REG_START_BLKADDR NFC_UNLOCKSTART_BLKADDR +#define REG_END_BLKADDR NFC_UNLOCKEND_BLKADDR +#define REG_NFC_RST NFC_CONFIG1 +#define REG_NFC_ONE_CYCLE NFC_CONFIG1 + +/* NFC V1/V2 Specific MACRO functions definitions */ + +#define raw_write(v, a) __raw_writew(v, a) +#define raw_read(a) __raw_readw(a) + +#define NFC_SET_BLS(val) val + +#define UNLOCK_ADDR(start_addr, end_addr) \ +{ \ + raw_write(start_addr, REG_START_BLKADDR); \ + raw_write(end_addr, REG_END_BLKADDR); \ +} + +#define NFC_SET_NFC_ACTIVE_CS(val) +#define NFC_GET_MAXCHIP_SP() 1 +#define NFC_SET_WPC(val) val + +#define NFC_SET_RBA(val) raw_write(val, REG_NFC_SET_RBA); + +#ifdef CONFIG_ARCH_MXC_HAS_NFC_V2_1 +#define READ_PAGE() send_read_page(0) +#define PROG_PAGE() send_prog_page(0) +#else +#define READ_PAGE() \ +do { \ + send_read_page(0); \ + send_read_page(1); \ + send_read_page(2); \ + send_read_page(3); \ +} while (0) + +#define PROG_PAGE() \ +do { \ + send_prog_page(0); \ + send_prog_page(1); \ + send_prog_page(2); \ + send_prog_page(3); \ +} while (0) +#endif +#define CHECK_NFC_RB 1 + +#endif + +#endif /* __MXC_ND2_H__ */ diff --git a/drivers/mtd/nand/nand_device_info.c b/drivers/mtd/nand/nand_device_info.c new file mode 100644 index 000000000000..3c6333f54e57 --- /dev/null +++ b/drivers/mtd/nand/nand_device_info.c @@ -0,0 +1,2286 @@ +/* + * Copyright (C) 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include + +#include "nand_device_info.h" + +/* + * Type 2 + */ +static struct nand_device_info nand_device_info_table_type_2[] __initdata = { + { + .end_of_table = false, + .manufacturer_code = 0x20, + .device_code = 0xf1, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 128LL*SZ_1M, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 30, + .data_hold_in_ns = 20, + .address_setup_in_ns = 25, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "NAND01GW3", + }, + { + .end_of_table = false, + .manufacturer_code = 0xad, + .device_code = 0xf1, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 128LL*SZ_1M, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 45, + .data_hold_in_ns = 30, + .address_setup_in_ns = 25, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + NULL, + }, + { + .end_of_table = false, + .manufacturer_code = 0x2c, + .device_code = 0xf1, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 128LL*SZ_1M, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 30, + .data_hold_in_ns = 20, + .address_setup_in_ns = 10, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + NULL, + }, + { + .end_of_table = false, + .manufacturer_code = 0xec, + .device_code = 0xf1, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 128LL*SZ_1M, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 35, + .data_hold_in_ns = 25, + .address_setup_in_ns = 0, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "K9F1F08", + }, + { + .end_of_table = false, + .manufacturer_code = 0x98, + .device_code = 0xf1, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 128LL*SZ_1M, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 30, + .data_hold_in_ns = 20, + .address_setup_in_ns = 0, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "TC58NVG0S3", + }, + { + .end_of_table = false, + .manufacturer_code = 0x45, + .device_code = 0xf1, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 128LL*SZ_1M, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 45, + .data_hold_in_ns = 32, + .address_setup_in_ns = 0, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + NULL, + }, + { + .end_of_table = false, + .manufacturer_code = 0x20, + .device_code = 0xda, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 256LL*SZ_1M, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 20, + .data_hold_in_ns = 30, + .address_setup_in_ns = 0, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "NAND02GW3", + }, + { + .end_of_table = false, + .manufacturer_code = 0xad, + .device_code = 0xda, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 256LL*SZ_1M, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 30, + .data_hold_in_ns = 25, + .address_setup_in_ns = 10, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "HY27UF082G2M, HY27UG082G2M, HY27UG082G1M", + }, + { + .end_of_table = false, + .manufacturer_code = 0x2c, + .device_code = 0xda, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 256LL*SZ_1M, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 20, + .data_hold_in_ns = 10, + .address_setup_in_ns = 10, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "MT29F2G08", + }, + { + .end_of_table = false, + .manufacturer_code = 0xec, + .device_code = 0xda, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 256LL*SZ_1M, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 20, + .data_hold_in_ns = 10, + .address_setup_in_ns = 20, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "K9F2G08U0M", + }, + { + .end_of_table = false, + .manufacturer_code = 0x98, + .device_code = 0xda, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 256LL*SZ_1M, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 20, + .data_hold_in_ns = 30, + .address_setup_in_ns = 0, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "TC58NVG1S3", + }, + { + .end_of_table = false, + .manufacturer_code = 0x45, + .device_code = 0xda, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 256LL*SZ_1M, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 45, + .data_hold_in_ns = 32, + .address_setup_in_ns = 0, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + NULL, + }, + { + .end_of_table = false, + .manufacturer_code = 0x20, + .device_code = 0xdc, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 512LL*SZ_1M, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 45, + .data_hold_in_ns = 30, + .address_setup_in_ns = 10, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + NULL, + }, + { + .end_of_table = false, + .manufacturer_code = 0xad, + .device_code = 0xdc, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 512LL*SZ_1M, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 45, + .data_hold_in_ns = 30, + .address_setup_in_ns = 10, + .gpmi_sample_delay_in_ns = 10, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "HY27UH084G2M, HY27UG084G2M, HY27UH084G1M", + }, + { + .end_of_table = false, + .manufacturer_code = 0x2c, + .device_code = 0xdc, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 512LL*SZ_1M, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 20, + .data_hold_in_ns = 10, + .address_setup_in_ns = 10, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "MT29F4G08", + }, + { + .end_of_table = false, + .manufacturer_code = 0xec, + .device_code = 0xdc, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 512LL*SZ_1M, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 25, + .data_hold_in_ns = 25, + .address_setup_in_ns = 20, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + NULL, + }, + { + .end_of_table = false, + .manufacturer_code = 0x98, + .device_code = 0xdc, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 512LL*SZ_1M, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 25, + .data_hold_in_ns = 25, + .address_setup_in_ns = 0, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "TH58NVG2S3", + }, + { + .end_of_table = false, + .manufacturer_code = 0x45, + .device_code = 0xdc, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 512LL*SZ_1M, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 45, + .data_hold_in_ns = 32, + .address_setup_in_ns = 0, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + NULL, + }, + { + .end_of_table = false, + .manufacturer_code = 0xad, + .device_code = 0xd3, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 1LL*SZ_1G, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 30, + .data_hold_in_ns = 25, + .address_setup_in_ns = 20, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "HY27UH088G2M", + }, + { + .end_of_table = false, + .manufacturer_code = 0x20, + .device_code = 0xd3, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 1LL*SZ_1G, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 45, + .data_hold_in_ns = 30, + .address_setup_in_ns = 10, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "NAND08GW3BxANx", + }, + { + .end_of_table = false, + .manufacturer_code = 0x2c, + .device_code = 0xd3, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 1LL*SZ_1G, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 25, + .data_hold_in_ns = 15, + .address_setup_in_ns = 10, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "MT29F8G08FABWG", + }, + { + .end_of_table = false, + .manufacturer_code = 0x98, + .device_code = 0xd3, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 1LL*SZ_1G, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 45, + .data_hold_in_ns = 32, + .address_setup_in_ns = 0, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + NULL, + }, + { + .end_of_table = false, + .manufacturer_code = 0x20, + .device_code = 0xd5, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 2LL*SZ_1G, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 45, + .data_hold_in_ns = 30, + .address_setup_in_ns = 10, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + NULL, + }, + { + .end_of_table = false, + .manufacturer_code = 0xad, + .device_code = 0xd5, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 2LL*SZ_1G, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 25, + .data_hold_in_ns = 30, + .address_setup_in_ns = 10, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + NULL, + }, + { + .end_of_table = false, + .manufacturer_code = 0x2c, + .device_code = 0xd5, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 2LL*SZ_1G, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 45, + .data_hold_in_ns = 32, + .address_setup_in_ns = 0, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + NULL, + }, + {true} +}; + +/* + * Large MLC + */ +static struct nand_device_info nand_device_info_table_large_mlc[] __initdata = { + { + .end_of_table = false, + .manufacturer_code = 0x98, + .device_code = 0xda, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 256LL*SZ_1M, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 20, + .data_hold_in_ns = 30, + .address_setup_in_ns = 0, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "TC58NVG1D4BFT00", + }, + { + .end_of_table = false, + .manufacturer_code = 0x45, + .device_code = 0xda, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 256LL*SZ_1M, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 20, + .data_hold_in_ns = 30, + .address_setup_in_ns = 0, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + NULL, + }, + { + .end_of_table = false, + .manufacturer_code = 0x45, + .device_code = 0xdc, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 512LL*SZ_1M, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 20, + .data_hold_in_ns = 30, + .address_setup_in_ns = 0, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + NULL, + }, + { + .end_of_table = false, + .manufacturer_code = 0x98, + .device_code = 0xd3, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 1LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 35, + .data_hold_in_ns = 30, + .address_setup_in_ns = 0, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "TH58NVG3D4xFT00", + }, + { + .end_of_table = false, + .manufacturer_code = 0x45, + .device_code = 0xd3, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 1LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 35, + .data_hold_in_ns = 20, + .address_setup_in_ns = 0, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + NULL, + }, + { + .end_of_table = false, + .manufacturer_code = 0x98, + .device_code = 0xd5, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 2LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 35, + .data_hold_in_ns = 15, + .address_setup_in_ns = 0, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "TH58NVG4D4xFT00", + }, + { + .end_of_table = false, + .manufacturer_code = 0x45, + .device_code = 0xd5, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 2LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 35, + .data_hold_in_ns = 15, + .address_setup_in_ns = 0, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + NULL, + }, + { + .end_of_table = false, + .manufacturer_code = 0x98, + .device_code = 0xdc, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 512LL*SZ_1M, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 20, + .data_hold_in_ns = 30, + .address_setup_in_ns = 0, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "TC58NVG2D4BFT00", + }, + { + .end_of_table = false, + .manufacturer_code = 0xec, + .device_code = 0xdc, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 512LL*SZ_1M, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 25, + .data_hold_in_ns = 15, + .address_setup_in_ns = 25, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "K9G4G08U0M", + }, + { + .end_of_table = false, + .manufacturer_code = 0xad, + .device_code = 0xdc, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 512LL*SZ_1M, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 45, + .data_hold_in_ns = 25, + .address_setup_in_ns = 50, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "HY27UT084G2M, HY27UU088G5M", + }, + { + .end_of_table = false, + .manufacturer_code = 0x20, + .device_code = 0xdc, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 512LL*SZ_1M, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 40, + .data_hold_in_ns = 20, + .address_setup_in_ns = 30, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "NAND04GW3C2AN1E", + }, + { + .end_of_table = false, + .manufacturer_code = 0xec, + .device_code = 0xd3, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 1LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 20, + .data_hold_in_ns = 15, + .address_setup_in_ns = 20, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "K9G8G08U0M, K9HAG08U1M", + }, + { + .end_of_table = false, + .manufacturer_code = 0xad, + .device_code = 0xd3, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 1LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 60, + .data_hold_in_ns = 30, + .address_setup_in_ns = 50, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "HY27UV08AG5M", + }, + { + .end_of_table = false, + .manufacturer_code = 0x2c, + .device_code = 0xd3, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 1LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 15, + .data_hold_in_ns = 15, + .address_setup_in_ns = 15, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "Intel JS29F08G08AAMiB1 and Micron MT29F8G08MAA; " + "Intel JS29F08G08CAMiB1 and Micron MT29F16G08QAA", + }, + { + .end_of_table = false, + .manufacturer_code = 0xec, + .device_code = 0xd5, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 2LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 20, + .data_hold_in_ns = 15, + .address_setup_in_ns = 20, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "K9LAG08U0M K9HBG08U1M K9GAG08U0M", + }, + { + .end_of_table = false, + .manufacturer_code = 0x2c, + .device_code = 0xd5, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 2LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 15, + .data_hold_in_ns = 10, + .address_setup_in_ns = 15, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "Intel JS29F32G08FAMiB1 and Micron MT29F32G08TAA", + }, + { + .end_of_table = false, + .manufacturer_code = 0x2c, + .device_code = 0xdc, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 512LL*SZ_1M, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 20, + .data_hold_in_ns = 20, + .address_setup_in_ns = 20, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "MT29F4G08", + }, + { + .end_of_table = false, + .manufacturer_code = 0x89, + .device_code = 0xd3, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 1LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 15, + .data_hold_in_ns = 10, + .address_setup_in_ns = 15, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "JS29F08G08AAMiB2, JS29F08G08CAMiB2", + }, + { + .end_of_table = false, + .manufacturer_code = 0x89, + .device_code = 0xd5, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 2LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 15, + .data_hold_in_ns = 10, + .address_setup_in_ns = 15, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "JS29F32G08FAMiB2", + }, + { + .end_of_table = false, + .manufacturer_code = 0xad, + .device_code = 0xd5, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 2LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 15, + .data_hold_in_ns = 10, + .address_setup_in_ns = 20, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "HY27UW08CGFM", + }, + {true} +}; + +/* + * Type 7 + */ +static struct nand_device_info nand_device_info_table_type_7[] __initdata = { + { + .end_of_table = false, + .manufacturer_code = 0x2c, + .device_code = 0xd3, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 1LL*SZ_1G, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 25, + .data_hold_in_ns = 15, + .address_setup_in_ns = 10, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "MT29F8G08FABWG", + }, + { + .end_of_table = false, + .manufacturer_code = 0x2c, + .device_code = 0xdc, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 512LL*SZ_1M, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 20, + .data_hold_in_ns = 10, + .address_setup_in_ns = 10, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "MT29F4G08AAA", + }, + { + .end_of_table = false, + .manufacturer_code = 0xec, + .device_code = 0xdc, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 512LL*SZ_1M, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 15, + .data_hold_in_ns = 12, + .address_setup_in_ns = 25, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "K9F4G08", + }, + { + .end_of_table = false, + .manufacturer_code = 0xec, + .device_code = 0xd3, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 1LL*SZ_1G, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 25, + .data_hold_in_ns = 15, + .address_setup_in_ns = 35, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "K9K8G08UXM, K9NBG08U5A, K9WAG08U1A", + }, + { + .end_of_table = false, + .manufacturer_code = 0xec, + .device_code = 0xd5, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 2LL*SZ_1G, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 15, + .data_hold_in_ns = 12, + .address_setup_in_ns = 25, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "K9WAG08UXM", + }, + { + .end_of_table = false, + .manufacturer_code = 0xec, + .device_code = 0xda, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 256LL*SZ_1M, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 20, + .data_hold_in_ns = 10, + .address_setup_in_ns = 20, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "K9F2G08U0A", + }, + { + .end_of_table = false, + .manufacturer_code = 0xec, + .device_code = 0xf1, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 128LL*SZ_1M, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 2*SZ_1K + 64, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 15, + .data_hold_in_ns = 12, + .address_setup_in_ns = 20, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "K9F1F08", + }, + {true} +}; + +/* + * Type 8 + */ +static struct nand_device_info nand_device_info_table_type_8[] __initdata = { + { + .end_of_table = false, + .manufacturer_code = 0xec, + .device_code = 0xd5, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 2LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 4*SZ_1K + 128, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 15, + .data_hold_in_ns = 10, + .address_setup_in_ns = 20, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "K9GAG08U0M", + }, + { + .end_of_table = false, + .manufacturer_code = 0xec, + .device_code = 0xd7, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 4LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 4*SZ_1K + 128, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 15, + .data_hold_in_ns = 15, + .address_setup_in_ns = 25, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "K9LBG08U0M (32Gb), K9HCG08U1M (64Gb), K9MDG08U5M (128Gb)", + }, + { + .end_of_table = false, + .manufacturer_code = 0xad, + .device_code = 0xd5, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 2LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 4*SZ_1K + 128, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 20, + .data_hold_in_ns = 20, + .address_setup_in_ns = 20, + .gpmi_sample_delay_in_ns = 0, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "H27UAG, H27UBG", + }, + { + .end_of_table = false, + .manufacturer_code = 0xad, + .device_code = 0xd7, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 4LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 4*SZ_1K + 128, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 23, + .data_hold_in_ns = 20, + .address_setup_in_ns = 25, + .gpmi_sample_delay_in_ns = 0, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "H27UCG", + }, + {true} +}; + +/* + * Type 9 + */ +static struct nand_device_info nand_device_info_table_type_9[] __initdata = { + { + .end_of_table = false, + .manufacturer_code = 0x98, + .device_code = 0xd3, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 1LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 4*SZ_1K + 218, + .ecc_strength_in_bits = 8, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 15, + .data_hold_in_ns = 15, + .address_setup_in_ns = 10, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "TC58NVG3D1DTG00", + }, + { + .end_of_table = false, + .manufacturer_code = 0x98, + .device_code = 0xd5, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 2LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 4*SZ_1K + 218, + .ecc_strength_in_bits = 8, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 15, + .data_hold_in_ns = 15, + .address_setup_in_ns = 10, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "TC58NVG4D1DTG00", + }, + { + .end_of_table = false, + .manufacturer_code = 0x98, + .device_code = 0xd7, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 4LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 4*SZ_1K + 218, + .ecc_strength_in_bits = 8, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 15, + .data_hold_in_ns = 15, + .address_setup_in_ns = 10, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "TH58NVG6D1DTG20", + }, + { + .end_of_table = false, + .manufacturer_code = 0x89, + .device_code = 0xd5, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 2LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 4*SZ_1K + 218, + .ecc_strength_in_bits = 8, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 10, + .data_hold_in_ns = 10, + .address_setup_in_ns = 15, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "JS29F16G08AAMC1, JS29F32G08CAMC1", + }, + { + .end_of_table = false, + .manufacturer_code = 0x2c, + .device_code = 0xd5, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 2LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 4*SZ_1K + 218, + .ecc_strength_in_bits = 8, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 15, + .data_hold_in_ns = 10, + .address_setup_in_ns = 15, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "MT29F16G08MAA, MT29F32G08QAA", + }, + { + .end_of_table = false, + .manufacturer_code = 0x2c, + .device_code = 0xd7, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 4LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 4*SZ_1K + 218, + .ecc_strength_in_bits = 8, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 15, + .data_hold_in_ns = 10, + .address_setup_in_ns = 15, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "MT29F64G08TAA (32Gb), MT29F32G08CBAAA (32Gb) MT29F64G08CFAAA (64Gb)", + }, + { + .end_of_table = false, + .manufacturer_code = 0x2c, + .device_code = 0xd9, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 8LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 4*SZ_1K + 218, + .ecc_strength_in_bits = 8, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 10, + .data_hold_in_ns = 10, + .address_setup_in_ns = 15, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "MT29F128G08CJAAA", + }, + { + .end_of_table = false, + .manufacturer_code = 0x89, + .device_code = 0xd7, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 4LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 4*SZ_1K + 218, + .ecc_strength_in_bits = 8, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 10, + .data_hold_in_ns = 10, + .address_setup_in_ns = 15, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "JSF64G08FAMC1", + }, + { + .end_of_table = false, + .manufacturer_code = 0xec, + .device_code = 0xd7, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 4LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 4*SZ_1K + 218, + .ecc_strength_in_bits = 8, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 20, + .data_hold_in_ns = 10, + .address_setup_in_ns = 25, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = 20, + .tRLOH_in_ns = 5, + .tRHOH_in_ns = 15, + "K9LBG08U0D", + }, + { + .end_of_table = false, + .manufacturer_code = 0xec, + .device_code = 0xd5, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 2LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 4*SZ_1K + 218, + .ecc_strength_in_bits = 8, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 20, + .data_hold_in_ns = 10, + .address_setup_in_ns = 20, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "K9GAG08U0D, K9LBG08U1D, K9HCG08U5D", + }, + {true} +}; + +/* + * Type 10 + */ +static struct nand_device_info nand_device_info_table_type_10[] __initdata = { + { + .end_of_table = false, + .manufacturer_code = 0xec, + .device_code = 0xd3, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 1LL*SZ_1G, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 4*SZ_1K + 128, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 15, + .data_hold_in_ns = 10, + .address_setup_in_ns = 20, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + NULL, + }, + { + .end_of_table = false, + .manufacturer_code = 0xec, + .device_code = 0xd5, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 2LL*SZ_1G, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 4*SZ_1K + 128, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 25, + .data_hold_in_ns = 15, + .address_setup_in_ns = 30, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + "K9NCG08U5M", + }, + { + .end_of_table = false, + .manufacturer_code = 0xec, + .device_code = 0xd7, + .cell_technology = NAND_DEVICE_CELL_TECH_SLC, + .chip_size_in_bytes = 4LL*SZ_1G, + .block_size_in_pages = 64, + .page_total_size_in_bytes = 4*SZ_1K + 128, + .ecc_strength_in_bits = 4, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 15, + .data_hold_in_ns = 15, + .address_setup_in_ns = 25, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = -1, + .tRLOH_in_ns = -1, + .tRHOH_in_ns = -1, + NULL, + }, + {true} +}; + +/* + * Type 11 + */ +static struct nand_device_info nand_device_info_table_type_11[] __initdata = { + { + .end_of_table = false, + .manufacturer_code = 0x98, + .device_code = 0xd7, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 4LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 8*SZ_1K + 376, + .ecc_strength_in_bits = 14, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 15, + .data_hold_in_ns = 10, + .address_setup_in_ns = 8, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = 20, + .tRLOH_in_ns = 5, + .tRHOH_in_ns = 25, + "TC58NVG5D2ELAM8 (4GB), TH58NVG6D2ELAM8 (8GB)", + }, + { + .end_of_table = false, + .manufacturer_code = 0x98, + .device_code = 0xde, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 8LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 8*SZ_1K + 376, + .ecc_strength_in_bits = 14, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 15, + .data_hold_in_ns = 10, + .address_setup_in_ns = 8, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = 20, + .tRLOH_in_ns = 5, + .tRHOH_in_ns = 25, + "TH58NVG7D2ELAM8", + }, + {true} +}; + +/* + * Type 15 + */ +static struct nand_device_info nand_device_info_table_type_15[] __initdata = { + { + .end_of_table = false, + .manufacturer_code = 0xec, + .device_code = 0xd7, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 4LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 8*SZ_1K + 436, + .ecc_strength_in_bits = 16, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 20, + .data_hold_in_ns = 10, + .address_setup_in_ns = 25, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = 25, + .tRLOH_in_ns = 5, + .tRHOH_in_ns = 15, + "K9GBG08U0M (4GB, 1CE); K9LCG08U1M (8GB, 2CE); K9HDG08U5M (16GB, 4CE)", + }, + {true} +}; + +/* + * BCH ECC12 + */ +static struct nand_device_info nand_device_info_table_bch_ecc12[] __initdata = { + { + .end_of_table = false, + .manufacturer_code = 0xad, + .device_code = 0xd7, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 4LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 4*SZ_1K + 224, + .ecc_strength_in_bits = 12, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 15, + .data_hold_in_ns = 10, + .address_setup_in_ns = 20, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = 20, + .tRLOH_in_ns = 5, + .tRHOH_in_ns = 15, + "H27UBG8T2M (4GB, 1CE), H27UCG8UDM (8GB, 2CE), H27UDG8VEM (16GB, 4CE)", + }, + { + .end_of_table = false, + .manufacturer_code = 0xad, + .device_code = 0xde, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 8LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 4*SZ_1K + 224, + .ecc_strength_in_bits = 12, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 15, + .data_hold_in_ns = 10, + .address_setup_in_ns = 20, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = 20, + .tRLOH_in_ns = 5, + .tRHOH_in_ns = 15, + "H27UEG8YEM (32GB, 4CE)", + }, + { + .end_of_table = false, + .manufacturer_code = 0x2c, + .device_code = 0xd7, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 4LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 4*SZ_1K + 218, + .ecc_strength_in_bits = 12, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 10, + .data_hold_in_ns = 10, + .address_setup_in_ns = 15, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = 16, + .tRLOH_in_ns = 5, + .tRHOH_in_ns = 15, + "MT29F32G08CBAAA (4GB, 1CE), MT29F64G08CFAAA (8GB, 2CE)", + }, + { + .end_of_table = false, + .manufacturer_code = 0x2c, + .device_code = 0xd9, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 8LL*SZ_1G, + .block_size_in_pages = 128, + .page_total_size_in_bytes = 4*SZ_1K + 218, + .ecc_strength_in_bits = 12, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 10, + .data_hold_in_ns = 10, + .address_setup_in_ns = 15, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = 16, + .tRLOH_in_ns = 5, + .tRHOH_in_ns = 15, + "MT29F128G08CJAAA (16GB, 2CE)", + }, + { + .end_of_table = false, + .manufacturer_code = 0x2c, + .device_code = 0x48, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 2LL*SZ_1G, + .block_size_in_pages = 256, + .page_total_size_in_bytes = 4*SZ_1K + 224, + .ecc_strength_in_bits = 12, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 15, + .data_hold_in_ns = 10, + .address_setup_in_ns = 20, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = 20, + .tRLOH_in_ns = 5, + .tRHOH_in_ns = 15, + "MT29F16G08CBABA (2GB, 1CE)", + }, + { + .end_of_table = false, + .manufacturer_code = 0x2c, + .device_code = 0x68, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 4LL*SZ_1G, + .block_size_in_pages = 256, + .page_total_size_in_bytes = 4*SZ_1K + 224, + .ecc_strength_in_bits = 12, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 15, + .data_hold_in_ns = 10, + .address_setup_in_ns = 20, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = 20, + .tRLOH_in_ns = 5, + .tRHOH_in_ns = 15, + "MT29F32G08CBABA (4GB, 1CE); " + "MT29F64G08CEABA (8GB, 2CE); " + "MT29F64G08CFABA (8GB, 2CE)", + }, + { + .end_of_table = false, + .manufacturer_code = 0x2c, + .device_code = 0x88, + .cell_technology = NAND_DEVICE_CELL_TECH_MLC, + .chip_size_in_bytes = 8LL*SZ_1G, + .block_size_in_pages = 256, + .page_total_size_in_bytes = 4*SZ_1K + 224, + .ecc_strength_in_bits = 12, + .ecc_size_in_bytes = 512, + .data_setup_in_ns = 15, + .data_hold_in_ns = 10, + .address_setup_in_ns = 20, + .gpmi_sample_delay_in_ns = 6, + .tREA_in_ns = 20, + .tRLOH_in_ns = 5, + .tRHOH_in_ns = 15, + "MT29F128G08CJABA (16GB, 2CE); " + "MT29F128G08CKABA (16GB, 2CE); " + "MT29F256G08CUABA (32GB, 4CE)", + }, + {true} +}; + +/* + * The following macros make it convenient to extract information from an ID + * byte array. All these macros begin with the prefix "ID_". + * + * Macros of the form: + * + * ID_GET_[_[_]] + * + * extract the given field from an ID byte array. Macros of the form: + * + * ID_[_[_]]_ + * + * contain the value for the given field that has the given meaning. + * + * If the appears, it means this macro represents a view of this + * field that is specific to the given manufacturer. + * + * If the appears, it means this macro represents a view of this + * field that the given manufacturer applies only under specific conditions. + * + * Here is a simple example: + * + * ID_PAGE_SIZE_CODE_2K + * + * This macro has the value of the "Page Size" field that indicates the page + * size is 2K. + * + * A more complicated example: + * + * ID_SAMSUNG_6_BYTE_PAGE_SIZE_CODE_8K (0x2) + * + * This macro has the value of the "Page Size" field for Samsung parts that + * indicates the page size is 8K. However, this interpretation is only correct + * for devices that return 6 ID bytes. + */ + +/* Byte 1 ------------------------------------------------------------------- */ + +#define ID_GET_BYTE_1(id) ((id)[0]) + +#define ID_GET_MFR_CODE(id) ID_GET_BYTE_1(id) + +/* Byte 2 ------------------------------------------------------------------- */ + +#define ID_GET_BYTE_2(id) ((id)[1]) + +#define ID_GET_DEVICE_CODE(id) ID_GET_BYTE_2(id) + #define ID_SAMSUNG_DEVICE_CODE_1_GBIT (0xf1) + #define ID_SAMSUNG_DEVICE_CODE_2_GBIT (0xda) + #define ID_HYNIX_DEVICE_CODE_ECC12 (0xd7) + #define ID_HYNIX_DEVICE_CODE_ECC12_LARGE (0xde) + #define ID_MICRON_DEVICE_CODE_ECC12 (0xd7) /* ECC12 */ + #define ID_MICRON_DEVICE_CODE_ECC12_LARGE (0xd9) /* ECC12 8GB/CE */ + #define ID_MICRON_DEVICE_CODE_ECC12_2GB_PER_CE (0x48) /* L63B 2GB/CE */ + #define ID_MICRON_DEVICE_CODE_ECC12_4GB_PER_CE (0x68) /* L63B 4GB/CE */ + #define ID_MICRON_DEVICE_CODE_ECC12_8GB_PER_CE (0x88) /* L63B 8GB/CE */ + +/* Byte 3 ------------------------------------------------------------------- */ + +#define ID_GET_BYTE_3(id) ((id)[2]) + +#define ID_GET_DIE_COUNT_CODE(id) ((ID_GET_BYTE_3(id) >> 0) & 0x3) + +#define ID_GET_CELL_TYPE_CODE(id) ((ID_GET_BYTE_3(id) >> 2) & 0x3) + #define ID_CELL_TYPE_CODE_SLC (0x0) /* All others => MLC. */ + +#define ID_GET_SAMSUNG_SIMUL_PROG(id) ((ID_GET_BYTE_3(id) >> 4) & 0x3) + +#define ID_GET_MICRON_SIMUL_PROG(id) ((ID_GET_BYTE_3(id) >> 4) & 0x3) + +#define ID_GET_CACHE_PROGRAM(id) ((ID_GET_BYTE_3(id) >> 7) & 0x1) + +/* Byte 4 ------------------------------------------------------------------- */ + +#define ID_GET_BYTE_4(id) ((id)[3]) + #define ID_HYNIX_BYTE_4_ECC12_DEVICE (0x25) + +#define ID_GET_PAGE_SIZE_CODE(id) ((ID_GET_BYTE_4(id) >> 0) & 0x3) + #define ID_PAGE_SIZE_CODE_1K (0x0) + #define ID_PAGE_SIZE_CODE_2K (0x1) + #define ID_PAGE_SIZE_CODE_4K (0x2) + #define ID_PAGE_SIZE_CODE_8K (0x3) + #define ID_SAMSUNG_6_BYTE_PAGE_SIZE_CODE_8K (0x2) + +#define ID_GET_OOB_SIZE_CODE(id) ((ID_GET_BYTE_4(id) >> 2) & 0x1) + +#define ID_GET_BLOCK_SIZE_CODE(id) ((ID_GET_BYTE_4(id) >> 4) & 0x3) + +/* Byte 5 ------------------------------------------------------------------- */ + +#define ID_GET_BYTE_5(id) ((id)[4]) + #define ID_MICRON_BYTE_5_ECC12 (0x84) + +#define ID_GET_SAMSUNG_ECC_LEVEL_CODE(id) ((ID_GET_BYTE_5(id) >> 4) & 0x7) + #define ID_SAMSUNG_ECC_LEVEL_CODE_8 (0x03) + #define ID_SAMSUNG_ECC_LEVEL_CODE_24 (0x05) + +#define ID_GET_PLANE_COUNT_CODE(id) ((ID_GET_BYTE_5(id) >> 2) & 0x3) + +/* Byte 6 ------------------------------------------------------------------- */ + +#define ID_GET_BYTE_6(id) ((id)[5]) + #define ID_TOSHIBA_BYTE_6_PAGE_SIZE_CODE_8K (0x54) + #define ID_TOSHIBA_BYTE_6_PAGE_SIZE_CODE_4K (0x13) + +#define ID_GET_SAMSUNG_DEVICE_VERSION_CODE(id) ((ID_GET_BYTE_6(id)>>0) & 0x7) + #define ID_SAMSUNG_DEVICE_VERSION_CODE_40NM (0x01) + +/* -------------------------------------------------------------------------- */ + +void nand_device_print_info(struct nand_device_info *info) +{ + unsigned i; + const char *mfr_name; + const char *cell_technology_name; + uint64_t chip_size; + const char *chip_size_units; + unsigned page_data_size_in_bytes; + unsigned page_oob_size_in_bytes; + + /* Check for nonsense. */ + + if (!info) + return; + + /* Prepare the manufacturer name. */ + + mfr_name = "Unknown"; + + for (i = 0; nand_manuf_ids[i].id; i++) { + if (nand_manuf_ids[i].id == info->manufacturer_code) { + mfr_name = nand_manuf_ids[i].name; + break; + } + } + + /* Prepare the name of the cell technology. */ + + switch (info->cell_technology) { + case NAND_DEVICE_CELL_TECH_SLC: + cell_technology_name = "SLC"; + break; + case NAND_DEVICE_CELL_TECH_MLC: + cell_technology_name = "MLC"; + break; + default: + cell_technology_name = "Unknown"; + break; + } + + /* Prepare the chip size. */ + + if ((info->chip_size_in_bytes >= SZ_1G) && + !(info->chip_size_in_bytes % SZ_1G)) { + chip_size = info->chip_size_in_bytes / ((uint64_t) SZ_1G); + chip_size_units = "GiB"; + } else if ((info->chip_size_in_bytes >= SZ_1M) && + !(info->chip_size_in_bytes % SZ_1M)) { + chip_size = info->chip_size_in_bytes / ((uint64_t) SZ_1M); + chip_size_units = "MiB"; + } else { + chip_size = info->chip_size_in_bytes; + chip_size_units = "B"; + } + + /* Prepare the page geometry. */ + + page_data_size_in_bytes = (1<<(fls(info->page_total_size_in_bytes)-1)); + page_oob_size_in_bytes = info->page_total_size_in_bytes - + page_data_size_in_bytes; + + /* Print the information. */ + + printk(KERN_INFO "Manufacturer : %s (0x%02x)\n", mfr_name, + info->manufacturer_code); + printk(KERN_INFO "Device Code : 0x%02x\n", info->device_code); + printk(KERN_INFO "Cell Technology : %s\n", cell_technology_name); + printk(KERN_INFO "Chip Size : %llu %s\n", chip_size, + chip_size_units); + printk(KERN_INFO "Pages per Block : %u\n", + info->block_size_in_pages); + printk(KERN_INFO "Page Geometry : %u+%u\n", page_data_size_in_bytes, + page_oob_size_in_bytes); + printk(KERN_INFO "ECC Strength : %u bits\n", + info->ecc_strength_in_bits); + printk(KERN_INFO "ECC Size : %u B\n", info->ecc_size_in_bytes); + printk(KERN_INFO "Data Setup Time : %u ns\n", info->data_setup_in_ns); + printk(KERN_INFO "Data Hold Time : %u ns\n", info->data_hold_in_ns); + printk(KERN_INFO "Address Setup Time: %u ns\n", + info->address_setup_in_ns); + printk(KERN_INFO "GPMI Sample Delay : %u ns\n", + info->gpmi_sample_delay_in_ns); + if (info->tREA_in_ns >= 0) + printk(KERN_INFO "tREA : %u ns\n", + info->tREA_in_ns); + else + printk(KERN_INFO "tREA : Unknown\n"); + if (info->tREA_in_ns >= 0) + printk(KERN_INFO "tRLOH : %u ns\n", + info->tRLOH_in_ns); + else + printk(KERN_INFO "tRLOH : Unknown\n"); + if (info->tREA_in_ns >= 0) + printk(KERN_INFO "tRHOH : %u ns\n", + info->tRHOH_in_ns); + else + printk(KERN_INFO "tRHOH : Unknown\n"); + if (info->description) + printk(KERN_INFO "Description : %s\n", info->description); + else + printk(KERN_INFO "Description : \n"); + +} + +static struct nand_device_info *nand_device_info_search( + struct nand_device_info *table, uint8_t mfr_code, uint8_t device_code) +{ + + for (; !table->end_of_table; table++) { + if (table->manufacturer_code != mfr_code) + continue; + if (table->device_code != device_code) + continue; + return table; + } + + return 0; + +} + +static struct nand_device_info * __init nand_device_info_fn_toshiba(const uint8_t id[]) +{ + struct nand_device_info *table; + + /* Check for an SLC device. */ + + if (ID_GET_CELL_TYPE_CODE(id) == ID_CELL_TYPE_CODE_SLC) { + /* Type 2 */ + return nand_device_info_search(nand_device_info_table_type_2, + ID_GET_MFR_CODE(id), ID_GET_DEVICE_CODE(id)); + } + + /* + * Look for 8K page Toshiba MLC devices. + * + * The page size field in byte 4 can't be used because the field was + * redefined in the 8K parts so the value meaning "8K page" is the same + * as the value meaning "4K page" on the 4K page devices. + * + * The only identifiable difference between the 4K and 8K page Toshiba + * devices with a device code of 0xd7 is the undocumented 6th ID byte. + * The 4K device returns a value of 0x13 and the 8K a value of 0x54. + * Toshiba has verified that this is an acceptable method to distinguish + * the two device families. + */ + + if (ID_GET_BYTE_6(id) == ID_TOSHIBA_BYTE_6_PAGE_SIZE_CODE_8K) { + /* Type 11 */ + table = nand_device_info_table_type_11; + } else if (ID_GET_PAGE_SIZE_CODE(id) == ID_PAGE_SIZE_CODE_4K) { + /* Type 9 */ + table = nand_device_info_table_type_9; + } else { + /* Large MLC */ + table = nand_device_info_table_large_mlc; + } + + return nand_device_info_search(table, ID_GET_MFR_CODE(id), + ID_GET_DEVICE_CODE(id)); + +} + +static struct nand_device_info * __init nand_device_info_fn_samsung(const uint8_t id[]) +{ + struct nand_device_info *table; + + /* Check for an MLC device. */ + + if (ID_GET_CELL_TYPE_CODE(id) != ID_CELL_TYPE_CODE_SLC) { + + /* Is this a Samsung 8K Page MLC device with 16 bit ECC? */ + if ((ID_GET_SAMSUNG_ECC_LEVEL_CODE(id) == + ID_SAMSUNG_ECC_LEVEL_CODE_24) && + (ID_GET_PAGE_SIZE_CODE(id) == + ID_SAMSUNG_6_BYTE_PAGE_SIZE_CODE_8K)) { + /* Type 15 */ + table = nand_device_info_table_type_15; + } + /* Is this a Samsung 42nm ECC8 device with a 6 byte ID? */ + else if ((ID_GET_SAMSUNG_ECC_LEVEL_CODE(id) == + ID_SAMSUNG_ECC_LEVEL_CODE_8) && + (ID_GET_SAMSUNG_DEVICE_VERSION_CODE(id) == + ID_SAMSUNG_DEVICE_VERSION_CODE_40NM)) { + /* Type 9 */ + table = nand_device_info_table_type_9; + } else if (ID_GET_PAGE_SIZE_CODE(id) == ID_PAGE_SIZE_CODE_4K) { + /* Type 8 */ + table = nand_device_info_table_type_8; + } else { + /* Large MLC */ + table = nand_device_info_table_large_mlc; + } + + } else { + + /* Check the page size first. */ + if (ID_GET_PAGE_SIZE_CODE(id) == ID_PAGE_SIZE_CODE_4K) { + /* Type 10 */ + table = nand_device_info_table_type_10; + } + /* Check the chip size. */ + else if (ID_GET_DEVICE_CODE(id) == + ID_SAMSUNG_DEVICE_CODE_1_GBIT) { + if (!ID_GET_CACHE_PROGRAM(id)) { + /* + * 128 MiB Samsung chips without cache program + * are Type 7. + * + * The K9F1G08U0B does not support multi-plane + * program, so the if statement below cannot be + * used to identify it. + */ + table = nand_device_info_table_type_7; + + } else { + /* Smaller sizes are Type 2 by default. */ + table = nand_device_info_table_type_2; + } + } else { + /* Check number of simultaneously programmed pages. */ + if (ID_GET_SAMSUNG_SIMUL_PROG(id) && + ID_GET_PLANE_COUNT_CODE(id)) { + /* Type 7 */ + table = nand_device_info_table_type_7; + } else { + /* Type 2 */ + table = nand_device_info_table_type_2; + } + + } + + } + + return nand_device_info_search(table, ID_GET_MFR_CODE(id), + ID_GET_DEVICE_CODE(id)); + +} + +static struct nand_device_info * __init nand_device_info_fn_stmicro(const uint8_t id[]) +{ + struct nand_device_info *table; + + /* Check for an SLC device. */ + + if (ID_GET_CELL_TYPE_CODE(id) == ID_CELL_TYPE_CODE_SLC) + /* Type 2 */ + table = nand_device_info_table_type_2; + else + /* Large MLC */ + table = nand_device_info_table_large_mlc; + + return nand_device_info_search(table, ID_GET_MFR_CODE(id), + ID_GET_DEVICE_CODE(id)); + +} + +static struct nand_device_info * __init nand_device_info_fn_hynix(const uint8_t id[]) +{ + struct nand_device_info *table; + + /* Check for an SLC device. */ + + if (ID_GET_CELL_TYPE_CODE(id) == ID_CELL_TYPE_CODE_SLC) { + /* Type 2 */ + return nand_device_info_search(nand_device_info_table_type_2, + ID_GET_MFR_CODE(id), ID_GET_DEVICE_CODE(id)); + } + + /* + * Check for ECC12 devices. + * + * We look at the 4th ID byte to distinguish some Hynix ECC12 devices + * from the similar ECC8 part. For example H27UBG8T2M (ECC12) 4th byte + * is 0x25, whereas H27UDG8WFM (ECC8) 4th byte is 0xB6. + */ + + if ((ID_GET_DEVICE_CODE(id) == ID_HYNIX_DEVICE_CODE_ECC12 && + ID_GET_BYTE_4(id) == ID_HYNIX_BYTE_4_ECC12_DEVICE) || + (ID_GET_DEVICE_CODE(id) == ID_HYNIX_DEVICE_CODE_ECC12_LARGE)) { + /* BCH ECC 12 */ + table = nand_device_info_table_bch_ecc12; + } else if (ID_GET_PAGE_SIZE_CODE(id) == ID_PAGE_SIZE_CODE_4K) { + /* + * So far, all other Samsung and Hynix 4K page devices are + * Type 8. + */ + table = nand_device_info_table_type_8; + } else + /* Large MLC */ + table = nand_device_info_table_large_mlc; + + return nand_device_info_search(table, ID_GET_MFR_CODE(id), + ID_GET_DEVICE_CODE(id)); + +} + +static struct nand_device_info * __init nand_device_info_fn_micron(const uint8_t id[]) +{ + struct nand_device_info *table; + + /* Check for an SLC device. */ + + if (ID_GET_CELL_TYPE_CODE(id) == ID_CELL_TYPE_CODE_SLC) { + + /* Check number of simultaneously programmed pages. */ + + if (ID_GET_MICRON_SIMUL_PROG(id)) { + /* Type 7 */ + table = nand_device_info_table_type_7; + } else { + /* Zero simultaneously programmed pages means Type 2. */ + table = nand_device_info_table_type_2; + } + + return nand_device_info_search(table, ID_GET_MFR_CODE(id), + ID_GET_DEVICE_CODE(id)); + + } + + /* + * We look at the 5th ID byte to distinguish some Micron ECC12 NANDs + * from the similar ECC8 part. + * + * For example MT29F64G08CFAAA (ECC12) 5th byte is 0x84, whereas + * MT29F64G08TAA (ECC8) 5th byte is 0x78. + * + * We also have a special case for the Micron L63B family + * (256 page/block), which has unique device codes but no ID fields that + * can easily be used to distinguish the family. + */ + + if ((ID_GET_DEVICE_CODE(id) == ID_MICRON_DEVICE_CODE_ECC12 && + ID_GET_BYTE_5(id) == ID_MICRON_BYTE_5_ECC12) || + (ID_GET_DEVICE_CODE(id) == ID_MICRON_DEVICE_CODE_ECC12_LARGE) || + (ID_GET_DEVICE_CODE(id) == ID_MICRON_DEVICE_CODE_ECC12_2GB_PER_CE) || + (ID_GET_DEVICE_CODE(id) == ID_MICRON_DEVICE_CODE_ECC12_4GB_PER_CE) || + (ID_GET_DEVICE_CODE(id) == ID_MICRON_DEVICE_CODE_ECC12_8GB_PER_CE)) { + /* BCH ECC 12 */ + table = nand_device_info_table_bch_ecc12; + } else if (ID_GET_PAGE_SIZE_CODE(id) == ID_PAGE_SIZE_CODE_4K) { + /* Toshiba devices with 4K pages are Type 9. */ + table = nand_device_info_table_type_9; + } else { + /* Large MLC */ + table = nand_device_info_table_large_mlc; + } + + return nand_device_info_search(table, ID_GET_MFR_CODE(id), + ID_GET_DEVICE_CODE(id)); + +} + +static struct nand_device_info * __init nand_device_info_fn_sandisk(const uint8_t id[]) +{ + struct nand_device_info *table; + + if (ID_GET_CELL_TYPE_CODE(id) != ID_CELL_TYPE_CODE_SLC) { + /* Large MLC */ + table = nand_device_info_table_large_mlc; + } else { + /* Type 2 */ + table = nand_device_info_table_type_2; + } + + return nand_device_info_search(table, ID_GET_MFR_CODE(id), + ID_GET_DEVICE_CODE(id)); + +} + +static struct nand_device_info * __init nand_device_info_fn_intel(const uint8_t id[]) +{ + struct nand_device_info *table; + + /* Check for an SLC device. */ + + if (ID_GET_CELL_TYPE_CODE(id) == ID_CELL_TYPE_CODE_SLC) { + /* Type 2 */ + return nand_device_info_search(nand_device_info_table_type_2, + ID_GET_MFR_CODE(id), ID_GET_DEVICE_CODE(id)); + } + + if (ID_GET_PAGE_SIZE_CODE(id) == ID_PAGE_SIZE_CODE_4K) { + /* Type 9 */ + table = nand_device_info_table_type_9; + } else { + /* Large MLC */ + table = nand_device_info_table_large_mlc; + } + + return nand_device_info_search(table, ID_GET_MFR_CODE(id), + ID_GET_DEVICE_CODE(id)); + +} + +/** + * struct nand_device_type_info - Information about a NAND Flash type. + * + * @name: A human-readable name for this type. + * @table: The device info table for this type. + */ + +struct nand_device_type_info { + struct nand_device_info *table; + const char *name; +}; + +/* + * A table that maps manufacturer IDs to device information tables. + */ + +static struct nand_device_type_info nand_device_type_directory[] __initdata = { + {nand_device_info_table_type_2, "Type 2" }, + {nand_device_info_table_large_mlc, "Large MLC"}, + {nand_device_info_table_type_7, "Type 7" }, + {nand_device_info_table_type_8, "Type 8" }, + {nand_device_info_table_type_9, "Type 9" }, + {nand_device_info_table_type_10, "Type 10" }, + {nand_device_info_table_type_11, "Type 11" }, + {nand_device_info_table_type_15, "Type 15" }, + {nand_device_info_table_bch_ecc12, "BCH ECC12"}, + {0, 0}, +}; + +/** + * struct nand_device_mfr_info - Information about a NAND Flash manufacturer. + * + * @id: The value of the first NAND Flash ID byte, which identifies the + * manufacturer. + * @fn: A pointer to a function to use for identifying devices from the + * given manufacturer. + */ + +struct nand_device_mfr_info { + uint8_t id; + struct nand_device_info *(*fn)(const uint8_t id[]); +}; + +/* + * A table that maps manufacturer IDs to device information tables. + */ + +static struct nand_device_mfr_info nand_device_mfr_directory[] __initdata = { + { + .id = NAND_MFR_TOSHIBA, + .fn = nand_device_info_fn_toshiba, + }, + { + .id = NAND_MFR_SAMSUNG, + .fn = nand_device_info_fn_samsung, + }, + { + .id = NAND_MFR_FUJITSU, + .fn = 0, + }, + { + .id = NAND_MFR_NATIONAL, + .fn = 0, + }, + { + .id = NAND_MFR_RENESAS, + .fn = 0, + }, + { + .id = NAND_MFR_STMICRO, + .fn = nand_device_info_fn_stmicro, + }, + { + .id = NAND_MFR_HYNIX, + .fn = nand_device_info_fn_hynix, + }, + { + .id = NAND_MFR_MICRON, + .fn = nand_device_info_fn_micron, + }, + { + .id = NAND_MFR_AMD, + .fn = 0, + }, + { + .id = NAND_MFR_SANDISK, + .fn = nand_device_info_fn_sandisk, + }, + { + .id = NAND_MFR_INTEL, + .fn = nand_device_info_fn_intel, + }, + {0, 0} +}; + +/** + * nand_device_info_test_table - Validate a device info table. + * + * This function runs tests on the given device info table to check that it + * meets the current assumptions. + */ + +static void __init nand_device_info_test_table( + struct nand_device_info *table, const char *name) +{ + unsigned i; + unsigned j; + uint8_t mfr_code; + uint8_t device_code; + + /* Loop over entries in this table. */ + + for (i = 0; !table[i].end_of_table; i++) { + + /* Get discriminating attributes of the current device. */ + + mfr_code = table[i].manufacturer_code; + device_code = table[i].device_code; + + /* Compare with the remaining devices in this table. */ + + for (j = i + 1; !table[j].end_of_table; j++) { + if ((mfr_code == table[j].manufacturer_code) && + (device_code == table[j].device_code)) + goto error; + } + + } + + return; + +error: + + printk(KERN_EMERG + "\n== NAND Flash device info table failed validity check ==\n"); + + printk(KERN_EMERG "\nDevice Info Table: %s\n", name); + printk(KERN_EMERG "\nTable Index %u\n", i); + nand_device_print_info(table + i); + printk(KERN_EMERG "\nTable Index %u\n", j); + nand_device_print_info(table + j); + printk(KERN_EMERG "\n"); + + BUG(); + +} + +/** + * nand_device_info_test_data - Test the NAND Flash device data. + */ + +static void __init nand_device_info_test_data(void) +{ + + unsigned i; + + for (i = 0; nand_device_type_directory[i].name; i++) { + nand_device_info_test_table( + nand_device_type_directory[i].table, + nand_device_type_directory[i].name); + } + +} + +struct nand_device_info * __init nand_device_get_info(const uint8_t id[]) +{ + unsigned i; + uint8_t mfr_id = ID_GET_MFR_CODE(id); + struct nand_device_info *(*fn)(const uint8_t id[]) = 0; + + /* Test the data. */ + + nand_device_info_test_data(); + + /* Look for information about this manufacturer. */ + + for (i = 0; nand_device_mfr_directory[i].id; i++) { + if (nand_device_mfr_directory[i].id == mfr_id) { + fn = nand_device_mfr_directory[i].fn; + break; + } + } + + if (!fn) + return 0; + + /* + * If control arrives here, we found both a table of device information, + * and a function we can use to identify the current device. Attempt to + * identify the device and return the result. + */ + + return fn(id); + +} diff --git a/drivers/mtd/nand/nand_device_info.h b/drivers/mtd/nand/nand_device_info.h new file mode 100644 index 000000000000..a0960b1cc1e6 --- /dev/null +++ b/drivers/mtd/nand/nand_device_info.h @@ -0,0 +1,140 @@ +/* + * Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#ifndef __DRIVERS_NAND_DEVICE_INFO_H +#define __DRIVERS_NAND_DEVICE_INFO_H + + /* + * The number of ID bytes to read from the NAND Flash device and hand over to + * the identification system. + */ + +#define NAND_DEVICE_ID_BYTE_COUNT (6) + + /* + * The number of ID bytes to read from the NAND Flash device and hand over to + * the identification system. + */ + +enum nand_device_cell_technology { + NAND_DEVICE_CELL_TECH_SLC = 0, + NAND_DEVICE_CELL_TECH_MLC = 1, +}; + +/** + * struct nand_device_info - Information about a single NAND Flash device. + * + * This structure contains all the *essential* information about a NAND Flash + * device, derived from the device's data sheet. For each manufacturer, we have + * an array of these structures. + * + * @end_of_table: If true, marks the end of a table of device + * information. + * @manufacturer_code: The manufacturer code (1st ID byte) reported by + * the device. + * @device_code: The device code (2nd ID byte) reported by the + * device. + * @cell_technology: The storage cell technology. + * @chip_size_in_bytes: The total size of the storage behind a single + * chip select, in bytes. Notice that this is *not* + * necessarily the total size of the storage in a + * *package*, which may contain several chips. + * @block_size_in_pages: The number of pages in a block. + * @page_total_size_in_bytes: The total size of a page, in bytes, including + * both the data and the OOB. + * @ecc_strength_in_bits: The strength of the ECC called for by the + * manufacturer, in number of correctable bits. + * @ecc_size_in_bytes: The size of the data block over which the + * manufacturer calls for the given ECC algorithm + * and strength. + * @data_setup_in_ns: The data setup time, in nanoseconds. Usually the + * maximum of tDS and tWP. A negative value + * indicates this characteristic isn't known. + * @data_hold_in_ns: The data hold time, in nanoseconds. Usually the + * maximum of tDH, tWH and tREH. A negative value + * indicates this characteristic isn't known. + * @address_setup_in_ns: The address setup time, in nanoseconds. Usually + * the maximum of tCLS, tCS and tALS. A negative + * value indicates this characteristic isn't known. + * @gpmi_sample_delay_in_ns: A GPMI-specific timing parameter. A negative + * value indicates this characteristic isn't known. + * @tREA_in_ns: tREA, in nanoseconds, from the data sheet. A + * negative value indicates this characteristic + * isn't known. + * @tRLOH_in_ns: tRLOH, in nanoseconds, from the data sheet. A + * negative value indicates this characteristic + * isn't known. + * @tRHOH_in_ns: tRHOH, in nanoseconds, from the data sheet. A + * negative value indicates this characteristic + * isn't known. + */ + +struct nand_device_info { + + /* End of table marker */ + + bool end_of_table; + + /* Manufacturer and Device codes */ + + uint8_t manufacturer_code; + uint8_t device_code; + + /* Technology */ + + enum nand_device_cell_technology cell_technology; + + /* Geometry */ + + uint64_t chip_size_in_bytes; + uint32_t block_size_in_pages; + uint16_t page_total_size_in_bytes; + + /* ECC */ + + uint8_t ecc_strength_in_bits; + uint16_t ecc_size_in_bytes; + + /* Timing */ + + int8_t data_setup_in_ns; + int8_t data_hold_in_ns; + int8_t address_setup_in_ns; + int8_t gpmi_sample_delay_in_ns; + int8_t tREA_in_ns; + int8_t tRLOH_in_ns; + int8_t tRHOH_in_ns; + + /* Description */ + + const char *description; + +}; + +/** + * nand_device_get_info - Get info about a device based on ID bytes. + * + * @id_bytes: An array of NAND_DEVICE_ID_BYTE_COUNT ID bytes retrieved from the + * NAND Flash device. + */ + +struct nand_device_info *nand_device_get_info(const uint8_t id_bytes[]); + +/** + * nand_device_print_info - Prints information about a NAND Flash device. + * + * @info A pointer to a NAND Flash device information structure. + */ + +void nand_device_print_info(struct nand_device_info *info); + +#endif diff --git a/drivers/mxc/Kconfig b/drivers/mxc/Kconfig new file mode 100644 index 000000000000..6e67087d2efa --- /dev/null +++ b/drivers/mxc/Kconfig @@ -0,0 +1,39 @@ +# drivers/video/mxc/Kconfig + +if ARCH_MXC + +menu "MXC support drivers" + +config MXC_IPU + bool "Image Processing Unit Driver" + depends on !ARCH_MX21 + depends on !ARCH_MX27 + depends on !ARCH_MX25 + select MXC_IPU_V1 if !ARCH_MX37 && !ARCH_MX5 + select MXC_IPU_V3 if ARCH_MX37 || ARCH_MX5 + select MXC_IPU_V3D if ARCH_MX37 + select MXC_IPU_V3EX if ARCH_MX5 + help + If you plan to use the Image Processing unit, say + Y here. IPU is needed by Framebuffer and V4L2 drivers. + +source "drivers/mxc/ipu/Kconfig" +source "drivers/mxc/ipu3/Kconfig" + +source "drivers/mxc/ssi/Kconfig" +source "drivers/mxc/dam/Kconfig" +source "drivers/mxc/pmic/Kconfig" +source "drivers/mxc/mcu_pmic/Kconfig" +source "drivers/mxc/security/Kconfig" +source "drivers/mxc/hmp4e/Kconfig" +source "drivers/mxc/hw_event/Kconfig" +source "drivers/mxc/vpu/Kconfig" +source "drivers/mxc/asrc/Kconfig" +source "drivers/mxc/bt/Kconfig" +source "drivers/mxc/gps_ioctrl/Kconfig" +source "drivers/mxc/mlb/Kconfig" +source "drivers/mxc/adc/Kconfig" + +endmenu + +endif diff --git a/drivers/mxc/Makefile b/drivers/mxc/Makefile new file mode 100644 index 000000000000..6416bc429888 --- /dev/null +++ b/drivers/mxc/Makefile @@ -0,0 +1,17 @@ +obj-$(CONFIG_MXC_IPU_V1) += ipu/ +obj-$(CONFIG_MXC_IPU_V3) += ipu3/ +obj-$(CONFIG_MXC_SSI) += ssi/ +obj-$(CONFIG_MXC_DAM) += dam/ + +obj-$(CONFIG_MXC_PMIC_MC9SDZ60) += mcu_pmic/ +obj-$(CONFIG_MXC_PMIC) += pmic/ + +obj-$(CONFIG_MXC_HMP4E) += hmp4e/ +obj-y += security/ +obj-$(CONFIG_MXC_VPU) += vpu/ +obj-$(CONFIG_MXC_HWEVENT) += hw_event/ +obj-$(CONFIG_MXC_ASRC) += asrc/ +obj-$(CONFIG_MXC_BLUETOOTH) += bt/ +obj-$(CONFIG_GPS_IOCTRL) += gps_ioctrl/ +obj-$(CONFIG_MXC_MLB) += mlb/ +obj-$(CONFIG_IMX_ADC) += adc/ diff --git a/drivers/mxc/adc/Kconfig b/drivers/mxc/adc/Kconfig new file mode 100644 index 000000000000..91ad23bc7cbe --- /dev/null +++ b/drivers/mxc/adc/Kconfig @@ -0,0 +1,14 @@ +# +# i.MX ADC devices +# + +menu "i.MX ADC support" + +config IMX_ADC + tristate "i.MX ADC" + depends on ARCH_MXC + default n + help + This selects the Freescale i.MX on-chip ADC driver. + +endmenu diff --git a/drivers/mxc/adc/Makefile b/drivers/mxc/adc/Makefile new file mode 100644 index 000000000000..e21e48ee1185 --- /dev/null +++ b/drivers/mxc/adc/Makefile @@ -0,0 +1,4 @@ +# +# Makefile for i.MX adc devices. +# +obj-$(CONFIG_IMX_ADC) += imx_adc.o diff --git a/drivers/mxc/adc/imx_adc.c b/drivers/mxc/adc/imx_adc.c new file mode 100644 index 000000000000..56538e79e2a0 --- /dev/null +++ b/drivers/mxc/adc/imx_adc.c @@ -0,0 +1,1134 @@ +/* + * Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file adc/imx_adc.c + * @brief This is the main file of i.MX ADC driver. + * + * @ingroup IMX_ADC + */ + +/* + * Includes + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "imx_adc_reg.h" + +static int imx_adc_major; + +/*! + * Number of users waiting in suspendq + */ +static int swait; + +/*! + * To indicate whether any of the adc devices are suspending + */ +static int suspend_flag; + +/*! + * The suspendq is used by blocking application calls + */ +static wait_queue_head_t suspendq; +static wait_queue_head_t tsq; + +static bool imx_adc_ready; +static bool ts_data_ready; +static int tsi_data = TSI_DATA; +static unsigned short ts_data_buf[16]; + +static struct class *imx_adc_class; +static struct imx_adc_data *adc_data; + +static DECLARE_MUTEX(general_convert_mutex); +static DECLARE_MUTEX(ts_convert_mutex); + +unsigned long tsc_base; + +int is_imx_adc_ready(void) +{ + return imx_adc_ready; +} +EXPORT_SYMBOL(is_imx_adc_ready); + +void tsc_clk_enable(void) +{ + unsigned long reg; + + clk_enable(adc_data->adc_clk); + + reg = __raw_readl(tsc_base + TGCR); + reg |= TGCR_IPG_CLK_EN; + __raw_writel(reg, tsc_base + TGCR); +} + +void tsc_clk_disable(void) +{ + unsigned long reg; + + clk_disable(adc_data->adc_clk); + + reg = __raw_readl(tsc_base + TGCR); + reg &= ~TGCR_IPG_CLK_EN; + __raw_writel(reg, tsc_base + TGCR); +} + +void tsc_self_reset(void) +{ + unsigned long reg; + + reg = __raw_readl(tsc_base + TGCR); + reg |= TGCR_TSC_RST; + __raw_writel(reg, tsc_base + TGCR); + + while (__raw_readl(tsc_base + TGCR) & TGCR_TSC_RST) + continue; +} + +/* Internal reference */ +void tsc_intref_enable(void) +{ + unsigned long reg; + + reg = __raw_readl(tsc_base + TGCR); + reg |= TGCR_INTREFEN; + __raw_writel(reg, tsc_base + TGCR); +} + +/* initialize touchscreen */ +void imx_tsc_init(void) +{ + unsigned long reg; + int lastitemid; + + /* Level sense */ + reg = __raw_readl(tsc_base + TCQCR); + reg &= ~CQCR_PD_CFG; /* edge sensitive */ + reg |= (0xf << CQCR_FIFOWATERMARK_SHIFT); /* watermark */ + __raw_writel(reg, tsc_base + TCQCR); + + /* Configure 4-wire */ + reg = TSC_4WIRE_PRECHARGE; + reg |= CC_IGS; + __raw_writel(reg, tsc_base + TCC0); + + reg = TSC_4WIRE_TOUCH_DETECT; + reg |= 3 << CC_NOS_SHIFT; /* 4 samples */ + reg |= 32 << CC_SETTLING_TIME_SHIFT; /* it's important! */ + __raw_writel(reg, tsc_base + TCC1); + + reg = TSC_4WIRE_X_MEASUMENT; + reg |= 3 << CC_NOS_SHIFT; /* 4 samples */ + reg |= 16 << CC_SETTLING_TIME_SHIFT; /* settling time */ + __raw_writel(reg, tsc_base + TCC2); + + reg = TSC_4WIRE_Y_MEASUMENT; + reg |= 3 << CC_NOS_SHIFT; /* 4 samples */ + reg |= 16 << CC_SETTLING_TIME_SHIFT; /* settling time */ + __raw_writel(reg, tsc_base + TCC3); + + reg = (TCQ_ITEM_TCC0 << TCQ_ITEM7_SHIFT) | + (TCQ_ITEM_TCC0 << TCQ_ITEM6_SHIFT) | + (TCQ_ITEM_TCC1 << TCQ_ITEM5_SHIFT) | + (TCQ_ITEM_TCC0 << TCQ_ITEM4_SHIFT) | + (TCQ_ITEM_TCC3 << TCQ_ITEM3_SHIFT) | + (TCQ_ITEM_TCC2 << TCQ_ITEM2_SHIFT) | + (TCQ_ITEM_TCC1 << TCQ_ITEM1_SHIFT) | + (TCQ_ITEM_TCC0 << TCQ_ITEM0_SHIFT); + __raw_writel(reg, tsc_base + TCQ_ITEM_7_0); + + lastitemid = 5; + reg = __raw_readl(tsc_base + TCQCR); + reg = (reg & ~CQCR_LAST_ITEM_ID_MASK) | + (lastitemid << CQCR_LAST_ITEM_ID_SHIFT); + __raw_writel(reg, tsc_base + TCQCR); + + /* Config idle for 4-wire */ + reg = TSC_4WIRE_PRECHARGE; + __raw_writel(reg, tsc_base + TICR); + + reg = TSC_4WIRE_TOUCH_DETECT; + __raw_writel(reg, tsc_base + TICR); + + /* pen down mask */ + reg = __raw_readl(tsc_base + TCQCR); + reg &= ~CQCR_PD_MSK; + __raw_writel(reg, tsc_base + TCQCR); + reg = __raw_readl(tsc_base + TCQMR); + reg &= ~TCQMR_PD_IRQ_MSK; + __raw_writel(reg, tsc_base + TCQMR); + + /* Debounce time = dbtime*8 adc clock cycles */ + reg = __raw_readl(tsc_base + TGCR); + reg &= ~TGCR_PDBTIME_MASK; + reg |= TGCR_PDBTIME128 | TGCR_HSYNC_EN; + __raw_writel(reg, tsc_base + TGCR); + + /* pen down enable */ + reg = __raw_readl(tsc_base + TGCR); + reg |= TGCR_PDB_EN; + __raw_writel(reg, tsc_base + TGCR); + reg |= TGCR_PD_EN; + __raw_writel(reg, tsc_base + TGCR); +} + +static irqreturn_t imx_adc_interrupt(int irq, void *dev_id) +{ + unsigned long reg; + + if (__raw_readl(tsc_base + TGSR) & 0x4) { + /* deep sleep wakeup interrupt */ + /* clear tgsr */ + __raw_writel(0, tsc_base + TGSR); + /* clear deep sleep wakeup irq */ + reg = __raw_readl(tsc_base + TGCR); + reg &= ~TGCR_SLPC; + __raw_writel(reg, tsc_base + TGCR); + /* un-mask pen down and pen down irq */ + reg = __raw_readl(tsc_base + TCQCR); + reg &= ~CQCR_PD_MSK; + __raw_writel(reg, tsc_base + TCQCR); + reg = __raw_readl(tsc_base + TCQMR); + reg &= ~TCQMR_PD_IRQ_MSK; + __raw_writel(reg, tsc_base + TCQMR); + } else if ((__raw_readl(tsc_base + TGSR) & 0x1) && + (__raw_readl(tsc_base + TCQSR) & 0x1)) { + + /* mask pen down detect irq */ + reg = __raw_readl(tsc_base + TCQMR); + reg |= TCQMR_PD_IRQ_MSK; + __raw_writel(reg, tsc_base + TCQMR); + + ts_data_ready = 1; + wake_up_interruptible(&tsq); + } + return IRQ_HANDLED; +} + +enum IMX_ADC_STATUS imx_adc_read_general(unsigned short *result) +{ + unsigned long reg; + unsigned int data_num = 0; + + reg = __raw_readl(tsc_base + GCQCR); + reg |= CQCR_FQS; + __raw_writel(reg, tsc_base + GCQCR); + + while (!(__raw_readl(tsc_base + GCQSR) & CQSR_EOQ)) + continue; + reg = __raw_readl(tsc_base + GCQCR); + reg &= ~CQCR_FQS; + __raw_writel(reg, tsc_base + GCQCR); + reg = __raw_readl(tsc_base + GCQSR); + reg |= CQSR_EOQ; + __raw_writel(reg, tsc_base + GCQSR); + + while (!(__raw_readl(tsc_base + GCQSR) & CQSR_EMPT)) { + result[data_num] = __raw_readl(tsc_base + GCQFIFO) >> + GCQFIFO_ADCOUT_SHIFT; + data_num++; + } + return IMX_ADC_SUCCESS; +} + +/*! + * This function will get raw (X,Y) value by converting the voltage + * @param touch_sample Pointer to touch sample + * + * return This funciton returns 0 if successful. + * + * + */ +enum IMX_ADC_STATUS imx_adc_read_ts(struct t_touch_screen *touch_sample, + int wait_tsi) +{ + unsigned long reg; + int data_num = 0; + int detect_sample1, detect_sample2; + + memset(ts_data_buf, 0, sizeof ts_data_buf); + touch_sample->valid_flag = 1; + + if (wait_tsi) { + /* Config idle for 4-wire */ + reg = TSC_4WIRE_TOUCH_DETECT; + __raw_writel(reg, tsc_base + TICR); + + /* Pen interrupt starts new conversion queue */ + reg = __raw_readl(tsc_base + TCQCR); + reg &= ~CQCR_QSM_MASK; + reg |= CQCR_QSM_PEN; + __raw_writel(reg, tsc_base + TCQCR); + + /* unmask pen down detect irq */ + reg = __raw_readl(tsc_base + TCQMR); + reg &= ~TCQMR_PD_IRQ_MSK; + __raw_writel(reg, tsc_base + TCQMR); + + wait_event_interruptible(tsq, ts_data_ready); + while (!(__raw_readl(tsc_base + TCQSR) & CQSR_EOQ)) + continue; + + /* stop the conversion */ + reg = __raw_readl(tsc_base + TCQCR); + reg &= ~CQCR_QSM_MASK; + __raw_writel(reg, tsc_base + TCQCR); + reg = CQSR_PD | CQSR_EOQ; + __raw_writel(reg, tsc_base + TCQSR); + + /* change configuration for FQS mode */ + tsi_data = TSI_DATA; + reg = (0x1 << CC_YPLLSW_SHIFT) | (0x1 << CC_XNURSW_SHIFT) | + CC_XPULSW; + __raw_writel(reg, tsc_base + TICR); + } else { + /* FQS semaphore */ + down(&ts_convert_mutex); + + reg = (0x1 << CC_YPLLSW_SHIFT) | (0x1 << CC_XNURSW_SHIFT) | + CC_XPULSW; + __raw_writel(reg, tsc_base + TICR); + + /* FQS */ + reg = __raw_readl(tsc_base + TCQCR); + reg &= ~CQCR_QSM_MASK; + reg |= CQCR_QSM_FQS; + __raw_writel(reg, tsc_base + TCQCR); + reg = __raw_readl(tsc_base + TCQCR); + reg |= CQCR_FQS; + __raw_writel(reg, tsc_base + TCQCR); + while (!(__raw_readl(tsc_base + TCQSR) & CQSR_EOQ)) + continue; + + /* stop FQS */ + reg = __raw_readl(tsc_base + TCQCR); + reg &= ~CQCR_QSM_MASK; + __raw_writel(reg, tsc_base + TCQCR); + reg = __raw_readl(tsc_base + TCQCR); + reg &= ~CQCR_FQS; + __raw_writel(reg, tsc_base + TCQCR); + + /* clear status bit */ + reg = __raw_readl(tsc_base + TCQSR); + reg |= CQSR_EOQ; + __raw_writel(reg, tsc_base + TCQSR); + tsi_data = FQS_DATA; + + /* Config idle for 4-wire */ + reg = TSC_4WIRE_PRECHARGE; + __raw_writel(reg, tsc_base + TICR); + + reg = TSC_4WIRE_TOUCH_DETECT; + __raw_writel(reg, tsc_base + TICR); + + } + + while (!(__raw_readl(tsc_base + TCQSR) & CQSR_EMPT)) { + reg = __raw_readl(tsc_base + TCQFIFO); + ts_data_buf[data_num] = reg; + data_num++; + } + + touch_sample->x_position1 = ts_data_buf[4] >> 4; + touch_sample->x_position2 = ts_data_buf[5] >> 4; + touch_sample->x_position3 = ts_data_buf[6] >> 4; + touch_sample->y_position1 = ts_data_buf[9] >> 4; + touch_sample->y_position2 = ts_data_buf[10] >> 4; + touch_sample->y_position3 = ts_data_buf[11] >> 4; + + detect_sample1 = ts_data_buf[0]; + detect_sample2 = ts_data_buf[12]; + + if ((detect_sample1 > 0x6000) || (detect_sample2 > 0x6000)) + touch_sample->valid_flag = 0; + + ts_data_ready = 0; + + if (!(touch_sample->x_position1 || + touch_sample->x_position2 || touch_sample->x_position3)) + touch_sample->contact_resistance = 0; + else + touch_sample->contact_resistance = 1; + + if (tsi_data == FQS_DATA) + up(&ts_convert_mutex); + return IMX_ADC_SUCCESS; +} + +/*! + * This function performs filtering and rejection of excessive noise prone + * sampl. + * + * @param ts_curr Touch screen value + * + * @return This function returns 0 on success, -1 otherwise. + */ +static int imx_adc_filter(struct t_touch_screen *ts_curr) +{ + + unsigned int ydiff1, ydiff2, ydiff3, xdiff1, xdiff2, xdiff3; + unsigned int sample_sumx, sample_sumy; + static unsigned int prev_x[FILTLEN], prev_y[FILTLEN]; + int index = 0; + unsigned int y_curr, x_curr; + static int filt_count; + /* Added a variable filt_type to decide filtering at run-time */ + unsigned int filt_type = 0; + + /* ignore the data converted when pen down and up */ + if ((ts_curr->contact_resistance == 0) || tsi_data == TSI_DATA) { + ts_curr->x_position = 0; + ts_curr->y_position = 0; + filt_count = 0; + return 0; + } + /* ignore the data valid */ + if (ts_curr->valid_flag == 0) + return -1; + + ydiff1 = abs(ts_curr->y_position1 - ts_curr->y_position2); + ydiff2 = abs(ts_curr->y_position2 - ts_curr->y_position3); + ydiff3 = abs(ts_curr->y_position1 - ts_curr->y_position3); + if ((ydiff1 > DELTA_Y_MAX) || + (ydiff2 > DELTA_Y_MAX) || (ydiff3 > DELTA_Y_MAX)) { + pr_debug("imx_adc_filter: Ret pos 1\n"); + return -1; + } + + xdiff1 = abs(ts_curr->x_position1 - ts_curr->x_position2); + xdiff2 = abs(ts_curr->x_position2 - ts_curr->x_position3); + xdiff3 = abs(ts_curr->x_position1 - ts_curr->x_position3); + + if ((xdiff1 > DELTA_X_MAX) || + (xdiff2 > DELTA_X_MAX) || (xdiff3 > DELTA_X_MAX)) { + pr_debug("imx_adc_filter: Ret pos 2\n"); + return -1; + } + /* Compute two closer values among the three available Y readouts */ + + if (ydiff1 < ydiff2) { + if (ydiff1 < ydiff3) { + /* Sample 0 & 1 closest together */ + sample_sumy = ts_curr->y_position1 + + ts_curr->y_position2; + } else { + /* Sample 0 & 2 closest together */ + sample_sumy = ts_curr->y_position1 + + ts_curr->y_position3; + } + } else { + if (ydiff2 < ydiff3) { + /* Sample 1 & 2 closest together */ + sample_sumy = ts_curr->y_position2 + + ts_curr->y_position3; + } else { + /* Sample 0 & 2 closest together */ + sample_sumy = ts_curr->y_position1 + + ts_curr->y_position3; + } + } + + /* + * Compute two closer values among the three available X + * readouts + */ + if (xdiff1 < xdiff2) { + if (xdiff1 < xdiff3) { + /* Sample 0 & 1 closest together */ + sample_sumx = ts_curr->x_position1 + + ts_curr->x_position2; + } else { + /* Sample 0 & 2 closest together */ + sample_sumx = ts_curr->x_position1 + + ts_curr->x_position3; + } + } else { + if (xdiff2 < xdiff3) { + /* Sample 1 & 2 closest together */ + sample_sumx = ts_curr->x_position2 + + ts_curr->x_position3; + } else { + /* Sample 0 & 2 closest together */ + sample_sumx = ts_curr->x_position1 + + ts_curr->x_position3; + } + } + + /* + * Wait FILTER_MIN_DELAY number of samples to restart + * filtering + */ + if (filt_count < FILTER_MIN_DELAY) { + /* + * Current output is the average of the two closer + * values and no filtering is used + */ + y_curr = (sample_sumy / 2); + x_curr = (sample_sumx / 2); + ts_curr->y_position = y_curr; + ts_curr->x_position = x_curr; + filt_count++; + + } else { + if (abs(sample_sumx - (prev_x[0] + prev_x[1])) > + (DELTA_X_MAX * 16)) { + pr_debug("imx_adc_filter: : Ret pos 3\n"); + return -1; + } + if (abs(sample_sumy - (prev_y[0] + prev_y[1])) > + (DELTA_Y_MAX * 16)) { + pr_debug("imx_adc_filter: : Ret pos 4\n"); + return -1; + } + sample_sumy /= 2; + sample_sumx /= 2; + /* Use hard filtering if the sample difference < 10 */ + if ((abs(sample_sumy - prev_y[0]) > 10) || + (abs(sample_sumx - prev_x[0]) > 10)) + filt_type = 1; + + /* + * Current outputs are the average of three previous + * values and the present readout + */ + y_curr = sample_sumy; + for (index = 0; index < FILTLEN; index++) { + if (filt_type == 0) + y_curr = y_curr + (prev_y[index]); + else + y_curr = y_curr + (prev_y[index] / 3); + } + if (filt_type == 0) + y_curr = y_curr >> 2; + else + y_curr = y_curr >> 1; + ts_curr->y_position = y_curr; + + x_curr = sample_sumx; + for (index = 0; index < FILTLEN; index++) { + if (filt_type == 0) + x_curr = x_curr + (prev_x[index]); + else + x_curr = x_curr + (prev_x[index] / 3); + } + if (filt_type == 0) + x_curr = x_curr >> 2; + else + x_curr = x_curr >> 1; + ts_curr->x_position = x_curr; + + } + + /* Update previous X and Y values */ + for (index = (FILTLEN - 1); index > 0; index--) { + prev_x[index] = prev_x[index - 1]; + prev_y[index] = prev_y[index - 1]; + } + + /* + * Current output will be the most recent past for the + * next sample + */ + prev_y[0] = y_curr; + prev_x[0] = x_curr; + + return 0; + +} + +/*! + * This function retrieves the current touch screen (X,Y) coordinates. + * + * @param touch_sample Pointer to touch sample. + * + * @return This function returns IMX_ADC_SUCCESS if successful. + */ +enum IMX_ADC_STATUS imx_adc_get_touch_sample(struct t_touch_screen + *touch_sample, int wait_tsi) +{ + if (imx_adc_read_ts(touch_sample, wait_tsi)) + return IMX_ADC_ERROR; + if (!imx_adc_filter(touch_sample)) + return IMX_ADC_SUCCESS; + else + return IMX_ADC_ERROR; +} +EXPORT_SYMBOL(imx_adc_get_touch_sample); + +void imx_adc_set_hsync(int on) +{ + unsigned long reg; + if (imx_adc_ready) { + reg = __raw_readl(tsc_base + TGCR); + if (on) + reg |= TGCR_HSYNC_EN; + else + reg &= ~TGCR_HSYNC_EN; + __raw_writel(reg, tsc_base + TGCR); + } +} +EXPORT_SYMBOL(imx_adc_set_hsync); + +/*! + * This is the suspend of power management for the i.MX ADC API. + * It supports SAVE and POWER_DOWN state. + * + * @param pdev the device + * @param state the state + * + * @return This function returns 0 if successful. + */ +static int imx_adc_suspend(struct platform_device *pdev, pm_message_t state) +{ + unsigned long reg; + + /* Config idle for 4-wire */ + reg = TSC_4WIRE_PRECHARGE; + __raw_writel(reg, tsc_base + TICR); + + reg = TSC_4WIRE_TOUCH_DETECT; + __raw_writel(reg, tsc_base + TICR); + + /* enable deep sleep wake up */ + reg = __raw_readl(tsc_base + TGCR); + reg |= TGCR_SLPC; + __raw_writel(reg, tsc_base + TGCR); + + /* mask pen down and pen down irq */ + reg = __raw_readl(tsc_base + TCQCR); + reg |= CQCR_PD_MSK; + __raw_writel(reg, tsc_base + TCQCR); + reg = __raw_readl(tsc_base + TCQMR); + reg |= TCQMR_PD_IRQ_MSK; + __raw_writel(reg, tsc_base + TCQMR); + + /* Set power mode to off */ + reg = __raw_readl(tsc_base + TGCR) & ~TGCR_POWER_MASK; + reg |= TGCR_POWER_OFF; + __raw_writel(reg, tsc_base + TGCR); + + if (device_may_wakeup(&pdev->dev)) { + enable_irq_wake(adc_data->irq); + } else { + suspend_flag = 1; + tsc_clk_disable(); + } + return 0; +}; + +/*! + * This is the resume of power management for the i.MX adc API. + * It supports RESTORE state. + * + * @param pdev the device + * + * @return This function returns 0 if successful. + */ +static int imx_adc_resume(struct platform_device *pdev) +{ + unsigned long reg; + + if (device_may_wakeup(&pdev->dev)) { + disable_irq_wake(adc_data->irq); + } else { + suspend_flag = 0; + tsc_clk_enable(); + while (swait > 0) { + swait--; + wake_up_interruptible(&suspendq); + } + } + + /* recover power mode */ + reg = __raw_readl(tsc_base + TGCR) & ~TGCR_POWER_MASK; + reg |= TGCR_POWER_SAVE; + __raw_writel(reg, tsc_base + TGCR); + + return 0; +} + +/*! + * This function implements the open method on an i.MX ADC device. + * + * @param inode pointer on the node + * @param file pointer on the file + * @return This function returns 0. + */ +static int imx_adc_open(struct inode *inode, struct file *file) +{ + while (suspend_flag) { + swait++; + /* Block if the device is suspended */ + if (wait_event_interruptible(suspendq, !suspend_flag)) + return -ERESTARTSYS; + } + pr_debug("imx_adc : imx_adc_open()\n"); + return 0; +} + +/*! + * This function implements the release method on an i.MX ADC device. + * + * @param inode pointer on the node + * @param file pointer on the file + * @return This function returns 0. + */ +static int imx_adc_free(struct inode *inode, struct file *file) +{ + pr_debug("imx_adc : imx_adc_free()\n"); + return 0; +} + +/*! + * This function initializes all ADC registers with default values. This + * function also registers the interrupt events. + * + * @return This function returns IMX_ADC_SUCCESS if successful. + */ +int imx_adc_init(void) +{ + unsigned long reg; + + pr_debug("imx_adc_init()\n"); + + if (suspend_flag) + return -EBUSY; + + tsc_clk_enable(); + + /* Reset */ + tsc_self_reset(); + + /* Internal reference */ + tsc_intref_enable(); + + /* Set power mode */ + reg = __raw_readl(tsc_base + TGCR) & ~TGCR_POWER_MASK; + reg |= TGCR_POWER_SAVE; + __raw_writel(reg, tsc_base + TGCR); + + imx_tsc_init(); + + return IMX_ADC_SUCCESS; +} +EXPORT_SYMBOL(imx_adc_init); + +/*! + * This function disables the ADC, de-registers the interrupt events. + * + * @return This function returns IMX_ADC_SUCCESS if successful. + */ +enum IMX_ADC_STATUS imx_adc_deinit(void) +{ + pr_debug("imx_adc_deinit()\n"); + + return IMX_ADC_SUCCESS; +} +EXPORT_SYMBOL(imx_adc_deinit); + +/*! + * This function triggers a conversion and returns one sampling result of one + * channel. + * + * @param channel The channel to be sampled + * @param result The pointer to the conversion result. The memory + * should be allocated by the caller of this function. + * + * @return This function returns IMX_ADC_SUCCESS if successful. + */ +enum IMX_ADC_STATUS imx_adc_convert(enum t_channel channel, + unsigned short *result) +{ + unsigned long reg; + int lastitemid; + struct t_touch_screen touch_sample; + + switch (channel) { + + case TS_X_POS: + imx_adc_get_touch_sample(&touch_sample, 0); + result[0] = touch_sample.x_position; + + /* if no pen down ,recover the register configuration */ + if (touch_sample.contact_resistance == 0) { + reg = __raw_readl(tsc_base + TCQCR); + reg &= ~CQCR_QSM_MASK; + reg |= CQCR_QSM_PEN; + __raw_writel(reg, tsc_base + TCQCR); + + reg = __raw_readl(tsc_base + TCQMR); + reg &= ~TCQMR_PD_IRQ_MSK; + __raw_writel(reg, tsc_base + TCQMR); + } + break; + + case TS_Y_POS: + imx_adc_get_touch_sample(&touch_sample, 0); + result[1] = touch_sample.y_position; + + /* if no pen down ,recover the register configuration */ + if (touch_sample.contact_resistance == 0) { + reg = __raw_readl(tsc_base + TCQCR); + reg &= ~CQCR_QSM_MASK; + reg |= CQCR_QSM_PEN; + __raw_writel(reg, tsc_base + TCQCR); + + reg = __raw_readl(tsc_base + TCQMR); + reg &= ~TCQMR_PD_IRQ_MSK; + __raw_writel(reg, tsc_base + TCQMR); + } + break; + + case GER_PURPOSE_ADC0: + down(&general_convert_mutex); + + lastitemid = 0; + reg = (0xf << CQCR_FIFOWATERMARK_SHIFT) | + (lastitemid << CQCR_LAST_ITEM_ID_SHIFT) | CQCR_QSM_FQS; + __raw_writel(reg, tsc_base + GCQCR); + + reg = TSC_GENERAL_ADC_GCC0; + reg |= (3 << CC_NOS_SHIFT) | (16 << CC_SETTLING_TIME_SHIFT); + __raw_writel(reg, tsc_base + GCC0); + + imx_adc_read_general(result); + up(&general_convert_mutex); + break; + + case GER_PURPOSE_ADC1: + down(&general_convert_mutex); + + lastitemid = 0; + reg = (0xf << CQCR_FIFOWATERMARK_SHIFT) | + (lastitemid << CQCR_LAST_ITEM_ID_SHIFT) | CQCR_QSM_FQS; + __raw_writel(reg, tsc_base + GCQCR); + + reg = TSC_GENERAL_ADC_GCC1; + reg |= (3 << CC_NOS_SHIFT) | (16 << CC_SETTLING_TIME_SHIFT); + __raw_writel(reg, tsc_base + GCC0); + + imx_adc_read_general(result); + up(&general_convert_mutex); + break; + + case GER_PURPOSE_ADC2: + down(&general_convert_mutex); + + lastitemid = 0; + reg = (0xf << CQCR_FIFOWATERMARK_SHIFT) | + (lastitemid << CQCR_LAST_ITEM_ID_SHIFT) | CQCR_QSM_FQS; + __raw_writel(reg, tsc_base + GCQCR); + + reg = TSC_GENERAL_ADC_GCC2; + reg |= (3 << CC_NOS_SHIFT) | (16 << CC_SETTLING_TIME_SHIFT); + __raw_writel(reg, tsc_base + GCC0); + + imx_adc_read_general(result); + up(&general_convert_mutex); + break; + + case GER_PURPOSE_MULTICHNNEL: + down(&general_convert_mutex); + + reg = TSC_GENERAL_ADC_GCC0; + reg |= (3 << CC_NOS_SHIFT) | (16 << CC_SETTLING_TIME_SHIFT); + __raw_writel(reg, tsc_base + GCC0); + + reg = TSC_GENERAL_ADC_GCC1; + reg |= (3 << CC_NOS_SHIFT) | (16 << CC_SETTLING_TIME_SHIFT); + __raw_writel(reg, tsc_base + GCC1); + + reg = TSC_GENERAL_ADC_GCC2; + reg |= (3 << CC_NOS_SHIFT) | (16 << CC_SETTLING_TIME_SHIFT); + __raw_writel(reg, tsc_base + GCC2); + + reg = (GCQ_ITEM_GCC2 << GCQ_ITEM2_SHIFT) | + (GCQ_ITEM_GCC1 << GCQ_ITEM1_SHIFT) | + (GCQ_ITEM_GCC0 << GCQ_ITEM0_SHIFT); + __raw_writel(reg, tsc_base + GCQ_ITEM_7_0); + + lastitemid = 2; + reg = (0xf << CQCR_FIFOWATERMARK_SHIFT) | + (lastitemid << CQCR_LAST_ITEM_ID_SHIFT) | CQCR_QSM_FQS; + __raw_writel(reg, tsc_base + GCQCR); + + imx_adc_read_general(result); + up(&general_convert_mutex); + break; + default: + pr_debug("%s: bad channel number\n", __func__); + return IMX_ADC_ERROR; + } + + return IMX_ADC_SUCCESS; +} +EXPORT_SYMBOL(imx_adc_convert); + +/*! + * This function triggers a conversion and returns sampling results of each + * specified channel. + * + * @param channels This input parameter is bitmap to specify channels + * to be sampled. + * @param result The pointer to array to store sampling results. + * The memory should be allocated by the caller of this + * function. + * + * @return This function returns IMX_ADC_SUCCESS if successful. + */ +enum IMX_ADC_STATUS imx_adc_convert_multichnnel(enum t_channel channels, + unsigned short *result) +{ + imx_adc_convert(GER_PURPOSE_MULTICHNNEL, result); + return IMX_ADC_SUCCESS; +} +EXPORT_SYMBOL(imx_adc_convert_multichnnel); + +/*! + * This function implements IOCTL controls on an i.MX ADC device. + * + * @param inode pointer on the node + * @param file pointer on the file + * @param cmd the command + * @param arg the parameter + * @return This function returns 0 if successful. + */ +static int imx_adc_ioctl(struct inode *inode, struct file *file, + unsigned int cmd, unsigned long arg) +{ + struct t_adc_convert_param *convert_param; + + if ((_IOC_TYPE(cmd) != 'p') && (_IOC_TYPE(cmd) != 'D')) + return -ENOTTY; + + while (suspend_flag) { + swait++; + /* Block if the device is suspended */ + if (wait_event_interruptible(suspendq, !suspend_flag)) + return -ERESTARTSYS; + } + + switch (cmd) { + case IMX_ADC_INIT: + pr_debug("init adc\n"); + CHECK_ERROR(imx_adc_init()); + break; + + case IMX_ADC_DEINIT: + pr_debug("deinit adc\n"); + CHECK_ERROR(imx_adc_deinit()); + break; + + case IMX_ADC_CONVERT: + convert_param = kmalloc(sizeof(*convert_param), GFP_KERNEL); + if (convert_param == NULL) + return -ENOMEM; + if (copy_from_user(convert_param, + (struct t_adc_convert_param *)arg, + sizeof(*convert_param))) { + kfree(convert_param); + return -EFAULT; + } + CHECK_ERROR_KFREE(imx_adc_convert(convert_param->channel, + convert_param->result), + (kfree(convert_param))); + + if (copy_to_user((struct t_adc_convert_param *)arg, + convert_param, sizeof(*convert_param))) { + kfree(convert_param); + return -EFAULT; + } + kfree(convert_param); + break; + + case IMX_ADC_CONVERT_MULTICHANNEL: + convert_param = kmalloc(sizeof(*convert_param), GFP_KERNEL); + if (convert_param == NULL) + return -ENOMEM; + if (copy_from_user(convert_param, + (struct t_adc_convert_param *)arg, + sizeof(*convert_param))) { + kfree(convert_param); + return -EFAULT; + } + CHECK_ERROR_KFREE(imx_adc_convert_multichnnel + (convert_param->channel, + convert_param->result), + (kfree(convert_param))); + + if (copy_to_user((struct t_adc_convert_param *)arg, + convert_param, sizeof(*convert_param))) { + kfree(convert_param); + return -EFAULT; + } + kfree(convert_param); + break; + + default: + pr_debug("imx_adc_ioctl: unsupported ioctl command 0x%x\n", + cmd); + return -EINVAL; + } + return 0; +} + +static struct file_operations imx_adc_fops = { + .owner = THIS_MODULE, + .ioctl = imx_adc_ioctl, + .open = imx_adc_open, + .release = imx_adc_free, +}; + +static int imx_adc_module_probe(struct platform_device *pdev) +{ + int ret = 0; + int retval; + struct device *temp_class; + struct resource *res; + void __iomem *base; + + /* ioremap the base address */ + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (res == NULL) { + dev_err(&pdev->dev, "No TSC base address provided\n"); + goto err_out0; + } + base = ioremap(res->start, res->end - res->start); + if (base == NULL) { + dev_err(&pdev->dev, "failed to rebase TSC base address\n"); + goto err_out0; + } + tsc_base = (unsigned long)base; + + /* create the chrdev */ + imx_adc_major = register_chrdev(0, "imx_adc", &imx_adc_fops); + + if (imx_adc_major < 0) { + dev_err(&pdev->dev, "Unable to get a major for imx_adc\n"); + return imx_adc_major; + } + init_waitqueue_head(&suspendq); + init_waitqueue_head(&tsq); + + imx_adc_class = class_create(THIS_MODULE, "imx_adc"); + if (IS_ERR(imx_adc_class)) { + dev_err(&pdev->dev, "Error creating imx_adc class.\n"); + ret = PTR_ERR(imx_adc_class); + goto err_out1; + } + + temp_class = device_create(imx_adc_class, NULL, + MKDEV(imx_adc_major, 0), NULL, "imx_adc"); + if (IS_ERR(temp_class)) { + dev_err(&pdev->dev, "Error creating imx_adc class device.\n"); + ret = PTR_ERR(temp_class); + goto err_out2; + } + + adc_data = kmalloc(sizeof(struct imx_adc_data), GFP_KERNEL); + if (adc_data == NULL) + return -ENOMEM; + adc_data->irq = platform_get_irq(pdev, 0); + retval = request_irq(adc_data->irq, imx_adc_interrupt, + 0, MOD_NAME, MOD_NAME); + if (retval) { + return retval; + } + adc_data->adc_clk = clk_get(&pdev->dev, "tchscrn_clk"); + + ret = imx_adc_init(); + + if (ret != IMX_ADC_SUCCESS) { + dev_err(&pdev->dev, "Error in imx_adc_init.\n"); + goto err_out4; + } + imx_adc_ready = 1; + + /* By default, devices should wakeup if they can */ + /* So TouchScreen is set as "should wakeup" as it can */ + device_init_wakeup(&pdev->dev, 1); + + pr_info("i.MX ADC at 0x%x irq %d\n", (unsigned int)res->start, + adc_data->irq); + return ret; + +err_out4: + device_destroy(imx_adc_class, MKDEV(imx_adc_major, 0)); +err_out2: + class_destroy(imx_adc_class); +err_out1: + unregister_chrdev(imx_adc_major, "imx_adc"); +err_out0: + return ret; +} + +static int imx_adc_module_remove(struct platform_device *pdev) +{ + imx_adc_ready = 0; + imx_adc_deinit(); + device_destroy(imx_adc_class, MKDEV(imx_adc_major, 0)); + class_destroy(imx_adc_class); + unregister_chrdev(imx_adc_major, "imx_adc"); + free_irq(adc_data->irq, MOD_NAME); + kfree(adc_data); + pr_debug("i.MX ADC successfully removed\n"); + return 0; +} + +static struct platform_driver imx_adc_driver = { + .driver = { + .name = "imx_adc", + }, + .suspend = imx_adc_suspend, + .resume = imx_adc_resume, + .probe = imx_adc_module_probe, + .remove = imx_adc_module_remove, +}; + +/* + * Initialization and Exit + */ +static int __init imx_adc_module_init(void) +{ + pr_debug("i.MX ADC driver loading...\n"); + return platform_driver_register(&imx_adc_driver); +} + +static void __exit imx_adc_module_exit(void) +{ + platform_driver_unregister(&imx_adc_driver); + pr_debug("i.MX ADC driver successfully unloaded\n"); +} + +/* + * Module entry points + */ + +module_init(imx_adc_module_init); +module_exit(imx_adc_module_exit); + +MODULE_DESCRIPTION("i.MX ADC device driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/adc/imx_adc_reg.h b/drivers/mxc/adc/imx_adc_reg.h new file mode 100644 index 000000000000..71e2d3b21930 --- /dev/null +++ b/drivers/mxc/adc/imx_adc_reg.h @@ -0,0 +1,242 @@ +/* + * Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU Lesser General + * Public License. You may obtain a copy of the GNU Lesser General + * Public License Version 2.1 or later at the following locations: + * + * http://www.opensource.org/licenses/lgpl-license.html + * http://www.gnu.org/copyleft/lgpl.html + */ + +#ifndef __IMX_ADC_H__ +#define __IMX_ADC_H__ + +/* TSC General Config Register */ +#define TGCR 0x000 +#define TGCR_IPG_CLK_EN (1 << 0) +#define TGCR_TSC_RST (1 << 1) +#define TGCR_FUNC_RST (1 << 2) +#define TGCR_SLPC (1 << 4) +#define TGCR_STLC (1 << 5) +#define TGCR_HSYNC_EN (1 << 6) +#define TGCR_HSYNC_POL (1 << 7) +#define TGCR_POWERMODE_SHIFT 8 +#define TGCR_POWER_OFF (0x0 << TGCR_POWERMODE_SHIFT) +#define TGCR_POWER_SAVE (0x1 << TGCR_POWERMODE_SHIFT) +#define TGCR_POWER_ON (0x3 << TGCR_POWERMODE_SHIFT) +#define TGCR_POWER_MASK (0x3 << TGCR_POWERMODE_SHIFT) +#define TGCR_INTREFEN (1 << 10) +#define TGCR_ADCCLKCFG_SHIFT 16 +#define TGCR_PD_EN (1 << 23) +#define TGCR_PDB_EN (1 << 24) +#define TGCR_PDBTIME_SHIFT 25 +#define TGCR_PDBTIME128 (0x3f << TGCR_PDBTIME_SHIFT) +#define TGCR_PDBTIME_MASK (0x7f << TGCR_PDBTIME_SHIFT) + +/* TSC General Status Register */ +#define TGSR 0x004 +#define TCQ_INT (1 << 0) +#define GCQ_INT (1 << 1) +#define SLP_INT (1 << 2) +#define TCQ_DMA (1 << 16) +#define GCQ_DMA (1 << 17) + +/* TSC IDLE Config Register */ +#define TICR 0x008 + +/* TouchScreen Convert Queue FIFO Register */ +#define TCQFIFO 0x400 +/* TouchScreen Convert Queue Control Register */ +#define TCQCR 0x404 +#define CQCR_QSM_SHIFT 0 +#define CQCR_QSM_STOP (0x0 << CQCR_QSM_SHIFT) +#define CQCR_QSM_PEN (0x1 << CQCR_QSM_SHIFT) +#define CQCR_QSM_FQS (0x2 << CQCR_QSM_SHIFT) +#define CQCR_QSM_FQS_PEN (0x3 << CQCR_QSM_SHIFT) +#define CQCR_QSM_MASK (0x3 << CQCR_QSM_SHIFT) +#define CQCR_FQS (1 << 2) +#define CQCR_RPT (1 << 3) +#define CQCR_LAST_ITEM_ID_SHIFT 4 +#define CQCR_LAST_ITEM_ID_MASK (0xf << CQCR_LAST_ITEM_ID_SHIFT) +#define CQCR_FIFOWATERMARK_SHIFT 8 +#define CQCR_FIFOWATERMARK_MASK (0xf << CQCR_FIFOWATERMARK_SHIFT) +#define CQCR_REPEATWAIT_SHIFT 12 +#define CQCR_REPEATWAIT_MASK (0xf << CQCR_REPEATWAIT_SHIFT) +#define CQCR_QRST (1 << 16) +#define CQCR_FRST (1 << 17) +#define CQCR_PD_MSK (1 << 18) +#define CQCR_PD_CFG (1 << 19) + +/* TouchScreen Convert Queue Status Register */ +#define TCQSR 0x408 +#define CQSR_PD (1 << 0) +#define CQSR_EOQ (1 << 1) +#define CQSR_FOR (1 << 4) +#define CQSR_FUR (1 << 5) +#define CQSR_FER (1 << 6) +#define CQSR_EMPT (1 << 13) +#define CQSR_FULL (1 << 14) +#define CQSR_FDRY (1 << 15) + +/* TouchScreen Convert Queue Mask Register */ +#define TCQMR 0x40c +#define TCQMR_PD_IRQ_MSK (1 << 0) +#define TCQMR_EOQ_IRQ_MSK (1 << 1) +#define TCQMR_FOR_IRQ_MSK (1 << 4) +#define TCQMR_FUR_IRQ_MSK (1 << 5) +#define TCQMR_FER_IRQ_MSK (1 << 6) +#define TCQMR_PD_DMA_MSK (1 << 16) +#define TCQMR_EOQ_DMA_MSK (1 << 17) +#define TCQMR_FOR_DMA_MSK (1 << 20) +#define TCQMR_FUR_DMA_MSK (1 << 21) +#define TCQMR_FER_DMA_MSK (1 << 22) +#define TCQMR_FDRY_DMA_MSK (1 << 31) + +/* TouchScreen Convert Queue ITEM 7~0 */ +#define TCQ_ITEM_7_0 0x420 + +/* TouchScreen Convert Queue ITEM 15~8 */ +#define TCQ_ITEM_15_8 0x424 + +#define TCQ_ITEM7_SHIFT 28 +#define TCQ_ITEM6_SHIFT 24 +#define TCQ_ITEM5_SHIFT 20 +#define TCQ_ITEM4_SHIFT 16 +#define TCQ_ITEM3_SHIFT 12 +#define TCQ_ITEM2_SHIFT 8 +#define TCQ_ITEM1_SHIFT 4 +#define TCQ_ITEM0_SHIFT 0 + +#define TCQ_ITEM_TCC0 0x0 +#define TCQ_ITEM_TCC1 0x1 +#define TCQ_ITEM_TCC2 0x2 +#define TCQ_ITEM_TCC3 0x3 +#define TCQ_ITEM_TCC4 0x4 +#define TCQ_ITEM_TCC5 0x5 +#define TCQ_ITEM_TCC6 0x6 +#define TCQ_ITEM_TCC7 0x7 +#define TCQ_ITEM_GCC7 0x8 +#define TCQ_ITEM_GCC6 0x9 +#define TCQ_ITEM_GCC5 0xa +#define TCQ_ITEM_GCC4 0xb +#define TCQ_ITEM_GCC3 0xc +#define TCQ_ITEM_GCC2 0xd +#define TCQ_ITEM_GCC1 0xe +#define TCQ_ITEM_GCC0 0xf + +/* TouchScreen Convert Config 0-7 */ +#define TCC0 0x440 +#define TCC1 0x444 +#define TCC2 0x448 +#define TCC3 0x44c +#define TCC4 0x450 +#define TCC5 0x454 +#define TCC6 0x458 +#define TCC7 0x45c +#define CC_PEN_IACK (1 << 1) +#define CC_SEL_REFN_SHIFT 2 +#define CC_SEL_REFN_YNLR (0x1 << CC_SEL_REFN_SHIFT) +#define CC_SEL_REFN_AGND (0x2 << CC_SEL_REFN_SHIFT) +#define CC_SEL_REFN_MASK (0x3 << CC_SEL_REFN_SHIFT) +#define CC_SELIN_SHIFT 4 +#define CC_SELIN_XPUL (0x0 << CC_SELIN_SHIFT) +#define CC_SELIN_YPLL (0x1 << CC_SELIN_SHIFT) +#define CC_SELIN_XNUR (0x2 << CC_SELIN_SHIFT) +#define CC_SELIN_YNLR (0x3 << CC_SELIN_SHIFT) +#define CC_SELIN_WIPER (0x4 << CC_SELIN_SHIFT) +#define CC_SELIN_INAUX0 (0x5 << CC_SELIN_SHIFT) +#define CC_SELIN_INAUX1 (0x6 << CC_SELIN_SHIFT) +#define CC_SELIN_INAUX2 (0x7 << CC_SELIN_SHIFT) +#define CC_SELIN_MASK (0x7 << CC_SELIN_SHIFT) +#define CC_SELREFP_SHIFT 7 +#define CC_SELREFP_YPLL (0x0 << CC_SELREFP_SHIFT) +#define CC_SELREFP_XPUL (0x1 << CC_SELREFP_SHIFT) +#define CC_SELREFP_EXT (0x2 << CC_SELREFP_SHIFT) +#define CC_SELREFP_INT (0x3 << CC_SELREFP_SHIFT) +#define CC_SELREFP_MASK (0x3 << CC_SELREFP_SHIFT) +#define CC_XPULSW (1 << 9) +#define CC_XNURSW_SHIFT 10 +#define CC_XNURSW_HIGH (0x0 << CC_XNURSW_SHIFT) +#define CC_XNURSW_OFF (0x1 << CC_XNURSW_SHIFT) +#define CC_XNURSW_LOW (0x3 << CC_XNURSW_SHIFT) +#define CC_XNURSW_MASK (0x3 << CC_XNURSW_SHIFT) +#define CC_YPLLSW_SHIFT 12 +#define CC_YPLLSW_MASK (0x3 << CC_YPLLSW_SHIFT) +#define CC_YNLRSW (1 << 14) +#define CC_WIPERSW (1 << 15) +#define CC_NOS_SHIFT 16 +#define CC_YPLLSW_HIGH (0x0 << CC_NOS_SHIFT) +#define CC_YPLLSW_OFF (0x1 << CC_NOS_SHIFT) +#define CC_YPLLSW_LOW (0x3 << CC_NOS_SHIFT) +#define CC_NOS_MASK (0xf << CC_NOS_SHIFT) +#define CC_IGS (1 << 20) +#define CC_SETTLING_TIME_SHIFT 24 +#define CC_SETTLING_TIME_MASK (0xff << CC_SETTLING_TIME_SHIFT) + +#define TSC_4WIRE_PRECHARGE 0x158c +#define TSC_4WIRE_TOUCH_DETECT 0x578e + +#define TSC_4WIRE_X_MEASUMENT 0x1c90 +#define TSC_4WIRE_Y_MEASUMENT 0x4604 + +#define TSC_GENERAL_ADC_GCC0 0x17dc +#define TSC_GENERAL_ADC_GCC1 0x17ec +#define TSC_GENERAL_ADC_GCC2 0x17fc + +/* GeneralADC Convert Queue FIFO Register */ +#define GCQFIFO 0x800 +#define GCQFIFO_ADCOUT_SHIFT 4 +#define GCQFIFO_ADCOUT_MASK (0xfff << GCQFIFO_ADCOUT_SHIFT) +/* GeneralADC Convert Queue Control Register */ +#define GCQCR 0x804 +/* GeneralADC Convert Queue Status Register */ +#define GCQSR 0x808 +/* GeneralADC Convert Queue Mask Register */ +#define GCQMR 0x80c + +/* GeneralADC Convert Queue ITEM 7~0 */ +#define GCQ_ITEM_7_0 0x820 +/* GeneralADC Convert Queue ITEM 15~8 */ +#define GCQ_ITEM_15_8 0x824 + +#define GCQ_ITEM7_SHIFT 28 +#define GCQ_ITEM6_SHIFT 24 +#define GCQ_ITEM5_SHIFT 20 +#define GCQ_ITEM4_SHIFT 16 +#define GCQ_ITEM3_SHIFT 12 +#define GCQ_ITEM2_SHIFT 8 +#define GCQ_ITEM1_SHIFT 4 +#define GCQ_ITEM0_SHIFT 0 + +#define GCQ_ITEM_GCC0 0x0 +#define GCQ_ITEM_GCC1 0x1 +#define GCQ_ITEM_GCC2 0x2 +#define GCQ_ITEM_GCC3 0x3 + +/* GeneralADC Convert Config 0-7 */ +#define GCC0 0x840 +#define GCC1 0x844 +#define GCC2 0x848 +#define GCC3 0x84c +#define GCC4 0x850 +#define GCC5 0x854 +#define GCC6 0x858 +#define GCC7 0x85c + +/* TSC Test Register R/W */ +#define TTR 0xc00 +/* TSC Monitor Register 1, 2 */ +#define MNT1 0xc04 +#define MNT2 0xc04 + +#define DETECT_ITEM_ID_1 1 +#define DETECT_ITEM_ID_2 5 +#define TS_X_ITEM_ID 2 +#define TS_Y_ITEM_ID 3 +#define TSI_DATA 1 +#define FQS_DATA 0 + +#endif /* __IMX_ADC_H__ */ diff --git a/drivers/mxc/asrc/Kconfig b/drivers/mxc/asrc/Kconfig new file mode 100644 index 000000000000..a4c66b19f067 --- /dev/null +++ b/drivers/mxc/asrc/Kconfig @@ -0,0 +1,13 @@ +# +# ASRC configuration +# + +menu "MXC Asynchronous Sample Rate Converter support" + +config MXC_ASRC + tristate "ASRC support" + depends on ARCH_MX35 + ---help--- + Say Y to get the ASRC service. + +endmenu diff --git a/drivers/mxc/asrc/Makefile b/drivers/mxc/asrc/Makefile new file mode 100644 index 000000000000..0d2487d389c7 --- /dev/null +++ b/drivers/mxc/asrc/Makefile @@ -0,0 +1,7 @@ +# +# Makefile for the kernel Asynchronous Sample Rate Converter driver +# + +ifeq ($(CONFIG_ARCH_MX35),y) + obj-$(CONFIG_MXC_ASRC) += mxc_asrc.o +endif diff --git a/drivers/mxc/asrc/mxc_asrc.c b/drivers/mxc/asrc/mxc_asrc.c new file mode 100644 index 000000000000..eccb2f6efff5 --- /dev/null +++ b/drivers/mxc/asrc/mxc_asrc.c @@ -0,0 +1,1692 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mxc_asrc.c + * + * @brief MXC Asynchronous Sample Rate Converter + * + * @ingroup SOUND + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static int asrc_major; +static struct class *asrc_class; +#define ASRC_PROC_PATH "driver/asrc" + +#define ASRC_RATIO_DECIMAL_DEPTH 26 + +DEFINE_SPINLOCK(data_lock); +DEFINE_SPINLOCK(input_int_lock); +DEFINE_SPINLOCK(output_int_lock); + +#define AICPA 0 /* Input Clock Divider A Offset */ +#define AICDA 3 /* Input Clock Prescaler A Offset */ +#define AICPB 6 /* Input Clock Divider B Offset */ +#define AICDB 9 /* Input Clock Prescaler B Offset */ +#define AOCPA 12 /* Output Clock Divider A Offset */ +#define AOCDA 15 /* Output Clock Prescaler A Offset */ +#define AOCPB 18 /* Output Clock Divider B Offset */ +#define AOCDB 21 /* Output Clock Prescaler B Offset */ +#define AICPC 0 /* Input Clock Divider C Offset */ +#define AICDC 3 /* Input Clock Prescaler C Offset */ +#define AOCDC 6 /* Output Clock Prescaler C Offset */ +#define AOCPC 9 /* Output Clock Divider C Offset */ + +char *asrc_pair_id[] = { + [0] = "ASRC RX PAIR A", + [1] = "ASRC TX PAIR A", + [2] = "ASRC RX PAIR B", + [3] = "ASRC TX PAIR B", + [4] = "ASRC RX PAIR C", + [5] = "ASRC TX PAIR C", +}; + +enum asrc_status { + ASRC_ASRSTR_AIDEA = 0x01, + ASRC_ASRSTR_AIDEB = 0x02, + ASRC_ASRSTR_AIDEC = 0x04, + ASRC_ASRSTR_AODFA = 0x08, + ASRC_ASRSTR_AODFB = 0x10, + ASRC_ASRSTR_AODFC = 0x20, + ASRC_ASRSTR_AOLE = 0x40, + ASRC_ASRSTR_FPWT = 0x80, + ASRC_ASRSTR_AIDUA = 0x100, + ASRC_ASRSTR_AIDUB = 0x200, + ASRC_ASRSTR_AIDUC = 0x400, + ASRC_ASRSTR_AODOA = 0x800, + ASRC_ASRSTR_AODOB = 0x1000, + ASRC_ASRSTR_AODOC = 0x2000, + ASRC_ASRSTR_AIOLA = 0x4000, + ASRC_ASRSTR_AIOLB = 0x8000, + ASRC_ASRSTR_AIOLC = 0x10000, + ASRC_ASRSTR_AOOLA = 0x20000, + ASRC_ASRSTR_AOOLB = 0x40000, + ASRC_ASRSTR_AOOLC = 0x80000, + ASRC_ASRSTR_ATQOL = 0x100000, + ASRC_ASRSTR_DSLCNT = 0x200000, +}; + +/* Sample rates are aligned with that defined in pcm.h file */ +static const unsigned char asrc_process_table[][8][2] = { + /* 32kHz 44.1kHz 48kHz 64kHz 88.2kHz 96kHz 176kHz 192kHz */ +/*5512Hz*/ + {{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0},}, +/*8kHz*/ + {{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0},}, +/*11025Hz*/ + {{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0},}, +/*16kHz*/ + {{0, 1}, {0, 1}, {0, 1}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0},}, +/*22050Hz*/ + {{0, 1}, {0, 1}, {0, 1}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0},}, +/*32kHz*/ + {{0, 1}, {0, 1}, {0, 1}, {0, 1}, {0, 1}, {0, 0}, {0, 0}, {0, 0},}, +/*44.1kHz*/ + {{0, 2}, {0, 1}, {0, 1}, {0, 1}, {0, 1}, {0, 1}, {0, 0}, {0, 0},}, +/*48kHz*/ + {{0, 2}, {0, 2}, {0, 1}, {0, 1}, {0, 1}, {0, 1}, {0, 0}, {0, 0},}, +/*64kHz*/ + {{1, 2}, {0, 2}, {0, 2}, {0, 1}, {0, 1}, {0, 1}, {0, 1}, {0, 0},}, +/*88.2kHz*/ + {{1, 2}, {1, 2}, {1, 2}, {1, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 1},}, +/*96kHz*/ + {{1, 2}, {1, 2}, {1, 2}, {1, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 1},}, +/*176kHz*/ + {{2, 2}, {2, 2}, {2, 2}, {2, 1}, {2, 1}, {2, 1}, {2, 1}, {2, 1},}, +/*192kHz*/ + {{2, 2}, {2, 2}, {2, 2}, {2, 1}, {2, 1}, {2, 1}, {2, 1}, {2, 1},}, +}; + +static const unsigned char asrc_divider_table[] = { +/*5500Hz 8kHz 11025Hz 16kHz 22050kHz 32kHz 44.1kHz 48kHz 64kHz 88.2kHz 96kHz 176400Hz 192kHz*/ + 0x07, 0x15, 0x06, 0x14, 0x05, 0x13, 0x04, 0x04, 0x12, 0x03, 0x03, 0x02, + 0x02, +}; + +static struct asrc_data *g_asrc_data; +static struct proc_dir_entry *proc_asrc; +static unsigned long asrc_vrt_base_addr; +static struct mxc_asrc_platform_data *mxc_asrc_data; + +static int asrc_set_clock_ratio(enum asrc_pair_index index, + int input_sample_rate, int output_sample_rate) +{ + int i; + int integ = 0; + unsigned long reg_val = 0; + + if (output_sample_rate == 0) + return -1; + while (input_sample_rate >= output_sample_rate) { + input_sample_rate -= output_sample_rate; + integ++; + } + reg_val |= (integ << 26); + + for (i = 1; i <= ASRC_RATIO_DECIMAL_DEPTH; i++) { + if ((input_sample_rate * 2) >= output_sample_rate) { + reg_val |= (1 << (ASRC_RATIO_DECIMAL_DEPTH - i)); + input_sample_rate = + input_sample_rate * 2 - output_sample_rate; + } else + input_sample_rate = input_sample_rate << 1; + + if (input_sample_rate == 0) + break; + } + + __raw_writel(reg_val, + (asrc_vrt_base_addr + ASRC_ASRIDRLA_REG + (index << 3))); + __raw_writel((reg_val >> 24), + (asrc_vrt_base_addr + ASRC_ASRIDRHA_REG + (index << 3))); + return 0; +} + +static int asrc_set_process_configuration(enum asrc_pair_index index, + int input_sample_rate, + int output_sample_rate) +{ + int i = 0, j = 0; + unsigned long reg; + switch (input_sample_rate) { + case 5512: + i = 0; + case 8000: + i = 1; + break; + case 11025: + i = 2; + break; + case 16000: + i = 3; + break; + case 22050: + i = 4; + break; + case 32000: + i = 5; + break; + case 44100: + i = 6; + break; + case 48000: + i = 7; + break; + case 64000: + i = 8; + break; + case 88200: + i = 9; + break; + case 96000: + i = 10; + break; + case 176400: + i = 11; + break; + case 192000: + i = 12; + break; + default: + return -1; + } + + switch (output_sample_rate) { + case 32000: + j = 0; + break; + case 44100: + j = 1; + break; + case 48000: + j = 2; + break; + case 64000: + j = 3; + break; + case 88200: + j = 4; + break; + case 96000: + j = 5; + break; + case 176400: + j = 6; + break; + case 192000: + j = 7; + break; + default: + return -1; + } + + reg = __raw_readl(asrc_vrt_base_addr + ASRC_ASRCFG_REG); + reg &= ~(0x0f << (6 + (index << 2))); + reg |= + ((asrc_process_table[i][j][0] << (6 + (index << 2))) | + (asrc_process_table[i][j][1] << (8 + (index << 2)))); + __raw_writel(reg, asrc_vrt_base_addr + ASRC_ASRCFG_REG); + + return 0; +} + +static int asrc_get_asrck_clock_divider(int sample_rate) +{ + int i = 0; + switch (sample_rate) { + case 5500: + i = 0; + break; + case 8000: + i = 1; + break; + case 11025: + i = 2; + break; + case 16000: + i = 3; + break; + case 22050: + i = 4; + break; + case 32000: + i = 5; + break; + case 44100: + i = 6; + break; + case 48000: + i = 7; + break; + case 64000: + i = 8; + break; + case 88200: + i = 9; + break; + case 96000: + i = 10; + break; + case 176400: + i = 11; + break; + case 192000: + i = 12; + break; + default: + return -1; + } + + return asrc_divider_table[i]; +} + +int asrc_req_pair(int chn_num, enum asrc_pair_index *index) +{ + int err = 0; + unsigned long lock_flags; + spin_lock_irqsave(&data_lock, lock_flags); + + if (chn_num > 2) { + if (g_asrc_data->asrc_pair[ASRC_PAIR_C].active + || (chn_num > g_asrc_data->asrc_pair[ASRC_PAIR_C].chn_max)) + err = -EBUSY; + else { + *index = ASRC_PAIR_C; + g_asrc_data->asrc_pair[ASRC_PAIR_C].chn_num = chn_num; + g_asrc_data->asrc_pair[ASRC_PAIR_C].active = 1; + } + } else { + if (g_asrc_data->asrc_pair[ASRC_PAIR_A].active || + (g_asrc_data->asrc_pair[ASRC_PAIR_A].chn_max == 0)) { + if (g_asrc_data->asrc_pair[ASRC_PAIR_B]. + active + || (g_asrc_data->asrc_pair[ASRC_PAIR_B]. + chn_max == 0)) + err = -EBUSY; + else { + *index = ASRC_PAIR_B; + g_asrc_data->asrc_pair[ASRC_PAIR_B].chn_num = 2; + g_asrc_data->asrc_pair[ASRC_PAIR_B].active = 1; + } + } else { + *index = ASRC_PAIR_A; + g_asrc_data->asrc_pair[ASRC_PAIR_A].chn_num = 2; + g_asrc_data->asrc_pair[ASRC_PAIR_A].active = 1; + } + } + spin_unlock_irqrestore(&data_lock, lock_flags); + return err; +} + +EXPORT_SYMBOL(asrc_req_pair); + +void asrc_release_pair(enum asrc_pair_index index) +{ + unsigned long reg; + unsigned long lock_flags; + + spin_lock_irqsave(&data_lock, lock_flags); + g_asrc_data->asrc_pair[index].active = 0; + g_asrc_data->asrc_pair[index].overload_error = 0; + /********Disable PAIR*************/ + reg = __raw_readl(asrc_vrt_base_addr + ASRC_ASRCTR_REG); + reg &= ~(1 << (index + 1)); + __raw_writel(reg, asrc_vrt_base_addr + ASRC_ASRCTR_REG); + spin_unlock_irqrestore(&data_lock, lock_flags); +} + +EXPORT_SYMBOL(asrc_release_pair); + +int asrc_config_pair(struct asrc_config *config) +{ + int err = 0; + int reg, tmp, channel_num; + unsigned long lock_flags; + /* Set the channel number */ + reg = __raw_readl(asrc_vrt_base_addr + ASRC_ASRCNCR_REG); + spin_lock_irqsave(&data_lock, lock_flags); + g_asrc_data->asrc_pair[config->pair].chn_num = config->channel_num; + spin_unlock_irqrestore(&data_lock, lock_flags); + reg &= + ~((0xFFFFFFFF >> (32 - mxc_asrc_data->channel_bits)) << + (mxc_asrc_data->channel_bits * config->pair)); + if (mxc_asrc_data->channel_bits > 3) + channel_num = config->channel_num; + else + channel_num = (config->channel_num + 1) / 2; + tmp = channel_num << (mxc_asrc_data->channel_bits * config->pair); + reg |= tmp; + __raw_writel(reg, asrc_vrt_base_addr + ASRC_ASRCNCR_REG); + + /* Set the clock source */ + reg = __raw_readl(asrc_vrt_base_addr + ASRC_ASRCSR_REG); + tmp = ~(0x0f << (config->pair << 2)); + reg &= tmp; + tmp = ~(0x0f << (12 + (config->pair << 2))); + reg &= tmp; + reg |= + ((config->inclk << (config->pair << 2)) | (config-> + outclk << (12 + + (config-> + pair << + 2)))); + + __raw_writel(reg, asrc_vrt_base_addr + ASRC_ASRCSR_REG); + + /* default setting */ + /* automatic selection for processing mode */ + reg = __raw_readl(asrc_vrt_base_addr + ASRC_ASRCTR_REG); + reg |= (1 << (20 + config->pair)); + reg &= ~(1 << (14 + (config->pair << 1))); + + __raw_writel(reg, asrc_vrt_base_addr + ASRC_ASRCTR_REG); + + reg = __raw_readl(asrc_vrt_base_addr + ASRC_ASRRA_REG); + reg &= 0xffbfffff; + __raw_writel(reg, asrc_vrt_base_addr + ASRC_ASRRA_REG); + + reg = __raw_readl(asrc_vrt_base_addr + ASRC_ASRCTR_REG); + reg = reg & (~(1 << 23)); + __raw_writel(reg, asrc_vrt_base_addr + ASRC_ASRCTR_REG); + + /* Default Clock Divider Setting */ + reg = __raw_readl(asrc_vrt_base_addr + ASRC_ASRCDR1_REG); + if (config->pair == ASRC_PAIR_A) { + reg = __raw_readl(asrc_vrt_base_addr + ASRC_ASRCDR1_REG); + reg &= 0xfc0fc0; + /* Input Part */ + if ((config->inclk & 0x0f) == INCLK_SPDIF_RX) + reg |= 7 << AICPA; + else if ((config->inclk & 0x0f) == INCLK_SPDIF_TX) + reg |= 6 << AICPA; + else if ((config->inclk & 0x0f) == INCLK_ASRCK1_CLK) { + tmp = + asrc_get_asrck_clock_divider(config-> + input_sample_rate); + reg |= tmp << AICPA; + } else { + if (config->word_width == 16 || config->word_width == 8) + reg |= 5 << AICPA; + else if (config->word_width == 32 + || config->word_width == 24) + reg |= 6 << AICPA; + else + err = -EFAULT; + } + /* Output Part */ + if ((config->outclk & 0x0f) == OUTCLK_SPDIF_RX) + reg |= 7 << AOCPA; + else if ((config->outclk & 0x0f) == OUTCLK_SPDIF_TX) + reg |= 6 << AOCPA; + else if ((config->outclk & 0x0f) == OUTCLK_ASRCK1_CLK) { + tmp = + asrc_get_asrck_clock_divider(config-> + output_sample_rate); + reg |= tmp << AOCPA; + } else { + if (config->word_width == 16 || config->word_width == 8) + reg |= 5 << AOCPA; + else if (config->word_width == 32 + || config->word_width == 24) + reg |= 6 << AOCPA; + else + err = -EFAULT; + } + + __raw_writel(reg, asrc_vrt_base_addr + ASRC_ASRCDR1_REG); + + } else if (config->pair == ASRC_PAIR_B) { + reg = __raw_readl(asrc_vrt_base_addr + ASRC_ASRCDR1_REG); + reg &= 0x03f03f; + /* Input Part */ + if ((config->inclk & 0x0f) == INCLK_SPDIF_RX) + reg |= 7 << AICPB; + else if ((config->inclk & 0x0f) == INCLK_SPDIF_TX) + reg |= 6 << AICPB; + else if ((config->inclk & 0x0f) == INCLK_ASRCK1_CLK) { + tmp = + asrc_get_asrck_clock_divider(config-> + input_sample_rate); + reg |= tmp << AICPB; + } else { + if (config->word_width == 16 || config->word_width == 8) + reg |= 5 << AICPB; + else if (config->word_width == 32 + || config->word_width == 24) + reg |= 6 << AICPB; + else + err = -EFAULT; + } + /* Output Part */ + if ((config->outclk & 0x0f) == OUTCLK_SPDIF_RX) + reg |= 7 << AOCPB; + else if ((config->outclk & 0x0f) == OUTCLK_SPDIF_TX) + reg |= 6 << AOCPB; + else if ((config->outclk & 0x0f) == OUTCLK_ASRCK1_CLK) { + tmp = + asrc_get_asrck_clock_divider(config-> + output_sample_rate); + reg |= tmp << AOCPB; + } else { + if (config->word_width == 16 || config->word_width == 8) + reg |= 5 << AOCPB; + else if (config->word_width == 32 + || config->word_width == 24) + reg |= 6 << AOCPB; + else + err = -EFAULT; + } + + __raw_writel(reg, asrc_vrt_base_addr + ASRC_ASRCDR1_REG); + + } else { + reg = __raw_readl(asrc_vrt_base_addr + ASRC_ASRCDR2_REG); + reg &= 0; + /* Input Part */ + if ((config->inclk & 0x0f) == INCLK_SPDIF_RX) + reg |= 7 << AICPC; + else if ((config->inclk & 0x0f) == INCLK_SPDIF_TX) + reg |= 6 << AICPC; + else if ((config->inclk & 0x0f) == INCLK_ASRCK1_CLK) { + tmp = + asrc_get_asrck_clock_divider(config-> + input_sample_rate); + reg |= tmp << AICPC; + } else { + if (config->word_width == 16 || config->word_width == 8) + reg |= 5 << AICPC; + else if (config->word_width == 32 + || config->word_width == 24) + reg |= 6 << AICPC; + else + err = -EFAULT; + } + /* Output Part */ + if ((config->outclk & 0x0f) == OUTCLK_SPDIF_RX) + reg |= 7 << AOCPC; + else if ((config->outclk & 0x0f) == OUTCLK_SPDIF_TX) + reg |= 6 << AOCPC; + else if ((config->outclk & 0x0f) == OUTCLK_ASRCK1_CLK) { + tmp = + asrc_get_asrck_clock_divider(config-> + output_sample_rate); + reg |= tmp << AOCPC; + } else { + if (config->word_width == 16 || config->word_width == 8) + reg |= 5 << AOCPC; + else if (config->word_width == 32 + || config->word_width == 24) + reg |= 6 << AOCPC; + else + err = -EFAULT; + } + __raw_writel(reg, asrc_vrt_base_addr + ASRC_ASRCDR2_REG); + + } + + /* check whether ideal ratio is a must */ + if ((config->inclk & 0x0f) == INCLK_NONE) { + reg = __raw_readl(asrc_vrt_base_addr + ASRC_ASRCTR_REG); + reg &= ~(1 << (20 + config->pair)); + reg |= (0x03 << (13 + (config->pair << 1))); + __raw_writel(reg, asrc_vrt_base_addr + ASRC_ASRCTR_REG); + err = asrc_set_clock_ratio(config->pair, + config->input_sample_rate, + config->output_sample_rate); + if (err < 0) + return err; + + err = asrc_set_process_configuration(config->pair, + config->input_sample_rate, + config-> + output_sample_rate); + if (err < 0) + return err; + } else if ((config->inclk & 0x0f) == INCLK_ASRCK1_CLK) { + if (config->input_sample_rate == 44100 + || config->input_sample_rate == 88200) { + pr_info + ("ASRC core clock cann't support sample rate %d\n", + config->input_sample_rate); + err = -EFAULT; + } + } else if ((config->outclk & 0x0f) == OUTCLK_ASRCK1_CLK) { + if (config->output_sample_rate == 44100 + || config->output_sample_rate == 88200) { + pr_info + ("ASRC core clock cann't support sample rate %d\n", + config->input_sample_rate); + err = -EFAULT; + } + } + + return err; +} + +EXPORT_SYMBOL(asrc_config_pair); + +void asrc_start_conv(enum asrc_pair_index index) +{ + int reg, reg_1; + unsigned long lock_flags; + int i; + + spin_lock_irqsave(&data_lock, lock_flags); + + reg = __raw_readl(asrc_vrt_base_addr + ASRC_ASRCTR_REG); + if ((reg & 0x0E) == 0) + clk_enable(mxc_asrc_data->asrc_audio_clk); + reg |= (1 << (1 + index)); + __raw_writel(reg, asrc_vrt_base_addr + ASRC_ASRCTR_REG); + + reg = __raw_readl(asrc_vrt_base_addr + ASRC_ASRCFG_REG); + while (!(reg & (1 << (index + 21)))) + reg = __raw_readl(asrc_vrt_base_addr + ASRC_ASRCFG_REG); + reg_1 = __raw_readl(asrc_vrt_base_addr + ASRC_ASRSTR_REG); + + reg = 0; + for (i = 0; i < 20; i++) { + __raw_writel(reg, + asrc_vrt_base_addr + ASRC_ASRDIA_REG + + (index << 3)); + __raw_writel(reg, + asrc_vrt_base_addr + ASRC_ASRDIA_REG + + (index << 3)); + __raw_writel(reg, + asrc_vrt_base_addr + ASRC_ASRDIA_REG + + (index << 3)); + __raw_writel(reg, + asrc_vrt_base_addr + ASRC_ASRDIA_REG + + (index << 3)); + __raw_writel(reg, + asrc_vrt_base_addr + ASRC_ASRDIA_REG + + (index << 3)); + __raw_writel(reg, + asrc_vrt_base_addr + ASRC_ASRDIA_REG + + (index << 3)); + __raw_writel(reg, + asrc_vrt_base_addr + ASRC_ASRDIA_REG + + (index << 3)); + __raw_writel(reg, + asrc_vrt_base_addr + ASRC_ASRDIA_REG + + (index << 3)); + } + + __raw_writel(0x40, asrc_vrt_base_addr + ASRC_ASRIER_REG); + spin_unlock_irqrestore(&data_lock, lock_flags); + return; +} + +EXPORT_SYMBOL(asrc_start_conv); + +void asrc_stop_conv(enum asrc_pair_index index) +{ + int reg; + unsigned long lock_flags; + spin_lock_irqsave(&data_lock, lock_flags); + reg = __raw_readl(asrc_vrt_base_addr + ASRC_ASRCTR_REG); + reg &= ~(1 << (1 + index)); + __raw_writel(reg, asrc_vrt_base_addr + ASRC_ASRCTR_REG); + if ((reg & 0x0E) == 0) + clk_disable(mxc_asrc_data->asrc_audio_clk); + spin_unlock_irqrestore(&data_lock, lock_flags); + return; +} + +EXPORT_SYMBOL(asrc_stop_conv); + +/*! + * @brief asrc interrupt handler + */ +static irqreturn_t asrc_isr(int irq, void *dev_id) +{ + unsigned long status; + int reg = 0x40; + + status = __raw_readl(asrc_vrt_base_addr + ASRC_ASRSTR_REG); + if (g_asrc_data->asrc_pair[ASRC_PAIR_A].active == 1) { + if (status & ASRC_ASRSTR_ATQOL) + g_asrc_data->asrc_pair[ASRC_PAIR_A].overload_error |= + ASRC_TASK_Q_OVERLOAD; + if (status & ASRC_ASRSTR_AOOLA) + g_asrc_data->asrc_pair[ASRC_PAIR_A].overload_error |= + ASRC_OUTPUT_TASK_OVERLOAD; + if (status & ASRC_ASRSTR_AIOLA) + g_asrc_data->asrc_pair[ASRC_PAIR_A].overload_error |= + ASRC_INPUT_TASK_OVERLOAD; + if (status & ASRC_ASRSTR_AODOA) + g_asrc_data->asrc_pair[ASRC_PAIR_A].overload_error |= + ASRC_OUTPUT_BUFFER_OVERFLOW; + if (status & ASRC_ASRSTR_AIDUA) + g_asrc_data->asrc_pair[ASRC_PAIR_A].overload_error |= + ASRC_INPUT_BUFFER_UNDERRUN; + } else if (g_asrc_data->asrc_pair[ASRC_PAIR_B].active == 1) { + if (status & ASRC_ASRSTR_ATQOL) + g_asrc_data->asrc_pair[ASRC_PAIR_B].overload_error |= + ASRC_TASK_Q_OVERLOAD; + if (status & ASRC_ASRSTR_AOOLB) + g_asrc_data->asrc_pair[ASRC_PAIR_B].overload_error |= + ASRC_OUTPUT_TASK_OVERLOAD; + if (status & ASRC_ASRSTR_AIOLB) + g_asrc_data->asrc_pair[ASRC_PAIR_B].overload_error |= + ASRC_INPUT_TASK_OVERLOAD; + if (status & ASRC_ASRSTR_AODOB) + g_asrc_data->asrc_pair[ASRC_PAIR_B].overload_error |= + ASRC_OUTPUT_BUFFER_OVERFLOW; + if (status & ASRC_ASRSTR_AIDUB) + g_asrc_data->asrc_pair[ASRC_PAIR_B].overload_error |= + ASRC_INPUT_BUFFER_UNDERRUN; + } else if (g_asrc_data->asrc_pair[ASRC_PAIR_C].active == 1) { + if (status & ASRC_ASRSTR_ATQOL) + g_asrc_data->asrc_pair[ASRC_PAIR_C].overload_error |= + ASRC_TASK_Q_OVERLOAD; + if (status & ASRC_ASRSTR_AOOLC) + g_asrc_data->asrc_pair[ASRC_PAIR_C].overload_error |= + ASRC_OUTPUT_TASK_OVERLOAD; + if (status & ASRC_ASRSTR_AIOLC) + g_asrc_data->asrc_pair[ASRC_PAIR_C].overload_error |= + ASRC_INPUT_TASK_OVERLOAD; + if (status & ASRC_ASRSTR_AODOC) + g_asrc_data->asrc_pair[ASRC_PAIR_C].overload_error |= + ASRC_OUTPUT_BUFFER_OVERFLOW; + if (status & ASRC_ASRSTR_AIDUC) + g_asrc_data->asrc_pair[ASRC_PAIR_C].overload_error |= + ASRC_INPUT_BUFFER_UNDERRUN; + } + + /* try to clean the overload error */ + __raw_writel(reg, asrc_vrt_base_addr + ASRC_ASRSTR_REG); + + return IRQ_HANDLED; +} + +void asrc_get_status(struct asrc_status_flags *flags) +{ + unsigned long lock_flags; + enum asrc_pair_index index; + + spin_lock_irqsave(&data_lock, lock_flags); + index = flags->index; + flags->overload_error = g_asrc_data->asrc_pair[index].overload_error; + + spin_unlock_irqrestore(&data_lock, lock_flags); + return; +} + +EXPORT_SYMBOL(asrc_get_status); + +static int mxc_init_asrc(void) +{ + /* Halt ASRC internal FP when input FIFO needs data for pair A, B, C */ + __raw_writel(0x0001, asrc_vrt_base_addr + ASRC_ASRCTR_REG); + + /* Enable overflow interrupt */ + __raw_writel(0x00, asrc_vrt_base_addr + ASRC_ASRIER_REG); + + /* Default 6: 2: 2 channel assignment */ + __raw_writel((0x06 << mxc_asrc_data->channel_bits * + 2) | (0x02 << mxc_asrc_data->channel_bits) | 0x02, + asrc_vrt_base_addr + ASRC_ASRCNCR_REG); + + /* Parameter Registers recommended settings */ + __raw_writel(0x7fffff, asrc_vrt_base_addr + ASRC_ASRPM1_REG); + __raw_writel(0x255555, asrc_vrt_base_addr + ASRC_ASRPM2_REG); + __raw_writel(0xff7280, asrc_vrt_base_addr + ASRC_ASRPM3_REG); + __raw_writel(0xff7280, asrc_vrt_base_addr + ASRC_ASRPM4_REG); + __raw_writel(0xff7280, asrc_vrt_base_addr + ASRC_ASRPM5_REG); + + __raw_writel(0x001f00, asrc_vrt_base_addr + ASRC_ASRTFR1); + + /* Set the processing clock for 76KHz, 133M */ + __raw_writel(0x06D6, asrc_vrt_base_addr + ASRC_ASR76K_REG); + + /* Set the processing clock for 56KHz, 133M */ + __raw_writel(0x0947, asrc_vrt_base_addr + ASRC_ASR56K_REG); + + if (request_irq(MXC_INT_ASRC, asrc_isr, 0, "asrc", NULL)) + return -1; + + return 0; +} + +static int asrc_get_output_buffer_size(int input_buffer_size, + int input_sample_rate, + int output_sample_rate) +{ + int i = 0; + int outbuffer_size = 0; + int outsample = output_sample_rate; + while (outsample >= input_sample_rate) { + ++i; + outsample -= input_sample_rate; + } + outbuffer_size = i * input_buffer_size; + i = 1; + while (((input_buffer_size >> i) > 2) && (outsample != 0)) { + if (((outsample << 1) - input_sample_rate) >= 0) { + outsample = (outsample << 1) - input_sample_rate; + outbuffer_size += (input_buffer_size >> i); + } else { + outsample = outsample << 1; + } + i++; + } + outbuffer_size = (outbuffer_size >> 3) << 3; + return outbuffer_size; +} + +static void asrc_input_dma_callback(void *data, int error, unsigned int count) +{ + struct asrc_pair_params *params; + struct dma_block *block; + mxc_dma_requestbuf_t dma_request; + unsigned long lock_flags; + + params = data; + + spin_lock_irqsave(&input_int_lock, lock_flags); + params->input_queue_empty--; + if (!list_empty(¶ms->input_queue)) { + block = + list_entry(params->input_queue.next, + struct dma_block, queue); + dma_request.src_addr = (dma_addr_t) block->dma_paddr; + dma_request.dst_addr = + (ASRC_BASE_ADDR + ASRC_ASRDIA_REG + (params->index << 3)); + dma_request.num_of_bytes = block->length; + mxc_dma_config(params->input_dma_channel, &dma_request, + 1, MXC_DMA_MODE_WRITE); + list_del(params->input_queue.next); + list_add_tail(&block->queue, ¶ms->input_done_queue); + params->input_queue_empty++; + } + params->input_counter++; + wake_up_interruptible(¶ms->input_wait_queue); + spin_unlock_irqrestore(&input_int_lock, lock_flags); + return; +} + +static void asrc_output_dma_callback(void *data, int error, unsigned int count) +{ + struct asrc_pair_params *params; + struct dma_block *block; + mxc_dma_requestbuf_t dma_request; + unsigned long lock_flags; + + params = data; + + spin_lock_irqsave(&output_int_lock, lock_flags); + params->output_queue_empty--; + + if (!list_empty(¶ms->output_queue)) { + block = + list_entry(params->output_queue.next, + struct dma_block, queue); + dma_request.src_addr = + (ASRC_BASE_ADDR + ASRC_ASRDOA_REG + (params->index << 3)); + dma_request.dst_addr = (dma_addr_t) block->dma_paddr; + dma_request.num_of_bytes = block->length; + mxc_dma_config(params->output_dma_channel, &dma_request, + 1, MXC_DMA_MODE_READ); + list_del(params->output_queue.next); + list_add_tail(&block->queue, ¶ms->output_done_queue); + params->output_queue_empty++; + } + params->output_counter++; + wake_up_interruptible(¶ms->output_wait_queue); + spin_unlock_irqrestore(&output_int_lock, lock_flags); + return; +} + +static void mxc_free_dma_buf(struct asrc_pair_params *params) +{ + int i; + for (i = 0; i < ASRC_DMA_BUFFER_NUM; i++) { + if (params->input_dma[i].dma_vaddr != NULL) { + dma_free_coherent(0, + params->input_buffer_size, + params->input_dma[i]. + dma_vaddr, + params->input_dma[i].dma_paddr); + params->input_dma[i].dma_vaddr = NULL; + } + if (params->output_dma[i].dma_vaddr != NULL) { + dma_free_coherent(0, + params->output_buffer_size, + params->output_dma[i]. + dma_vaddr, + params->output_dma[i].dma_paddr); + params->output_dma[i].dma_vaddr = NULL; + } + } + + return; +} + +static int mxc_allocate_dma_buf(struct asrc_pair_params *params) +{ + int i; + for (i = 0; i < ASRC_DMA_BUFFER_NUM; i++) { + params->input_dma[i].dma_vaddr = + dma_alloc_coherent(0, params->input_buffer_size, + ¶ms->input_dma[i].dma_paddr, + GFP_DMA | GFP_KERNEL); + if (params->input_dma[i].dma_vaddr == NULL) { + mxc_free_dma_buf(params); + pr_info("can't allocate buff\n"); + return -ENOBUFS; + } + } + for (i = 0; i < ASRC_DMA_BUFFER_NUM; i++) { + params->output_dma[i].dma_vaddr = + dma_alloc_coherent(0, + params->output_buffer_size, + ¶ms->output_dma[i].dma_paddr, + GFP_DMA | GFP_KERNEL); + if (params->output_dma[i].dma_vaddr == NULL) { + mxc_free_dma_buf(params); + return -ENOBUFS; + } + } + + return 0; +} + +/*! + * asrc interface - ioctl function + * + * @param inode struct inode * + * + * @param file struct file * + * + * @param cmd unsigned int + * + * @param arg unsigned long + * + * @return 0 success, ENODEV for invalid device instance, + * -1 for other errors. + */ +static int asrc_ioctl(struct inode *inode, struct file *file, + unsigned int cmd, unsigned long arg) +{ + int err = 0; + struct asrc_pair_params *params; + params = file->private_data; + + if (down_interruptible(¶ms->busy_lock)) + return -EBUSY; + switch (cmd) { + case ASRC_REQ_PAIR: + { + struct asrc_req req; + if (copy_from_user(&req, (void __user *)arg, + sizeof(struct asrc_req))) { + err = -EFAULT; + break; + } + err = asrc_req_pair(req.chn_num, &req.index); + if (err < 0) + break; + params->pair_hold = 1; + params->index = req.index; + if (copy_to_user + ((void __user *)arg, &req, sizeof(struct asrc_req))) + err = -EFAULT; + + break; + } + case ASRC_CONFIG_PAIR: + { + struct asrc_config config; + mxc_dma_device_t rx_id, tx_id; + char *rx_name, *tx_name; + int channel = -1; + if (copy_from_user + (&config, (void __user *)arg, + sizeof(struct asrc_config))) { + err = -EFAULT; + break; + } + err = asrc_config_pair(&config); + if (err < 0) + break; + params->output_buffer_size = + asrc_get_output_buffer_size(config. + dma_buffer_size, + config. + input_sample_rate, + config. + output_sample_rate); + params->input_buffer_size = config.dma_buffer_size; + if (config.buffer_num > ASRC_DMA_BUFFER_NUM) + params->buffer_num = ASRC_DMA_BUFFER_NUM; + else + params->buffer_num = config.buffer_num; + err = mxc_allocate_dma_buf(params); + if (err < 0) + break; + + /* TBD - need to update when new SDMA interface ready */ + if (config.pair == ASRC_PAIR_A) { + rx_id = MXC_DMA_ASRC_A_RX; + tx_id = MXC_DMA_ASRC_A_TX; + rx_name = asrc_pair_id[0]; + tx_name = asrc_pair_id[1]; + } else if (config.pair == ASRC_PAIR_B) { + rx_id = MXC_DMA_ASRC_B_RX; + tx_id = MXC_DMA_ASRC_B_TX; + rx_name = asrc_pair_id[2]; + tx_name = asrc_pair_id[3]; + } else { + rx_id = MXC_DMA_ASRC_C_RX; + tx_id = MXC_DMA_ASRC_C_TX; + rx_name = asrc_pair_id[4]; + tx_name = asrc_pair_id[5]; + } + channel = mxc_dma_request(rx_id, rx_name); + params->input_dma_channel = channel; + err = mxc_dma_callback_set(channel, (mxc_dma_callback_t) + asrc_input_dma_callback, + (void *)params); + channel = mxc_dma_request(tx_id, tx_name); + params->output_dma_channel = channel; + err = mxc_dma_callback_set(channel, (mxc_dma_callback_t) + asrc_output_dma_callback, + (void *)params); + /* TBD - need to update when new SDMA interface ready */ + params->input_queue_empty = 0; + params->output_queue_empty = 0; + INIT_LIST_HEAD(¶ms->input_queue); + INIT_LIST_HEAD(¶ms->input_done_queue); + INIT_LIST_HEAD(¶ms->output_queue); + INIT_LIST_HEAD(¶ms->output_done_queue); + init_waitqueue_head(¶ms->input_wait_queue); + init_waitqueue_head(¶ms->output_wait_queue); + + if (copy_to_user + ((void __user *)arg, &config, + sizeof(struct asrc_config))) + err = -EFAULT; + break; + } + case ASRC_QUERYBUF: + { + struct asrc_querybuf buffer; + if (copy_from_user + (&buffer, (void __user *)arg, + sizeof(struct asrc_querybuf))) { + err = -EFAULT; + break; + } + buffer.input_offset = + (unsigned long)params->input_dma[buffer. + buffer_index]. + dma_paddr; + buffer.input_length = params->input_buffer_size; + buffer.output_offset = + (unsigned long)params->output_dma[buffer. + buffer_index]. + dma_paddr; + buffer.output_length = params->output_buffer_size; + if (copy_to_user + ((void __user *)arg, &buffer, + sizeof(struct asrc_querybuf))) + err = -EFAULT; + break; + } + case ASRC_RELEASE_PAIR: + { + enum asrc_pair_index index; + if (copy_from_user + (&index, (void __user *)arg, + sizeof(enum asrc_pair_index))) { + err = -EFAULT; + break; + } + + mxc_dma_free(params->input_dma_channel); + mxc_dma_free(params->output_dma_channel); + mxc_free_dma_buf(params); + asrc_release_pair(index); + params->pair_hold = 0; + break; + } + case ASRC_Q_INBUF: + { + struct asrc_buffer buf; + struct dma_block *block; + mxc_dma_requestbuf_t dma_request; + unsigned long lock_flags; + if (copy_from_user + (&buf, (void __user *)arg, + sizeof(struct asrc_buffer))) { + err = -EFAULT; + break; + } + spin_lock_irqsave(&input_int_lock, lock_flags); + params->input_dma[buf.index].index = buf.index; + params->input_dma[buf.index].length = buf.length; + list_add_tail(¶ms->input_dma[buf.index]. + queue, ¶ms->input_queue); + if (params->asrc_active == 0 + || params->input_queue_empty == 0) { + block = + list_entry(params->input_queue.next, + struct dma_block, queue); + dma_request.src_addr = + (dma_addr_t) block->dma_paddr; + dma_request.dst_addr = + (ASRC_BASE_ADDR + ASRC_ASRDIA_REG + + (params->index << 3)); + dma_request.num_of_bytes = block->length; + mxc_dma_config(params-> + input_dma_channel, + &dma_request, 1, + MXC_DMA_MODE_WRITE); + params->input_queue_empty++; + list_del(params->input_queue.next); + list_add_tail(&block->queue, + ¶ms->input_done_queue); + } + + spin_unlock_irqrestore(&input_int_lock, lock_flags); + break; + } + case ASRC_DQ_INBUF:{ + struct asrc_buffer buf; + struct dma_block *block; + unsigned long lock_flags; + if (copy_from_user + (&buf, (void __user *)arg, + sizeof(struct asrc_buffer))) { + err = -EFAULT; + break; + } + /* if ASRC is inactive, nonsense to DQ buffer */ + if (params->asrc_active == 0) { + err = -EFAULT; + buf.buf_valid = ASRC_BUF_NA; + if (copy_to_user + ((void __user *)arg, &buf, + sizeof(struct asrc_buffer))) + err = -EFAULT; + break; + } + + if (!wait_event_interruptible_timeout + (params->input_wait_queue, + params->input_counter != 0, 10 * HZ)) { + pr_info + ("ASRC_DQ_INBUF timeout counter %x\n", + params->input_counter); + err = -ETIME; + break; + } else if (signal_pending(current)) { + pr_info("ASRC_DQ_INBUF interrupt received\n"); + err = -ERESTARTSYS; + break; + } + spin_lock_irqsave(&input_int_lock, lock_flags); + params->input_counter--; + block = + list_entry(params->input_done_queue.next, + struct dma_block, queue); + list_del(params->input_done_queue.next); + spin_unlock_irqrestore(&input_int_lock, lock_flags); + buf.index = block->index; + buf.length = block->length; + buf.buf_valid = ASRC_BUF_AV; + if (copy_to_user + ((void __user *)arg, &buf, + sizeof(struct asrc_buffer))) + err = -EFAULT; + + break; + } + case ASRC_Q_OUTBUF:{ + struct asrc_buffer buf; + struct dma_block *block; + mxc_dma_requestbuf_t dma_request; + unsigned long lock_flags; + if (copy_from_user + (&buf, (void __user *)arg, + sizeof(struct asrc_buffer))) { + err = -EFAULT; + break; + } + spin_lock_irqsave(&output_int_lock, lock_flags); + params->output_dma[buf.index].index = buf.index; + params->output_dma[buf.index].length = buf.length; + list_add_tail(¶ms->output_dma[buf.index]. + queue, ¶ms->output_queue); + if (params->asrc_active == 0 + || params->output_queue_empty == 0) { + block = + list_entry(params->output_queue. + next, struct dma_block, queue); + dma_request.src_addr = + (ASRC_BASE_ADDR + ASRC_ASRDOA_REG + + (params->index << 3)); + dma_request.dst_addr = + (dma_addr_t) block->dma_paddr; + dma_request.num_of_bytes = block->length; + mxc_dma_config(params-> + output_dma_channel, + &dma_request, 1, + MXC_DMA_MODE_READ); + list_del(params->output_queue.next); + list_add_tail(&block->queue, + ¶ms->output_done_queue); + params->output_queue_empty++; + } + + spin_unlock_irqrestore(&output_int_lock, lock_flags); + break; + } + case ASRC_DQ_OUTBUF:{ + struct asrc_buffer buf; + struct dma_block *block; + unsigned long lock_flags; + if (copy_from_user + (&buf, (void __user *)arg, + sizeof(struct asrc_buffer))) { + err = -EFAULT; + break; + } + /* if ASRC is inactive, nonsense to DQ buffer */ + if (params->asrc_active == 0) { + buf.buf_valid = ASRC_BUF_NA; + err = -EFAULT; + if (copy_to_user + ((void __user *)arg, &buf, + sizeof(struct asrc_buffer))) + err = -EFAULT; + break; + } + + if (!wait_event_interruptible_timeout + (params->output_wait_queue, + params->output_counter != 0, 10 * HZ)) { + pr_info + ("ASRC_DQ_OUTBUF timeout counter %x\n", + params->output_counter); + err = -ETIME; + break; + } else if (signal_pending(current)) { + pr_info("ASRC_DQ_INBUF interrupt received\n"); + err = -ERESTARTSYS; + break; + } + spin_lock_irqsave(&output_int_lock, lock_flags); + params->output_counter--; + block = + list_entry(params->output_done_queue.next, + struct dma_block, queue); + list_del(params->output_done_queue.next); + spin_unlock_irqrestore(&output_int_lock, lock_flags); + buf.index = block->index; + buf.length = block->length; + buf.buf_valid = ASRC_BUF_AV; + if (copy_to_user + ((void __user *)arg, &buf, + sizeof(struct asrc_buffer))) + err = -EFAULT; + + break; + } + case ASRC_START_CONV:{ + enum asrc_pair_index index; + unsigned long lock_flags; + if (copy_from_user + (&index, (void __user *)arg, + sizeof(enum asrc_pair_index))) { + err = -EFAULT; + break; + } + + spin_lock_irqsave(&input_int_lock, lock_flags); + if (params->input_queue_empty == 0) { + err = -EFAULT; + pr_info + ("ASRC_START_CONV - no block available\n"); + break; + } + spin_unlock_irqrestore(&input_int_lock, lock_flags); + params->asrc_active = 1; + + asrc_start_conv(index); + mxc_dma_enable(params->input_dma_channel); + mxc_dma_enable(params->output_dma_channel); + break; + } + case ASRC_STOP_CONV:{ + enum asrc_pair_index index; + if (copy_from_user + (&index, (void __user *)arg, + sizeof(enum asrc_pair_index))) { + err = -EFAULT; + break; + } + mxc_dma_disable(params->input_dma_channel); + mxc_dma_disable(params->output_dma_channel); + asrc_stop_conv(index); + params->asrc_active = 0; + break; + } + case ASRC_STATUS:{ + struct asrc_status_flags flags; + if (copy_from_user + (&flags, (void __user *)arg, + sizeof(struct asrc_status_flags))) { + err = -EFAULT; + break; + } + asrc_get_status(&flags); + if (copy_to_user + ((void __user *)arg, &flags, + sizeof(struct asrc_status_flags))) + err = -EFAULT; + break; + } + case ASRC_FLUSH:{ + /* flush input dma buffer */ + unsigned long lock_flags; + mxc_dma_device_t rx_id, tx_id; + char *rx_name, *tx_name; + int channel = -1; + spin_lock_irqsave(&input_int_lock, lock_flags); + while (!list_empty(¶ms->input_queue)) + list_del(params->input_queue.next); + while (!list_empty(¶ms->input_done_queue)) + list_del(params->input_done_queue.next); + params->input_counter = 0; + params->input_queue_empty = 0; + spin_unlock_irqrestore(&input_int_lock, lock_flags); + + /* flush output dma buffer */ + spin_lock_irqsave(&output_int_lock, lock_flags); + while (!list_empty(¶ms->output_queue)) + list_del(params->output_queue.next); + while (!list_empty(¶ms->output_done_queue)) + list_del(params->output_done_queue.next); + params->output_counter = 0; + params->output_queue_empty = 0; + spin_unlock_irqrestore(&output_int_lock, lock_flags); + + /* release DMA and request again */ + mxc_dma_free(params->input_dma_channel); + mxc_dma_free(params->output_dma_channel); + if (params->index == ASRC_PAIR_A) { + rx_id = MXC_DMA_ASRC_A_RX; + tx_id = MXC_DMA_ASRC_A_TX; + rx_name = asrc_pair_id[0]; + tx_name = asrc_pair_id[1]; + } else if (params->index == ASRC_PAIR_B) { + rx_id = MXC_DMA_ASRC_B_RX; + tx_id = MXC_DMA_ASRC_B_TX; + rx_name = asrc_pair_id[2]; + tx_name = asrc_pair_id[3]; + } else { + rx_id = MXC_DMA_ASRC_C_RX; + tx_id = MXC_DMA_ASRC_C_TX; + rx_name = asrc_pair_id[4]; + tx_name = asrc_pair_id[5]; + } + channel = mxc_dma_request(rx_id, rx_name); + params->input_dma_channel = channel; + err = mxc_dma_callback_set(channel, (mxc_dma_callback_t) + asrc_input_dma_callback, + (void *)params); + channel = mxc_dma_request(tx_id, tx_name); + params->output_dma_channel = channel; + err = mxc_dma_callback_set(channel, (mxc_dma_callback_t) + asrc_output_dma_callback, + (void *)params); + + break; + } + default: + break; + } + + up(¶ms->busy_lock); + return err; +} + +/*! + * asrc interface - open function + * + * @param inode structure inode * + * + * @param file structure file * + * + * @return status 0 success, ENODEV invalid device instance, + * ENOBUFS failed to allocate buffer, ERESTARTSYS interrupted by user + */ +static int mxc_asrc_open(struct inode *inode, struct file *file) +{ + int err = 0; + struct asrc_pair_params *pair_params; + if (signal_pending(current)) + return -EINTR; + pair_params = kzalloc(sizeof(struct asrc_pair_params), GFP_KERNEL); + if (pair_params == NULL) { + pr_debug("Failed to allocate pair_params\n"); + err = -ENOBUFS; + } + + init_MUTEX(&pair_params->busy_lock); + file->private_data = pair_params; + return err; +} + +/*! + * asrc interface - close function + * + * @param inode struct inode * + * @param file structure file * + * + * @return status 0 Success, EINTR busy lock error, ENOBUFS remap_page error + */ +static int mxc_asrc_close(struct inode *inode, struct file *file) +{ + struct asrc_pair_params *pair_params; + pair_params = file->private_data; + if (pair_params->asrc_active == 1) { + mxc_dma_disable(pair_params->input_dma_channel); + mxc_dma_disable(pair_params->output_dma_channel); + asrc_stop_conv(pair_params->index); + wake_up_interruptible(&pair_params->input_wait_queue); + wake_up_interruptible(&pair_params->output_wait_queue); + } + if (pair_params->pair_hold == 1) { + mxc_dma_free(pair_params->input_dma_channel); + mxc_dma_free(pair_params->output_dma_channel); + mxc_free_dma_buf(pair_params); + asrc_release_pair(pair_params->index); + } + kfree(pair_params); + file->private_data = NULL; + return 0; +} + +/*! + * asrc interface - mmap function + * + * @param file structure file * + * + * @param vma structure vm_area_struct * + * + * @return status 0 Success, EINTR busy lock error, ENOBUFS remap_page error + */ +static int mxc_asrc_mmap(struct file *file, struct vm_area_struct *vma) +{ + unsigned long size; + int res = 0; + size = vma->vm_end - vma->vm_start; + vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); + if (remap_pfn_range(vma, vma->vm_start, + vma->vm_pgoff, size, vma->vm_page_prot)) + return -ENOBUFS; + + vma->vm_flags &= ~VM_IO; + return res; +} + +static struct file_operations asrc_fops = { + .owner = THIS_MODULE, + .ioctl = asrc_ioctl, + .mmap = mxc_asrc_mmap, + .open = mxc_asrc_open, + .release = mxc_asrc_close, +}; + +static int asrc_read_proc_attr(char *page, char **start, off_t off, + int count, int *eof, void *data) +{ + unsigned long reg; + int len = 0; + reg = __raw_readl(asrc_vrt_base_addr + ASRC_ASRCNCR_REG); + + len += sprintf(page, "ANCA: %d\n", + (int)(reg & + (0xFFFFFFFF >> + (32 - mxc_asrc_data->channel_bits)))); + len += + sprintf(page + len, "ANCB: %d\n", + (int)((reg >> mxc_asrc_data-> + channel_bits) & (0xFFFFFFFF >> (32 - + mxc_asrc_data-> + channel_bits)))); + len += + sprintf(page + len, "ANCC: %d\n", + (int)((reg >> (mxc_asrc_data->channel_bits * 2)) & + (0xFFFFFFFF >> (32 - mxc_asrc_data->channel_bits)))); + + if (off > len) + return 0; + + *eof = (len <= count) ? 1 : 0; + *start = page + off; + + return min(count, len - (int)off); +} + +static int asrc_write_proc_attr(struct file *file, const char *buffer, + unsigned long count, void *data) +{ + char buf[50]; + unsigned long reg; + int na, nb, nc; + int total; + if (count > 48) + return -EINVAL; + if (copy_from_user(buf, buffer, count)) { + pr_debug("Attr proc write, Failed to copy buffer from user\n"); + return -EFAULT; + } + + reg = __raw_readl(asrc_vrt_base_addr + ASRC_ASRCNCR_REG); + sscanf(buf, "ANCA: %d\nANCB: %d\nANCC: %d", &na, &nb, &nc); + if (mxc_asrc_data->channel_bits > 3) + total = 10; + else + total = 5; + if ((na + nb + nc) != total) { + pr_info("Wrong ASRCNR settings\n"); + return -EFAULT; + } + reg = na | (nb << mxc_asrc_data-> + channel_bits) | (nc << (mxc_asrc_data->channel_bits * 2)); + + __raw_writel(reg, asrc_vrt_base_addr + ASRC_ASRCNCR_REG); + + return count; +} + +static void asrc_proc_create(void) +{ + struct proc_dir_entry *proc_attr; + proc_asrc = proc_mkdir(ASRC_PROC_PATH, NULL); + if (proc_asrc) { + proc_attr = create_proc_entry("ChSettings", + S_IFREG | S_IRUGO | + S_IWUSR, proc_asrc); + if (proc_attr) { + proc_attr->read_proc = asrc_read_proc_attr; + proc_attr->write_proc = asrc_write_proc_attr; + proc_attr->size = 48; + proc_attr->uid = proc_attr->gid = 0; + } else { + remove_proc_entry(ASRC_PROC_PATH, NULL); + pr_info("Failed to create proc attribute entry \n"); + } + } else { + pr_info("ASRC: Failed to create proc entry %s\n", + ASRC_PROC_PATH); + } +} + +/*! + * Entry point for the asrc device + * + * @param pdev Pionter to the registered platform device + * @return Error code indicating success or failure + */ +static int mxc_asrc_probe(struct platform_device *pdev) +{ + int err = 0; + struct resource *res; + struct device *temp_class; + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!res) + return -ENOENT; + + g_asrc_data = kzalloc(sizeof(struct asrc_data), GFP_KERNEL); + + if (g_asrc_data == NULL) { + pr_info("Failed to allocate g_asrc_data\n"); + return -ENOMEM; + } + + g_asrc_data->asrc_pair[0].chn_max = 2; + g_asrc_data->asrc_pair[1].chn_max = 2; + g_asrc_data->asrc_pair[2].chn_max = 6; + g_asrc_data->asrc_pair[0].overload_error = 0; + g_asrc_data->asrc_pair[1].overload_error = 0; + g_asrc_data->asrc_pair[2].overload_error = 0; + + asrc_major = register_chrdev(asrc_major, "mxc_asrc", &asrc_fops); + if (asrc_major < 0) { + pr_info("Unable to register asrc device\n"); + err = -EBUSY; + goto error; + } + + asrc_class = class_create(THIS_MODULE, "mxc_asrc"); + if (IS_ERR(asrc_class)) { + err = PTR_ERR(asrc_class); + goto err_out_chrdev; + } + + temp_class = device_create(asrc_class, NULL, MKDEV(asrc_major, 0), + NULL, "mxc_asrc"); + if (IS_ERR(temp_class)) { + err = PTR_ERR(temp_class); + goto err_out_class; + } + + asrc_vrt_base_addr = + (unsigned long)ioremap(res->start, res->end - res->start + 1); + + mxc_asrc_data = + (struct mxc_asrc_platform_data *)pdev->dev.platform_data; + clk_enable(mxc_asrc_data->asrc_core_clk); + + asrc_proc_create(); + err = mxc_init_asrc(); + if (err < 0) + goto err_out_class; + + goto out; + + err_out_class: + clk_disable(mxc_asrc_data->asrc_core_clk); + device_destroy(asrc_class, MKDEV(asrc_major, 0)); + class_destroy(asrc_class); + err_out_chrdev: + unregister_chrdev(asrc_major, "mxc_asrc"); + error: + kfree(g_asrc_data); + out: + pr_info("mxc_asrc registered\n"); + return err; +} + +/*! + * Exit asrc device + * + * @param pdev Pionter to the registered platform device + * @return Error code indicating success or failure + */ +static int mxc_asrc_remove(struct platform_device *pdev) +{ + free_irq(MXC_INT_ASRC, NULL); + kfree(g_asrc_data); + clk_disable(mxc_asrc_data->asrc_core_clk); + mxc_asrc_data = NULL; + iounmap((unsigned long __iomem *)asrc_vrt_base_addr); + remove_proc_entry("ChSettings", proc_asrc); + remove_proc_entry(ASRC_PROC_PATH, NULL); + device_destroy(asrc_class, MKDEV(asrc_major, 0)); + class_destroy(asrc_class); + unregister_chrdev(asrc_major, "mxc_asrc"); + return 0; +} + +/*! mxc asrc driver definition + * + */ +static struct platform_driver mxc_asrc_driver = { + .driver = { + .name = "mxc_asrc", + }, + .probe = mxc_asrc_probe, + .remove = mxc_asrc_remove, +}; + +/*! + * Register asrc driver + * + */ +static __init int asrc_init(void) +{ + int ret; + ret = platform_driver_register(&mxc_asrc_driver); + return ret; +} + +/*! + * Exit and free the asrc data + * + */ static void __exit asrc_exit(void) +{ + platform_driver_unregister(&mxc_asrc_driver); + return; +} + +module_init(asrc_init); +module_exit(asrc_exit); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("Asynchronous Sample Rate Converter"); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/bt/Kconfig b/drivers/mxc/bt/Kconfig new file mode 100644 index 000000000000..9dbfbe57a14f --- /dev/null +++ b/drivers/mxc/bt/Kconfig @@ -0,0 +1,13 @@ +# +# Bluetooth configuration +# + +menu "MXC Bluetooth support" + +config MXC_BLUETOOTH + tristate "MXC Bluetooth support" + depends on MACH_MX31_3DS || MACH_MX35_3DS || MACH_MX37_3DS || MACH_MX51_3DS + ---help--- + Say Y to get the third party Bluetooth service. + +endmenu diff --git a/drivers/mxc/bt/Makefile b/drivers/mxc/bt/Makefile new file mode 100644 index 000000000000..91bc4cff380e --- /dev/null +++ b/drivers/mxc/bt/Makefile @@ -0,0 +1,4 @@ +# +# Makefile for the kernel Bluetooth power-on/reset +# +obj-$(CONFIG_MXC_BLUETOOTH) += mxc_bt.o diff --git a/drivers/mxc/bt/mxc_bt.c b/drivers/mxc/bt/mxc_bt.c new file mode 100644 index 000000000000..4ac37d06f2e9 --- /dev/null +++ b/drivers/mxc/bt/mxc_bt.c @@ -0,0 +1,128 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mxc_bt.c + * + * @brief MXC Thirty party Bluetooth + * + */ + +#include +#include +#include +#include +#include +#include + +static struct regulator *bt_vdd; +static struct regulator *bt_vdd_parent; +static struct regulator *bt_vusb; +static struct regulator *bt_vusb_parent; + +/*! + * This function poweron the bluetooth hardware module + * + * @param pdev Pointer to the platform device + * @return 0 on success, -1 otherwise. + */ +static int mxc_bt_probe(struct platform_device *pdev) +{ + struct mxc_bt_platform_data *platform_data; + platform_data = (struct mxc_bt_platform_data *)pdev->dev.platform_data; + if (platform_data->bt_vdd) { + bt_vdd = regulator_get(&pdev->dev, platform_data->bt_vdd); + regulator_enable(bt_vdd); + } + if (platform_data->bt_vdd_parent) { + bt_vdd_parent = + regulator_get(&pdev->dev, platform_data->bt_vdd_parent); + regulator_enable(bt_vdd_parent); + } + if (platform_data->bt_vusb) { + bt_vusb = regulator_get(&pdev->dev, platform_data->bt_vusb); + regulator_enable(bt_vusb); + } + if (platform_data->bt_vusb_parent) { + bt_vusb_parent = + regulator_get(&pdev->dev, platform_data->bt_vusb_parent); + regulator_enable(bt_vusb_parent); + } + + if (platform_data->bt_reset != NULL) + platform_data->bt_reset(); + return 0; + +} + +/*! + * This function poweroff the bluetooth hardware module + * + * @param pdev Pointer to the platform device + * @return 0 on success, -1 otherwise. + */ +static int mxc_bt_remove(struct platform_device *pdev) +{ + struct mxc_bt_platform_data *platform_data; + platform_data = (struct mxc_bt_platform_data *)pdev->dev.platform_data; + if (bt_vdd) { + regulator_disable(bt_vdd); + regulator_put(bt_vdd); + } + if (bt_vdd_parent) { + regulator_disable(bt_vdd_parent); + regulator_put(bt_vdd_parent); + } + if (bt_vusb) { + regulator_disable(bt_vusb); + regulator_put(bt_vusb); + } + if (bt_vusb_parent) { + regulator_disable(bt_vusb_parent); + regulator_put(bt_vusb_parent); + } + return 0; + +} + +static struct platform_driver bluetooth_driver = { + .driver = { + .name = "mxc_bt", + }, + .probe = mxc_bt_probe, + .remove = mxc_bt_remove, +}; + +/*! + * Register bluetooth driver module + * + */ +static __init int bluetooth_init(void) +{ + return platform_driver_register(&bluetooth_driver); +} + +/*! + * Exit and free the bluetooth module + * + */ +static void __exit bluetooth_exit(void) +{ + platform_driver_unregister(&bluetooth_driver); +} + +module_init(bluetooth_init); +module_exit(bluetooth_exit); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MXC Thirty party Bluetooth"); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/dam/Kconfig b/drivers/mxc/dam/Kconfig new file mode 100644 index 000000000000..7b4bee92f648 --- /dev/null +++ b/drivers/mxc/dam/Kconfig @@ -0,0 +1,13 @@ +# +# DAM API configuration +# + +menu "MXC Digital Audio Multiplexer support" + +config MXC_DAM + tristate "DAM support" + depends on ARCH_MXC + ---help--- + Say Y to get the Digital Audio Multiplexer services API available on MXC platform. + +endmenu diff --git a/drivers/mxc/dam/Makefile b/drivers/mxc/dam/Makefile new file mode 100644 index 000000000000..b5afdc143dfa --- /dev/null +++ b/drivers/mxc/dam/Makefile @@ -0,0 +1,9 @@ +# +# Makefile for the kernel Digital Audio MUX (DAM) device driver. +# + +ifeq ($(CONFIG_ARCH_MX27),y) + obj-$(CONFIG_MXC_DAM) += dam_v1.o +else + obj-$(CONFIG_MXC_DAM) += dam.o +endif diff --git a/drivers/mxc/dam/dam.c b/drivers/mxc/dam/dam.c new file mode 100644 index 000000000000..76ce04e7f171 --- /dev/null +++ b/drivers/mxc/dam/dam.c @@ -0,0 +1,427 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file dam.c + * @brief This is the brief documentation for this dam.c file. + * + * This file contains the implementation of the DAM driver main services + * + * @ingroup DAM + */ + +#include +#include +#include +#include +#include +#include "dam.h" + +/*! + * This include to define bool type, false and true definitions. + */ +#include + +#define ModifyRegister32(a, b, c) (c = (((c)&(~(a))) | (b))) + +#define DAM_VIRT_BASE_ADDR IO_ADDRESS(AUDMUX_BASE_ADDR) + +#ifndef _reg_DAM_PTCR1 +#define _reg_DAM_PTCR1 (*((volatile unsigned long *) \ + (DAM_VIRT_BASE_ADDR + 0x00))) +#endif + +#ifndef _reg_DAM_PDCR1 +#define _reg_DAM_PDCR1 (*((volatile unsigned long *) \ + (DAM_VIRT_BASE_ADDR + 0x04))) +#endif + +#ifndef _reg_DAM_PTCR2 +#define _reg_DAM_PTCR2 (*((volatile unsigned long *) \ + (DAM_VIRT_BASE_ADDR + 0x08))) +#endif + +#ifndef _reg_DAM_PDCR2 +#define _reg_DAM_PDCR2 (*((volatile unsigned long *) \ + (DAM_VIRT_BASE_ADDR + 0x0C))) +#endif + +#ifndef _reg_DAM_PTCR3 +#define _reg_DAM_PTCR3 (*((volatile unsigned long *) \ + (DAM_VIRT_BASE_ADDR + 0x10))) +#endif + +#ifndef _reg_DAM_PDCR3 +#define _reg_DAM_PDCR3 (*((volatile unsigned long *) \ + (DAM_VIRT_BASE_ADDR + 0x14))) +#endif + +#ifndef _reg_DAM_PTCR4 +#define _reg_DAM_PTCR4 (*((volatile unsigned long *) \ + (DAM_VIRT_BASE_ADDR + 0x18))) +#endif + +#ifndef _reg_DAM_PDCR4 +#define _reg_DAM_PDCR4 (*((volatile unsigned long *) \ + (DAM_VIRT_BASE_ADDR + 0x1C))) +#endif + +#ifndef _reg_DAM_PTCR5 +#define _reg_DAM_PTCR5 (*((volatile unsigned long *) \ + (DAM_VIRT_BASE_ADDR + 0x20))) +#endif + +#ifndef _reg_DAM_PDCR5 +#define _reg_DAM_PDCR5 (*((volatile unsigned long *) \ + (DAM_VIRT_BASE_ADDR + 0x24))) +#endif + +#ifndef _reg_DAM_PTCR6 +#define _reg_DAM_PTCR6 (*((volatile unsigned long *) \ + (DAM_VIRT_BASE_ADDR + 0x28))) +#endif + +#ifndef _reg_DAM_PDCR6 +#define _reg_DAM_PDCR6 (*((volatile unsigned long *) \ + (DAM_VIRT_BASE_ADDR + 0x2C))) +#endif + +#ifndef _reg_DAM_PTCR7 +#define _reg_DAM_PTCR7 (*((volatile unsigned long *) \ + (DAM_VIRT_BASE_ADDR + 0x30))) +#endif + +#ifndef _reg_DAM_PDCR7 +#define _reg_DAM_PDCR7 (*((volatile unsigned long *) \ + (DAM_VIRT_BASE_ADDR + 0x34))) +#endif + +#ifndef _reg_DAM_CNMCR +#define _reg_DAM_CNMCR (*((volatile unsigned long *) \ + (DAM_VIRT_BASE_ADDR + 0x38))) +#endif + +#ifndef _reg_DAM_PTCR +#define _reg_DAM_PTCR(a) (*((volatile unsigned long *) \ + (DAM_VIRT_BASE_ADDR + a*8))) +#endif + +#ifndef _reg_DAM_PDCR +#define _reg_DAM_PDCR(a) (*((volatile unsigned long *) \ + (DAM_VIRT_BASE_ADDR + 4 + a*8))) +#endif + +/*! + * PTCR Registers bit shift definitions + */ +#define dam_synchronous_mode_shift 11 +#define dam_receive_clock_select_shift 12 +#define dam_receive_clock_direction_shift 16 +#define dam_receive_frame_sync_select_shift 17 +#define dam_receive_frame_sync_direction_shift 21 +#define dam_transmit_clock_select_shift 22 +#define dam_transmit_clock_direction_shift 26 +#define dam_transmit_frame_sync_select_shift 27 +#define dam_transmit_frame_sync_direction_shift 31 +#define dam_selection_mask 0xF + +/*! + * HPDCR Register bit shift definitions + */ +#define dam_internal_network_mode_shift 0 +#define dam_mode_shift 8 +#define dam_transmit_receive_switch_shift 12 +#define dam_receive_data_select_shift 13 + +/*! + * HPDCR Register bit masq definitions + */ +#define dam_mode_masq 0x03 +#define dam_internal_network_mode_mask 0xFF + +/*! + * CNMCR Register bit shift definitions + */ +#define dam_ce_bus_port_cntlow_shift 0 +#define dam_ce_bus_port_cnthigh_shift 8 +#define dam_ce_bus_port_clkpol_shift 16 +#define dam_ce_bus_port_fspol_shift 17 +#define dam_ce_bus_port_enable_shift 18 + +#define DAM_NAME "dam" + +EXPORT_SYMBOL(dam_select_mode); +EXPORT_SYMBOL(dam_select_RxClk_direction); +EXPORT_SYMBOL(dam_select_RxClk_source); +EXPORT_SYMBOL(dam_select_RxD_source); +EXPORT_SYMBOL(dam_select_RxFS_direction); +EXPORT_SYMBOL(dam_select_RxFS_source); +EXPORT_SYMBOL(dam_select_TxClk_direction); +EXPORT_SYMBOL(dam_select_TxClk_source); +EXPORT_SYMBOL(dam_select_TxFS_direction); +EXPORT_SYMBOL(dam_select_TxFS_source); +EXPORT_SYMBOL(dam_set_internal_network_mode_mask); +EXPORT_SYMBOL(dam_set_synchronous); +EXPORT_SYMBOL(dam_switch_Tx_Rx); +EXPORT_SYMBOL(dam_reset_register); + +/*! + * This function selects the operation mode of the port. + * + * @param port the DAM port to configure + * @param the_mode the operation mode of the port + * + * @return This function returns the result of the operation + * (0 if successful, -1 otherwise). + */ +int dam_select_mode(dam_port port, dam_mode the_mode) +{ + int result; + result = 0; + + ModifyRegister32(dam_mode_masq << dam_mode_shift, + the_mode << dam_mode_shift, _reg_DAM_PDCR(port)); + + return result; +} + +/*! + * This function controls Receive clock signal direction for the port. + * + * @param port the DAM port to configure + * @param direction the Rx clock signal direction + */ +void dam_select_RxClk_direction(dam_port port, signal_direction direction) +{ + ModifyRegister32(1 << dam_receive_clock_direction_shift, + direction << dam_receive_clock_direction_shift, + _reg_DAM_PTCR(port)); +} + +/*! + * This function controls Receive clock signal source for the port. + * + * @param p_config the DAM port to configure + * @param from_RxClk the signal comes from RxClk or TxClk of + * the source port + * @param p_source the source port + */ +void dam_select_RxClk_source(dam_port p_config, + bool from_RxClk, dam_port p_source) +{ + ModifyRegister32(dam_selection_mask << dam_receive_clock_select_shift, + ((from_RxClk << 3) | p_source) << + dam_receive_clock_select_shift, + _reg_DAM_PTCR(p_config)); +} + +/*! + * This function selects the source port for the RxD data. + * + * @param p_config the DAM port to configure + * @param p_source the source port + */ +void dam_select_RxD_source(dam_port p_config, dam_port p_source) +{ + ModifyRegister32(dam_selection_mask << dam_receive_data_select_shift, + p_source << dam_receive_data_select_shift, + _reg_DAM_PDCR(p_config)); +} + +/*! + * This function controls Receive Frame Sync signal direction for the port. + * + * @param port the DAM port to configure + * @param direction the Rx Frame Sync signal direction + */ +void dam_select_RxFS_direction(dam_port port, signal_direction direction) +{ + ModifyRegister32(1 << dam_receive_frame_sync_direction_shift, + direction << dam_receive_frame_sync_direction_shift, + _reg_DAM_PTCR(port)); +} + +/*! + * This function controls Receive Frame Sync signal source for the port. + * + * @param p_config the DAM port to configure + * @param from_RxFS the signal comes from RxFS or TxFS of + * the source port + * @param p_source the source port + */ +void dam_select_RxFS_source(dam_port p_config, + bool from_RxFS, dam_port p_source) +{ + ModifyRegister32(dam_selection_mask << + dam_receive_frame_sync_select_shift, + ((from_RxFS << 3) | p_source) << + dam_receive_frame_sync_select_shift, + _reg_DAM_PTCR(p_config)); +} + +/*! + * This function controls Transmit clock signal direction for the port. + * + * @param port the DAM port to configure + * @param direction the Tx clock signal direction + */ +void dam_select_TxClk_direction(dam_port port, signal_direction direction) +{ + ModifyRegister32(1 << dam_transmit_clock_direction_shift, + direction << dam_transmit_clock_direction_shift, + _reg_DAM_PTCR(port)); +} + +/*! + * This function controls Transmit clock signal source for the port. + * + * @param p_config the DAM port to configure + * @param from_RxClk the signal comes from RxClk or TxClk of + * the source port + * @param p_source the source port + */ +void dam_select_TxClk_source(dam_port p_config, + bool from_RxClk, dam_port p_source) +{ + ModifyRegister32(dam_selection_mask << dam_transmit_clock_select_shift, + ((from_RxClk << 3) | p_source) << + dam_transmit_clock_select_shift, + _reg_DAM_PTCR(p_config)); +} + +/*! + * This function controls Transmit Frame Sync signal direction for the port. + * + * @param port the DAM port to configure + * @param direction the Tx Frame Sync signal direction + */ +void dam_select_TxFS_direction(dam_port port, signal_direction direction) +{ + ModifyRegister32(1 << dam_transmit_frame_sync_direction_shift, + direction << dam_transmit_frame_sync_direction_shift, + _reg_DAM_PTCR(port)); +} + +/*! + * This function controls Transmit Frame Sync signal source for the port. + * + * @param p_config the DAM port to configure + * @param from_RxFS the signal comes from RxFS or TxFS of + * the source port + * @param p_source the source port + */ +void dam_select_TxFS_source(dam_port p_config, + bool from_RxFS, dam_port p_source) +{ + ModifyRegister32(dam_selection_mask << + dam_transmit_frame_sync_select_shift, + ((from_RxFS << 3) | p_source) << + dam_transmit_frame_sync_select_shift, + _reg_DAM_PTCR(p_config)); +} + +/*! + * This function sets a bit mask that selects the port from which of the RxD + * signals are to be ANDed together for internal network mode. + * Bit 6 represents RxD from Port7 and bit0 represents RxD from Port1. + * 1 excludes RxDn from ANDing. 0 includes RxDn for ANDing. + * + * @param port the DAM port to configure + * @param bit_mask the bit mask + * + * @return This function returns the result of the operation + * (0 if successful, -1 otherwise). + */ +int dam_set_internal_network_mode_mask(dam_port port, unsigned char bit_mask) +{ + int result; + result = 0; + + ModifyRegister32(dam_internal_network_mode_mask << + dam_internal_network_mode_shift, + bit_mask << dam_internal_network_mode_shift, + _reg_DAM_PDCR(port)); + + return result; +} + +/*! + * This function controls whether or not the port is in synchronous mode. + * When the synchronous mode is selected, the receive and the transmit sections + * use common clock and frame sync signals. + * When the synchronous mode is not selected, separate clock and frame sync + * signals are used for the transmit and the receive sections. + * The defaut value is the synchronous mode selected. + * + * @param port the DAM port to configure + * @param synchronous the state to assign + */ +void dam_set_synchronous(dam_port port, bool synchronous) +{ + ModifyRegister32(1 << dam_synchronous_mode_shift, + synchronous << dam_synchronous_mode_shift, + _reg_DAM_PTCR(port)); +} + +/*! + * This function swaps the transmit and receive signals from (Da-TxD, Db-RxD) + * to (Da-RxD, Db-TxD). + * This default signal configuration is Da-TxD, Db-RxD. + * + * @param port the DAM port to configure + * @param value the switch state + */ +void dam_switch_Tx_Rx(dam_port port, bool value) +{ + ModifyRegister32(1 << dam_transmit_receive_switch_shift, + value << dam_transmit_receive_switch_shift, + _reg_DAM_PDCR(port)); +} + +/*! + * This function resets the two registers of the selected port. + * + * @param port the DAM port to reset + */ +void dam_reset_register(dam_port port) +{ + ModifyRegister32(0xFFFFFFFF, 0x00000000, _reg_DAM_PTCR(port)); + ModifyRegister32(0xFFFFFFFF, 0x00000000, _reg_DAM_PDCR(port)); +} + +/*! + * This function implements the init function of the DAM device. + * This function is called when the module is loaded. + * + * @return This function returns 0. + */ +static int __init dam_init(void) +{ + return 0; +} + +/*! + * This function implements the exit function of the SPI device. + * This function is called when the module is unloaded. + * + */ +static void __exit dam_exit(void) +{ +} + +module_init(dam_init); +module_exit(dam_exit); + +MODULE_DESCRIPTION("DAM char device driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/dam/dam.h b/drivers/mxc/dam/dam.h new file mode 100644 index 000000000000..ad49c8e3c5b1 --- /dev/null +++ b/drivers/mxc/dam/dam.h @@ -0,0 +1,258 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + + /*! + * @defgroup DAM Digital Audio Multiplexer (AUDMUX) Driver + */ + + /*! + * @file dam.h + * @brief This is the brief documentation for this dam.h file. + * + * This header file contains DAM driver functions prototypes. + * + * @ingroup DAM + */ + +#ifndef __MXC_DAM_H__ +#define __MXC_DAM_H__ + +/*! + * This enumeration describes the Digital Audio Multiplexer mode. + */ +typedef enum { + + /*! + * Normal mode + */ + normal_mode = 0, + + /*! + * Internal network mode + */ + internal_network_mode = 1, + + /*! + * CE bus network mode + */ + CE_bus_network_mode = 2 +} dam_mode; + +/*! + * This enumeration describes the port. + */ +typedef enum { + + /*! + * The port 1 + */ + port_1 = 0, + + /*! + * The port 2 + */ + port_2 = 1, + + /*! + * The port 3 + */ + port_3 = 2, + + /*! + * The port 4 + */ + port_4 = 3, + + /*! + * The port 5 + */ + port_5 = 4, + + /*! + * The port 6 + */ + port_6 = 5, + + /*! + * The port 7 + */ + port_7 = 6 +} dam_port; + +/*! + * This enumeration describes the signal direction. + */ +typedef enum { + + /*! + * Signal In + */ + signal_in = 0, + + /*! + * Signal Out + */ + signal_out = 1 +} signal_direction; + +/*! + * Test purpose definition + */ +#define TEST_DAM 1 + +#ifdef TEST_DAM + +#define DAM_IOCTL 0x55 +#define DAM_CONFIG_SSI1_MC13783 _IOWR(DAM_IOCTL, 1, int) +#define DAM_CONFIG_SSI2_MC13783 _IOWR(DAM_IOCTL, 2, int) +#define DAM_CONFIG_SSI_NETWORK_MODE_MC13783 _IOWR(DAM_IOCTL, 3, int) +#endif + +/*! + * This function selects the operation mode of the port. + * + * @param port the DAM port to configure + * @param the_mode the operation mode of the port + * @return This function returns the result of the operation + * (0 if successful, -1 otherwise). + */ +int dam_select_mode(dam_port port, dam_mode the_mode); + +/*! + * This function controls Receive clock signal direction for the port. + * + * @param port the DAM port to configure + * @param direction the Rx clock signal direction + */ +void dam_select_RxClk_direction(dam_port port, signal_direction direction); + +/*! + * This function controls Receive clock signal source for the port. + * + * @param p_config the DAM port to configure + * @param from_RxClk the signal comes from RxClk or TxClk of + * the source port + * @param p_source the source port + */ +void dam_select_RxClk_source(dam_port p_config, bool from_RxClk, + dam_port p_source); + +/*! + * This function selects the source port for the RxD data. + * + * @param p_config the DAM port to configure + * @param p_source the source port + */ +void dam_select_RxD_source(dam_port p_config, dam_port p_source); + +/*! + * This function controls Receive Frame Sync signal direction for the port. + * + * @param port the DAM port to configure + * @param direction the Rx Frame Sync signal direction + */ +void dam_select_RxFS_direction(dam_port port, signal_direction direction); + +/*! + * This function controls Receive Frame Sync signal source for the port. + * + * @param p_config the DAM port to configure + * @param from_RxFS the signal comes from RxFS or TxFS of + * the source port + * @param p_source the source port + */ +void dam_select_RxFS_source(dam_port p_config, bool from_RxFS, + dam_port p_source); + +/*! + * This function controls Transmit clock signal direction for the port. + * + * @param port the DAM port to configure + * @param direction the Tx clock signal direction + */ +void dam_select_TxClk_direction(dam_port port, signal_direction direction); + +/*! + * This function controls Transmit clock signal source for the port. + * + * @param p_config the DAM port to configure + * @param from_RxClk the signal comes from RxClk or TxClk of + * the source port + * @param p_source the source port + */ +void dam_select_TxClk_source(dam_port p_config, bool from_RxClk, + dam_port p_source); + +/*! + * This function controls Transmit Frame Sync signal direction for the port. + * + * @param port the DAM port to configure + * @param direction the Tx Frame Sync signal direction + */ +void dam_select_TxFS_direction(dam_port port, signal_direction direction); + +/*! + * This function controls Transmit Frame Sync signal source for the port. + * + * @param p_config the DAM port to configure + * @param from_RxFS the signal comes from RxFS or TxFS of + * the source port + * @param p_source the source port + */ +void dam_select_TxFS_source(dam_port p_config, bool from_RxFS, + dam_port p_source); + +/*! + * This function sets a bit mask that selects the port from which of + * the RxD signals are to be ANDed together for internal network mode. + * Bit 6 represents RxD from Port7 and bit0 represents RxD from Port1. + * 1 excludes RxDn from ANDing. 0 includes RxDn for ANDing. + * + * @param port the DAM port to configure + * @param bit_mask the bit mask + * @return This function returns the result of the operation + * (0 if successful, -1 otherwise). + */ +int dam_set_internal_network_mode_mask(dam_port port, unsigned char bit_mask); + +/*! + * This function controls whether or not the port is in synchronous mode. + * When the synchronous mode is selected, the receive and the transmit sections + * use common clock and frame sync signals. + * When the synchronous mode is not selected, separate clock and frame sync + * signals are used for the transmit and the receive sections. + * The defaut value is the synchronous mode selected. + * + * @param port the DAM port to configure + * @param synchronous the state to assign + */ +void dam_set_synchronous(dam_port port, bool synchronous); + +/*! + * This function swaps the transmit and receive signals from (Da-TxD, Db-RxD) to + * (Da-RxD, Db-TxD). + * This default signal configuration is Da-TxD, Db-RxD. + * + * @param port the DAM port to configure + * @param value the switch state + */ +void dam_switch_Tx_Rx(dam_port port, bool value); + +/*! + * This function resets the two registers of the selected port. + * + * @param port the DAM port to reset + */ +void dam_reset_register(dam_port port); + +#endif diff --git a/drivers/mxc/dam/dam_v1.c b/drivers/mxc/dam/dam_v1.c new file mode 100644 index 000000000000..b6c9a6f068e5 --- /dev/null +++ b/drivers/mxc/dam/dam_v1.c @@ -0,0 +1,617 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file dam_v1.c + * @brief This is the brief documentation for this dam_v1.c file. + * + * This file contains the implementation of the DAM driver main services + * + * @ingroup DAM + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "dam.h" + +/*! + * This include to define bool type, false and true definitions. + */ +#include + +#define DAM_VIRT_BASE_ADDR IO_ADDRESS(AUDMUX_BASE_ADDR) + +#define ModifyRegister32(a, b, c) do {\ + __raw_writel(((__raw_readl(c)) & (~(a))) | (b), (c));\ +} while (0) + +#ifndef _reg_DAM_HPCR1 +#define _reg_DAM_HPCR1 (*((volatile unsigned long *) \ + (DAM_VIRT_BASE_ADDR + 0x00))) +#endif + +#ifndef _reg_DAM_HPCR2 +#define _reg_DAM_HPCR2 (*((volatile unsigned long *) \ + (DAM_VIRT_BASE_ADDR + 0x04))) +#endif + +#ifndef _reg_DAM_HPCR3 +#define _reg_DAM_HPCR3 (*((volatile unsigned long *) \ + (DAM_VIRT_BASE_ADDR + 0x08))) +#endif + +#ifndef _reg_DAM_PPCR1 +#define _reg_DAM_PPCR1 (*((volatile unsigned long *) \ + (DAM_VIRT_BASE_ADDR + 0x10))) +#endif + +#ifndef _reg_DAM_PPCR2 +#define _reg_DAM_PPCR2 (*((volatile unsigned long *) \ + (DAM_VIRT_BASE_ADDR + 0x14))) +#endif + +#ifndef _reg_DAM_PPCR3 +#define _reg_DAM_PPCR3 (*((volatile unsigned long *) \ + (DAM_VIRT_BASE_ADDR + 0x1c))) +#endif + +#ifndef _reg_DAM_HPCR +#define _reg_DAM_HPCR(a) ((volatile unsigned long *) \ + (DAM_VIRT_BASE_ADDR + (a)*4)) +#endif + +#ifndef _reg_DAM_PPCR +#define _reg_DAM_PPCR(a) ((volatile unsigned long *) \ + (DAM_VIRT_BASE_ADDR + 0x0c + (0x04 << (a-3)))) +#endif + +/*! + * HPCR/PPCR Registers bit shift definitions + */ +#define dam_transmit_frame_sync_direction_shift 31 +#define dam_transmit_clock_direction_shift 30 +#define dam_transmit_frame_sync_select_shift 26 +#define dam_transmit_clock_select_shift 26 +#define dam_receive_frame_sync_direction_shift 25 +#define dam_receive_clock_direction_shift 24 +#define dam_receive_clock_select_shift 20 +#define dam_receive_frame_sync_select_shift 20 + +#define dam_receive_data_select_shift 13 +#define dam_synchronous_mode_shift 12 + +#define dam_transmit_receive_switch_shift 10 + +#define dam_mode_shift 8 +#define dam_internal_network_mode_shift 0 + +/*! + * HPCR/PPCR Register bit masq definitions + */ +/*#define dam_selection_mask 0xF*/ +#define dam_fs_selection_mask 0xF +#define dam_clk_selection_mask 0xF +#define dam_dat_selection_mask 0x7 +/*#define dam_mode_masq 0x03*/ +#define dam_internal_network_mode_mask 0xFF + +/*! + * HPCR/PPCR Register reset value definitions + */ +#define dam_hpcr_default_value 0x00001000 +#define dam_ppcr_default_value 0x00001000 + +#define DAM_NAME "dam" +static struct class *mxc_dam_class; + +EXPORT_SYMBOL(dam_select_mode); +EXPORT_SYMBOL(dam_select_RxClk_direction); +EXPORT_SYMBOL(dam_select_RxClk_source); +EXPORT_SYMBOL(dam_select_RxD_source); +EXPORT_SYMBOL(dam_select_RxFS_direction); +EXPORT_SYMBOL(dam_select_RxFS_source); +EXPORT_SYMBOL(dam_select_TxClk_direction); +EXPORT_SYMBOL(dam_select_TxClk_source); +EXPORT_SYMBOL(dam_select_TxFS_direction); +EXPORT_SYMBOL(dam_select_TxFS_source); +EXPORT_SYMBOL(dam_set_internal_network_mode_mask); +EXPORT_SYMBOL(dam_set_synchronous); +EXPORT_SYMBOL(dam_switch_Tx_Rx); +EXPORT_SYMBOL(dam_reset_register); + +/*! + * DAM major + */ +#ifdef TEST_DAM +static int major_dam; + +typedef struct _mxc_cfg { + int reg; + int val; +} mxc_cfg; + +#endif + +/*! + * This function selects the operation mode of the port. + * + * @param port the DAM port to configure + * @param the_mode the operation mode of the port + * + * @return This function returns the result of the operation + * (0 if successful, -1 otherwise). + */ +int dam_select_mode(dam_port port, dam_mode the_mode) +{ + int result; + result = 0; + + if (port >= 3) + the_mode = normal_mode; + ModifyRegister32(1 << dam_mode_shift, + the_mode << dam_mode_shift, _reg_DAM_HPCR(port)); + + return result; +} + +/*! + * This function controls Receive clock signal direction for the port. + * + * @param port the DAM port to configure + * @param direction the Rx clock signal direction + */ +void dam_select_RxClk_direction(dam_port port, signal_direction direction) +{ + if (port < 3) { + ModifyRegister32(1 << dam_receive_clock_direction_shift, + direction << dam_receive_clock_direction_shift, + _reg_DAM_HPCR(port)); + } else { + ModifyRegister32(1 << dam_receive_clock_direction_shift, + direction << dam_receive_clock_direction_shift, + _reg_DAM_PPCR(port)); + } + return; +} + +/*! + * This function controls Receive clock signal source for the port. + * + * @param p_config the DAM port to configure + * @param from_RxClk the signal comes from RxClk or TxClk of + * the source port + * @param p_source the source port + */ +void dam_select_RxClk_source(dam_port p_config, + bool from_RxClk, dam_port p_source) +{ + if (p_config < 3) { + ModifyRegister32(dam_clk_selection_mask << + dam_receive_clock_select_shift, + ((from_RxClk << 3) | p_source) << + dam_receive_clock_select_shift, + _reg_DAM_HPCR(p_config)); + } else { + ModifyRegister32(dam_clk_selection_mask << + dam_receive_clock_select_shift, + ((from_RxClk << 3) | p_source) << + dam_receive_clock_select_shift, + _reg_DAM_PPCR(p_config)); + } + return; +} + +/*! + * This function selects the source port for the RxD data. + * + * @param p_config the DAM port to configure + * @param p_source the source port + */ +void dam_select_RxD_source(dam_port p_config, dam_port p_source) +{ + if (p_config < 3) { + ModifyRegister32(dam_dat_selection_mask << + dam_receive_data_select_shift, + p_source << dam_receive_data_select_shift, + _reg_DAM_HPCR(p_config)); + } else { + ModifyRegister32(dam_dat_selection_mask << + dam_receive_data_select_shift, + p_source << dam_receive_data_select_shift, + _reg_DAM_PPCR(p_config)); + } + return; +} + +/*! + * This function controls Receive Frame Sync signal direction for the port. + * + * @param port the DAM port to configure + * @param direction the Rx Frame Sync signal direction + */ +void dam_select_RxFS_direction(dam_port port, signal_direction direction) +{ + if (port < 3) { + ModifyRegister32(1 << dam_receive_frame_sync_direction_shift, + direction << + dam_receive_frame_sync_direction_shift, + _reg_DAM_HPCR(port)); + } else { + ModifyRegister32(1 << dam_receive_frame_sync_direction_shift, + direction << + dam_receive_frame_sync_direction_shift, + _reg_DAM_PPCR(port)); + } + return; +} + +/*! + * This function controls Receive Frame Sync signal source for the port. + * + * @param p_config the DAM port to configure + * @param from_RxFS the signal comes from RxFS or TxFS of + * the source port + * @param p_source the source port + */ +void dam_select_RxFS_source(dam_port p_config, + bool from_RxFS, dam_port p_source) +{ + if (p_config < 3) { + ModifyRegister32(dam_fs_selection_mask << + dam_receive_frame_sync_select_shift, + ((from_RxFS << 3) | p_source) << + dam_receive_frame_sync_select_shift, + _reg_DAM_HPCR(p_config)); + } else { + ModifyRegister32(dam_fs_selection_mask << + dam_receive_frame_sync_select_shift, + ((from_RxFS << 3) | p_source) << + dam_receive_frame_sync_select_shift, + _reg_DAM_PPCR(p_config)); + } + return; +} + +/*! + * This function controls Transmit clock signal direction for the port. + * + * @param port the DAM port to configure + * @param direction the Tx clock signal direction + */ +void dam_select_TxClk_direction(dam_port port, signal_direction direction) +{ + if (port < 3) { + ModifyRegister32(1 << dam_transmit_clock_direction_shift, + direction << + dam_transmit_clock_direction_shift, + _reg_DAM_HPCR(port)); + } else { + ModifyRegister32(1 << dam_transmit_clock_direction_shift, + direction << + dam_transmit_clock_direction_shift, + _reg_DAM_PPCR(port)); + } + return; +} + +/*! + * This function controls Transmit clock signal source for the port. + * + * @param p_config the DAM port to configure + * @param from_RxClk the signal comes from RxClk or TxClk of + * the source port + * @param p_source the source port + */ +void dam_select_TxClk_source(dam_port p_config, + bool from_RxClk, dam_port p_source) +{ + if (p_config < 3) { + ModifyRegister32(dam_clk_selection_mask << + dam_transmit_clock_select_shift, + ((from_RxClk << 3) | p_source) << + dam_transmit_clock_select_shift, + _reg_DAM_HPCR(p_config)); + } else { + ModifyRegister32(dam_clk_selection_mask << + dam_transmit_clock_select_shift, + ((from_RxClk << 3) | p_source) << + dam_transmit_clock_select_shift, + _reg_DAM_PPCR(p_config)); + } + return; +} + +/*! + * This function controls Transmit Frame Sync signal direction for the port. + * + * @param port the DAM port to configure + * @param direction the Tx Frame Sync signal direction + */ +void dam_select_TxFS_direction(dam_port port, signal_direction direction) +{ + if (port < 3) { + ModifyRegister32(1 << dam_transmit_frame_sync_direction_shift, + direction << + dam_transmit_frame_sync_direction_shift, + _reg_DAM_HPCR(port)); + } else { + ModifyRegister32(1 << dam_transmit_frame_sync_direction_shift, + direction << + dam_transmit_frame_sync_direction_shift, + _reg_DAM_HPCR(port)); + } + return; +} + +/*! + * This function controls Transmit Frame Sync signal source for the port. + * + * @param p_config the DAM port to configure + * @param from_RxFS the signal comes from RxFS or TxFS of + * the source port + * @param p_source the source port + */ +void dam_select_TxFS_source(dam_port p_config, + bool from_RxFS, dam_port p_source) +{ + if (p_config < 3) { + ModifyRegister32(dam_fs_selection_mask << + dam_transmit_frame_sync_select_shift, + ((from_RxFS << 3) | p_source) << + dam_transmit_frame_sync_select_shift, + _reg_DAM_HPCR(p_config)); + } else { + ModifyRegister32(dam_fs_selection_mask << + dam_transmit_frame_sync_select_shift, + ((from_RxFS << 3) | p_source) << + dam_transmit_frame_sync_select_shift, + _reg_DAM_PPCR(p_config)); + } + return; +} + +/*! + * This function sets a bit mask that selects the port from which of the RxD + * signals are to be ANDed together for internal network mode. + * Bit 6 represents RxD from Port7 and bit0 represents RxD from Port1. + * 1 excludes RxDn from ANDing. 0 includes RxDn for ANDing. + * + * @param port the DAM port to configure + * @param bit_mask the bit mask + * + * @return This function returns the result of the operation + * (0 if successful, -1 otherwise). + */ +int dam_set_internal_network_mode_mask(dam_port port, unsigned char bit_mask) +{ + int result; + result = 0; + + ModifyRegister32(dam_internal_network_mode_mask << + dam_internal_network_mode_shift, + bit_mask << dam_internal_network_mode_shift, + _reg_DAM_HPCR(port)); + return result; +} + +/*! + * This function controls whether or not the port is in synchronous mode. + * When the synchronous mode is selected, the receive and the transmit sections + * use common clock and frame sync signals. + * When the synchronous mode is not selected, separate clock and frame sync + * signals are used for the transmit and the receive sections. + * The defaut value is the synchronous mode selected. + * + * @param port the DAM port to configure + * @param synchronous the state to assign + */ +void dam_set_synchronous(dam_port port, bool synchronous) +{ + if (port < 3) { + ModifyRegister32(1 << dam_synchronous_mode_shift, + synchronous << dam_synchronous_mode_shift, + _reg_DAM_HPCR(port)); + } else { + ModifyRegister32(1 << dam_synchronous_mode_shift, + synchronous << dam_synchronous_mode_shift, + _reg_DAM_PPCR(port)); + } + return; +} + +/*! + * This function swaps the transmit and receive signals from (Da-TxD, Db-RxD) + * to (Da-RxD, Db-TxD). + * This default signal configuration is Da-TxD, Db-RxD. + * + * @param port the DAM port to configure + * @param value the switch state + */ +void dam_switch_Tx_Rx(dam_port port, bool value) +{ + if (port < 3) { + ModifyRegister32(1 << dam_transmit_receive_switch_shift, + value << dam_transmit_receive_switch_shift, + _reg_DAM_HPCR(port)); + } else { + ModifyRegister32(1 << dam_transmit_receive_switch_shift, + value << dam_transmit_receive_switch_shift, + _reg_DAM_PPCR(port)); + } + return; +} + +/*! + * This function resets the two registers of the selected port. + * + * @param port the DAM port to reset + */ +void dam_reset_register(dam_port port) +{ + if (port < 3) { + ModifyRegister32(0xFFFFFFFF, dam_hpcr_default_value, + _reg_DAM_HPCR(port)); + } else { + ModifyRegister32(0xFFFFFFFF, dam_ppcr_default_value, + _reg_DAM_PPCR(port)); + } + return; +} + +#ifdef TEST_DAM + +/*! + * This function implements IOCTL controls on a DAM device. + * + * @param inode pointer on the node + * @param file pointer on the file + * @param cmd the command + * @param arg the parameter :\n + * DAM_CONFIG_SSI1:\n + * data from port 1 to port 4, clock and FS from port 1 (SSI1)\n + * DAM_CONFIG_SSI2:\n + * data from port 2 to port 5, clock and FS from port 2 (SSI2)\n + * DAM_CONFIG_SSI_NETWORK_MODE:\n + * network mode for mix digital with data from port 1 to port4,\n + * data from port 2 to port 4, clock and FS from port 1 (SSI1) + * + * @return This function returns 0 if successful. + */ +static int dam_ioctl(struct inode *inode, + struct file *file, unsigned int cmd, unsigned long arg) +{ + return 0; +} + +/*! + * This function implements the open method on a DAM device. + * + * @param inode pointer on the node + * @param file pointer on the file + * + * @return This function returns 0. + */ +static int dam_open(struct inode *inode, struct file *file) +{ + /* DBG_PRINTK("ssi : dam_open()\n"); */ + return 0; +} + +/*! + * This function implements the release method on a DAM device. + * + * @param inode pointer on the node + * @param file pointer on the file + * + * @return This function returns 0. + */ +static int dam_free(struct inode *inode, struct file *file) +{ + /* DBG_PRINTK("ssi : dam_free()\n"); */ + return 0; +} + +/*! + * This structure defines file operations for a DAM device. + */ +static struct file_operations dam_fops = { + + /*! + * the owner + */ + .owner = THIS_MODULE, + + /*! + * the ioctl operation + */ + .ioctl = dam_ioctl, + + /*! + * the open operation + */ + .open = dam_open, + + /*! + * the release operation + */ + .release = dam_free, +}; + +#endif + +/*! + * This function implements the init function of the DAM device. + * This function is called when the module is loaded. + * + * @return This function returns 0. + */ +static int __init dam_init(void) +{ +#ifdef TEST_DAM + struct device *temp_class; + printk(KERN_DEBUG "dam : dam_init(void) \n"); + + major_dam = register_chrdev(0, DAM_NAME, &dam_fops); + if (major_dam < 0) { + printk(KERN_WARNING "Unable to get a major for dam"); + return major_dam; + } + + mxc_dam_class = class_create(THIS_MODULE, DAM_NAME); + if (IS_ERR(mxc_dam_class)) { + goto err_out; + } + + temp_class = device_create(mxc_dam_class, NULL, + MKDEV(major_dam, 0), NULL, DAM_NAME); + if (IS_ERR(temp_class)) { + goto err_out; + } +#endif + return 0; + + err_out: + printk(KERN_ERR "Error creating dam class device.\n"); + device_destroy(mxc_dam_class, MKDEV(major_dam, 0)); + class_destroy(mxc_dam_class); + unregister_chrdev(major_dam, DAM_NAME); + return -1; +} + +/*! + * This function implements the exit function of the SPI device. + * This function is called when the module is unloaded. + * + */ +static void __exit dam_exit(void) +{ +#ifdef TEST_DAM + device_destroy(mxc_dam_class, MKDEV(major_dam, 0)); + class_destroy(mxc_dam_class); + unregister_chrdev(major_dam, DAM_NAME); + printk(KERN_DEBUG "dam : successfully unloaded\n"); +#endif +} + +module_init(dam_init); +module_exit(dam_exit); + +MODULE_DESCRIPTION("DAM char device driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/gps_ioctrl/Kconfig b/drivers/mxc/gps_ioctrl/Kconfig new file mode 100644 index 000000000000..0a85d1636dd7 --- /dev/null +++ b/drivers/mxc/gps_ioctrl/Kconfig @@ -0,0 +1,13 @@ +# +# BROADCOM GPS configuration +# + +menu "Broadcom GPS ioctrl support" + +config GPS_IOCTRL + tristate "GPS ioctrl support" + depends on MACH_MX31_3DS || MACH_MX35_3DS || MACH_MX37_3DS || MACH_MX51_3DS + ---help--- + Say Y to enable Broadcom GPS ioctrl on MXC platform. + +endmenu diff --git a/drivers/mxc/gps_ioctrl/Makefile b/drivers/mxc/gps_ioctrl/Makefile new file mode 100644 index 000000000000..c52d7c9f151c --- /dev/null +++ b/drivers/mxc/gps_ioctrl/Makefile @@ -0,0 +1,5 @@ +# +# Makefile for the GPIO device driver module. +# +obj-$(CONFIG_GPS_IOCTRL) += gps_gpiodrv.o +gps_gpiodrv-objs := agpsgpiodev.o diff --git a/drivers/mxc/gps_ioctrl/agpsgpiodev.c b/drivers/mxc/gps_ioctrl/agpsgpiodev.c new file mode 100644 index 000000000000..9b2afef24075 --- /dev/null +++ b/drivers/mxc/gps_ioctrl/agpsgpiodev.c @@ -0,0 +1,332 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file agpsgpiodev.c + * + * @brief Main file for GPIO kernel module. Contains driver entry/exit + * + */ + +#include +#include /* Async notification */ +#include /* for get_user, put_user, access_ok */ +#include /* jiffies */ +#include +#include +#include +#include +#include +#include +#include +#include +#include "agpsgpiodev.h" + +extern void gpio_gps_active(void); +extern void gpio_gps_inactive(void); +extern int gpio_gps_access(int para); + +struct mxc_gps_platform_data *mxc_gps_ioctrl_data; +static int Device_Open; /* Only allow a single user of this device */ +static struct cdev mxc_gps_cdev; +static dev_t agps_gpio_dev; +static struct class *gps_class; +static struct device *gps_class_dev; + +/* Write GPIO from user space */ +static int ioctl_writegpio(int arg) +{ + + /* Bit 0 of arg identifies the GPIO pin to write: + 0 = GPS_RESET_GPIO, 1 = GPS_POWER_GPIO. + Bit 1 of arg identifies the value to write (0 or 1). */ + + /* Bit 2 should be 0 to show this access is write */ + return gpio_gps_access(arg & (~0x4)); +} + +/* Read GPIO from user space */ +static int ioctl_readgpio(int arg) +{ + /* Bit 0 of arg identifies the GPIO pin to read: + 0 = GPS_RESET_GPIO. 1 = GPS_POWER_GPIO + Bit 2 should be 1 to show this access is read */ + return gpio_gps_access(arg | 0x4); +} + +static int device_open(struct inode *inode, struct file *fp) +{ + /* We don't want to talk to two processes at the same time. */ + if (Device_Open) { + printk(KERN_DEBUG "device_open() - Returning EBUSY. \ + Device already open... \n"); + return -EBUSY; + } + Device_Open++; /* BUGBUG : Not protected! */ + try_module_get(THIS_MODULE); + + return 0; +} + +static int device_release(struct inode *inode, struct file *fp) +{ + /* We're now ready for our next caller */ + Device_Open--; + module_put(THIS_MODULE); + + return 0; +} + +static int device_ioctl(struct inode *inode, struct file *fp, + unsigned int cmd, unsigned long arg) +{ + int err = 0; + + /* Extract the type and number bitfields, and don't decode wrong cmds. + Return ENOTTY (inappropriate ioctl) before access_ok() */ + if (_IOC_TYPE(cmd) != MAJOR_NUM) { + printk(KERN_ERR + "device_ioctl() - Error! IOC_TYPE = %d. Expected %d\n", + _IOC_TYPE(cmd), MAJOR_NUM); + return -ENOTTY; + } + if (_IOC_NR(cmd) > IOCTL_MAXNUMBER) { + printk(KERN_ERR + "device_ioctl() - Error!" + "IOC_NR = %d greater than max supported(%d)\n", + _IOC_NR(cmd), IOCTL_MAXNUMBER); + return -ENOTTY; + } + + /* The direction is a bitmask, and VERIFY_WRITE catches R/W transfers. + `Type' is user-oriented, while access_ok is kernel-oriented, so the + concept of "read" and "write" is reversed. I think this is primarily + for good coding practice. You can easily do any kind of R/W access + without these checks and IOCTL code can be implemented "randomly"! */ + if (_IOC_DIR(cmd) & _IOC_READ) + err = + !access_ok(VERIFY_WRITE, (void __user *)arg, + _IOC_SIZE(cmd)); + + else if (_IOC_DIR(cmd) & _IOC_WRITE) + err = + !access_ok(VERIFY_READ, (void __user *)arg, _IOC_SIZE(cmd)); + if (err) { + printk(KERN_ERR + "device_ioctl() - Error! User arg not valid" + "for selected access (R/W/RW). Cmd %d\n", + _IOC_TYPE(cmd)); + return -EFAULT; + } + + /* Note: Read and writing data to user buffer can be done using regular + pointer stuff but we may also use get_user() or put_user() */ + + /* Cmd and arg has been verified... */ + switch (cmd) { + case IOCTL_WRITEGPIO: + return ioctl_writegpio((int)arg); + case IOCTL_READGPIO: + return ioctl_readgpio((int)arg); + default: + printk(KERN_ERR "device_ioctl() - Invalid IOCTL (0x%x)\n", cmd); + return EINVAL; + } + return 0; +} + +struct file_operations Fops = { + .ioctl = device_ioctl, + .open = device_open, + .release = device_release, +}; + +/* Initialize the module - Register the character device */ +int init_chrdev(struct device *dev) +{ + int ret, gps_major; + + ret = alloc_chrdev_region(&agps_gpio_dev, 1, 1, "agps_gpio"); + gps_major = MAJOR(agps_gpio_dev); + if (ret < 0) { + dev_err(dev, "can't get major %d\n", gps_major); + goto err3; + } + + cdev_init(&mxc_gps_cdev, &Fops); + mxc_gps_cdev.owner = THIS_MODULE; + + ret = cdev_add(&mxc_gps_cdev, agps_gpio_dev, 1); + if (ret) { + dev_err(dev, "can't add cdev\n"); + goto err2; + } + + /* create class and device for udev information */ + gps_class = class_create(THIS_MODULE, "gps"); + if (IS_ERR(gps_class)) { + dev_err(dev, "failed to create gps class\n"); + ret = -ENOMEM; + goto err1; + } + + gps_class_dev = device_create(gps_class, NULL, MKDEV(gps_major, 1), NULL, + AGPSGPIO_DEVICE_FILE_NAME); + if (IS_ERR(gps_class_dev)) { + dev_err(dev, "failed to create gps gpio class device\n"); + ret = -ENOMEM; + goto err0; + } + + return 0; +err0: + class_destroy(gps_class); +err1: + cdev_del(&mxc_gps_cdev); +err2: + unregister_chrdev_region(agps_gpio_dev, 1); +err3: + return ret; +} + +/* Cleanup - unregister the appropriate file from /proc. */ +void cleanup_chrdev(void) +{ + /* destroy gps device class */ + device_destroy(gps_class, MKDEV(MAJOR(agps_gpio_dev), 1)); + class_destroy(gps_class); + + /* Unregister the device */ + cdev_del(&mxc_gps_cdev); + unregister_chrdev_region(agps_gpio_dev, 1); +} + +/*! + * This function initializes the driver in terms of memory of the soundcard + * and some basic HW clock settings. + * + * @return 0 on success, -1 otherwise. + */ +static int __init gps_ioctrl_probe(struct platform_device *pdev) +{ + struct regulator *gps_regu; + + mxc_gps_ioctrl_data = + (struct mxc_gps_platform_data *)pdev->dev.platform_data; + + /* open GPS GPO3 1v8 for GL gps support */ + if (mxc_gps_ioctrl_data->core_reg != NULL) { + mxc_gps_ioctrl_data->gps_regu_core = + regulator_get(&(pdev->dev), mxc_gps_ioctrl_data->core_reg); + gps_regu = mxc_gps_ioctrl_data->gps_regu_core; + if (!IS_ERR_VALUE((u32)gps_regu)) { + regulator_set_voltage(gps_regu, 1800000, 1800000); + regulator_enable(gps_regu); + } else { + return -1; + } + } + /* open GPS GPO1 2v8 for GL gps support */ + if (mxc_gps_ioctrl_data->analog_reg != NULL) { + mxc_gps_ioctrl_data->gps_regu_analog = + regulator_get(&(pdev->dev), + mxc_gps_ioctrl_data->analog_reg); + gps_regu = mxc_gps_ioctrl_data->gps_regu_analog; + if (!IS_ERR_VALUE((u32)gps_regu)) { + regulator_set_voltage(gps_regu, 2800000, 2800000); + regulator_enable(gps_regu); + } else { + return -1; + } + } + gpio_gps_active(); + + /* Register character device */ + init_chrdev(&(pdev->dev)); + return 0; +} + +static int gps_ioctrl_remove(struct platform_device *pdev) +{ + struct regulator *gps_regu; + + mxc_gps_ioctrl_data = + (struct mxc_gps_platform_data *)pdev->dev.platform_data; + + /* Character device cleanup.. */ + cleanup_chrdev(); + gpio_gps_inactive(); + + /* close GPS GPO3 1v8 for GL gps */ + gps_regu = mxc_gps_ioctrl_data->gps_regu_core; + if (mxc_gps_ioctrl_data->core_reg != NULL) { + regulator_disable(gps_regu); + regulator_put(gps_regu); + } + /* close GPS GPO1 2v8 for GL gps */ + gps_regu = mxc_gps_ioctrl_data->gps_regu_analog; + if (mxc_gps_ioctrl_data->analog_reg != NULL) { + regulator_disable(gps_regu); + regulator_put(gps_regu); + } + + return 0; +} + +static int gps_ioctrl_suspend(struct platform_device *pdev, pm_message_t state) +{ + /* PowerEn toggle off */ + ioctl_writegpio(0x1); + return 0; +} + +static int gps_ioctrl_resume(struct platform_device *pdev) +{ + /* PowerEn pull up */ + ioctl_writegpio(0x3); + return 0; +} + +static struct platform_driver gps_ioctrl_driver = { + .probe = gps_ioctrl_probe, + .remove = gps_ioctrl_remove, + .suspend = gps_ioctrl_suspend, + .resume = gps_ioctrl_resume, + .driver = { + .name = "gps_ioctrl", + }, +}; + +/*! + * Entry point for GPS ioctrl module. + * + */ +static int __init gps_ioctrl_init(void) +{ + return platform_driver_register(&gps_ioctrl_driver); +} + +/*! + * unloading module. + * + */ +static void __exit gps_ioctrl_exit(void) +{ + platform_driver_unregister(&gps_ioctrl_driver); +} + +module_init(gps_ioctrl_init); +module_exit(gps_ioctrl_exit); +MODULE_DESCRIPTION("GPIO DEVICE DRIVER"); +MODULE_AUTHOR("Freescale Semiconductor"); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/gps_ioctrl/agpsgpiodev.h b/drivers/mxc/gps_ioctrl/agpsgpiodev.h new file mode 100644 index 000000000000..099608785b1b --- /dev/null +++ b/drivers/mxc/gps_ioctrl/agpsgpiodev.h @@ -0,0 +1,46 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file agpsgpiodev.h + * + * @brief head file of Simple character device interface for AGPS kernel module. + * + * @ingroup + */ + +#ifndef AGPSGPIODEV_H +#define AGPSGPIODEV_H + +#include + +#define USE_BLOCKING /* Test driver with blocking calls */ +#undef USE_FASYNC /* Test driver with async notification */ + +/* The major device number. We can't rely on dynamic registration any more + because ioctls need to know it */ +#define MAJOR_NUM 100 + +#define IOCTL_WRITEGPIO _IOWR(MAJOR_NUM, 1, char *) +#define IOCTL_READGPIO _IOR(MAJOR_NUM, 2, char *) +#define IOCTL_MAXNUMBER 2 + +/* The name of the device file */ +#define AGPSGPIO_DEVICE_FILE_NAME "agpsgpio" + +/* Exported prototypes */ +int init_chrdev(struct device *dev); +void cleanup_chrdev(void); +void wakeup(void); + +#endif diff --git a/drivers/mxc/hmp4e/Kconfig b/drivers/mxc/hmp4e/Kconfig new file mode 100644 index 000000000000..fdd7dbc041ba --- /dev/null +++ b/drivers/mxc/hmp4e/Kconfig @@ -0,0 +1,24 @@ +# +# MPEG4 Encoder kernel module configuration +# + +menu "MXC MPEG4 Encoder Kernel module support" + +config MXC_HMP4E + tristate "MPEG4 Encoder support" + depends on ARCH_MXC + depends on !ARCH_MX27 + default y + ---help--- + Say Y to get the MPEG4 Encoder kernel module available on + MXC platform. + +config MXC_HMP4E_DEBUG + bool "MXC MPEG4 Debug messages" + depends on MXC_HMP4E != n + default n + ---help--- + Say Y here if you need the Encoder driver to print debug messages. + This is an option for developers, most people should say N here. + +endmenu diff --git a/drivers/mxc/hmp4e/Makefile b/drivers/mxc/hmp4e/Makefile new file mode 100644 index 000000000000..0efe11fbdbc8 --- /dev/null +++ b/drivers/mxc/hmp4e/Makefile @@ -0,0 +1,8 @@ +# +# Makefile for the MPEG4 Encoder kernel module. + +obj-$(CONFIG_MXC_HMP4E) += mxc_hmp4e.o + +ifeq ($(CONFIG_MXC_HMP4E_DEBUG),y) +EXTRA_CFLAGS += -DDEBUG +endif diff --git a/drivers/mxc/hmp4e/mxc_hmp4e.c b/drivers/mxc/hmp4e/mxc_hmp4e.c new file mode 100644 index 000000000000..aebaf445b4de --- /dev/null +++ b/drivers/mxc/hmp4e/mxc_hmp4e.c @@ -0,0 +1,812 @@ +/* + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/* + * Encoder device driver (kernel module) + * + * Copyright (C) 2005 Hantro Products Oy. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +#include +#include +#include /* __init,__exit directives */ +#include /* remap_page_range / remap_pfn_range */ +#include /* for struct file_operations */ +#include /* standard error codes */ +#include /* for device registeration for PM */ +#include /* for msleep_interruptible */ +#include +#include /* for dma_alloc_consistent */ +#include +#include /* for ioctl __get_user, __put_user */ +#include +#include "mxc_hmp4e.h" /* MPEG4 encoder specific */ + +/* here's all the must remember stuff */ +typedef struct { + ulong buffaddr; + u32 buffsize; + ulong iobaseaddr; + u32 iosize; + volatile u32 *hwregs; + u32 irq; + u16 hwid_offset; + u16 intr_offset; + u16 busy_offset; + u16 type; /* Encoder type, CIF = 0, VGA = 1 */ + u16 clk_gate; + u16 busy_val; + struct fasync_struct *async_queue; +#ifdef CONFIG_PM + s32 suspend_state; + wait_queue_head_t power_queue; +#endif +} hmp4e_t; + +/* and this is our MAJOR; use 0 for dynamic allocation (recommended)*/ +static s32 hmp4e_major; + +static u32 hmp4e_phys; +static struct class *hmp4e_class; +static hmp4e_t hmp4e_data; + +/*! MPEG4 enc clock handle. */ +static struct clk *hmp4e_clk; + +/* + * avoid "enable_irq(x) unbalanced from ..." + * error messages from the kernel, since {ena,dis}able_irq() + * calls are stacked in kernel. + */ +static bool irq_enable; + +ulong base_port = MPEG4_ENC_BASE_ADDR; +u32 irq = MXC_INT_MPEG4_ENCODER; + +module_param(base_port, long, 000); +module_param(irq, int, 000); + +/*! + * These variables store the register values when HMP4E is in suspend mode. + */ +#ifdef CONFIG_PM +u32 io_regs[64]; +#endif + +static s32 hmp4e_map_buffer(struct file *filp, struct vm_area_struct *vma); +static s32 hmp4e_map_hwregs(struct file *filp, struct vm_area_struct *vma); +static void hmp4e_reset(hmp4e_t *dev); +irqreturn_t hmp4e_isr(s32 irq, void *dev_id); + +/*! + * This funtion is called to write h/w register. + * + * @param val value to be written into the register + * @param offset register offset + * + */ +static inline void hmp4e_write(u32 val, u32 offset) +{ + hmp4e_t *dev = &hmp4e_data; + __raw_writel(val, (dev->hwregs + offset)); +} + +/*! + * This funtion is called to read h/w register. + * + * @param offset register offset + * + * @return This function returns the value read from the register. + * + */ +static inline u32 hmp4e_read(u32 offset) +{ + hmp4e_t *dev = &hmp4e_data; + u32 val; + + val = __raw_readl(dev->hwregs + offset); + + return val; +} + +/*! + * The device's mmap method. The VFS has kindly prepared the process's + * vm_area_struct for us, so we examine this to see what was requested. + * + * @param filp pointer to struct file + * @param vma pointer to struct vma_area_struct + * + * @return This function returns 0 if successful or -ve value on error. + * + */ +static s32 hmp4e_mmap(struct file *filp, struct vm_area_struct *vma) +{ + s32 result; + ulong offset = vma->vm_pgoff << PAGE_SHIFT; + + pr_debug("hmp4e_mmap: size = %lu off = 0x%08lx\n", + (unsigned long)(vma->vm_end - vma->vm_start), offset); + + if (offset == 0) { + result = hmp4e_map_buffer(filp, vma); + } else if (offset == hmp4e_data.iobaseaddr) { + result = hmp4e_map_hwregs(filp, vma); + } else { + pr_debug("hmp4e: mmap invalid value\n"); + result = -EINVAL; + } + + return result; +} + +/*! + * This funtion is called to handle ioctls. + * + * @param inode pointer to struct inode + * @param filp pointer to struct file + * @param cmd ioctl command + * @param arg user data + * + * @return This function returns 0 if successful or -ve value on error. + * + */ +static s32 hmp4e_ioctl(struct inode *inode, struct file *filp, + u32 cmd, ulong arg) +{ + s32 err = 0, retval = 0; + ulong offset = 0; + hmp4e_t *dev = &hmp4e_data; + write_t bwrite; + +#ifdef CONFIG_PM + wait_event_interruptible(hmp4e_data.power_queue, + hmp4e_data.suspend_state == 0); +#endif + + /* + * extract the type and number bitfields, and don't decode + * wrong cmds: return ENOTTY (inappropriate ioctl) before access_ok() + */ + if (_IOC_TYPE(cmd) != HMP4E_IOC_MAGIC) { + pr_debug("hmp4e: ioctl invalid magic\n"); + return -ENOTTY; + } + + if (_IOC_NR(cmd) > HMP4E_IOC_MAXNR) { + pr_debug("hmp4e: ioctl exceeds max ioctl\n"); + return -ENOTTY; + } + + /* + * the direction is a bitmask, and VERIFY_WRITE catches R/W + * transfers. `Type' is user-oriented, while + * access_ok is kernel-oriented, so the concept of "read" and + * "write" is reversed + */ + if (_IOC_DIR(cmd) & _IOC_READ) { + err = !access_ok(VERIFY_WRITE, (void *)arg, _IOC_SIZE(cmd)); + } else if (_IOC_DIR(cmd) & _IOC_WRITE) { + err = !access_ok(VERIFY_READ, (void *)arg, _IOC_SIZE(cmd)); + } + + if (err) { + pr_debug("hmp4e: ioctl invalid direction\n"); + return -EFAULT; + } + + switch (cmd) { + case HMP4E_IOCHARDRESET: + break; + + case HMP4E_IOCGBUFBUSADDRESS: + retval = __put_user((ulong) hmp4e_phys, (u32 *) arg); + break; + + case HMP4E_IOCGBUFSIZE: + retval = __put_user(hmp4e_data.buffsize, (u32 *) arg); + break; + + case HMP4E_IOCSREGWRITE: + if (dev->type != 1) { /* This ioctl only for VGA */ + pr_debug("hmp4e: HMP4E_IOCSREGWRITE invalid\n"); + retval = -EINVAL; + break; + } + + retval = __copy_from_user(&bwrite, (u32 *) arg, + sizeof(write_t)); + + if (bwrite.offset <= hmp4e_data.iosize - 4) { + hmp4e_write(bwrite.data, (bwrite.offset / 4)); + } else { + pr_debug("hmp4e: HMP4E_IOCSREGWRITE failed\n"); + retval = -EFAULT; + } + break; + + case HMP4E_IOCXREGREAD: + if (dev->type != 1) { /* This ioctl only for VGA */ + pr_debug("hmp4e: HMP4E_IOCSREGWRITE invalid\n"); + retval = -EINVAL; + break; + } + + retval = __get_user(offset, (ulong *) arg); + if (offset <= hmp4e_data.iosize - 4) { + __put_user(hmp4e_read((offset / 4)), (ulong *) arg); + } else { + pr_debug("hmp4e: HMP4E_IOCXREGREAD failed\n"); + retval = -EFAULT; + } + break; + + case HMP4E_IOCGHWOFFSET: + __put_user(hmp4e_data.iobaseaddr, (ulong *) arg); + break; + + case HMP4E_IOCGHWIOSIZE: + __put_user(hmp4e_data.iosize, (u32 *) arg); + break; + + case HMP4E_IOC_CLI: + if (irq_enable == true) { + disable_irq(hmp4e_data.irq); + irq_enable = false; + } + break; + + case HMP4E_IOC_STI: + if (irq_enable == false) { + enable_irq(hmp4e_data.irq); + irq_enable = true; + } + break; + + default: + pr_debug("unknown case %x\n", cmd); + } + + return retval; +} + +/*! + * This funtion is called when the device is opened. + * + * @param inode pointer to struct inode + * @param filp pointer to struct file + * + * @return This function returns 0 if successful or -ve value on error. + * + */ +static s32 hmp4e_open(struct inode *inode, struct file *filp) +{ + hmp4e_t *dev = &hmp4e_data; + + filp->private_data = (void *)dev; + + if (request_irq(dev->irq, hmp4e_isr, 0, "mxc_hmp4e", dev) != 0) { + pr_debug("hmp4e: request irq failed\n"); + return -EBUSY; + } + + if (irq_enable == false) { + irq_enable = true; + } + clk_enable(hmp4e_clk); + return 0; +} + +static s32 hmp4e_fasync(s32 fd, struct file *filp, s32 mode) +{ + hmp4e_t *dev = (hmp4e_t *) filp->private_data; + return fasync_helper(fd, filp, mode, &dev->async_queue); +} + +/*! + * This funtion is called when the device is closed. + * + * @param inode pointer to struct inode + * @param filp pointer to struct file + * + * @return This function returns 0. + * + */ +static s32 hmp4e_release(struct inode *inode, struct file *filp) +{ + hmp4e_t *dev = (hmp4e_t *) filp->private_data; + + /* this is necessary if user process exited asynchronously */ + if (irq_enable == true) { + disable_irq(dev->irq); + irq_enable = false; + } + + /* reset hardware */ + hmp4e_reset(&hmp4e_data); + + /* free the encoder IRQ */ + free_irq(dev->irq, (void *)dev); + + /* remove this filp from the asynchronusly notified filp's */ + hmp4e_fasync(-1, filp, 0); + clk_disable(hmp4e_clk); + return 0; +} + +/* VFS methods */ +static struct file_operations hmp4e_fops = { + .owner = THIS_MODULE, + .open = hmp4e_open, + .release = hmp4e_release, + .ioctl = hmp4e_ioctl, + .mmap = hmp4e_mmap, + .fasync = hmp4e_fasync, +}; + +/*! + * This funtion allocates physical contigous memory. + * + * @param size size of memory to be allocated + * + * @return This function returns 0 if successful or -ve value on error. + * + */ +static s32 hmp4e_alloc(u32 size) +{ + hmp4e_data.buffsize = PAGE_ALIGN(size); + hmp4e_data.buffaddr = + (ulong) dma_alloc_coherent(NULL, hmp4e_data.buffsize, + (dma_addr_t *) &hmp4e_phys, + GFP_DMA | GFP_KERNEL); + + if (hmp4e_data.buffaddr == 0) { + printk(KERN_ERR "hmp4e: couldn't allocate data buffer\n"); + return -ENOMEM; + } + + memset((s8 *) hmp4e_data.buffaddr, 0, hmp4e_data.buffsize); + return 0; +} + +/*! + * This funtion frees the DMAed memory. + */ +static void hmp4e_free(void) +{ + if (hmp4e_data.buffaddr != 0) { + dma_free_coherent(NULL, hmp4e_data.buffsize, + (void *)hmp4e_data.buffaddr, hmp4e_phys); + hmp4e_data.buffaddr = 0; + } +} + +/*! + * This funtion maps the shared buffer in memory. + * + * @param filp pointer to struct file + * @param vma pointer to struct vm_area_struct + * + * @return This function returns 0 if successful or -ve value on error. + * + */ +static s32 hmp4e_map_buffer(struct file *filp, struct vm_area_struct *vma) +{ + ulong phys; + ulong start = (u32) vma->vm_start; + ulong size = (u32) (vma->vm_end - vma->vm_start); + + /* if userspace tries to mmap beyond end of our buffer, fail */ + if (size > hmp4e_data.buffsize) { + pr_debug("hmp4e: hmp4e_map_buffer, invalid size\n"); + return -EINVAL; + } + + vma->vm_flags |= VM_RESERVED | VM_IO; + vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); + + phys = hmp4e_phys; + + if (remap_pfn_range(vma, start, phys >> PAGE_SHIFT, size, + vma->vm_page_prot)) { + pr_debug("hmp4e: failed mmapping shared buffer\n"); + return -EAGAIN; + } + + return 0; +} + +/*! + * This funtion maps the h/w register space in memory. + * + * @param filp pointer to struct file + * @param vma pointer to struct vm_area_struct + * + * @return This function returns 0 if successful or -ve value on error. + * + */ +static s32 hmp4e_map_hwregs(struct file *filp, struct vm_area_struct *vma) +{ + ulong phys; + ulong start = (unsigned long)vma->vm_start; + ulong size = (unsigned long)(vma->vm_end - vma->vm_start); + + /* if userspace tries to mmap beyond end of our buffer, fail */ + if (size > PAGE_SIZE) { + pr_debug("hmp4e: hmp4e_map_hwregs, invalid size\n"); + return -EINVAL; + } + + vma->vm_flags |= VM_RESERVED | VM_IO; + vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); + + /* Remember this won't work for vmalloc()d memory ! */ + phys = hmp4e_data.iobaseaddr; + + if (remap_pfn_range(vma, start, phys >> PAGE_SHIFT, hmp4e_data.iosize, + vma->vm_page_prot)) { + pr_debug("hmp4e: failed mmapping HW registers\n"); + return -EAGAIN; + } + + return 0; +} + +/*! + * This function is the interrupt service routine. + * + * @param irq the irq number + * @param dev_id driver data when ISR was regiatered + * + * @return The return value is IRQ_HANDLED. + * + */ +irqreturn_t hmp4e_isr(s32 irq, void *dev_id) +{ + hmp4e_t *dev = (hmp4e_t *) dev_id; + u32 offset = dev->intr_offset; + + u32 irq_status = hmp4e_read(offset); + + /* clear enc IRQ */ + hmp4e_write(irq_status & (~0x01), offset); + + if (dev->async_queue) + kill_fasync(&dev->async_queue, SIGIO, POLL_IN); + + return IRQ_HANDLED; +} + +/*! + * This function is called to reset the encoder. + * + * @param dev pointer to struct hmp4e_data + * + */ +static void hmp4e_reset(hmp4e_t *dev) +{ + s32 i; + + /* enable HCLK for register reset */ + hmp4e_write(dev->clk_gate, 0); + + /* Reset registers, except ECR0 (0x00) and ID (read-only) */ + for (i = 1; i < (dev->iosize / 4); i += 1) { + if (i == dev->hwid_offset) /* ID is read only */ + continue; + + /* Only for CIF, not used */ + if ((dev->type == 0) && (i == 14)) + continue; + + hmp4e_write(0, i); + } + + /* disable HCLK */ + hmp4e_write(0, 0); + return; +} + +/*! + * This function is called during the driver binding process. This function + * does the hardware initialization. + * + * @param dev the device structure used to store device specific + * information that is used by the suspend, resume and remove + * functions + * + * @return The function returns 0 if successful. + */ +static s32 hmp4e_probe(struct platform_device *pdev) +{ + s32 result; + u32 hwid; + struct device *temp_class; + + hmp4e_data.iobaseaddr = base_port; + hmp4e_data.irq = irq; + hmp4e_data.buffaddr = 0; + + /* map hw i/o registers into kernel space */ + hmp4e_data.hwregs = (volatile void *)IO_ADDRESS(hmp4e_data.iobaseaddr); + + hmp4e_clk = clk_get(&pdev->dev, "mpeg4_clk"); + if (IS_ERR(hmp4e_clk)) { + printk(KERN_INFO "hmp4e: Unable to get clock\n"); + return -EIO; + } + + clk_enable(hmp4e_clk); + + /* check hw id for encoder signature */ + hwid = hmp4e_read(7); + if ((hwid & 0xffff) == 0x1882) { /* CIF first */ + hmp4e_data.type = 0; + hmp4e_data.iosize = (16 * 4); + hmp4e_data.hwid_offset = 7; + hmp4e_data.intr_offset = 5; + hmp4e_data.clk_gate = (1 << 1); + hmp4e_data.buffsize = 512000; + hmp4e_data.busy_offset = 0; + hmp4e_data.busy_val = 1; + } else { + hwid = hmp4e_read((0x88 / 4)); + if ((hwid & 0xffff0000) == 0x52510000) { /* VGA */ + hmp4e_data.type = 1; + hmp4e_data.iosize = (35 * 4); + hmp4e_data.hwid_offset = (0x88 / 4); + hmp4e_data.intr_offset = (0x10 / 4); + hmp4e_data.clk_gate = (1 << 12); + hmp4e_data.buffsize = 1048576; + hmp4e_data.busy_offset = (0x10 / 4); + hmp4e_data.busy_val = (1 << 1); + } else { + printk(KERN_INFO "hmp4e: HW ID not found\n"); + goto error1; + } + } + + /* Reset hardware */ + hmp4e_reset(&hmp4e_data); + + /* allocate memory shared with ewl */ + result = hmp4e_alloc(hmp4e_data.buffsize); + if (result < 0) + goto error1; + + result = register_chrdev(hmp4e_major, "hmp4e", &hmp4e_fops); + if (result <= 0) { + pr_debug("hmp4e: unable to get major %d\n", hmp4e_major); + goto error2; + } + + hmp4e_major = result; + + hmp4e_class = class_create(THIS_MODULE, "hmp4e"); + if (IS_ERR(hmp4e_class)) { + pr_debug("Error creating hmp4e class.\n"); + goto error3; + } + + temp_class = device_create(hmp4e_class, NULL, MKDEV(hmp4e_major, 0), NULL, + "hmp4e"); + if (IS_ERR(temp_class)) { + pr_debug("Error creating hmp4e class device.\n"); + goto error4; + } + + platform_set_drvdata(pdev, &hmp4e_data); + +#ifdef CONFIG_PM + hmp4e_data.async_queue = NULL; + hmp4e_data.suspend_state = 0; + init_waitqueue_head(&hmp4e_data.power_queue); +#endif + + printk(KERN_INFO "hmp4e: %s encoder initialized\n", + hmp4e_data.type ? "VGA" : "CIF"); + clk_disable(hmp4e_clk); + return 0; + + error4: + class_destroy(hmp4e_class); + error3: + unregister_chrdev(hmp4e_major, "hmp4e"); + error2: + hmp4e_free(); + error1: + clk_disable(hmp4e_clk); + clk_put(hmp4e_clk); + printk(KERN_INFO "hmp4e: module not inserted\n"); + return -EIO; +} + +/*! + * Dissociates the driver. + * + * @param dev the device structure + * + * @return The function always returns 0. + */ +static s32 hmp4e_remove(struct platform_device *pdev) +{ + device_destroy(hmp4e_class, MKDEV(hmp4e_major, 0)); + class_destroy(hmp4e_class); + unregister_chrdev(hmp4e_major, "hmp4e"); + hmp4e_free(); + clk_disable(hmp4e_clk); + clk_put(hmp4e_clk); + platform_set_drvdata(pdev, NULL); + return 0; +} + +#ifdef CONFIG_PM +/*! + * This is the suspend of power management for the Hantro MPEG4 module + * + * @param dev the device + * @param state the state + * + * @return This function always returns 0. + */ +static s32 hmp4e_suspend(struct platform_device *pdev, pm_message_t state) +{ + s32 i; + hmp4e_t *pdata = &hmp4e_data; + + /* + * how many times msleep_interruptible will be called before + * giving up + */ + s32 timeout = 10; + + pr_debug("hmp4e: Suspend\n"); + hmp4e_data.suspend_state = 1; + + /* check if encoder is currently running */ + while ((hmp4e_read(pdata->busy_offset) & (pdata->busy_val)) && + --timeout) { + pr_debug("hmp4e: encoder is running, going to sleep\n"); + msleep_interruptible((unsigned int)30); + } + + if (!timeout) { + pr_debug("hmp4e: timeout suspending, resetting encoder\n"); + hmp4e_write(hmp4e_read(pdata->busy_offset) & + (~pdata->busy_val), pdata->busy_offset); + } + + /* first read register 0 */ + io_regs[0] = hmp4e_read(0); + + /* then override HCLK to make sure other registers can be read */ + hmp4e_write(pdata->clk_gate, 0); + + /* read other registers */ + for (i = 1; i < (pdata->iosize / 4); i += 1) { + + /* Only for CIF, not used */ + if ((pdata->type == 0) && (i == 14)) + continue; + + io_regs[i] = hmp4e_read(i); + } + + /* restore value of register 0 */ + hmp4e_write(io_regs[0], 0); + + /* stop HCLK */ + hmp4e_write(0, 0); + clk_disable(hmp4e_clk); + return 0; +}; + +/*! + * This is the resume of power management for the Hantro MPEG4 module + * It suports RESTORE state. + * + * @param pdev the platform device + * + * @return This function always returns 0 + */ +static s32 hmp4e_resume(struct platform_device *pdev) +{ + s32 i; + u32 status; + hmp4e_t *pdata = &hmp4e_data; + + pr_debug("hmp4e: Resume\n"); + clk_enable(hmp4e_clk); + + /* override HCLK to make sure registers can be written */ + hmp4e_write(pdata->clk_gate, 0x00); + + for (i = 1; i < (pdata->iosize / 4); i += 1) { + if (i == pdata->hwid_offset) /* Read only */ + continue; + + /* Only for CIF, not used */ + if ((pdata->type == 0) && (i == 14)) + continue; + + hmp4e_write(io_regs[i], i); + } + + /* write register 0 last */ + hmp4e_write(io_regs[0], 0x00); + + /* Clear the suspend flag */ + hmp4e_data.suspend_state = 0; + + /* Unblock the wait queue */ + wake_up_interruptible(&hmp4e_data.power_queue); + + /* Continue operations */ + status = hmp4e_read(pdata->intr_offset); + if (status & 0x1) { + hmp4e_write(status & (~0x01), pdata->intr_offset); + if (hmp4e_data.async_queue) + kill_fasync(&hmp4e_data.async_queue, SIGIO, POLL_IN); + } + + return 0; +}; + +#endif + +static struct platform_driver hmp4e_driver = { + .driver = { + .name = "mxc_hmp4e", + }, + .probe = hmp4e_probe, + .remove = hmp4e_remove, +#ifdef CONFIG_PM + .suspend = hmp4e_suspend, + .resume = hmp4e_resume, +#endif +}; + +static s32 __init hmp4e_init(void) +{ + printk(KERN_INFO "hmp4e: init\n"); + platform_driver_register(&hmp4e_driver); + return 0; +} + +static void __exit hmp4e_cleanup(void) +{ + platform_driver_unregister(&hmp4e_driver); + printk(KERN_INFO "hmp4e: module removed\n"); +} + +module_init(hmp4e_init); +module_exit(hmp4e_cleanup); + +/* module description */ +MODULE_AUTHOR("Hantro Products Oy"); +MODULE_DESCRIPTION("Device driver for Hantro's hardware based MPEG4 encoder"); +MODULE_SUPPORTED_DEVICE("5251/4251 MPEG4 Encoder"); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/hmp4e/mxc_hmp4e.h b/drivers/mxc/hmp4e/mxc_hmp4e.h new file mode 100644 index 000000000000..ed882b09e167 --- /dev/null +++ b/drivers/mxc/hmp4e/mxc_hmp4e.h @@ -0,0 +1,70 @@ +/* + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/* + * Encoder device driver (kernel module headers) + * + * Copyright (C) 2005 Hantro Products Oy. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#ifndef _HMP4ENC_H_ +#define _HMP4ENC_H_ +#include /* needed for the _IOW etc stuff used later */ + +/* this is for writing data through ioctl to registers*/ +typedef struct { + unsigned long data; + unsigned long offset; +} write_t; + +/* + * Ioctl definitions + */ + +/* Use 'k' as magic number */ +#define HMP4E_IOC_MAGIC 'k' +/* + * S means "Set" through a ptr, + * T means "Tell" directly with the argument value + * G means "Get": reply by setting through a pointer + * Q means "Query": response is on the return value + * X means "eXchange": G and S atomically + * H means "sHift": T and Q atomically + */ +#define HMP4E_IOCGBUFBUSADDRESS _IOR(HMP4E_IOC_MAGIC, 1, unsigned long *) +#define HMP4E_IOCGBUFSIZE _IOR(HMP4E_IOC_MAGIC, 2, unsigned int *) +#define HMP4E_IOCGHWOFFSET _IOR(HMP4E_IOC_MAGIC, 3, unsigned long *) +#define HMP4E_IOCGHWIOSIZE _IOR(HMP4E_IOC_MAGIC, 4, unsigned int *) +#define HMP4E_IOC_CLI _IO(HMP4E_IOC_MAGIC, 5) +#define HMP4E_IOC_STI _IO(HMP4E_IOC_MAGIC, 6) +#define HMP4E_IOCHARDRESET _IO(HMP4E_IOC_MAGIC, 7) +#define HMP4E_IOCSREGWRITE _IOW(HMP4E_IOC_MAGIC, 8, write_t) +#define HMP4E_IOCXREGREAD _IOWR(HMP4E_IOC_MAGIC, 9, unsigned long) + +#define HMP4E_IOC_MAXNR 9 + +#endif /* !_HMP4ENC_H_ */ diff --git a/drivers/mxc/hw_event/Kconfig b/drivers/mxc/hw_event/Kconfig new file mode 100644 index 000000000000..bcf479689501 --- /dev/null +++ b/drivers/mxc/hw_event/Kconfig @@ -0,0 +1,11 @@ +menu "MXC HARDWARE EVENT" + +config MXC_HWEVENT + bool "MXC Hardware Event Handler" + default y + depends on ARCH_MXC + help + If you plan to use the Hardware Event Handler in the MXC, say + Y here. If unsure, select Y. + +endmenu diff --git a/drivers/mxc/hw_event/Makefile b/drivers/mxc/hw_event/Makefile new file mode 100644 index 000000000000..a53fe2b45e04 --- /dev/null +++ b/drivers/mxc/hw_event/Makefile @@ -0,0 +1 @@ +obj-$(CONFIG_MXC_HWEVENT) += mxc_hw_event.o diff --git a/drivers/mxc/hw_event/mxc_hw_event.c b/drivers/mxc/hw_event/mxc_hw_event.c new file mode 100644 index 000000000000..655e4c821986 --- /dev/null +++ b/drivers/mxc/hw_event/mxc_hw_event.c @@ -0,0 +1,266 @@ +/* + * Copyright 2007-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * mxc_hw_event.c + * Collect the hardware events, send to user by netlink + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#define EVENT_POOL_SIZE 10 + +struct hw_event_elem { + struct mxc_hw_event event; + struct list_head list; +}; + +static struct sock *nl_event_sock; /* netlink socket */ +static struct list_head event_head; +static struct list_head free_head; +static struct hw_event_elem events_pool[EVENT_POOL_SIZE]; /* event pool */ +static DEFINE_SPINLOCK(list_lock); +static DECLARE_WAIT_QUEUE_HEAD(event_wq); +static unsigned int seq; /* send seq */ +static int initialized; +static struct task_struct *hwevent_kthread; + +/*! + * main HW event handler thread + */ +static int hw_event_thread(void *data) +{ + struct sk_buff *skb = NULL; + struct nlmsghdr *nlh = NULL; + unsigned int size; + struct hw_event_elem *event, *n; + LIST_HEAD(tmp_head); + DEFINE_WAIT(wait); + + while (1) { + + prepare_to_wait(&event_wq, &wait, TASK_INTERRUPTIBLE); + /* wait for event coming */ + if (!freezing(current) && !kthread_should_stop() && + list_empty(&event_head)) + schedule(); + finish_wait(&event_wq, &wait); + + try_to_freeze(); + + if (kthread_should_stop()) + break; + + /* fetch event from list */ + spin_lock_irq(&list_lock); + tmp_head = event_head; + tmp_head.prev->next = &tmp_head; + tmp_head.next->prev = &tmp_head; + /* clear the event list head */ + INIT_LIST_HEAD(&event_head); + spin_unlock_irq(&list_lock); + + list_for_each_entry_safe(event, n, &tmp_head, list) { + + size = NLMSG_SPACE(sizeof(struct mxc_hw_event)); + skb = alloc_skb(size, GFP_KERNEL); + if (!skb) { + /* if failed alloc skb, we drop this event */ + printk(KERN_WARNING + "mxc_hw_event: skb_alloc() failed\n"); + goto alloc_failure; + } + + /* put the netlink header struct to skb */ + nlh = + NLMSG_PUT(skb, 0, seq++, NLMSG_DONE, + size - sizeof(*nlh)); + + /* fill the netlink data */ + memcpy((struct mxc_hw_event *)NLMSG_DATA(nlh), + &event->event, sizeof(struct mxc_hw_event)); + + /* free the event node, set to unused */ + spin_lock_irq(&list_lock); + list_move(&event->list, &free_head); + spin_unlock_irq(&list_lock); + + /* send to all process that create this socket */ + NETLINK_CB(skb).pid = 0; /* sender pid */ + NETLINK_CB(skb).dst_group = HW_EVENT_GROUP; + /* broadcast the event */ + netlink_broadcast(nl_event_sock, skb, 0, HW_EVENT_GROUP, + GFP_KERNEL); + + continue; + nlmsg_failure: + printk(KERN_WARNING + "mxc_hw_event: No tailroom for NLMSG in skb\n"); + alloc_failure: + /* free the event node, set to unused */ + spin_lock_irq(&list_lock); + list_del(&event->list); + list_add_tail(&event->list, &free_head); + spin_unlock_irq(&list_lock); + } + } + + return 0; +} + +/*! + * + * @priority the event priority, REALTIME, EMERENCY, NORMAL + * @new_event event id to be send + */ +int hw_event_send(int priority, struct mxc_hw_event *new_event) +{ + unsigned int size; + struct sk_buff *skb = NULL; + struct nlmsghdr *nlh = NULL; + struct mxc_hw_event *event; + struct hw_event_elem *event_elem; + int ret; + unsigned long flag; + struct list_head *list_node; + + if (!initialized) { + pr_info("HW Event module has not been initialized\n"); + return -1; + } + + if (priority == HWE_HIGH_PRIORITY) { + /** + * the most high priority event, + * we send it immediatly. + */ + + size = NLMSG_SPACE(sizeof(struct mxc_hw_event)); + + /* alloc skb */ + if (in_interrupt()) { + skb = alloc_skb(size, GFP_ATOMIC); + } else { + skb = alloc_skb(size, GFP_KERNEL); + } + if (!skb) { + /* if failed alloc skb, we drop this event */ + printk(KERN_WARNING + "hw_event send: skb_alloc() failed\n"); + goto send_later; + } + + /* put the netlink header struct to skb */ + nlh = NLMSG_PUT(skb, 0, seq++, NLMSG_DONE, size - sizeof(*nlh)); + + /* fill the netlink data */ + event = (struct mxc_hw_event *)NLMSG_DATA(nlh); + memcpy(event, new_event, sizeof(struct mxc_hw_event)); + + /* send to all process that create this socket */ + NETLINK_CB(skb).pid = 0; /* sender pid */ + NETLINK_CB(skb).dst_group = HW_EVENT_GROUP; + /* broadcast the event */ + ret = netlink_broadcast(nl_event_sock, skb, 0, HW_EVENT_GROUP, + in_interrupt() ? GFP_ATOMIC : + GFP_KERNEL); + if (ret) { + + nlmsg_failure: + /* send failed */ + kfree_skb(skb); + goto send_later; + } + + return 0; + } + + send_later: + spin_lock_irqsave(&list_lock, flag); + if (list_empty(&free_head)) { + spin_unlock_irqrestore(&list_lock, flag); + /* no more free event node */ + printk(KERN_WARNING "mxc_event send: no more free node\n"); + return -1; + } + + /* get a free node from free list, and added to event list */ + list_node = free_head.next; + /* fill event */ + event_elem = list_entry(list_node, struct hw_event_elem, list); + event_elem->event = *new_event; + list_move(list_node, &event_head); + spin_unlock_irqrestore(&list_lock, flag); + + wake_up(&event_wq); + + return 0; +} + +static int __init mxc_hw_event_init(void) +{ + int i; + + /* initial the list head for event and free */ + INIT_LIST_HEAD(&free_head); + INIT_LIST_HEAD(&event_head); + + /* initial the free list */ + for (i = 0; i < EVENT_POOL_SIZE; i++) + list_add_tail(&events_pool[i].list, &free_head); + + /* create netlink kernel sock */ + nl_event_sock = + netlink_kernel_create(&init_net, NETLINK_USERSOCK, 0, NULL, NULL, + THIS_MODULE); + if (!nl_event_sock) { + printk(KERN_WARNING + "mxc_hw_event: Fail to create netlink socket.\n"); + return 1; + } + + hwevent_kthread = kthread_run(hw_event_thread, NULL, "hwevent"); + if (IS_ERR(hwevent_kthread)) { + printk(KERN_WARNING + "mxc_hw_event: Fail to create hwevent thread.\n"); + return 1; + } + + initialized = 1; + + return 0; +} + +static void __exit mxc_hw_event_exit(void) +{ + kthread_stop(hwevent_kthread); + /* wait for thread completion */ + sock_release(nl_event_sock->sk_socket); +} + +module_init(mxc_hw_event_init); +module_exit(mxc_hw_event_exit); + +EXPORT_SYMBOL(hw_event_send); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/ipu/Kconfig b/drivers/mxc/ipu/Kconfig new file mode 100644 index 000000000000..919cb598c294 --- /dev/null +++ b/drivers/mxc/ipu/Kconfig @@ -0,0 +1,4 @@ +config MXC_IPU_V1 + bool + +source "drivers/mxc/ipu/pf/Kconfig" diff --git a/drivers/mxc/ipu/Makefile b/drivers/mxc/ipu/Makefile new file mode 100644 index 000000000000..4e9f19f9afa5 --- /dev/null +++ b/drivers/mxc/ipu/Makefile @@ -0,0 +1,5 @@ +obj-$(CONFIG_MXC_IPU_V1) = mxc_ipu.o + +mxc_ipu-objs := ipu_common.o ipu_sdc.o ipu_adc.o ipu_ic.o ipu_csi.o ipu_device.o ipu_calc_stripes_sizes.o + +obj-$(CONFIG_MXC_IPU_PF) += pf/ diff --git a/drivers/mxc/ipu/ipu_adc.c b/drivers/mxc/ipu/ipu_adc.c new file mode 100644 index 000000000000..ee3cf916b2f3 --- /dev/null +++ b/drivers/mxc/ipu/ipu_adc.c @@ -0,0 +1,689 @@ +/* + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/* + * @file ipu_adc.c + * + * @brief IPU ADC functions + * + * @ingroup IPU + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "ipu_prv.h" +#include "ipu_regs.h" +#include "ipu_param_mem.h" + +/*#define ADC_CHAN1_SA_MASK 0xFF800000 */ + +static void _ipu_set_cmd_data_mappings(display_port_t disp, + uint32_t pixel_fmt, int ifc_width); + +int32_t _ipu_adc_init_channel(ipu_channel_t chan, display_port_t disp, + mcu_mode_t cmd, int16_t x_pos, int16_t y_pos) +{ + uint32_t reg; + uint32_t start_addr, stride; + unsigned long lock_flags; + uint32_t size; + + size = 0; + + switch (disp) { + case DISP0: + reg = __raw_readl(ADC_DISP0_CONF); + stride = reg & ADC_DISP_CONF_SL_MASK; + break; + case DISP1: + reg = __raw_readl(ADC_DISP1_CONF); + stride = reg & ADC_DISP_CONF_SL_MASK; + break; + case DISP2: + reg = __raw_readl(ADC_DISP2_CONF); + stride = reg & ADC_DISP_CONF_SL_MASK; + break; + default: + return -EINVAL; + } + + if (stride == 0) + return -EINVAL; + + stride++; + start_addr = (y_pos * stride) + x_pos; + + spin_lock_irqsave(&ipu_lock, lock_flags); + reg = __raw_readl(ADC_CONF); + + switch (chan) { + case ADC_SYS1: + reg &= ~0x00FF4000; + reg |= + ((uint32_t) size << 21 | (uint32_t) disp << 19 | (uint32_t) + cmd << 16); + + __raw_writel(start_addr, ADC_SYSCHA1_SA); + break; + + case ADC_SYS2: + reg &= ~0xFF008000; + reg |= + ((uint32_t) size << 29 | (uint32_t) disp << 27 | (uint32_t) + cmd << 24); + + __raw_writel(start_addr, ADC_SYSCHA2_SA); + break; + + case CSI_PRP_VF_ADC: + case MEM_PRP_VF_ADC: + reg &= ~0x000000F9; + reg |= + ((uint32_t) size << 5 | (uint32_t) disp << 3 | + ADC_CONF_PRP_EN); + + __raw_writel(start_addr, ADC_PRPCHAN_SA); + break; + + case MEM_PP_ADC: + reg &= ~0x00003F02; + reg |= + ((uint32_t) size << 10 | (uint32_t) disp << 8 | + ADC_CONF_PP_EN); + + __raw_writel(start_addr, ADC_PPCHAN_SA); + break; + default: + spin_unlock_irqrestore(&ipu_lock, lock_flags); + return -1; + break; + } + __raw_writel(reg, ADC_CONF); + spin_unlock_irqrestore(&ipu_lock, lock_flags); + return 0; +} + +int32_t _ipu_adc_uninit_channel(ipu_channel_t chan) +{ + uint32_t reg; + unsigned long lock_flags; + + spin_lock_irqsave(&ipu_lock, lock_flags); + reg = __raw_readl(ADC_CONF); + + switch (chan) { + case ADC_SYS1: + reg &= ~0x00FF4000; + break; + case ADC_SYS2: + reg &= ~0xFF008000; + break; + case CSI_PRP_VF_ADC: + case MEM_PRP_VF_ADC: + reg &= ~0x000000F9; + break; + case MEM_PP_ADC: + reg &= ~0x00003F02; + break; + default: + spin_unlock_irqrestore(&ipu_lock, lock_flags); + return -1; + break; + } + __raw_writel(reg, ADC_CONF); + spin_unlock_irqrestore(&ipu_lock, lock_flags); + return 0; +} + +int32_t ipu_adc_write_template(display_port_t disp, uint32_t *pCmd, bool write) +{ + uint32_t ima_addr = 0; + uint32_t row_nu; + int i; + + /* Set IPU_IMA_ADDR (IPU Internal Memory Access Address) */ + /* MEM_NU = 0x0001 (CPM) */ + /* ROW_NU = 2*N ( N is channel number) */ + /* WORD_NU = 0 */ + if (write) { + row_nu = (uint32_t) disp * 2 * ATM_ADDR_RANGE; + } else { + row_nu = ((uint32_t) disp * 2 + 1) * ATM_ADDR_RANGE; + } + + /* form template addr for IPU_IMA_ADDR */ + ima_addr = (0x3 << 16 /*Template memory */ | row_nu << 3); + + __raw_writel(ima_addr, IPU_IMA_ADDR); + + /* write template data for IPU_IMA_DATA */ + for (i = 0; i < TEMPLATE_BUF_SIZE; i++) + /* only DATA field are needed */ + __raw_writel(pCmd[i], IPU_IMA_DATA); + + return 0; +} + +int32_t +ipu_adc_write_cmd(display_port_t disp, cmddata_t type, + uint32_t cmd, const uint32_t *params, uint16_t numParams) +{ + uint16_t i; + int disable_di = 0; + u32 reg; + unsigned long lock_flags; + + spin_lock_irqsave(&ipu_lock, lock_flags); + reg = __raw_readl(IPU_CONF); + if ((reg & IPU_CONF_DI_EN) == 0) { + disable_di = 1; + reg |= IPU_CONF_DI_EN; + __raw_writel(reg, IPU_CONF); + } + spin_unlock_irqrestore(&ipu_lock, lock_flags); + + __raw_writel((uint32_t) ((type ? 0x0 : 0x1) | disp << 1 | 0x10), + DI_DISP_LLA_CONF); + __raw_writel(cmd, DI_DISP_LLA_DATA); + udelay(3); + + __raw_writel((uint32_t) (0x10 | disp << 1 | 0x11), DI_DISP_LLA_CONF); + for (i = 0; i < numParams; i++) { + __raw_writel(params[i], DI_DISP_LLA_DATA); + udelay(3); + } + + if (disable_di) { + spin_lock_irqsave(&ipu_lock, lock_flags); + reg = __raw_readl(IPU_CONF); + reg &= ~IPU_CONF_DI_EN; + __raw_writel(reg, IPU_CONF); + spin_unlock_irqrestore(&ipu_lock, lock_flags); + } + + return 0; +} + +int32_t ipu_adc_set_update_mode(ipu_channel_t channel, + ipu_adc_update_mode_t mode, + uint32_t refresh_rate, unsigned long addr, + uint32_t *size) +{ + int32_t err = 0; + uint32_t ref_per, reg, src = 0; + unsigned long lock_flags; + uint32_t ipu_freq; + + ipu_freq = clk_get_rate(g_ipu_clk); + + spin_lock_irqsave(&ipu_lock, lock_flags); + + reg = __raw_readl(IPU_FS_DISP_FLOW); + reg &= ~FS_AUTO_REF_PER_MASK; + switch (mode) { + case IPU_ADC_REFRESH_NONE: + src = 0; + break; + case IPU_ADC_AUTO_REFRESH: + if (refresh_rate == 0) { + err = -EINVAL; + goto err0; + } + ref_per = ipu_freq / ((1UL << 17) * refresh_rate); + ref_per--; + reg |= ref_per << FS_AUTO_REF_PER_OFFSET; + + src = FS_SRC_AUTOREF; + break; + case IPU_ADC_AUTO_REFRESH_SNOOP: + if (refresh_rate == 0) { + err = -EINVAL; + goto err0; + } + ref_per = ipu_freq / ((1UL << 17) * refresh_rate); + ref_per--; + reg |= ref_per << FS_AUTO_REF_PER_OFFSET; + + src = FS_SRC_AUTOREF_SNOOP; + break; + case IPU_ADC_SNOOPING: + src = FS_SRC_SNOOP; + break; + } + + switch (channel) { + case ADC_SYS1: + reg &= ~FS_ADC1_SRC_SEL_MASK; + reg |= src << FS_ADC1_SRC_SEL_OFFSET; + break; + case ADC_SYS2: + reg &= ~FS_ADC2_SRC_SEL_MASK; + reg |= src << FS_ADC2_SRC_SEL_OFFSET; + break; + default: + spin_unlock_irqrestore(&ipu_lock, lock_flags); + return -EINVAL; + } + __raw_writel(reg, IPU_FS_DISP_FLOW); + + /* Setup bus snooping */ + if ((mode == IPU_ADC_AUTO_REFRESH_SNOOP) || (mode == IPU_ADC_SNOOPING)) { + err = mxc_snoop_set_config(0, addr, *size); + if (err > 0) { + *size = err; + err = 0; + } + } else { + mxc_snoop_set_config(0, 0, 0); + } + + err0: + spin_unlock_irqrestore(&ipu_lock, lock_flags); + return err; +} + +int32_t ipu_adc_get_snooping_status(uint32_t *statl, uint32_t *stath) +{ + return mxc_snoop_get_status(0, statl, stath); +} + +int32_t ipu_adc_init_panel(display_port_t disp, + uint16_t width, uint16_t height, + uint32_t pixel_fmt, + uint32_t stride, + ipu_adc_sig_cfg_t sig, + display_addressing_t addr, + uint32_t vsync_width, vsync_t mode) +{ + uint32_t temp; + unsigned long lock_flags; + uint32_t ser_conf; + uint32_t disp_conf; + uint32_t adc_disp_conf; + uint32_t adc_disp_vsync; + uint32_t old_pol; + + if ((disp != DISP1) && (disp != DISP2) && + (sig.ifc_mode >= IPU_ADC_IFC_MODE_3WIRE_SERIAL)) { + return -EINVAL; + } +/* adc_disp_conf = ((uint32_t)((((size == 3)||(size == 2))?1:0)<<14) | */ +/* (uint32_t)addr<<12 | (stride-1)); */ + adc_disp_conf = (uint32_t) addr << 12 | (stride - 1); + + _ipu_set_cmd_data_mappings(disp, pixel_fmt, sig.ifc_width); + + spin_lock_irqsave(&ipu_lock, lock_flags); + disp_conf = __raw_readl(DI_DISP_IF_CONF); + old_pol = __raw_readl(DI_DISP_SIG_POL); + adc_disp_vsync = __raw_readl(ADC_DISP_VSYNC); + + switch (disp) { + case DISP0: + __raw_writel(adc_disp_conf, ADC_DISP0_CONF); + __raw_writel((((height - 1) << 16) | (width - 1)), + ADC_DISP0_SS); + + adc_disp_vsync &= ~(ADC_DISP_VSYNC_D0_MODE_MASK | + ADC_DISP_VSYNC_D0_WIDTH_MASK); + adc_disp_vsync |= (vsync_width << 16) | (uint32_t) mode; + + old_pol &= ~0x2000003FL; + old_pol |= sig.data_pol | sig.cs_pol << 1 | + sig.addr_pol << 2 | sig.read_pol << 3 | + sig.write_pol << 4 | sig.Vsync_pol << 5 | + sig.burst_pol << 29; + __raw_writel(old_pol, DI_DISP_SIG_POL); + + disp_conf &= ~0x0000001FL; + disp_conf |= (sig.burst_mode << 3) | (sig.ifc_mode << 1) | + DI_CONF_DISP0_EN; + __raw_writel(disp_conf, DI_DISP_IF_CONF); + break; + case DISP1: + __raw_writel(adc_disp_conf, ADC_DISP1_CONF); + __raw_writel((((height - 1) << 16) | (width - 1)), + ADC_DISP12_SS); + + adc_disp_vsync &= ~(ADC_DISP_VSYNC_D12_MODE_MASK | + ADC_DISP_VSYNC_D12_WIDTH_MASK); + adc_disp_vsync |= (vsync_width << 16) | (uint32_t) mode; + + old_pol &= ~0x4000FF00L; + old_pol |= (sig.Vsync_pol << 6 | sig.data_pol << 8 | + sig.cs_pol << 9 | sig.addr_pol << 10 | + sig.read_pol << 11 | sig.write_pol << 12 | + sig.clk_pol << 14 | sig.burst_pol << 30); + __raw_writel(old_pol, DI_DISP_SIG_POL); + + disp_conf &= ~0x00003F00L; + if (sig.ifc_mode >= IPU_ADC_IFC_MODE_3WIRE_SERIAL) { + ser_conf = (sig.ifc_width - 1) << + DI_SER_DISPx_CONF_SER_BIT_NUM_OFFSET; + if (sig.ser_preamble_len) { + ser_conf |= DI_SER_DISPx_CONF_PREAMBLE_EN; + ser_conf |= sig.ser_preamble << + DI_SER_DISPx_CONF_PREAMBLE_OFFSET; + ser_conf |= (sig.ser_preamble_len - 1) << + DI_SER_DISPx_CONF_PREAMBLE_LEN_OFFSET; + } + + ser_conf |= + sig.ser_rw_mode << DI_SER_DISPx_CONF_RW_CFG_OFFSET; + + if (sig.burst_mode == IPU_ADC_BURST_SERIAL) + ser_conf |= DI_SER_DISPx_CONF_BURST_MODE_EN; + __raw_writel(ser_conf, DI_SER_DISP1_CONF); + } else { /* parallel interface */ + disp_conf |= (uint32_t) (sig.burst_mode << 12); + } + disp_conf |= (sig.ifc_mode << 9) | DI_CONF_DISP1_EN; + __raw_writel(disp_conf, DI_DISP_IF_CONF); + break; + case DISP2: + __raw_writel(adc_disp_conf, ADC_DISP2_CONF); + __raw_writel((((height - 1) << 16) | (width - 1)), + ADC_DISP12_SS); + + adc_disp_vsync &= ~(ADC_DISP_VSYNC_D12_MODE_MASK | + ADC_DISP_VSYNC_D12_WIDTH_MASK); + adc_disp_vsync |= (vsync_width << 16) | (uint32_t) mode; + + old_pol &= ~0x80FF0000L; + temp = (uint32_t) (sig.data_pol << 16 | sig.cs_pol << 17 | + sig.addr_pol << 18 | sig.read_pol << 19 | + sig.write_pol << 20 | sig.Vsync_pol << 6 | + sig.burst_pol << 31 | sig.clk_pol << 22); + __raw_writel(temp | old_pol, DI_DISP_SIG_POL); + + disp_conf &= ~0x003F0000L; + if (sig.ifc_mode >= IPU_ADC_IFC_MODE_3WIRE_SERIAL) { + ser_conf = (sig.ifc_width - 1) << + DI_SER_DISPx_CONF_SER_BIT_NUM_OFFSET; + if (sig.ser_preamble_len) { + ser_conf |= DI_SER_DISPx_CONF_PREAMBLE_EN; + ser_conf |= sig.ser_preamble << + DI_SER_DISPx_CONF_PREAMBLE_OFFSET; + ser_conf |= (sig.ser_preamble_len - 1) << + DI_SER_DISPx_CONF_PREAMBLE_LEN_OFFSET; + + } + + ser_conf |= + sig.ser_rw_mode << DI_SER_DISPx_CONF_RW_CFG_OFFSET; + + if (sig.burst_mode == IPU_ADC_BURST_SERIAL) + ser_conf |= DI_SER_DISPx_CONF_BURST_MODE_EN; + __raw_writel(ser_conf, DI_SER_DISP2_CONF); + } else { /* parallel interface */ + disp_conf |= (uint32_t) (sig.burst_mode << 20); + } + disp_conf |= (sig.ifc_mode << 17) | DI_CONF_DISP2_EN; + __raw_writel(disp_conf, DI_DISP_IF_CONF); + break; + default: + break; + } + + __raw_writel(adc_disp_vsync, ADC_DISP_VSYNC); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + + return 0; +} + +int32_t ipu_adc_init_ifc_timing(display_port_t disp, bool read, + uint32_t cycle_time, + uint32_t up_time, + uint32_t down_time, + uint32_t read_latch_time, uint32_t pixel_clk) +{ + uint32_t reg; + uint32_t time_conf3 = 0; + uint32_t clk_per; + uint32_t up_per; + uint32_t down_per; + uint32_t read_per; + uint32_t pixclk_per = 0; + uint32_t ipu_freq; + + ipu_freq = clk_get_rate(g_ipu_clk); + + clk_per = (cycle_time * (ipu_freq / 1000L) * 16L) / 1000000L; + up_per = (up_time * (ipu_freq / 1000L) * 4L) / 1000000L; + down_per = (down_time * (ipu_freq / 1000L) * 4L) / 1000000L; + + reg = (clk_per << DISPx_IF_CLK_PER_OFFSET) | + (up_per << DISPx_IF_CLK_UP_OFFSET) | + (down_per << DISPx_IF_CLK_DOWN_OFFSET); + + if (read) { + read_per = + (read_latch_time * (ipu_freq / 1000L) * 4L) / 1000000L; + if (pixel_clk) + pixclk_per = (ipu_freq * 16L) / pixel_clk; + time_conf3 = (read_per << DISPx_IF_CLK_READ_EN_OFFSET) | + (pixclk_per << DISPx_PIX_CLK_PER_OFFSET); + } + + dev_dbg(g_ipu_dev, "DI_DISPx_TIME_CONF_1/2 = 0x%08X\n", reg); + dev_dbg(g_ipu_dev, "DI_DISPx_TIME_CONF_3 = 0x%08X\n", time_conf3); + + switch (disp) { + case DISP0: + if (read) { + __raw_writel(reg, DI_DISP0_TIME_CONF_2); + __raw_writel(time_conf3, DI_DISP0_TIME_CONF_3); + } else { + __raw_writel(reg, DI_DISP0_TIME_CONF_1); + } + break; + case DISP1: + if (read) { + __raw_writel(reg, DI_DISP1_TIME_CONF_2); + __raw_writel(time_conf3, DI_DISP1_TIME_CONF_3); + } else { + __raw_writel(reg, DI_DISP1_TIME_CONF_1); + } + break; + case DISP2: + if (read) { + __raw_writel(reg, DI_DISP2_TIME_CONF_2); + __raw_writel(time_conf3, DI_DISP2_TIME_CONF_3); + } else { + __raw_writel(reg, DI_DISP2_TIME_CONF_1); + } + break; + default: + return -EINVAL; + break; + } + + return 0; +} + +struct ipu_adc_di_map { + uint32_t map_byte1; + uint32_t map_byte2; + uint32_t map_byte3; + uint32_t cycle_cnt; +}; + +static const struct ipu_adc_di_map di_mappings[] = { + [0] = { + /* RGB888, 8-bit bus */ + .map_byte1 = 0x1600AAAA, + .map_byte2 = 0x00E05555, + .map_byte2 = 0x00070000, + .cycle_cnt = 3, + }, + [1] = { + /* RGB666, 8-bit bus */ + .map_byte1 = 0x1C00AAAF, + .map_byte2 = 0x00E0555F, + .map_byte3 = 0x0007000F, + .cycle_cnt = 3, + }, + [2] = { + /* RGB565, 8-bit bus */ + .map_byte1 = 0x008055BF, + .map_byte2 = 0x0142015F, + .map_byte3 = 0x0007003F, + .cycle_cnt = 2, + }, + [3] = { + /* RGB888, 24-bit bus */ + .map_byte1 = 0x0007000F, + .map_byte2 = 0x000F000F, + .map_byte3 = 0x0017000F, + .cycle_cnt = 1, + }, + [4] = { + /* RGB666, 18-bit bus */ + .map_byte1 = 0x0005000F, + .map_byte2 = 0x000B000F, + .map_byte3 = 0x0011000F, + .cycle_cnt = 1, + }, + [5] = { + /* RGB565, 16-bit bus */ + .map_byte1 = 0x0004003F, + .map_byte2 = 0x000A000F, + .map_byte3 = 0x000F003F, + .cycle_cnt = 1, + }, +}; + +/* Private methods */ +static void _ipu_set_cmd_data_mappings(display_port_t disp, + uint32_t pixel_fmt, int ifc_width) +{ + uint32_t reg; + u32 map = 0; + + if (ifc_width == 8) { + switch (pixel_fmt) { + case IPU_PIX_FMT_BGR24: + map = 0; + break; + case IPU_PIX_FMT_RGB666: + map = 1; + break; + case IPU_PIX_FMT_RGB565: + map = 2; + break; + default: + break; + } + } else if (ifc_width >= 16) { + switch (pixel_fmt) { + case IPU_PIX_FMT_BGR24: + map = 3; + break; + case IPU_PIX_FMT_RGB666: + map = 4; + break; + case IPU_PIX_FMT_RGB565: + map = 5; + break; + default: + break; + } + } + + switch (disp) { + case DISP0: + if (ifc_width == 8) { + __raw_writel(0x00070000, DI_DISP0_CB0_MAP); + __raw_writel(0x0000FFFF, DI_DISP0_CB1_MAP); + __raw_writel(0x0000FFFF, DI_DISP0_CB2_MAP); + } else { + __raw_writel(0x00070000, DI_DISP0_CB0_MAP); + __raw_writel(0x000F0000, DI_DISP0_CB1_MAP); + __raw_writel(0x0000FFFF, DI_DISP0_CB2_MAP); + } + __raw_writel(di_mappings[map].map_byte1, DI_DISP0_DB0_MAP); + __raw_writel(di_mappings[map].map_byte2, DI_DISP0_DB1_MAP); + __raw_writel(di_mappings[map].map_byte3, DI_DISP0_DB2_MAP); + reg = __raw_readl(DI_DISP_ACC_CC); + reg &= ~DISP0_IF_CLK_CNT_D_MASK; + reg |= (di_mappings[map].cycle_cnt - 1) << + DISP0_IF_CLK_CNT_D_OFFSET; + __raw_writel(reg, DI_DISP_ACC_CC); + break; + case DISP1: + if (ifc_width == 8) { + __raw_writel(0x00070000, DI_DISP1_CB0_MAP); + __raw_writel(0x0000FFFF, DI_DISP1_CB1_MAP); + __raw_writel(0x0000FFFF, DI_DISP1_CB2_MAP); + } else { + __raw_writel(0x00070000, DI_DISP1_CB0_MAP); + __raw_writel(0x000F0000, DI_DISP1_CB1_MAP); + __raw_writel(0x0000FFFF, DI_DISP1_CB2_MAP); + } + __raw_writel(di_mappings[map].map_byte1, DI_DISP1_DB0_MAP); + __raw_writel(di_mappings[map].map_byte2, DI_DISP1_DB1_MAP); + __raw_writel(di_mappings[map].map_byte3, DI_DISP1_DB2_MAP); + reg = __raw_readl(DI_DISP_ACC_CC); + reg &= ~DISP1_IF_CLK_CNT_D_MASK; + reg |= (di_mappings[map].cycle_cnt - 1) << + DISP1_IF_CLK_CNT_D_OFFSET; + __raw_writel(reg, DI_DISP_ACC_CC); + break; + case DISP2: + if (ifc_width == 8) { + __raw_writel(0x00070000, DI_DISP2_CB0_MAP); + __raw_writel(0x0000FFFF, DI_DISP2_CB1_MAP); + __raw_writel(0x0000FFFF, DI_DISP2_CB2_MAP); + } else { + __raw_writel(0x00070000, DI_DISP2_CB0_MAP); + __raw_writel(0x000F0000, DI_DISP2_CB1_MAP); + __raw_writel(0x0000FFFF, DI_DISP2_CB2_MAP); + } + __raw_writel(di_mappings[map].map_byte1, DI_DISP2_DB0_MAP); + __raw_writel(di_mappings[map].map_byte2, DI_DISP2_DB1_MAP); + __raw_writel(di_mappings[map].map_byte3, DI_DISP2_DB2_MAP); + reg = __raw_readl(DI_DISP_ACC_CC); + reg &= ~DISP2_IF_CLK_CNT_D_MASK; + reg |= (di_mappings[map].cycle_cnt - 1) << + DISP2_IF_CLK_CNT_D_OFFSET; + __raw_writel(reg, DI_DISP_ACC_CC); + break; + default: + break; + } +} + +void ipu_disp_direct_write(ipu_channel_t channel, u32 value, u32 offset) +{ + /*TODO*/ +} + +int ipu_init_async_panel(int disp, int type, uint32_t cycle_time, + uint32_t pixel_fmt, ipu_adc_sig_cfg_t sig) +{ + /*TODO:uniform interface for ipu async panel init*/ + return -1; +} + +EXPORT_SYMBOL(ipu_adc_write_template); +EXPORT_SYMBOL(ipu_adc_write_cmd); +EXPORT_SYMBOL(ipu_adc_set_update_mode); +EXPORT_SYMBOL(ipu_adc_init_panel); +EXPORT_SYMBOL(ipu_adc_init_ifc_timing); diff --git a/drivers/mxc/ipu/ipu_calc_stripes_sizes.c b/drivers/mxc/ipu/ipu_calc_stripes_sizes.c new file mode 100644 index 000000000000..3a45c0bfc488 --- /dev/null +++ b/drivers/mxc/ipu/ipu_calc_stripes_sizes.c @@ -0,0 +1,374 @@ +/* + * Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/* + * @file ipu_calc_stripes_sizes.c + * + * @brief IPU IC functions + * + * @ingroup IPU + */ + +#include +#include +#include + +#define BPP_32 0 +#define BPP_16 3 +#define BPP_8 5 +#define BPP_24 1 +#define BPP_12 4 +#define BPP_18 2 + +static u64 _do_div(u64 a, u32 b) +{ + u64 div; + div = a; + do_div(div, b); + return div; +} + +static u32 truncate(u32 up, /* 0: down; else: up */ + u64 a, /* must be non-negative */ + u32 b) +{ + u32 d; + u64 div; + div = _do_div(a, b); + d = b * (div >> 32); + if (up && (a > (((u64)d) << 32))) + return d+b; + else + return d; +} + +static unsigned int f_calc(unsigned int pfs, unsigned int bpp, unsigned int *write) +{/* return input_f */ + unsigned int f_calculated = 0; + switch (pfs) { + case IPU_PIX_FMT_YVU422P: + case IPU_PIX_FMT_YUV422P: + case IPU_PIX_FMT_YUV420P2: + case IPU_PIX_FMT_YUV420P: + f_calculated = 16; + break; + + case IPU_PIX_FMT_NV12: + f_calculated = 8; + break; + + default: + f_calculated = 0; + break; + + } + if (!f_calculated) { + switch (bpp) { + case BPP_32: + f_calculated = 2; + break; + + case BPP_16: + f_calculated = 4; + break; + + case BPP_8: + case BPP_24: + f_calculated = 8; + break; + + case BPP_12: + f_calculated = 16; + break; + + case BPP_18: + f_calculated = 32; + break; + + default: + f_calculated = 0; + break; + } + } + return f_calculated; +} + + +static unsigned int m_calc(unsigned int pfs) +{ + unsigned int m_calculated = 0; + switch (pfs) { + case IPU_PIX_FMT_YUV420P2: + case IPU_PIX_FMT_YUV420P: + case IPU_PIX_FMT_YVU422P: + case IPU_PIX_FMT_YUV422P: + case IPU_PIX_FMT_YVU420P: + case IPU_PIX_FMT_NV12: + m_calculated = 8; + break; + + case IPU_PIX_FMT_YUYV: + case IPU_PIX_FMT_UYVY: + m_calculated = 2; + break; + + default: + m_calculated = 1; + break; + + } + return m_calculated; +} + + +/* Stripe parameters calculator */ +/************************************************************************** +Notes: +MSW = the maximal width allowed for a stripe + i.MX31: 720, i.MX35: 800, i.MX37/51/53: 1024 +cirr = the maximal inverse resizing ratio for which overlap in the input + is requested; typically cirr~2 +equal_stripes: + 0: each stripe is allowed to have independent parameters + for maximal image quality + 1: the stripes are requested to have identical parameters + (except the base address), for maximal performance +If performance is the top priority (above image quality) + Avoid overlap, by setting CIRR = 0 + This will also force effectively identical_stripes = 1 + Choose IF & OF that corresponds to the same IOX/SX for both stripes + Choose IFW & OFW such that + IFW/IM, IFW/IF, OFW/OM, OFW/OF are even integers + The function returns an error status: + 0: no error + 1: invalid input parameters -> aborted without result + Valid parameters should satisfy the following conditions + IFW <= OFW, otherwise downsizing is required + - which is not supported yet + 4 <= IFW,OFW, so some interpolation may be needed even without overlap + IM, OM, IF, OF should not vanish + 2*IF <= IFW + so the frame can be split to two equal stripes, even without overlap + 2*(OF+IF/irr_opt) <= OFW + so a valid positive INW exists even for equal stripes + OF <= MSW, otherwise, the left stripe cannot be sufficiently large + MSW < OFW, so splitting to stripes is required + OFW <= 2*MSW, so two stripes are sufficient + (this also implies that 2<=MSW) + 2: OF is not a multiple of OM - not fully-supported yet + Output is produced but OW is not guaranited to be a multiple of OM + 4: OFW reduced to be a multiple of OM + 8: CIRR > 1: truncated to 1 + Overlap is not supported (and not needed) y for upsizing) +**************************************************************************/ +int ipu_calc_stripes_sizes(const unsigned int input_frame_width, + /* input frame width;>1 */ + unsigned int output_frame_width, /* output frame width; >1 */ + const unsigned int maximal_stripe_width, + /* the maximal width allowed for a stripe */ + const unsigned long long cirr, /* see above */ + const unsigned int equal_stripes, /* see above */ + u32 input_pixelformat,/* pixel format after of read channel*/ + u32 output_pixelformat,/* pixel format after of write channel*/ + struct stripe_param *left, + struct stripe_param *right) +{ + const unsigned int irr_frac_bits = 13; + const unsigned long irr_steps = 1 << irr_frac_bits; + const u64 dirr = ((u64)1) << (32 - 2); + /* The maximum relative difference allowed between the irrs */ + const u64 cr = ((u64)4) << 32; + /* The importance ratio between the two terms in the cost function below */ + + unsigned int status; + unsigned int temp; + unsigned int onw_min; + unsigned int inw, onw, inw_best = 0; + /* number of pixels in the left stripe NOT hidden by the right stripe */ + u64 irr_opt; /* the optimal inverse resizing ratio */ + u64 rr_opt; /* the optimal resizing ratio = 1/irr_opt*/ + u64 dinw; /* the misalignment between the stripes */ + /* (measured in units of input columns) */ + u64 difwl, difwr; + /* The number of input columns not reflected in the output */ + /* the resizing ratio used for the right stripe is */ + /* left->irr and right->irr respectively */ + u64 cost, cost_min; + u64 div; /* result of division */ + + unsigned int input_m, input_f, output_m, output_f; /* parameters for upsizing by stripes */ + + status = 0; + + /* M, F calculations */ + /* read back pfs from params */ + + input_f = f_calc(input_pixelformat, 0, NULL); + input_m = 16; + /* BPP should be used in the out_F calc */ + /* Temporarily not used */ + /* out_F = F_calc(idmac->pfs, idmac->bpp, NULL); */ + + output_f = 16; + output_m = m_calc(output_pixelformat); + + + if ((output_frame_width < input_frame_width) || (input_frame_width < 4) + || (output_frame_width < 4)) + return 1; + + irr_opt = _do_div((((u64)(input_frame_width - 1)) << 32), + (output_frame_width - 1)); + rr_opt = _do_div((((u64)(output_frame_width - 1)) << 32), + (input_frame_width - 1)); + + if ((input_m == 0) || (output_m == 0) || (input_f == 0) || (output_f == 0) + || (input_frame_width < (2 * input_f)) + || ((((u64)output_frame_width) << 32) < + (2 * ((((u64)output_f) << 32) + (input_f * rr_opt)))) + || (maximal_stripe_width < output_f) + || (output_frame_width <= maximal_stripe_width) + || ((2 * maximal_stripe_width) < output_frame_width)) + return 1; + + if (output_f % output_m) + status += 2; + + temp = truncate(0, (((u64)output_frame_width) << 32), output_m); + if (temp < output_frame_width) { + output_frame_width = temp; + status += 4; + } + + if (equal_stripes) { + if ((irr_opt > cirr) /* overlap in the input is not requested */ + && ((input_frame_width % (input_m << 1)) == 0) + && ((input_frame_width % (input_f << 1)) == 0) + && ((output_frame_width % (output_m << 1)) == 0) + && ((output_frame_width % (output_f << 1)) == 0)) { + /* without overlap */ + left->input_width = right->input_width = right->input_column = + input_frame_width >> 1; + left->output_width = right->output_width = right->output_column = + output_frame_width >> 1; + left->input_column = right->input_column = 0; + div = _do_div(((((u64)irr_steps) << 32) * + (right->input_width - 1)), (right->output_width - 1)); + left->irr = right->irr = truncate(0, div, 1); + } else { /* with overlap */ + onw = truncate(0, (((u64)output_frame_width) << 32) >> 1, + output_f); + inw = truncate(0, onw * irr_opt, input_f); + /* this is the maximal inw which allows the same resizing ratio */ + /* in both stripes */ + onw = truncate(1, (inw * rr_opt), output_f); + div = _do_div((((u64)(irr_steps * inw)) << + 32), onw); + left->irr = right->irr = truncate(0, div, 1); + left->output_width = right->output_width = + output_frame_width - onw; + /* These are valid assignments for output_width, */ + /* assuming output_f is a multiple of output_m */ + div = (((u64)(left->output_width-1) * (left->irr)) << 32); + div = (((u64)1) << 32) + _do_div(div, irr_steps); + + left->input_width = right->input_width = truncate(1, div, input_m); + + div = _do_div((((u64)((right->output_width - 1) * right->irr)) << + 32), irr_steps); + difwr = (((u64)(input_frame_width - 1 - inw)) << 32) - div; + div = _do_div((difwr + (((u64)input_f) << 32)), 2); + left->input_column = truncate(0, div, input_f); + + + /* This splits the truncated input columns evenly */ + /* between the left and right margins */ + right->input_column = left->input_column + inw; + left->output_column = 0; + right->output_column = onw; + } + } else { /* independent stripes */ + onw_min = output_frame_width - maximal_stripe_width; + /* onw is a multiple of output_f, in the range */ + /* [max(output_f,output_frame_width-maximal_stripe_width),*/ + /*min(output_frame_width-2,maximal_stripe_width)] */ + /* definitely beyond the cost of any valid setting */ + cost_min = (((u64)input_frame_width) << 32) + cr; + onw = truncate(0, ((u64)maximal_stripe_width), output_f); + if (output_frame_width - onw == 1) + onw -= output_f; /* => onw and output_frame_width-1-onw are positive */ + inw = truncate(0, onw * irr_opt, input_f); + /* this is the maximal inw which allows the same resizing ratio */ + /* in both stripes */ + onw = truncate(1, inw * rr_opt, output_f); + do { + div = _do_div((((u64)(irr_steps * inw)) << 32), onw); + left->irr = truncate(0, div, 1); + div = _do_div((((u64)(onw * left->irr)) << 32), + irr_steps); + dinw = (((u64)inw) << 32) - div; + + div = _do_div((((u64)((output_frame_width - 1 - onw) * left->irr)) << + 32), irr_steps); + + difwl = (((u64)(input_frame_width - 1 - inw)) << 32) - div; + + cost = difwl + (((u64)(cr * dinw)) >> 32); + + if (cost < cost_min) { + inw_best = inw; + cost_min = cost; + } + + inw -= input_f; + onw = truncate(1, inw * rr_opt, output_f); + /* This is the minimal onw which allows the same resizing ratio */ + /* in both stripes */ + } while (onw >= onw_min); + + inw = inw_best; + onw = truncate(1, inw * rr_opt, output_f); + div = _do_div((((u64)(irr_steps * inw)) << 32), onw); + left->irr = truncate(0, div, 1); + + left->output_width = onw; + right->output_width = output_frame_width - onw; + /* These are valid assignments for output_width, */ + /* assuming output_f is a multiple of output_m */ + left->input_width = truncate(1, ((u64)(inw + 1)) << 32, input_m); + right->input_width = truncate(1, ((u64)(input_frame_width - inw)) << + 32, input_m); + + div = _do_div((((u64)(irr_steps * (input_frame_width - 1 - inw))) << + 32), (right->output_width - 1)); + right->irr = truncate(0, div, 1); + temp = truncate(0, ((u64)left->irr) * ((((u64)1) << 32) + dirr), 1); + if (temp < right->irr) + right->irr = temp; + div = _do_div(((u64)((right->output_width - 1) * right->irr) << + 32), irr_steps); + difwr = (u64)(input_frame_width - 1 - inw) - div; + + + div = _do_div((difwr + (((u64)input_f) << 32)), 2); + left->input_column = truncate(0, div, input_f); + + /* This splits the truncated input columns evenly */ + /* between the left and right margins */ + right->input_column = left->input_column + inw; + left->output_column = 0; + right->output_column = onw; + } + return status; +} +EXPORT_SYMBOL(ipu_calc_stripes_sizes); diff --git a/drivers/mxc/ipu/ipu_common.c b/drivers/mxc/ipu/ipu_common.c new file mode 100644 index 000000000000..a9ab8b8a2edf --- /dev/null +++ b/drivers/mxc/ipu/ipu_common.c @@ -0,0 +1,1970 @@ +/* + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file ipu_common.c + * + * @brief This file contains the IPU driver common API functions. + * + * @ingroup IPU + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ipu_prv.h" +#include "ipu_regs.h" +#include "ipu_param_mem.h" + +/* + * This type definition is used to define a node in the GPIO interrupt queue for + * registered interrupts for GPIO pins. Each node contains the GPIO signal number + * associated with the ISR and the actual ISR function pointer. + */ +struct ipu_irq_node { + irqreturn_t(*handler) (int, void *); /*!< the ISR */ + const char *name; /*!< device associated with the interrupt */ + void *dev_id; /*!< some unique information for the ISR */ + __u32 flags; /*!< not used */ +}; + +/* Globals */ +struct clk *g_ipu_clk; +struct clk *g_ipu_csi_clk; +static struct clk *dfm_clk; +int g_ipu_irq[2]; +int g_ipu_hw_rev; +bool g_sec_chan_en[21]; +uint32_t g_channel_init_mask; +DEFINE_SPINLOCK(ipu_lock); +struct device *g_ipu_dev; + +static struct ipu_irq_node ipu_irq_list[IPU_IRQ_COUNT]; +static const char driver_name[] = "mxc_ipu"; + +static uint32_t g_ipu_config; +static uint32_t g_channel_init_mask_backup; +static bool g_csi_used; + +/* Static functions */ +static irqreturn_t ipu_irq_handler(int irq, void *desc); +static void _ipu_pf_init(ipu_channel_params_t *params); +static void _ipu_pf_uninit(void); + +static inline uint32_t channel_2_dma(ipu_channel_t ch, ipu_buffer_t type) +{ + return ((type == IPU_INPUT_BUFFER) ? ((uint32_t) ch & 0xFF) : + ((type == IPU_OUTPUT_BUFFER) ? (((uint32_t) ch >> 8) & 0xFF) + : (((uint32_t) ch >> 16) & 0xFF))); +}; + +static inline uint32_t DMAParamAddr(uint32_t dma_ch) +{ + return 0x10000 | (dma_ch << 4); +}; + +/*! + * This function is called by the driver framework to initialize the IPU + * hardware. + * + * @param dev The device structure for the IPU passed in by the framework. + * + * @return This function returns 0 on success or negative error code on error + */ +static +int ipu_probe(struct platform_device *pdev) +{ + struct mxc_ipu_config *ipu_conf = pdev->dev.platform_data; + + spin_lock_init(&ipu_lock); + + g_ipu_dev = &pdev->dev; + g_ipu_hw_rev = ipu_conf->rev; + + /* Register IPU interrupts */ + g_ipu_irq[0] = platform_get_irq(pdev, 0); + if (g_ipu_irq[0] < 0) + return -EINVAL; + + if (request_irq(g_ipu_irq[0], ipu_irq_handler, 0, driver_name, 0) != 0) { + dev_err(g_ipu_dev, "request SYNC interrupt failed\n"); + return -EBUSY; + } + /* Some platforms have 2 IPU interrupts */ + g_ipu_irq[1] = platform_get_irq(pdev, 1); + if (g_ipu_irq[1] >= 0) { + if (request_irq + (g_ipu_irq[1], ipu_irq_handler, 0, driver_name, 0) != 0) { + dev_err(g_ipu_dev, "request ERR interrupt failed\n"); + return -EBUSY; + } + } + + /* Enable IPU and CSI clocks */ + /* Get IPU clock freq */ + g_ipu_clk = clk_get(&pdev->dev, "ipu_clk"); + dev_dbg(g_ipu_dev, "ipu_clk = %lu\n", clk_get_rate(g_ipu_clk)); + + g_ipu_csi_clk = clk_get(&pdev->dev, "csi_clk"); + + dfm_clk = clk_get(NULL, "dfm_clk"); + + clk_enable(g_ipu_clk); + + /* resetting the CONF register of the IPU */ + __raw_writel(0x00000000, IPU_CONF); + + __raw_writel(0x00100010L, DI_HSP_CLK_PER); + + /* Set SDC refresh channels as high priority */ + __raw_writel(0x0000C000L, IDMAC_CHA_PRI); + + /* Set to max back to back burst requests */ + __raw_writel(0x00000000L, IDMAC_CONF); + + register_ipu_device(); + + return 0; +} + +/*! + * This function is called to initialize a logical IPU channel. + * + * @param channel Input parameter for the logical channel ID to initalize. + * + * @param params Input parameter containing union of channel initialization + * parameters. + * + * @return This function returns 0 on success or negative error code on fail + */ +int32_t ipu_init_channel(ipu_channel_t channel, ipu_channel_params_t *params) +{ + uint32_t ipu_conf; + uint32_t reg; + unsigned long lock_flags; + + dev_dbg(g_ipu_dev, "init channel = %d\n", IPU_CHAN_ID(channel)); + + if ((channel != MEM_SDC_BG) && (channel != MEM_SDC_FG) && + (channel != MEM_ROT_ENC_MEM) && (channel != MEM_ROT_VF_MEM) && + (channel != MEM_ROT_PP_MEM) && (channel != CSI_MEM) + && (params == NULL)) { + return -EINVAL; + } + + spin_lock_irqsave(&ipu_lock, lock_flags); + + ipu_conf = __raw_readl(IPU_CONF); + if (ipu_conf == 0) { + clk_enable(g_ipu_clk); + } + + if (g_channel_init_mask & (1L << IPU_CHAN_ID(channel))) { + dev_err(g_ipu_dev, "Warning: channel already initialized %d\n", + IPU_CHAN_ID(channel)); + } + + switch (channel) { + case CSI_PRP_VF_MEM: + reg = __raw_readl(IPU_FS_PROC_FLOW); + __raw_writel(reg & ~FS_VF_IN_VALID, IPU_FS_PROC_FLOW); + + if (params->mem_prp_vf_mem.graphics_combine_en) + g_sec_chan_en[IPU_CHAN_ID(channel)] = true; + + _ipu_ic_init_prpvf(params, true); + break; + case CSI_PRP_VF_ADC: + reg = __raw_readl(IPU_FS_PROC_FLOW); + __raw_writel(reg | (FS_DEST_ADC << FS_PRPVF_DEST_SEL_OFFSET), + IPU_FS_PROC_FLOW); + + _ipu_adc_init_channel(CSI_PRP_VF_ADC, + params->csi_prp_vf_adc.disp, + WriteTemplateNonSeq, + params->csi_prp_vf_adc.out_left, + params->csi_prp_vf_adc.out_top); + + _ipu_ic_init_prpvf(params, true); + break; + case MEM_PRP_VF_MEM: + reg = __raw_readl(IPU_FS_PROC_FLOW); + __raw_writel(reg | FS_VF_IN_VALID, IPU_FS_PROC_FLOW); + + if (params->mem_prp_vf_mem.graphics_combine_en) + g_sec_chan_en[IPU_CHAN_ID(channel)] = true; + + _ipu_ic_init_prpvf(params, false); + break; + case MEM_ROT_VF_MEM: + _ipu_ic_init_rotate_vf(params); + break; + case CSI_PRP_ENC_MEM: + reg = __raw_readl(IPU_FS_PROC_FLOW); + __raw_writel(reg & ~FS_ENC_IN_VALID, IPU_FS_PROC_FLOW); + _ipu_ic_init_prpenc(params, true); + break; + case MEM_PRP_ENC_MEM: + reg = __raw_readl(IPU_FS_PROC_FLOW); + __raw_writel(reg | FS_ENC_IN_VALID, IPU_FS_PROC_FLOW); + _ipu_ic_init_prpenc(params, false); + break; + case MEM_ROT_ENC_MEM: + _ipu_ic_init_rotate_enc(params); + break; + case MEM_PP_ADC: + reg = __raw_readl(IPU_FS_PROC_FLOW); + __raw_writel(reg | (FS_DEST_ADC << FS_PP_DEST_SEL_OFFSET), + IPU_FS_PROC_FLOW); + + _ipu_adc_init_channel(MEM_PP_ADC, params->mem_pp_adc.disp, + WriteTemplateNonSeq, + params->mem_pp_adc.out_left, + params->mem_pp_adc.out_top); + + if (params->mem_pp_adc.graphics_combine_en) + g_sec_chan_en[IPU_CHAN_ID(channel)] = true; + + _ipu_ic_init_pp(params); + break; + case MEM_PP_MEM: + if (params->mem_pp_mem.graphics_combine_en) + g_sec_chan_en[IPU_CHAN_ID(channel)] = true; + + _ipu_ic_init_pp(params); + break; + case MEM_ROT_PP_MEM: + _ipu_ic_init_rotate_pp(params); + break; + case CSI_MEM: + _ipu_ic_init_csi(params); + break; + + case MEM_PF_Y_MEM: + case MEM_PF_U_MEM: + case MEM_PF_V_MEM: + /* Enable PF block */ + _ipu_pf_init(params); + break; + + case MEM_SDC_BG: + break; + case MEM_SDC_FG: + break; + case ADC_SYS1: + _ipu_adc_init_channel(ADC_SYS1, params->adc_sys1.disp, + params->adc_sys1.ch_mode, + params->adc_sys1.out_left, + params->adc_sys1.out_top); + break; + case ADC_SYS2: + _ipu_adc_init_channel(ADC_SYS2, params->adc_sys2.disp, + params->adc_sys2.ch_mode, + params->adc_sys2.out_left, + params->adc_sys2.out_top); + break; + default: + dev_err(g_ipu_dev, "Missing channel initialization\n"); + spin_unlock_irqrestore(&ipu_lock, lock_flags); + return -EINVAL; + } + + /* Enable IPU sub module */ + g_channel_init_mask |= 1L << IPU_CHAN_ID(channel); + + if (g_channel_init_mask & 0x00000066L) { /*CSI */ + ipu_conf |= IPU_CONF_CSI_EN; + if (cpu_is_mx31() || cpu_is_mx32()) { + g_csi_used = true; + } + } + if (g_channel_init_mask & 0x00001FFFL) { /*IC */ + ipu_conf |= IPU_CONF_IC_EN; + } + if (g_channel_init_mask & 0x00000A10L) { /*ROT */ + ipu_conf |= IPU_CONF_ROT_EN; + } + if (g_channel_init_mask & 0x0001C000L) { /*SDC */ + ipu_conf |= IPU_CONF_SDC_EN | IPU_CONF_DI_EN; + } + if (g_channel_init_mask & 0x00061140L) { /*ADC */ + ipu_conf |= IPU_CONF_ADC_EN | IPU_CONF_DI_EN; + } + if (g_channel_init_mask & 0x00380000L) { /*PF */ + ipu_conf |= IPU_CONF_PF_EN; + } + __raw_writel(ipu_conf, IPU_CONF); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + + return 0; +} + +/*! + * This function is called to uninitialize a logical IPU channel. + * + * @param channel Input parameter for the logical channel ID to uninitalize. + */ +void ipu_uninit_channel(ipu_channel_t channel) +{ + unsigned long lock_flags; + uint32_t reg; + uint32_t dma, mask = 0; + uint32_t ipu_conf; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + if ((g_channel_init_mask & (1L << IPU_CHAN_ID(channel))) == 0) { + dev_err(g_ipu_dev, "Channel already uninitialized %d\n", + IPU_CHAN_ID(channel)); + spin_unlock_irqrestore(&ipu_lock, lock_flags); + return; + } + + /* Make sure channel is disabled */ + /* Get input and output dma channels */ + dma = channel_2_dma(channel, IPU_OUTPUT_BUFFER); + if (dma != IDMA_CHAN_INVALID) + mask |= 1UL << dma; + dma = channel_2_dma(channel, IPU_INPUT_BUFFER); + if (dma != IDMA_CHAN_INVALID) + mask |= 1UL << dma; + /* Get secondary input dma channel */ + if (g_sec_chan_en[IPU_CHAN_ID(channel)]) { + dma = channel_2_dma(channel, IPU_SEC_INPUT_BUFFER); + if (dma != IDMA_CHAN_INVALID) { + mask |= 1UL << dma; + } + } + if (mask & __raw_readl(IDMAC_CHA_EN)) { + dev_err(g_ipu_dev, + "Channel %d is not disabled, disable first\n", + IPU_CHAN_ID(channel)); + spin_unlock_irqrestore(&ipu_lock, lock_flags); + return; + } + + /* Reset the double buffer */ + reg = __raw_readl(IPU_CHA_DB_MODE_SEL); + __raw_writel(reg & ~mask, IPU_CHA_DB_MODE_SEL); + + g_sec_chan_en[IPU_CHAN_ID(channel)] = false; + + switch (channel) { + case CSI_MEM: + _ipu_ic_uninit_csi(); + break; + case CSI_PRP_VF_ADC: + reg = __raw_readl(IPU_FS_PROC_FLOW); + __raw_writel(reg & ~FS_PRPVF_DEST_SEL_MASK, IPU_FS_PROC_FLOW); + + _ipu_adc_uninit_channel(CSI_PRP_VF_ADC); + + /* Fall thru */ + case CSI_PRP_VF_MEM: + case MEM_PRP_VF_MEM: + _ipu_ic_uninit_prpvf(); + break; + case MEM_PRP_VF_ADC: + break; + case MEM_ROT_VF_MEM: + _ipu_ic_uninit_rotate_vf(); + break; + case CSI_PRP_ENC_MEM: + case MEM_PRP_ENC_MEM: + _ipu_ic_uninit_prpenc(); + break; + case MEM_ROT_ENC_MEM: + _ipu_ic_uninit_rotate_enc(); + break; + case MEM_PP_ADC: + reg = __raw_readl(IPU_FS_PROC_FLOW); + __raw_writel(reg & ~FS_PP_DEST_SEL_MASK, IPU_FS_PROC_FLOW); + + _ipu_adc_uninit_channel(MEM_PP_ADC); + + /* Fall thru */ + case MEM_PP_MEM: + _ipu_ic_uninit_pp(); + break; + case MEM_ROT_PP_MEM: + _ipu_ic_uninit_rotate_pp(); + break; + + case MEM_PF_Y_MEM: + _ipu_pf_uninit(); + break; + case MEM_PF_U_MEM: + case MEM_PF_V_MEM: + break; + + case MEM_SDC_BG: + break; + case MEM_SDC_FG: + break; + case ADC_SYS1: + _ipu_adc_uninit_channel(ADC_SYS1); + break; + case ADC_SYS2: + _ipu_adc_uninit_channel(ADC_SYS2); + break; + case MEM_SDC_MASK: + case CHAN_NONE: + break; + } + + g_channel_init_mask &= ~(1L << IPU_CHAN_ID(channel)); + + ipu_conf = __raw_readl(IPU_CONF); + if ((g_channel_init_mask & 0x00000066L) == 0) { /*CSI */ + ipu_conf &= ~IPU_CONF_CSI_EN; + } + if ((g_channel_init_mask & 0x00001FFFL) == 0) { /*IC */ + ipu_conf &= ~IPU_CONF_IC_EN; + } + if ((g_channel_init_mask & 0x00000A10L) == 0) { /*ROT */ + ipu_conf &= ~IPU_CONF_ROT_EN; + } + if ((g_channel_init_mask & 0x0001C000L) == 0) { /*SDC */ + ipu_conf &= ~IPU_CONF_SDC_EN; + } + if ((g_channel_init_mask & 0x00061140L) == 0) { /*ADC */ + ipu_conf &= ~IPU_CONF_ADC_EN; + } + if ((g_channel_init_mask & 0x0007D140L) == 0) { /*DI */ + ipu_conf &= ~IPU_CONF_DI_EN; + } + if ((g_channel_init_mask & 0x00380000L) == 0) { /*PF */ + ipu_conf &= ~IPU_CONF_PF_EN; + } + __raw_writel(ipu_conf, IPU_CONF); + if (ipu_conf == 0) { + clk_disable(g_ipu_clk); + } + + spin_unlock_irqrestore(&ipu_lock, lock_flags); +} + +/*! + * This function is called to initialize a buffer for logical IPU channel. + * + * @param channel Input parameter for the logical channel ID. + * + * @param type Input parameter which buffer to initialize. + * + * @param pixel_fmt Input parameter for pixel format of buffer. Pixel + * format is a FOURCC ASCII code. + * + * @param width Input parameter for width of buffer in pixels. + * + * @param height Input parameter for height of buffer in pixels. + * + * @param stride Input parameter for stride length of buffer + * in pixels. + * + * @param rot_mode Input parameter for rotation setting of buffer. + * A rotation setting other than \b IPU_ROTATE_VERT_FLIP + * should only be used for input buffers of rotation + * channels. + * + * @param phyaddr_0 Input parameter buffer 0 physical address. + * + * @param phyaddr_1 Input parameter buffer 1 physical address. + * Setting this to a value other than NULL enables + * double buffering mode. + * + * @param u private u offset for additional cropping, + * zero if not used. + * + * @param v private v offset for additional cropping, + * zero if not used. + * + * @return This function returns 0 on success or negative error code on fail + */ +int32_t ipu_init_channel_buffer(ipu_channel_t channel, ipu_buffer_t type, + uint32_t pixel_fmt, + uint16_t width, uint16_t height, + uint32_t stride, + ipu_rotate_mode_t rot_mode, + dma_addr_t phyaddr_0, dma_addr_t phyaddr_1, + uint32_t u, uint32_t v) +{ + uint32_t params[10]; + unsigned long lock_flags; + uint32_t reg; + uint32_t dma_chan; + + dma_chan = channel_2_dma(channel, type); + + if (stride < width * bytes_per_pixel(pixel_fmt)) + stride = width * bytes_per_pixel(pixel_fmt); + + if (dma_chan == IDMA_CHAN_INVALID) + return -EINVAL; + + if (stride % 4) { + dev_err(g_ipu_dev, + "Stride must be 32-bit aligned, stride = %d\n", stride); + return -EINVAL; + } + /* IC channels' width must be multiple of 8 pixels */ + if ((dma_chan <= 13) && (width % 8)) { + dev_err(g_ipu_dev, "width must be 8 pixel multiple\n"); + return -EINVAL; + } + /* Build parameter memory data for DMA channel */ + _ipu_ch_param_set_size(params, pixel_fmt, width, height, stride, u, v); + _ipu_ch_param_set_buffer(params, phyaddr_0, phyaddr_1); + _ipu_ch_param_set_rotation(params, rot_mode); + /* Some channels (rotation) have restriction on burst length */ + if ((dma_chan == 10) || (dma_chan == 11) || (dma_chan == 13)) { + _ipu_ch_param_set_burst_size(params, 8); + } else if (dma_chan == 24) { /* PF QP channel */ + _ipu_ch_param_set_burst_size(params, 4); + } else if (dma_chan == 25) { /* PF H264 BS channel */ + _ipu_ch_param_set_burst_size(params, 16); + } else if (((dma_chan == 14) || (dma_chan == 15)) && + pixel_fmt == IPU_PIX_FMT_RGB565) { + _ipu_ch_param_set_burst_size(params, 16); + } + + spin_lock_irqsave(&ipu_lock, lock_flags); + + _ipu_write_param_mem(DMAParamAddr(dma_chan), params, 10); + + reg = __raw_readl(IPU_CHA_DB_MODE_SEL); + if (phyaddr_1) { + reg |= 1UL << dma_chan; + } else { + reg &= ~(1UL << dma_chan); + } + __raw_writel(reg, IPU_CHA_DB_MODE_SEL); + + /* Reset to buffer 0 */ + __raw_writel(1UL << dma_chan, IPU_CHA_CUR_BUF); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + + return 0; +} + +/*! + * This function is called to update the physical address of a buffer for + * a logical IPU channel. + * + * @param channel Input parameter for the logical channel ID. + * + * @param type Input parameter which buffer to initialize. + * + * @param bufNum Input parameter for which buffer number to update. + * 0 or 1 are the only valid values. + * + * @param phyaddr Input parameter buffer physical address. + * + * @return This function returns 0 on success or negative error code on + * fail. This function will fail if the buffer is set to ready. + */ +int32_t ipu_update_channel_buffer(ipu_channel_t channel, ipu_buffer_t type, + uint32_t bufNum, dma_addr_t phyaddr) +{ + uint32_t reg; + unsigned long lock_flags; + uint32_t dma_chan = channel_2_dma(channel, type); + + if (dma_chan == IDMA_CHAN_INVALID) + return -EINVAL; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + if (bufNum == 0) { + reg = __raw_readl(IPU_CHA_BUF0_RDY); + if (reg & (1UL << dma_chan)) { + spin_unlock_irqrestore(&ipu_lock, lock_flags); + return -EACCES; + } + __raw_writel(DMAParamAddr(dma_chan) + 0x0008UL, IPU_IMA_ADDR); + __raw_writel(phyaddr, IPU_IMA_DATA); + } else { + reg = __raw_readl(IPU_CHA_BUF1_RDY); + if (reg & (1UL << dma_chan)) { + spin_unlock_irqrestore(&ipu_lock, lock_flags); + return -EACCES; + } + __raw_writel(DMAParamAddr(dma_chan) + 0x0009UL, IPU_IMA_ADDR); + __raw_writel(phyaddr, IPU_IMA_DATA); + } + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + dev_dbg(g_ipu_dev, "IPU: update IDMA ch %d buf %d = 0x%08X\n", + dma_chan, bufNum, phyaddr); + return 0; +} + +/*! + * This function is called to initialize a buffer for logical IPU channel. + * + * @param channel Input parameter for the logical channel ID. + * + * @param type Input parameter which buffer to initialize. + * + * @param pixel_fmt Input parameter for pixel format of buffer. + * Pixel format is a FOURCC ASCII code. + * + * @param width Input parameter for width of buffer in pixels. + * + * @param height Input parameter for height of buffer in pixels. + * + * @param stride Input parameter for stride length of buffer + * in pixels. + * + * @param u predefined private u offset for additional cropping, + * zero if not used. + * + * @param v predefined private v offset for additional cropping, + * zero if not used. + * + * @param vertical_offset vertical offset for Y coordinate + * in the existed frame + * + * + * @param horizontal_offset horizontal offset for X coordinate + * in the existed frame + * + * + * @return Returns 0 on success or negative error code on fail + * This function will fail if any buffer is set to ready. + */ + +int32_t ipu_update_channel_offset(ipu_channel_t channel, ipu_buffer_t type, + uint32_t pixel_fmt, + uint16_t width, uint16_t height, + uint32_t stride, + uint32_t u, uint32_t v, + uint32_t vertical_offset, uint32_t horizontal_offset) +{ + uint32_t reg; + int ret = 0; + unsigned long lock_flags; + uint32_t dma_chan = channel_2_dma(channel, type); + + if (dma_chan == IDMA_CHAN_INVALID) + return -EINVAL; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + ret = -EACCES; + spin_unlock_irqrestore(&ipu_lock, lock_flags); + return ret; +} +EXPORT_SYMBOL(ipu_update_channel_offset); + +/*! + * This function is called to set a channel's buffer as ready. + * + * @param channel Input parameter for the logical channel ID. + * + * @param type Input parameter which buffer to initialize. + * + * @param bufNum Input parameter for which buffer number set to + * ready state. + * + * @return This function returns 0 on success or negative error code on fail + */ +int32_t ipu_select_buffer(ipu_channel_t channel, ipu_buffer_t type, + uint32_t bufNum) +{ + uint32_t dma_chan = channel_2_dma(channel, type); + + if (dma_chan == IDMA_CHAN_INVALID) + return -EINVAL; + + if (bufNum == 0) { + /*Mark buffer 0 as ready. */ + __raw_writel(1UL << dma_chan, IPU_CHA_BUF0_RDY); + } else { + /*Mark buffer 1 as ready. */ + __raw_writel(1UL << dma_chan, IPU_CHA_BUF1_RDY); + } + return 0; +} + +/*! + * This function check buffer ready for a logical channel. + * + * @param channel Input parameter for the logical channel ID. + * + * @param type Input parameter which buffer to clear. + * + * @param bufNum Input parameter for which buffer number clear + * ready state. + * + */ +int32_t ipu_check_buffer_busy(ipu_channel_t channel, ipu_buffer_t type, + uint32_t bufNum) +{ + uint32_t dma_chan = channel_2_dma(channel, type); + uint32_t reg; + + if (dma_chan == IDMA_CHAN_INVALID) + return -EINVAL; + + if (bufNum == 0) + reg = __raw_readl(IPU_CHA_BUF0_RDY); + else + reg = __raw_readl(IPU_CHA_BUF1_RDY); + + if (reg & (1UL << dma_chan)) + return 1; + else + return 0; +} +EXPORT_SYMBOL(ipu_check_buffer_busy); + +/*! + * This function links 2 channels together for automatic frame + * synchronization. The output of the source channel is linked to the input of + * the destination channel. + * + * @param src_ch Input parameter for the logical channel ID of + * the source channel. + * + * @param dest_ch Input parameter for the logical channel ID of + * the destination channel. + * + * @return This function returns 0 on success or negative error code on + * fail. + */ +int32_t ipu_link_channels(ipu_channel_t src_ch, ipu_channel_t dest_ch) +{ + unsigned long lock_flags; + uint32_t out_dma; + uint32_t in_dma; + bool isProc; + uint32_t value; + uint32_t mask; + uint32_t offset; + uint32_t fs_proc_flow; + uint32_t fs_disp_flow; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + fs_proc_flow = __raw_readl(IPU_FS_PROC_FLOW); + fs_disp_flow = __raw_readl(IPU_FS_DISP_FLOW); + + out_dma = (1UL << channel_2_dma(src_ch, IPU_OUTPUT_BUFFER)); + in_dma = (1UL << channel_2_dma(dest_ch, IPU_INPUT_BUFFER)); + + /* PROCESS THE OUTPUT DMA CH */ + switch (out_dma) { + /*VF-> */ + case IDMA_IC_1: + pr_debug("Link VF->"); + isProc = true; + mask = FS_PRPVF_DEST_SEL_MASK; + offset = FS_PRPVF_DEST_SEL_OFFSET; + value = (in_dma == IDMA_IC_11) ? FS_DEST_ROT : /*->VF_ROT */ + (in_dma == IDMA_ADC_SYS1_WR) ? FS_DEST_ADC1 : /* ->ADC1 */ + (in_dma == IDMA_ADC_SYS2_WR) ? FS_DEST_ADC2 : /* ->ADC2 */ + (in_dma == IDMA_SDC_BG) ? FS_DEST_SDC_BG : /*->SDC_BG */ + (in_dma == IDMA_SDC_FG) ? FS_DEST_SDC_FG : /*->SDC_FG */ + (in_dma == IDMA_ADC_SYS1_WR) ? FS_DEST_ADC1 : /*->ADC1 */ + /* ->ADCDirect */ + 0; + break; + + /*VF_ROT-> */ + case IDMA_IC_9: + pr_debug("Link VF_ROT->"); + isProc = true; + mask = FS_PRPVF_ROT_DEST_SEL_MASK; + offset = FS_PRPVF_ROT_DEST_SEL_OFFSET; + value = (in_dma == IDMA_ADC_SYS1_WR) ? FS_DEST_ADC1 : /*->ADC1 */ + (in_dma == IDMA_ADC_SYS2_WR) ? FS_DEST_ADC2 : /* ->ADC2 */ + (in_dma == IDMA_SDC_BG) ? FS_DEST_SDC_BG : /*->SDC_BG */ + (in_dma == IDMA_SDC_FG) ? FS_DEST_SDC_FG : /*->SDC_FG */ + 0; + break; + + /*ENC-> */ + case IDMA_IC_0: + pr_debug("Link ENC->"); + isProc = true; + mask = 0; + offset = 0; + value = (in_dma == IDMA_IC_10) ? FS_PRPENC_DEST_SEL : /*->ENC_ROT */ + 0; + break; + + /*PP-> */ + case IDMA_IC_2: + pr_debug("Link PP->"); + isProc = true; + mask = FS_PP_DEST_SEL_MASK; + offset = FS_PP_DEST_SEL_OFFSET; + value = (in_dma == IDMA_IC_13) ? FS_DEST_ROT : /*->PP_ROT */ + (in_dma == IDMA_ADC_SYS1_WR) ? FS_DEST_ADC1 : /* ->ADC1 */ + (in_dma == IDMA_ADC_SYS2_WR) ? FS_DEST_ADC2 : /* ->ADC2 */ + (in_dma == IDMA_SDC_BG) ? FS_DEST_SDC_BG : /*->SDC_BG */ + (in_dma == IDMA_SDC_FG) ? FS_DEST_SDC_FG : /*->SDC_FG */ + /* ->ADCDirect */ + 0; + break; + + /*PP_ROT-> */ + case IDMA_IC_12: + pr_debug("Link PP_ROT->"); + isProc = true; + mask = FS_PP_ROT_DEST_SEL_MASK; + offset = FS_PP_ROT_DEST_SEL_OFFSET; + value = (in_dma == IDMA_IC_5) ? FS_DEST_ROT : /*->PP */ + (in_dma == IDMA_ADC_SYS1_WR) ? FS_DEST_ADC1 : /* ->ADC1 */ + (in_dma == IDMA_ADC_SYS2_WR) ? FS_DEST_ADC2 : /* ->ADC2 */ + (in_dma == IDMA_SDC_BG) ? FS_DEST_SDC_BG : /*->SDC_BG */ + (in_dma == IDMA_SDC_FG) ? FS_DEST_SDC_FG : /*->SDC_FG */ + 0; + break; + + /*PF-> */ + case IDMA_PF_Y_OUT: + case IDMA_PF_U_OUT: + case IDMA_PF_V_OUT: + pr_debug("Link PF->"); + isProc = true; + mask = FS_PF_DEST_SEL_MASK; + offset = FS_PF_DEST_SEL_OFFSET; + value = (in_dma == IDMA_IC_5) ? FS_PF_DEST_PP : + (in_dma == IDMA_IC_13) ? FS_PF_DEST_ROT : 0; + break; + + /* Invalid Chainings: ENC_ROT-> */ + default: + pr_debug("Link Invalid->"); + value = 0; + break; + + } + + if (value) { + if (isProc) { + fs_proc_flow &= ~mask; + fs_proc_flow |= (value << offset); + } else { + fs_disp_flow &= ~mask; + fs_disp_flow |= (value << offset); + } + } else { + dev_err(g_ipu_dev, "Invalid channel chaining %d -> %d\n", + out_dma, in_dma); + return -EINVAL; + } + + /* PROCESS THE INPUT DMA CH */ + switch (in_dma) { + /* ->VF_ROT */ + case IDMA_IC_11: + pr_debug("VF_ROT\n"); + isProc = true; + mask = 0; + offset = 0; + value = (out_dma == IDMA_IC_1) ? FS_PRPVF_ROT_SRC_SEL : /*VF-> */ + 0; + break; + + /* ->ENC_ROT */ + case IDMA_IC_10: + pr_debug("ENC_ROT\n"); + isProc = true; + mask = 0; + offset = 0; + value = (out_dma == IDMA_IC_0) ? FS_PRPENC_ROT_SRC_SEL : /*ENC-> */ + 0; + break; + + /* ->PP */ + case IDMA_IC_5: + pr_debug("PP\n"); + isProc = true; + mask = FS_PP_SRC_SEL_MASK; + offset = FS_PP_SRC_SEL_OFFSET; + value = (out_dma == IDMA_PF_Y_OUT) ? FS_PP_SRC_PF : /*PF-> */ + (out_dma == IDMA_PF_U_OUT) ? FS_PP_SRC_PF : /*PF-> */ + (out_dma == IDMA_PF_V_OUT) ? FS_PP_SRC_PF : /*PF-> */ + (out_dma == IDMA_IC_12) ? FS_PP_SRC_ROT : /*PP_ROT-> */ + 0; + break; + + /* ->PP_ROT */ + case IDMA_IC_13: + pr_debug("PP_ROT\n"); + isProc = true; + mask = FS_PP_ROT_SRC_SEL_MASK; + offset = FS_PP_ROT_SRC_SEL_OFFSET; + value = (out_dma == IDMA_PF_Y_OUT) ? FS_PP_SRC_PF : /*PF-> */ + (out_dma == IDMA_PF_U_OUT) ? FS_PP_SRC_PF : /*PF-> */ + (out_dma == IDMA_PF_V_OUT) ? FS_PP_SRC_PF : /*PF-> */ + (out_dma == IDMA_IC_2) ? FS_ROT_SRC_PP : /*PP-> */ + 0; + break; + + /* ->SDC_BG */ + case IDMA_SDC_BG: + pr_debug("SDC_BG\n"); + isProc = false; + mask = FS_SDC_BG_SRC_SEL_MASK; + offset = FS_SDC_BG_SRC_SEL_OFFSET; + value = (out_dma == IDMA_IC_9) ? FS_SRC_ROT_VF : /*VF_ROT-> */ + (out_dma == IDMA_IC_12) ? FS_SRC_ROT_PP : /*PP_ROT-> */ + (out_dma == IDMA_IC_1) ? FS_SRC_VF : /*VF-> */ + (out_dma == IDMA_IC_2) ? FS_SRC_PP : /*PP-> */ + 0; + break; + + /* ->SDC_FG */ + case IDMA_SDC_FG: + pr_debug("SDC_FG\n"); + isProc = false; + mask = FS_SDC_FG_SRC_SEL_MASK; + offset = FS_SDC_FG_SRC_SEL_OFFSET; + value = (out_dma == IDMA_IC_9) ? FS_SRC_ROT_VF : /*VF_ROT-> */ + (out_dma == IDMA_IC_12) ? FS_SRC_ROT_PP : /*PP_ROT-> */ + (out_dma == IDMA_IC_1) ? FS_SRC_VF : /*VF-> */ + (out_dma == IDMA_IC_2) ? FS_SRC_PP : /*PP-> */ + 0; + break; + + /* ->ADC1 */ + case IDMA_ADC_SYS1_WR: + pr_debug("ADC_SYS1\n"); + isProc = false; + mask = FS_ADC1_SRC_SEL_MASK; + offset = FS_ADC1_SRC_SEL_OFFSET; + value = (out_dma == IDMA_IC_9) ? FS_SRC_ROT_VF : /*VF_ROT-> */ + (out_dma == IDMA_IC_12) ? FS_SRC_ROT_PP : /*PP_ROT-> */ + (out_dma == IDMA_IC_1) ? FS_SRC_VF : /*VF-> */ + (out_dma == IDMA_IC_2) ? FS_SRC_PP : /*PP-> */ + 0; + break; + + /* ->ADC2 */ + case IDMA_ADC_SYS2_WR: + pr_debug("ADC_SYS2\n"); + isProc = false; + mask = FS_ADC2_SRC_SEL_MASK; + offset = FS_ADC2_SRC_SEL_OFFSET; + value = (out_dma == IDMA_IC_9) ? FS_SRC_ROT_VF : /*VF_ROT-> */ + (out_dma == IDMA_IC_12) ? FS_SRC_ROT_PP : /*PP_ROT-> */ + (out_dma == IDMA_IC_1) ? FS_SRC_VF : /*VF-> */ + (out_dma == IDMA_IC_2) ? FS_SRC_PP : /*PP-> */ + 0; + break; + + /*Invalid chains: */ + /* ->ENC, ->VF, ->PF, ->VF_COMBINE, ->PP_COMBINE */ + default: + pr_debug("Invalid\n"); + value = 0; + break; + + } + + if (value) { + if (isProc) { + fs_proc_flow &= ~mask; + fs_proc_flow |= (value << offset); + } else { + fs_disp_flow &= ~mask; + fs_disp_flow |= (value << offset); + } + } else { + dev_err(g_ipu_dev, "Invalid channel chaining %d -> %d\n", + out_dma, in_dma); + return -EINVAL; + } + + __raw_writel(fs_proc_flow, IPU_FS_PROC_FLOW); + __raw_writel(fs_disp_flow, IPU_FS_DISP_FLOW); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + return 0; +} + +/*! + * This function unlinks 2 channels and disables automatic frame + * synchronization. + * + * @param src_ch Input parameter for the logical channel ID of + * the source channel. + * + * @param dest_ch Input parameter for the logical channel ID of + * the destination channel. + * + * @return This function returns 0 on success or negative error code on + * fail. + */ +int32_t ipu_unlink_channels(ipu_channel_t src_ch, ipu_channel_t dest_ch) +{ + unsigned long lock_flags; + uint32_t out_dma; + uint32_t in_dma; + uint32_t fs_proc_flow; + uint32_t fs_disp_flow; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + fs_proc_flow = __raw_readl(IPU_FS_PROC_FLOW); + fs_disp_flow = __raw_readl(IPU_FS_DISP_FLOW); + + out_dma = (1UL << channel_2_dma(src_ch, IPU_OUTPUT_BUFFER)); + in_dma = (1UL << channel_2_dma(dest_ch, IPU_INPUT_BUFFER)); + + /*clear the src_ch's output destination */ + switch (out_dma) { + /*VF-> */ + case IDMA_IC_1: + pr_debug("Unlink VF->"); + fs_proc_flow &= ~FS_PRPVF_DEST_SEL_MASK; + break; + + /*VF_ROT-> */ + case IDMA_IC_9: + pr_debug("Unlink VF_Rot->"); + fs_proc_flow &= ~FS_PRPVF_ROT_DEST_SEL_MASK; + break; + + /*ENC-> */ + case IDMA_IC_0: + pr_debug("Unlink ENC->"); + fs_proc_flow &= ~FS_PRPENC_DEST_SEL; + break; + + /*PP-> */ + case IDMA_IC_2: + pr_debug("Unlink PP->"); + fs_proc_flow &= ~FS_PP_DEST_SEL_MASK; + break; + + /*PP_ROT-> */ + case IDMA_IC_12: + pr_debug("Unlink PP_ROT->"); + fs_proc_flow &= ~FS_PP_ROT_DEST_SEL_MASK; + break; + + /*PF-> */ + case IDMA_PF_Y_OUT: + case IDMA_PF_U_OUT: + case IDMA_PF_V_OUT: + pr_debug("Unlink PF->"); + fs_proc_flow &= ~FS_PF_DEST_SEL_MASK; + break; + + default: /*ENC_ROT-> */ + pr_debug("Unlink Invalid->"); + break; + } + + /*clear the dest_ch's input source */ + switch (in_dma) { + /*->VF_ROT*/ + case IDMA_IC_11: + pr_debug("VF_ROT\n"); + fs_proc_flow &= ~FS_PRPVF_ROT_SRC_SEL; + break; + + /*->Enc_ROT*/ + case IDMA_IC_10: + pr_debug("ENC_ROT\n"); + fs_proc_flow &= ~FS_PRPENC_ROT_SRC_SEL; + break; + + /*->PP*/ + case IDMA_IC_5: + pr_debug("PP\n"); + fs_proc_flow &= ~FS_PP_SRC_SEL_MASK; + break; + + /*->PP_ROT*/ + case IDMA_IC_13: + pr_debug("PP_ROT\n"); + fs_proc_flow &= ~FS_PP_ROT_SRC_SEL_MASK; + break; + + /*->SDC_FG*/ + case IDMA_SDC_FG: + pr_debug("SDC_FG\n"); + fs_disp_flow &= ~FS_SDC_FG_SRC_SEL_MASK; + break; + + /*->SDC_BG*/ + case IDMA_SDC_BG: + pr_debug("SDC_BG\n"); + fs_disp_flow &= ~FS_SDC_BG_SRC_SEL_MASK; + break; + + /*->ADC1*/ + case IDMA_ADC_SYS1_WR: + pr_debug("ADC_SYS1\n"); + fs_disp_flow &= ~FS_ADC1_SRC_SEL_MASK; + break; + + /*->ADC2*/ + case IDMA_ADC_SYS2_WR: + pr_debug("ADC_SYS2\n"); + fs_disp_flow &= ~FS_ADC2_SRC_SEL_MASK; + break; + + default: /*->VF, ->ENC, ->VF_COMBINE, ->PP_COMBINE, ->PF*/ + pr_debug("Invalid\n"); + break; + } + + __raw_writel(fs_proc_flow, IPU_FS_PROC_FLOW); + __raw_writel(fs_disp_flow, IPU_FS_DISP_FLOW); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + return 0; +} + +/*! + * This function check whether a logical channel was enabled. + * + * @param channel Input parameter for the logical channel ID. + * + * @return This function returns 1 while request channel is enabled or + * 0 for not enabled. + */ +int32_t ipu_is_channel_busy(ipu_channel_t channel) +{ + uint32_t reg; + uint32_t in_dma; + uint32_t out_dma; + + out_dma = channel_2_dma(channel, IPU_OUTPUT_BUFFER); + in_dma = channel_2_dma(channel, IPU_INPUT_BUFFER); + + reg = __raw_readl(IDMAC_CHA_EN); + + if (reg & ((1UL << out_dma) | (1UL << in_dma))) + return 1; + return 0; +} +EXPORT_SYMBOL(ipu_is_channel_busy); + +/*! + * This function enables a logical channel. + * + * @param channel Input parameter for the logical channel ID. + * + * @return This function returns 0 on success or negative error code on + * fail. + */ +int32_t ipu_enable_channel(ipu_channel_t channel) +{ + uint32_t reg; + unsigned long lock_flags; + uint32_t in_dma; + uint32_t sec_dma; + uint32_t out_dma; + uint32_t chan_mask = 0; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + reg = __raw_readl(IDMAC_CHA_EN); + + /* Get input and output dma channels */ + out_dma = channel_2_dma(channel, IPU_OUTPUT_BUFFER); + if (out_dma != IDMA_CHAN_INVALID) + reg |= 1UL << out_dma; + in_dma = channel_2_dma(channel, IPU_INPUT_BUFFER); + if (in_dma != IDMA_CHAN_INVALID) + reg |= 1UL << in_dma; + + /* Get secondary input dma channel */ + if (g_sec_chan_en[IPU_CHAN_ID(channel)]) { + sec_dma = channel_2_dma(channel, IPU_SEC_INPUT_BUFFER); + if (sec_dma != IDMA_CHAN_INVALID) { + reg |= 1UL << sec_dma; + } + } + + __raw_writel(reg | chan_mask, IDMAC_CHA_EN); + + if (IPU_CHAN_ID(channel) <= IPU_CHAN_ID(MEM_PP_ADC)) { + _ipu_ic_enable_task(channel); + } else if (channel == MEM_SDC_BG) { + dev_dbg(g_ipu_dev, "Initializing SDC BG\n"); + _ipu_sdc_bg_init(NULL); + } else if (channel == MEM_SDC_FG) { + dev_dbg(g_ipu_dev, "Initializing SDC FG\n"); + _ipu_sdc_fg_init(NULL); + } + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + return 0; +} + +/*! + * This function clear buffer ready for a logical channel. + * + * @param channel Input parameter for the logical channel ID. + * + * @param type Input parameter which buffer to clear. + * + * @param bufNum Input parameter for which buffer number clear + * ready state. + * + */ +void ipu_clear_buffer_ready(ipu_channel_t channel, ipu_buffer_t type, + uint32_t bufNum) +{ + /*TODO*/ +} +EXPORT_SYMBOL(ipu_clear_buffer_ready); + +uint32_t ipu_get_cur_buffer_idx(ipu_channel_t channel, ipu_buffer_t type) +{ + uint32_t reg, dma_chan; + + dma_chan = channel_2_dma(channel, type); + + reg = __raw_readl(IPU_CHA_CUR_BUF); + if (reg & (1UL << dma_chan)) + return 1; + else + return 0; +} +EXPORT_SYMBOL(ipu_get_cur_buffer_idx); + +/*! + * This function disables a logical channel. + * + * @param channel Input parameter for the logical channel ID. + * + * @param wait_for_stop Flag to set whether to wait for channel end + * of frame or return immediately. + * + * @return This function returns 0 on success or negative error code on + * fail. + */ +int32_t ipu_disable_channel(ipu_channel_t channel, bool wait_for_stop) +{ + uint32_t reg; + unsigned long lock_flags; + uint32_t sec_dma; + uint32_t in_dma; + uint32_t out_dma; + uint32_t chan_mask = 0; + uint32_t timeout; + uint32_t eof_intr; + uint32_t enabled; + + /* Get input and output dma channels */ + out_dma = channel_2_dma(channel, IPU_OUTPUT_BUFFER); + if (out_dma != IDMA_CHAN_INVALID) + chan_mask = 1UL << out_dma; + in_dma = channel_2_dma(channel, IPU_INPUT_BUFFER); + if (in_dma != IDMA_CHAN_INVALID) + chan_mask |= 1UL << in_dma; + sec_dma = channel_2_dma(channel, IPU_SEC_INPUT_BUFFER); + if (sec_dma != IDMA_CHAN_INVALID) + chan_mask |= 1UL << sec_dma; + + if (wait_for_stop && channel != MEM_SDC_FG && channel != MEM_SDC_BG) { + timeout = 40; + while ((__raw_readl(IDMAC_CHA_BUSY) & chan_mask) || + (_ipu_channel_status(channel) == TASK_STAT_ACTIVE)) { + timeout--; + msleep(10); + if (timeout == 0) { + printk + (KERN_INFO + "MXC IPU: Warning - timeout waiting for channel to stop,\n" + "\tbuf0_rdy = 0x%08X, buf1_rdy = 0x%08X\n" + "\tbusy = 0x%08X, tstat = 0x%08X\n\tmask = 0x%08X\n", + __raw_readl(IPU_CHA_BUF0_RDY), + __raw_readl(IPU_CHA_BUF1_RDY), + __raw_readl(IDMAC_CHA_BUSY), + __raw_readl(IPU_TASKS_STAT), chan_mask); + break; + } + } + dev_dbg(g_ipu_dev, "timeout = %d * 10ms\n", 40 - timeout); + } + /* SDC BG and FG must be disabled before DMA is disabled */ + if ((channel == MEM_SDC_BG) || (channel == MEM_SDC_FG)) { + + if (channel == MEM_SDC_BG) + eof_intr = IPU_IRQ_SDC_BG_EOF; + else + eof_intr = IPU_IRQ_SDC_FG_EOF; + + /* Wait for any buffer flips to finsh */ + timeout = 4; + while (timeout && + ((__raw_readl(IPU_CHA_BUF0_RDY) & chan_mask) || + (__raw_readl(IPU_CHA_BUF1_RDY) & chan_mask))) { + msleep(10); + timeout--; + } + + spin_lock_irqsave(&ipu_lock, lock_flags); + ipu_clear_irq(eof_intr); + if (channel == MEM_SDC_BG) + enabled = _ipu_sdc_bg_uninit(); + else + enabled = _ipu_sdc_fg_uninit(); + spin_unlock_irqrestore(&ipu_lock, lock_flags); + + if (enabled && wait_for_stop) { + timeout = 5; + } else { + timeout = 0; + } + while (timeout && !ipu_get_irq_status(eof_intr)) { + msleep(5); + timeout--; + } + } + + spin_lock_irqsave(&ipu_lock, lock_flags); + + /* Disable IC task */ + if (IPU_CHAN_ID(channel) <= IPU_CHAN_ID(MEM_PP_ADC)) { + _ipu_ic_disable_task(channel); + } + + /* Disable DMA channel(s) */ + reg = __raw_readl(IDMAC_CHA_EN); + __raw_writel(reg & ~chan_mask, IDMAC_CHA_EN); + + /* Clear DMA related interrupts */ + __raw_writel(chan_mask, IPU_INT_STAT_1); + __raw_writel(chan_mask, IPU_INT_STAT_2); + __raw_writel(chan_mask, IPU_INT_STAT_4); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + + return 0; +} + +int32_t ipu_enable_csi(uint32_t csi) +{ + return 0; +} + + +int32_t ipu_disable_csi(uint32_t csi) +{ + return 0; +} + +static +irqreturn_t ipu_irq_handler(int irq, void *desc) +{ + uint32_t line_base = 0; + uint32_t line; + irqreturn_t result = IRQ_NONE; + uint32_t int_stat; + + int_stat = __raw_readl(IPU_INT_STAT_1); + int_stat &= __raw_readl(IPU_INT_CTRL_1); + __raw_writel(int_stat, IPU_INT_STAT_1); + while ((line = ffs(int_stat)) != 0) { + int_stat &= ~(1UL << (line - 1)); + line += line_base - 1; + result |= + ipu_irq_list[line].handler(line, ipu_irq_list[line].dev_id); + } + + line_base = 32; + int_stat = __raw_readl(IPU_INT_STAT_2); + int_stat &= __raw_readl(IPU_INT_CTRL_2); + __raw_writel(int_stat, IPU_INT_STAT_2); + while ((line = ffs(int_stat)) != 0) { + int_stat &= ~(1UL << (line - 1)); + line += line_base - 1; + result |= + ipu_irq_list[line].handler(line, ipu_irq_list[line].dev_id); + } + + line_base = 64; + int_stat = __raw_readl(IPU_INT_STAT_3); + int_stat &= __raw_readl(IPU_INT_CTRL_3); + __raw_writel(int_stat, IPU_INT_STAT_3); + while ((line = ffs(int_stat)) != 0) { + int_stat &= ~(1UL << (line - 1)); + line += line_base - 1; + result |= + ipu_irq_list[line].handler(line, ipu_irq_list[line].dev_id); + } + + line_base = 96; + int_stat = __raw_readl(IPU_INT_STAT_4); + int_stat &= __raw_readl(IPU_INT_CTRL_4); + __raw_writel(int_stat, IPU_INT_STAT_4); + while ((line = ffs(int_stat)) != 0) { + int_stat &= ~(1UL << (line - 1)); + line += line_base - 1; + result |= + ipu_irq_list[line].handler(line, ipu_irq_list[line].dev_id); + } + + line_base = 128; + int_stat = __raw_readl(IPU_INT_STAT_5); + int_stat &= __raw_readl(IPU_INT_CTRL_5); + __raw_writel(int_stat, IPU_INT_STAT_5); + while ((line = ffs(int_stat)) != 0) { + int_stat &= ~(1UL << (line - 1)); + line += line_base - 1; + result |= + ipu_irq_list[line].handler(line, ipu_irq_list[line].dev_id); + } + + return result; +} + +/*! + * This function enables the interrupt for the specified interrupt line. + * The interrupt lines are defined in \b ipu_irq_line enum. + * + * @param irq Interrupt line to enable interrupt for. + * + */ +void ipu_enable_irq(uint32_t irq) +{ + uint32_t reg; + unsigned long lock_flags; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + reg = __raw_readl(IPUIRQ_2_CTRLREG(irq)); + reg |= IPUIRQ_2_MASK(irq); + __raw_writel(reg, IPUIRQ_2_CTRLREG(irq)); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); +} + +/*! + * This function disables the interrupt for the specified interrupt line. + * The interrupt lines are defined in \b ipu_irq_line enum. + * + * @param irq Interrupt line to disable interrupt for. + * + */ +void ipu_disable_irq(uint32_t irq) +{ + uint32_t reg; + unsigned long lock_flags; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + reg = __raw_readl(IPUIRQ_2_CTRLREG(irq)); + reg &= ~IPUIRQ_2_MASK(irq); + __raw_writel(reg, IPUIRQ_2_CTRLREG(irq)); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); +} + +/*! + * This function clears the interrupt for the specified interrupt line. + * The interrupt lines are defined in \b ipu_irq_line enum. + * + * @param irq Interrupt line to clear interrupt for. + * + */ +void ipu_clear_irq(uint32_t irq) +{ + __raw_writel(IPUIRQ_2_MASK(irq), IPUIRQ_2_STATREG(irq)); +} + +/*! + * This function returns the current interrupt status for the specified interrupt + * line. The interrupt lines are defined in \b ipu_irq_line enum. + * + * @param irq Interrupt line to get status for. + * + * @return Returns true if the interrupt is pending/asserted or false if + * the interrupt is not pending. + */ +bool ipu_get_irq_status(uint32_t irq) +{ + uint32_t reg = __raw_readl(IPUIRQ_2_STATREG(irq)); + + if (reg & IPUIRQ_2_MASK(irq)) + return true; + else + return false; +} + +/*! + * This function registers an interrupt handler function for the specified + * interrupt line. The interrupt lines are defined in \b ipu_irq_line enum. + * + * @param irq Interrupt line to get status for. + * + * @param handler Input parameter for address of the handler + * function. + * + * @param irq_flags Flags for interrupt mode. Currently not used. + * + * @param devname Input parameter for string name of driver + * registering the handler. + * + * @param dev_id Input parameter for pointer of data to be passed + * to the handler. + * + * @return This function returns 0 on success or negative error code on + * fail. + */ +int ipu_request_irq(uint32_t irq, + irqreturn_t(*handler) (int, void *), + uint32_t irq_flags, const char *devname, void *dev_id) +{ + unsigned long lock_flags; + + BUG_ON(irq >= IPU_IRQ_COUNT); + + spin_lock_irqsave(&ipu_lock, lock_flags); + + if (ipu_irq_list[irq].handler != NULL) { + dev_err(g_ipu_dev, + "ipu_request_irq - handler already installed on irq %d\n", + irq); + spin_unlock_irqrestore(&ipu_lock, lock_flags); + return -EINVAL; + } + + ipu_irq_list[irq].handler = handler; + ipu_irq_list[irq].flags = irq_flags; + ipu_irq_list[irq].dev_id = dev_id; + ipu_irq_list[irq].name = devname; + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + + ipu_enable_irq(irq); /* enable the interrupt */ + + return 0; +} + +/*! + * This function unregisters an interrupt handler for the specified interrupt + * line. The interrupt lines are defined in \b ipu_irq_line enum. + * + * @param irq Interrupt line to get status for. + * + * @param dev_id Input parameter for pointer of data to be passed + * to the handler. This must match value passed to + * ipu_request_irq(). + * + */ +void ipu_free_irq(uint32_t irq, void *dev_id) +{ + ipu_disable_irq(irq); /* disable the interrupt */ + + if (ipu_irq_list[irq].dev_id == dev_id) { + ipu_irq_list[irq].handler = NULL; + } +} + +/*! + * This function sets the post-filter pause row for h.264 mode. + * + * @param pause_row The last row to process before pausing. + * + * @return This function returns 0 on success or negative error code on + * fail. + * + */ +int32_t ipu_pf_set_pause_row(uint32_t pause_row) +{ + int32_t retval = 0; + uint32_t timeout = 5; + unsigned long lock_flags; + uint32_t reg; + + reg = __raw_readl(IPU_TASKS_STAT); + while ((reg & TSTAT_PF_MASK) && ((reg & TSTAT_PF_H264_PAUSE) == 0)) { + timeout--; + msleep(5); + if (timeout == 0) { + dev_err(g_ipu_dev, "PF Timeout - tstat = 0x%08X\n", + __raw_readl(IPU_TASKS_STAT)); + retval = -ETIMEDOUT; + goto err0; + } + } + + spin_lock_irqsave(&ipu_lock, lock_flags); + + reg = __raw_readl(PF_CONF); + + /* Set the pause row */ + if (pause_row) { + reg &= ~PF_CONF_PAUSE_ROW_MASK; + reg |= PF_CONF_PAUSE_EN | pause_row << PF_CONF_PAUSE_ROW_SHIFT; + } else { + reg &= ~(PF_CONF_PAUSE_EN | PF_CONF_PAUSE_ROW_MASK); + } + __raw_writel(reg, PF_CONF); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + err0: + return retval; +} + +/* Private functions */ +void _ipu_write_param_mem(uint32_t addr, uint32_t *data, uint32_t numWords) +{ + for (; numWords > 0; numWords--) { + dev_dbg(g_ipu_dev, + "write param mem - addr = 0x%08X, data = 0x%08X\n", + addr, *data); + __raw_writel(addr, IPU_IMA_ADDR); + __raw_writel(*data++, IPU_IMA_DATA); + addr++; + if ((addr & 0x7) == 5) { + addr &= ~0x7; /* set to word 0 */ + addr += 8; /* increment to next row */ + } + } +} + +static void _ipu_pf_init(ipu_channel_params_t *params) +{ + uint32_t reg; + + /*Setup the type of filtering required */ + switch (params->mem_pf_mem.operation) { + case PF_MPEG4_DEBLOCK: + case PF_MPEG4_DERING: + case PF_MPEG4_DEBLOCK_DERING: + g_sec_chan_en[IPU_CHAN_ID(MEM_PF_Y_MEM)] = true; + g_sec_chan_en[IPU_CHAN_ID(MEM_PF_U_MEM)] = false; + break; + case PF_H264_DEBLOCK: + g_sec_chan_en[IPU_CHAN_ID(MEM_PF_Y_MEM)] = true; + g_sec_chan_en[IPU_CHAN_ID(MEM_PF_U_MEM)] = true; + break; + default: + g_sec_chan_en[IPU_CHAN_ID(MEM_PF_Y_MEM)] = false; + g_sec_chan_en[IPU_CHAN_ID(MEM_PF_U_MEM)] = false; + return; + break; + } + reg = params->mem_pf_mem.operation; + __raw_writel(reg, PF_CONF); +} + +static void _ipu_pf_uninit(void) +{ + __raw_writel(0x0L, PF_CONF); + g_sec_chan_en[IPU_CHAN_ID(MEM_PF_Y_MEM)] = false; + g_sec_chan_en[IPU_CHAN_ID(MEM_PF_U_MEM)] = false; +} + +uint32_t _ipu_channel_status(ipu_channel_t channel) +{ + uint32_t stat = 0; + uint32_t task_stat_reg = __raw_readl(IPU_TASKS_STAT); + + switch (channel) { + case CSI_MEM: + stat = + (task_stat_reg & TSTAT_CSI2MEM_MASK) >> + TSTAT_CSI2MEM_OFFSET; + break; + case CSI_PRP_VF_ADC: + case CSI_PRP_VF_MEM: + case MEM_PRP_VF_ADC: + case MEM_PRP_VF_MEM: + stat = (task_stat_reg & TSTAT_VF_MASK) >> TSTAT_VF_OFFSET; + break; + case MEM_ROT_VF_MEM: + stat = + (task_stat_reg & TSTAT_VF_ROT_MASK) >> TSTAT_VF_ROT_OFFSET; + break; + case CSI_PRP_ENC_MEM: + case MEM_PRP_ENC_MEM: + stat = (task_stat_reg & TSTAT_ENC_MASK) >> TSTAT_ENC_OFFSET; + break; + case MEM_ROT_ENC_MEM: + stat = + (task_stat_reg & TSTAT_ENC_ROT_MASK) >> + TSTAT_ENC_ROT_OFFSET; + break; + case MEM_PP_ADC: + case MEM_PP_MEM: + stat = (task_stat_reg & TSTAT_PP_MASK) >> TSTAT_PP_OFFSET; + break; + case MEM_ROT_PP_MEM: + stat = + (task_stat_reg & TSTAT_PP_ROT_MASK) >> TSTAT_PP_ROT_OFFSET; + break; + + case MEM_PF_Y_MEM: + case MEM_PF_U_MEM: + case MEM_PF_V_MEM: + stat = (task_stat_reg & TSTAT_PF_MASK) >> TSTAT_PF_OFFSET; + break; + case MEM_SDC_BG: + break; + case MEM_SDC_FG: + break; + case ADC_SYS1: + stat = + (task_stat_reg & TSTAT_ADCSYS1_MASK) >> + TSTAT_ADCSYS1_OFFSET; + break; + case ADC_SYS2: + stat = + (task_stat_reg & TSTAT_ADCSYS2_MASK) >> + TSTAT_ADCSYS2_OFFSET; + break; + case MEM_SDC_MASK: + default: + stat = TASK_STAT_IDLE; + break; + } + return stat; +} + +uint32_t bytes_per_pixel(uint32_t fmt) +{ + switch (fmt) { + case IPU_PIX_FMT_GENERIC: /*generic data */ + case IPU_PIX_FMT_RGB332: + case IPU_PIX_FMT_YUV420P: + case IPU_PIX_FMT_YUV422P: + return 1; + break; + case IPU_PIX_FMT_RGB565: + case IPU_PIX_FMT_YUYV: + case IPU_PIX_FMT_UYVY: + return 2; + break; + case IPU_PIX_FMT_BGR24: + case IPU_PIX_FMT_RGB24: + return 3; + break; + case IPU_PIX_FMT_GENERIC_32: /*generic data */ + case IPU_PIX_FMT_BGR32: + case IPU_PIX_FMT_RGB32: + case IPU_PIX_FMT_ABGR32: + return 4; + break; + default: + return 1; + break; + } + return 0; +} + +void ipu_set_csc_coefficients(ipu_channel_t channel, int32_t param[][3]) +{ + /* TODO */ +} +EXPORT_SYMBOL(ipu_set_csc_coefficients); + +ipu_color_space_t format_to_colorspace(uint32_t fmt) +{ + switch (fmt) { + case IPU_PIX_FMT_RGB565: + case IPU_PIX_FMT_BGR24: + case IPU_PIX_FMT_RGB24: + case IPU_PIX_FMT_BGR32: + case IPU_PIX_FMT_RGB32: + return RGB; + break; + + default: + return YCbCr; + break; + } + return RGB; + +} + +static u32 saved_disp3_time_conf; +static bool in_lpdr_mode; +static struct clk *default_ipu_parent_clk; + +int ipu_lowpwr_display_enable(void) +{ + unsigned long rate, div; + struct clk *parent_clk = g_ipu_clk; + + if (in_lpdr_mode || IS_ERR(dfm_clk)) { + return -EINVAL; + } + + if (g_channel_init_mask != (1L << IPU_CHAN_ID(MEM_SDC_BG))) { + dev_err(g_ipu_dev, "LPDR mode requires only SDC BG active.\n"); + return -EINVAL; + } + + default_ipu_parent_clk = clk_get_parent(g_ipu_clk); + in_lpdr_mode = true; + + /* Calculate current pixel clock rate */ + rate = clk_get_rate(g_ipu_clk) * 16; + saved_disp3_time_conf = __raw_readl(DI_DISP3_TIME_CONF); + div = saved_disp3_time_conf & 0xFFF; + rate /= div; + rate *= 4; /* min hsp clk is 4x pixel clk */ + + /* Initialize DFM clock */ + rate = clk_round_rate(dfm_clk, rate); + clk_set_rate(dfm_clk, rate); + clk_enable(dfm_clk); + + /* Wait for next VSYNC */ + __raw_writel(IPUIRQ_2_MASK(IPU_IRQ_SDC_DISP3_VSYNC), + IPUIRQ_2_STATREG(IPU_IRQ_SDC_DISP3_VSYNC)); + while ((__raw_readl(IPUIRQ_2_STATREG(IPU_IRQ_SDC_DISP3_VSYNC)) & + IPUIRQ_2_MASK(IPU_IRQ_SDC_DISP3_VSYNC)) == 0) + msleep_interruptible(1); + + /* Set display clock divider to divide by 4 */ + __raw_writel(((0x8) << 22) | 0x40, DI_DISP3_TIME_CONF); + + clk_set_parent(parent_clk, dfm_clk); + + return 0; +} + +int ipu_lowpwr_display_disable(void) +{ + struct clk *parent_clk = g_ipu_clk; + + if (!in_lpdr_mode || IS_ERR(dfm_clk)) { + return -EINVAL; + } + + if (g_channel_init_mask != (1L << IPU_CHAN_ID(MEM_SDC_BG))) { + dev_err(g_ipu_dev, "LPDR mode requires only SDC BG active.\n"); + return -EINVAL; + } + + in_lpdr_mode = false; + + /* Wait for next VSYNC */ + __raw_writel(IPUIRQ_2_MASK(IPU_IRQ_SDC_DISP3_VSYNC), + IPUIRQ_2_STATREG(IPU_IRQ_SDC_DISP3_VSYNC)); + while ((__raw_readl(IPUIRQ_2_STATREG(IPU_IRQ_SDC_DISP3_VSYNC)) & + IPUIRQ_2_MASK(IPU_IRQ_SDC_DISP3_VSYNC)) == 0) + msleep_interruptible(1); + + __raw_writel(saved_disp3_time_conf, DI_DISP3_TIME_CONF); + clk_set_parent(parent_clk, default_ipu_parent_clk); + clk_disable(dfm_clk); + + return 0; +} + +static int ipu_suspend(struct platform_device *pdev, pm_message_t state) +{ + if (cpu_is_mx31() || cpu_is_mx32()) { + /* work-around for i.Mx31 SR mode after camera related test */ + if (g_csi_used) { + g_ipu_config = __raw_readl(IPU_CONF); + clk_enable(g_ipu_csi_clk); + __raw_writel(0x51, IPU_CONF); + g_channel_init_mask_backup = g_channel_init_mask; + g_channel_init_mask |= 2; + } + } else if (cpu_is_mx35()) { + g_ipu_config = __raw_readl(IPU_CONF); + /* Disable the clock of display otherwise the backlight cannot + * be close after camera/tvin related test */ + __raw_writel(g_ipu_config & 0xfbf, IPU_CONF); + } + + return 0; +} + +static int ipu_resume(struct platform_device *pdev) +{ + if (cpu_is_mx31() || cpu_is_mx32()) { + /* work-around for i.Mx31 SR mode after camera related test */ + if (g_csi_used) { + __raw_writel(g_ipu_config, IPU_CONF); + clk_disable(g_ipu_csi_clk); + g_channel_init_mask = g_channel_init_mask_backup; + } + } else if (cpu_is_mx35()) { + __raw_writel(g_ipu_config, IPU_CONF); + } + + return 0; +} + +/*! + * This structure contains pointers to the power management callback functions. + */ +static struct platform_driver mxcipu_driver = { + .driver = { + .name = "mxc_ipu", + }, + .probe = ipu_probe, + .suspend = ipu_suspend, + .resume = ipu_resume, +}; + +int32_t __init ipu_gen_init(void) +{ + int32_t ret; + + ret = platform_driver_register(&mxcipu_driver); + return 0; +} + +subsys_initcall(ipu_gen_init); + +static void __exit ipu_gen_uninit(void) +{ + if (g_ipu_irq[0]) + free_irq(g_ipu_irq[0], 0); + if (g_ipu_irq[1]) + free_irq(g_ipu_irq[1], 0); + + platform_driver_unregister(&mxcipu_driver); +} + +module_exit(ipu_gen_uninit); + +EXPORT_SYMBOL(ipu_init_channel); +EXPORT_SYMBOL(ipu_uninit_channel); +EXPORT_SYMBOL(ipu_init_channel_buffer); +EXPORT_SYMBOL(ipu_unlink_channels); +EXPORT_SYMBOL(ipu_update_channel_buffer); +EXPORT_SYMBOL(ipu_select_buffer); +EXPORT_SYMBOL(ipu_link_channels); +EXPORT_SYMBOL(ipu_enable_channel); +EXPORT_SYMBOL(ipu_disable_channel); +EXPORT_SYMBOL(ipu_enable_csi); +EXPORT_SYMBOL(ipu_disable_csi); +EXPORT_SYMBOL(ipu_enable_irq); +EXPORT_SYMBOL(ipu_disable_irq); +EXPORT_SYMBOL(ipu_clear_irq); +EXPORT_SYMBOL(ipu_get_irq_status); +EXPORT_SYMBOL(ipu_request_irq); +EXPORT_SYMBOL(ipu_free_irq); +EXPORT_SYMBOL(ipu_pf_set_pause_row); +EXPORT_SYMBOL(bytes_per_pixel); diff --git a/drivers/mxc/ipu/ipu_csi.c b/drivers/mxc/ipu/ipu_csi.c new file mode 100644 index 000000000000..268f7a076ce5 --- /dev/null +++ b/drivers/mxc/ipu/ipu_csi.c @@ -0,0 +1,225 @@ +/* + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file ipu_csi.c + * + * @brief IPU CMOS Sensor interface functions + * + * @ingroup IPU + */ +#include +#include +#include +#include +#include +#include +#include + +#include "ipu_prv.h" +#include "ipu_regs.h" + +static bool gipu_csi_get_mclk_flag; +static int csi_mclk_flag; + +extern void gpio_sensor_suspend(bool flag); + +/*! + * ipu_csi_init_interface + * Sets initial values for the CSI registers. + * The width and height of the sensor and the actual frame size will be + * set to the same values. + * @param width Sensor width + * @param height Sensor height + * @param pixel_fmt pixel format + * @param sig ipu_csi_signal_cfg_t structure + * + * @return 0 for success, -EINVAL for error + */ +int32_t +ipu_csi_init_interface(uint16_t width, uint16_t height, uint32_t pixel_fmt, + ipu_csi_signal_cfg_t sig) +{ + uint32_t data = 0; + + /* Set SENS_DATA_FORMAT bits (8 and 9) + RGB or YUV444 is 0 which is current value in data so not set explicitly + This is also the default value if attempts are made to set it to + something invalid. */ + switch (pixel_fmt) { + case IPU_PIX_FMT_UYVY: + data = CSI_SENS_CONF_DATA_FMT_YUV422; + break; + case IPU_PIX_FMT_RGB24: + case IPU_PIX_FMT_BGR24: + data = CSI_SENS_CONF_DATA_FMT_RGB_YUV444; + break; + case IPU_PIX_FMT_GENERIC: + data = CSI_SENS_CONF_DATA_FMT_BAYER; + break; + default: + return -EINVAL; + } + + /* Set the CSI_SENS_CONF register remaining fields */ + data |= sig.data_width << CSI_SENS_CONF_DATA_WIDTH_SHIFT | + sig.data_pol << CSI_SENS_CONF_DATA_POL_SHIFT | + sig.Vsync_pol << CSI_SENS_CONF_VSYNC_POL_SHIFT | + sig.Hsync_pol << CSI_SENS_CONF_HSYNC_POL_SHIFT | + sig.pixclk_pol << CSI_SENS_CONF_PIX_CLK_POL_SHIFT | + sig.ext_vsync << CSI_SENS_CONF_EXT_VSYNC_SHIFT | + sig.clk_mode << CSI_SENS_CONF_SENS_PRTCL_SHIFT | + sig.sens_clksrc << CSI_SENS_CONF_SENS_CLKSRC_SHIFT; + + __raw_writel(data, CSI_SENS_CONF); + + /* Setup frame size */ + __raw_writel(width | height << 16, CSI_SENS_FRM_SIZE); + + __raw_writel(width << 16, CSI_FLASH_STROBE_1); + __raw_writel(height << 16 | 0x22, CSI_FLASH_STROBE_2); + + /* Set CCIR registers */ + if (sig.clk_mode == IPU_CSI_CLK_MODE_CCIR656_PROGRESSIVE) { + __raw_writel(0x40030, CSI_CCIR_CODE_1); + __raw_writel(0xFF0000, CSI_CCIR_CODE_3); + } else if (sig.clk_mode == IPU_CSI_CLK_MODE_CCIR656_INTERLACED) { + __raw_writel(0xD07DF, CSI_CCIR_CODE_1); + __raw_writel(0x40596, CSI_CCIR_CODE_2); + __raw_writel(0xFF0000, CSI_CCIR_CODE_3); + } + + dev_dbg(g_ipu_dev, "CSI_SENS_CONF = 0x%08X\n", + __raw_readl(CSI_SENS_CONF)); + dev_dbg(g_ipu_dev, "CSI_ACT_FRM_SIZE = 0x%08X\n", + __raw_readl(CSI_ACT_FRM_SIZE)); + + return 0; +} + +/*! + * ipu_csi_flash_strobe + * + * @param flag true to turn on flash strobe + * + * @return 0 for success + */ +void ipu_csi_flash_strobe(bool flag) +{ + if (flag == true) { + __raw_writel(__raw_readl(CSI_FLASH_STROBE_2) | 0x1, + CSI_FLASH_STROBE_2); + } +} + +/*! + * ipu_csi_enable_mclk + * + * @param src enum define which source to control the clk + * CSI_MCLK_VF CSI_MCLK_ENC CSI_MCLK_RAW CSI_MCLK_I2C + * @param flag true to enable mclk, false to disable mclk + * @param wait true to wait 100ms make clock stable, false not wait + * + * @return 0 for success + */ +int32_t ipu_csi_enable_mclk(int src, bool flag, bool wait) +{ + if (flag == true) { + csi_mclk_flag |= src; + } else { + csi_mclk_flag &= ~src; + } + + if (gipu_csi_get_mclk_flag == flag) + return 0; + + if (flag == true) { + clk_enable(g_ipu_csi_clk); + if (wait == true) + msleep(10); + /*printk("enable csi clock from source %d\n", src); */ + gipu_csi_get_mclk_flag = true; + } else if (csi_mclk_flag == 0) { + clk_disable(g_ipu_csi_clk); + /*printk("disable csi clock from source %d\n", src); */ + gipu_csi_get_mclk_flag = flag; + } + + return 0; +} + +/*! + * ipu_csi_read_mclk_flag + * + * @return csi_mclk_flag + */ +int ipu_csi_read_mclk_flag(void) +{ + return csi_mclk_flag; +} + +/*! + * ipu_csi_get_window_size + * + * @param width pointer to window width + * @param height pointer to window height + * @param dummy dummy for IPUv1 to keep the same interface with IPUv3 + * + */ +void ipu_csi_get_window_size(uint32_t *width, uint32_t *height, + uint32_t dummy) +{ + uint32_t reg; + + reg = __raw_readl(CSI_ACT_FRM_SIZE); + *width = (reg & 0xFFFF) + 1; + *height = (reg >> 16 & 0xFFFF) + 1; +} + +/*! + * ipu_csi_set_window_size + * + * @param width window width + * @param height window height + * @param dummy dummy for IPUv1 to keep the same interface with IPUv3 + * + */ +void ipu_csi_set_window_size(uint32_t width, uint32_t height, uint32_t dummy) +{ + __raw_writel((width - 1) | (height - 1) << 16, CSI_ACT_FRM_SIZE); +} + +/*! + * ipu_csi_set_window_pos + * + * @param left uint32 window x start + * @param top uint32 window y start + * @param dummy dummy for IPUv1 to keep the same interface with IPUv3 + * + */ +void ipu_csi_set_window_pos(uint32_t left, uint32_t top, uint32_t dummy) +{ + uint32_t temp = __raw_readl(CSI_OUT_FRM_CTRL); + temp &= 0xffff0000; + temp = top | (left << 8) | temp; + __raw_writel(temp, CSI_OUT_FRM_CTRL); +} + +/* Exported symbols for modules. */ +EXPORT_SYMBOL(ipu_csi_set_window_pos); +EXPORT_SYMBOL(ipu_csi_set_window_size); +EXPORT_SYMBOL(ipu_csi_get_window_size); +EXPORT_SYMBOL(ipu_csi_read_mclk_flag); +EXPORT_SYMBOL(ipu_csi_enable_mclk); +EXPORT_SYMBOL(ipu_csi_flash_strobe); +EXPORT_SYMBOL(ipu_csi_init_interface); diff --git a/drivers/mxc/ipu/ipu_device.c b/drivers/mxc/ipu/ipu_device.c new file mode 100644 index 000000000000..57314f7ebae8 --- /dev/null +++ b/drivers/mxc/ipu/ipu_device.c @@ -0,0 +1,696 @@ +/* + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file ipu_device.c + * + * @brief This file contains the IPU driver device interface and fops functions. + * + * @ingroup IPU + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ipu_prv.h" +#include "ipu_regs.h" +#include "ipu_param_mem.h" + +/* Strucutures and variables for exporting MXC IPU as device*/ + +#define MAX_Q_SIZE 10 + +static int mxc_ipu_major; +static struct class *mxc_ipu_class; + +DEFINE_SPINLOCK(queue_lock); +static DECLARE_MUTEX(user_mutex); + +static wait_queue_head_t waitq; +static int pending_events; +int read_ptr; +int write_ptr; + +ipu_event_info events[MAX_Q_SIZE]; + +int register_ipu_device(void); + +/* Static functions */ + +int get_events(ipu_event_info *p) +{ + unsigned long flags; + int ret = 0, i, cnt, found = 0; + spin_lock_irqsave(&queue_lock, flags); + if (pending_events != 0) { + if (write_ptr > read_ptr) + cnt = write_ptr - read_ptr; + else + cnt = MAX_Q_SIZE - read_ptr + write_ptr; + for (i = 0; i < cnt; i++) { + if (p->irq == events[read_ptr].irq) { + *p = events[read_ptr]; + events[read_ptr].irq = 0; + read_ptr++; + if (read_ptr >= MAX_Q_SIZE) + read_ptr = 0; + found = 1; + break; + } + + if (events[read_ptr].irq) { + events[write_ptr] = events[read_ptr]; + events[read_ptr].irq = 0; + write_ptr++; + if (write_ptr >= MAX_Q_SIZE) + write_ptr = 0; + } else + pending_events--; + + read_ptr++; + if (read_ptr >= MAX_Q_SIZE) + read_ptr = 0; + } + if (found) + pending_events--; + else + ret = -1; + } else { + ret = -1; + } + + spin_unlock_irqrestore(&queue_lock, flags); + return ret; +} + +static irqreturn_t mxc_ipu_generic_handler(int irq, void *dev_id) +{ + ipu_event_info e; + + e.irq = irq; + e.dev = dev_id; + events[write_ptr] = e; + write_ptr++; + if (write_ptr >= MAX_Q_SIZE) + write_ptr = 0; + pending_events++; + /* Wakeup any blocking user context */ + wake_up_interruptible(&waitq); + return IRQ_HANDLED; +} + +static int mxc_ipu_open(struct inode *inode, struct file *file) +{ + int ret = 0; + return ret; +} +static int mxc_ipu_ioctl(struct inode *inode, struct file *file, + unsigned int cmd, unsigned long arg) +{ + int ret = 0; + + switch (cmd) { + + case IPU_INIT_CHANNEL: + { + ipu_channel_parm parm; + if (copy_from_user + (&parm, (ipu_channel_parm *) arg, + sizeof(ipu_channel_parm))) { + return -EFAULT; + } + if (!parm.flag) { + ret = + ipu_init_channel(parm.channel, + &parm.params); + } else { + ret = ipu_init_channel(parm.channel, NULL); + } + } + break; + + case IPU_UNINIT_CHANNEL: + { + ipu_channel_t ch; + int __user *argp = (void __user *)arg; + if (get_user(ch, argp)) + return -EFAULT; + ipu_uninit_channel(ch); + } + break; + + case IPU_INIT_CHANNEL_BUFFER: + { + ipu_channel_buf_parm parm; + if (copy_from_user + (&parm, (ipu_channel_buf_parm *) arg, + sizeof(ipu_channel_buf_parm))) { + return -EFAULT; + } + ret = + ipu_init_channel_buffer(parm.channel, parm.type, + parm.pixel_fmt, + parm.width, parm.height, + parm.stride, + parm.rot_mode, + parm.phyaddr_0, + parm.phyaddr_1, + parm.u_offset, + parm.v_offset); + + } + break; + + case IPU_UPDATE_CHANNEL_BUFFER: + { + ipu_channel_buf_parm parm; + if (copy_from_user + (&parm, (ipu_channel_buf_parm *) arg, + sizeof(ipu_channel_buf_parm))) { + return -EFAULT; + } + if ((parm.phyaddr_0 != (dma_addr_t) NULL) + && (parm.phyaddr_1 == (dma_addr_t) NULL)) { + ret = + ipu_update_channel_buffer(parm.channel, + parm.type, + parm.bufNum, + parm.phyaddr_0); + } else if ((parm.phyaddr_0 == (dma_addr_t) NULL) + && (parm.phyaddr_1 != (dma_addr_t) NULL)) { + ret = + ipu_update_channel_buffer(parm.channel, + parm.type, + parm.bufNum, + parm.phyaddr_1); + } else { + ret = -1; + } + + } + break; + case IPU_SELECT_CHANNEL_BUFFER: + { + ipu_channel_buf_parm parm; + if (copy_from_user + (&parm, (ipu_channel_buf_parm *) arg, + sizeof(ipu_channel_buf_parm))) { + return -EFAULT; + } + ret = + ipu_select_buffer(parm.channel, parm.type, + parm.bufNum); + + } + break; + case IPU_LINK_CHANNELS: + { + ipu_channel_link link; + if (copy_from_user + (&link, (ipu_channel_link *) arg, + sizeof(ipu_channel_link))) { + return -EFAULT; + } + ret = ipu_link_channels(link.src_ch, link.dest_ch); + + } + break; + case IPU_UNLINK_CHANNELS: + { + ipu_channel_link link; + if (copy_from_user + (&link, (ipu_channel_link *) arg, + sizeof(ipu_channel_link))) { + return -EFAULT; + } + ret = ipu_unlink_channels(link.src_ch, link.dest_ch); + + } + break; + case IPU_ENABLE_CHANNEL: + { + ipu_channel_t ch; + int __user *argp = (void __user *)arg; + if (get_user(ch, argp)) + return -EFAULT; + ipu_enable_channel(ch); + } + break; + case IPU_DISABLE_CHANNEL: + { + ipu_channel_info info; + if (copy_from_user + (&info, (ipu_channel_info *) arg, + sizeof(ipu_channel_info))) { + return -EFAULT; + } + ret = ipu_disable_channel(info.channel, info.stop); + } + break; + case IPU_ENABLE_IRQ: + { + uint32_t irq; + int __user *argp = (void __user *)arg; + if (get_user(irq, argp)) + return -EFAULT; + ipu_enable_irq(irq); + } + break; + case IPU_DISABLE_IRQ: + { + uint32_t irq; + int __user *argp = (void __user *)arg; + if (get_user(irq, argp)) + return -EFAULT; + ipu_disable_irq(irq); + } + break; + case IPU_CLEAR_IRQ: + { + uint32_t irq; + int __user *argp = (void __user *)arg; + if (get_user(irq, argp)) + return -EFAULT; + ipu_clear_irq(irq); + } + break; + case IPU_FREE_IRQ: + { + ipu_irq_info info; + if (copy_from_user + (&info, (ipu_irq_info *) arg, + sizeof(ipu_irq_info))) { + return -EFAULT; + } + ipu_free_irq(info.irq, info.dev_id); + } + break; + case IPU_REQUEST_IRQ_STATUS: + { + uint32_t irq; + int __user *argp = (void __user *)arg; + if (get_user(irq, argp)) + return -EFAULT; + ret = ipu_get_irq_status(irq); + } + break; + case IPU_SDC_INIT_PANEL: + { + ipu_sdc_panel_info sinfo; + if (copy_from_user + (&sinfo, (ipu_sdc_panel_info *) arg, + sizeof(ipu_sdc_panel_info))) { + return -EFAULT; + } + ret = + ipu_sdc_init_panel(sinfo.panel, sinfo.pixel_clk, + sinfo.width, sinfo.height, + sinfo.pixel_fmt, + sinfo.hStartWidth, + sinfo.hSyncWidth, + sinfo.hEndWidth, + sinfo.vStartWidth, + sinfo.vSyncWidth, + sinfo.vEndWidth, sinfo.signal); + } + break; + case IPU_SDC_SET_WIN_POS: + { + ipu_sdc_window_pos pos; + if (copy_from_user + (&pos, (ipu_sdc_window_pos *) arg, + sizeof(ipu_sdc_window_pos))) { + return -EFAULT; + } + ret = + ipu_disp_set_window_pos(pos.channel, pos.x_pos, + pos.y_pos); + + } + break; + case IPU_SDC_SET_GLOBAL_ALPHA: + { + ipu_sdc_global_alpha g; + if (copy_from_user + (&g, (ipu_sdc_global_alpha *) arg, + sizeof(ipu_sdc_global_alpha))) { + return -EFAULT; + } + ret = ipu_sdc_set_global_alpha(g.enable, g.alpha); + } + break; + case IPU_SDC_SET_COLOR_KEY: + { + ipu_sdc_color_key c; + if (copy_from_user + (&c, (ipu_sdc_color_key *) arg, + sizeof(ipu_sdc_color_key))) { + return -EFAULT; + } + ret = + ipu_sdc_set_color_key(c.channel, c.enable, + c.colorKey); + } + break; + case IPU_SDC_SET_BRIGHTNESS: + { + uint8_t b; + int __user *argp = (void __user *)arg; + if (get_user(b, argp)) + return -EFAULT; + ret = ipu_sdc_set_brightness(b); + + } + break; + case IPU_REGISTER_GENERIC_ISR: + { + ipu_event_info info; + if (copy_from_user + (&info, (ipu_event_info *) arg, + sizeof(ipu_event_info))) { + return -EFAULT; + } + ret = + ipu_request_irq(info.irq, mxc_ipu_generic_handler, + 0, "video_sink", info.dev); + } + break; + case IPU_GET_EVENT: + /* User will have to allocate event_type structure and pass the pointer in arg */ + { + ipu_event_info info; + int r = -1; + + if (copy_from_user + (&info, (ipu_event_info *) arg, + sizeof(ipu_event_info))) + return -EFAULT; + + r = get_events(&info); + if (r == -1) { + wait_event_interruptible_timeout(waitq, + (pending_events != 0), 2 * HZ); + r = get_events(&info); + } + ret = -1; + if (r == 0) { + if (!copy_to_user((ipu_event_info *) arg, + &info, sizeof(ipu_event_info))) + ret = 0; + } + } + break; + case IPU_ADC_WRITE_TEMPLATE: + { + ipu_adc_template temp; + if (copy_from_user + (&temp, (ipu_adc_template *) arg, sizeof(temp))) { + return -EFAULT; + } + ret = + ipu_adc_write_template(temp.disp, temp.pCmd, + temp.write); + } + break; + case IPU_ADC_UPDATE: + { + ipu_adc_update update; + if (copy_from_user + (&update, (ipu_adc_update *) arg, sizeof(update))) { + return -EFAULT; + } + ret = + ipu_adc_set_update_mode(update.channel, update.mode, + update.refresh_rate, + update.addr, update.size); + } + break; + case IPU_ADC_SNOOP: + { + ipu_adc_snoop snoop; + if (copy_from_user + (&snoop, (ipu_adc_snoop *) arg, sizeof(snoop))) { + return -EFAULT; + } + ret = + ipu_adc_get_snooping_status(snoop.statl, + snoop.stath); + } + break; + case IPU_ADC_CMD: + { + ipu_adc_cmd cmd; + if (copy_from_user + (&cmd, (ipu_adc_cmd *) arg, sizeof(cmd))) { + return -EFAULT; + } + ret = + ipu_adc_write_cmd(cmd.disp, cmd.type, cmd.cmd, + cmd.params, cmd.numParams); + } + break; + case IPU_ADC_INIT_PANEL: + { + ipu_adc_panel panel; + if (copy_from_user + (&panel, (ipu_adc_panel *) arg, sizeof(panel))) { + return -EFAULT; + } + ret = + ipu_adc_init_panel(panel.disp, panel.width, + panel.height, panel.pixel_fmt, + panel.stride, panel.signal, + panel.addr, panel.vsync_width, + panel.mode); + } + break; + case IPU_ADC_IFC_TIMING: + { + ipu_adc_ifc_timing t; + if (copy_from_user + (&t, (ipu_adc_ifc_timing *) arg, sizeof(t))) { + return -EFAULT; + } + ret = + ipu_adc_init_ifc_timing(t.disp, t.read, + t.cycle_time, t.up_time, + t.down_time, + t.read_latch_time, + t.pixel_clk); + } + break; + case IPU_CSI_INIT_INTERFACE: + { + ipu_csi_interface c; + if (copy_from_user + (&c, (ipu_csi_interface *) arg, sizeof(c))) + return -EFAULT; + ret = + ipu_csi_init_interface(c.width, c.height, + c.pixel_fmt, c.signal); + } + break; + case IPU_CSI_ENABLE_MCLK: + { + ipu_csi_mclk m; + if (copy_from_user(&m, (ipu_csi_mclk *) arg, sizeof(m))) + return -EFAULT; + ret = ipu_csi_enable_mclk(m.src, m.flag, m.wait); + } + break; + case IPU_CSI_READ_MCLK_FLAG: + { + ret = ipu_csi_read_mclk_flag(); + } + break; + case IPU_CSI_FLASH_STROBE: + { + bool strobe; + int __user *argp = (void __user *)arg; + if (get_user(strobe, argp)) + return -EFAULT; + ipu_csi_flash_strobe(strobe); + } + break; + case IPU_CSI_GET_WIN_SIZE: + { + ipu_csi_window_size w; + int dummy = 0; + ipu_csi_get_window_size(&w.width, &w.height, dummy); + if (copy_to_user + ((ipu_csi_window_size *) arg, &w, sizeof(w))) + return -EFAULT; + } + break; + case IPU_CSI_SET_WIN_SIZE: + { + ipu_csi_window_size w; + int dummy = 0; + if (copy_from_user + (&w, (ipu_csi_window_size *) arg, sizeof(w))) + return -EFAULT; + ipu_csi_set_window_size(w.width, w.height, dummy); + } + break; + case IPU_CSI_SET_WINDOW: + { + ipu_csi_window p; + int dummy = 0; + if (copy_from_user + (&p, (ipu_csi_window *) arg, sizeof(p))) + return -EFAULT; + ipu_csi_set_window_pos(p.left, p.top, dummy); + } + break; + case IPU_PF_SET_PAUSE_ROW: + { + uint32_t p; + int __user *argp = (void __user *)arg; + if (get_user(p, argp)) + return -EFAULT; + ret = ipu_pf_set_pause_row(p); + } + break; + case IPU_ALOC_MEM: + { + ipu_mem_info info; + if (copy_from_user + (&info, (ipu_mem_info *) arg, + sizeof(ipu_mem_info))) + return -EFAULT; + + info.vaddr = dma_alloc_coherent(0, + PAGE_ALIGN(info.size), + &info.paddr, + GFP_DMA | GFP_KERNEL); + if (info.vaddr == 0) { + printk(KERN_ERR "dma alloc failed!\n"); + return -ENOBUFS; + } + if (copy_to_user((ipu_mem_info *) arg, &info, + sizeof(ipu_mem_info)) > 0) + return -EFAULT; + } + break; + case IPU_FREE_MEM: + { + ipu_mem_info info; + if (copy_from_user + (&info, (ipu_mem_info *) arg, + sizeof(ipu_mem_info))) + return -EFAULT; + + if (info.vaddr != 0) + dma_free_coherent(0, PAGE_ALIGN(info.size), + info.vaddr, info.paddr); + else + return -EFAULT; + } + break; + case IPU_IS_CHAN_BUSY: + { + ipu_channel_t chan; + if (copy_from_user + (&chan, (ipu_channel_t *)arg, + sizeof(ipu_channel_t))) + return -EFAULT; + + if (ipu_is_channel_busy(chan)) + ret = 1; + else + ret = 0; + } + break; + default: + break; + + } + return ret; +} + +static int mxc_ipu_mmap(struct file *file, struct vm_area_struct *vma) +{ + vma->vm_page_prot = pgprot_writethru(vma->vm_page_prot); + + if (remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff, + vma->vm_end - vma->vm_start, + vma->vm_page_prot)) { + printk(KERN_ERR + "mmap failed!\n"); + return -ENOBUFS; + } + return 0; +} + +static int mxc_ipu_release(struct inode *inode, struct file *file) +{ + return 0; +} + +static struct file_operations mxc_ipu_fops = { + .owner = THIS_MODULE, + .open = mxc_ipu_open, + .mmap = mxc_ipu_mmap, + .release = mxc_ipu_release, + .ioctl = mxc_ipu_ioctl +}; + +int register_ipu_device() +{ + int ret = 0; + struct device *temp; + mxc_ipu_major = register_chrdev(0, "mxc_ipu", &mxc_ipu_fops); + if (mxc_ipu_major < 0) { + printk(KERN_ERR + "Unable to register Mxc Ipu as a char device\n"); + return mxc_ipu_major; + } + + mxc_ipu_class = class_create(THIS_MODULE, "mxc_ipu"); + if (IS_ERR(mxc_ipu_class)) { + printk(KERN_ERR "Unable to create class for Mxc Ipu\n"); + ret = PTR_ERR(mxc_ipu_class); + goto err1; + } + + temp = device_create(mxc_ipu_class, NULL, MKDEV(mxc_ipu_major, 0), NULL, + "mxc_ipu"); + + if (IS_ERR(temp)) { + printk(KERN_ERR "Unable to create class device for Mxc Ipu\n"); + ret = PTR_ERR(temp); + goto err2; + } + spin_lock_init(&queue_lock); + init_waitqueue_head(&waitq); + return ret; + + err2: + class_destroy(mxc_ipu_class); + err1: + unregister_chrdev(mxc_ipu_major, "mxc_ipu"); + return ret; + +} diff --git a/drivers/mxc/ipu/ipu_ic.c b/drivers/mxc/ipu/ipu_ic.c new file mode 100644 index 000000000000..28f002fc2e53 --- /dev/null +++ b/drivers/mxc/ipu/ipu_ic.c @@ -0,0 +1,590 @@ +/* + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/* + * @file ipu_ic.c + * + * @brief IPU IC functions + * + * @ingroup IPU + */ +#include +#include +#include +#include +#include +#include + +#include "ipu_prv.h" +#include "ipu_regs.h" +#include "ipu_param_mem.h" + +enum { + IC_TASK_VIEWFINDER, + IC_TASK_ENCODER, + IC_TASK_POST_PROCESSOR +}; + +extern int g_ipu_hw_rev; +static void _init_csc(uint8_t ic_task, ipu_color_space_t in_format, + ipu_color_space_t out_format); +static bool _calc_resize_coeffs(uint32_t inSize, uint32_t outSize, + uint32_t *resizeCoeff, + uint32_t *downsizeCoeff); + +void _ipu_ic_enable_task(ipu_channel_t channel) +{ + uint32_t ic_conf; + + ic_conf = __raw_readl(IC_CONF); + switch (channel) { + case CSI_PRP_VF_ADC: + case MEM_PRP_VF_ADC: + case CSI_PRP_VF_MEM: + case MEM_PRP_VF_MEM: + ic_conf |= IC_CONF_PRPVF_EN; + break; + case MEM_ROT_VF_MEM: + ic_conf |= IC_CONF_PRPVF_ROT_EN; + break; + case CSI_PRP_ENC_MEM: + case MEM_PRP_ENC_MEM: + ic_conf |= IC_CONF_PRPENC_EN; + break; + case MEM_ROT_ENC_MEM: + ic_conf |= IC_CONF_PRPENC_ROT_EN; + break; + case MEM_PP_ADC: + case MEM_PP_MEM: + ic_conf |= IC_CONF_PP_EN; + break; + case MEM_ROT_PP_MEM: + ic_conf |= IC_CONF_PP_ROT_EN; + break; + case CSI_MEM: + ic_conf |= IC_CONF_RWS_EN | IC_CONF_PRPENC_EN; + break; + default: + break; + } + __raw_writel(ic_conf, IC_CONF); +} + +void _ipu_ic_disable_task(ipu_channel_t channel) +{ + uint32_t ic_conf; + + ic_conf = __raw_readl(IC_CONF); + switch (channel) { + case CSI_PRP_VF_ADC: + case MEM_PRP_VF_ADC: + case CSI_PRP_VF_MEM: + case MEM_PRP_VF_MEM: + ic_conf &= ~IC_CONF_PRPVF_EN; + break; + case MEM_ROT_VF_MEM: + ic_conf &= ~IC_CONF_PRPVF_ROT_EN; + break; + case CSI_PRP_ENC_MEM: + case MEM_PRP_ENC_MEM: + ic_conf &= ~IC_CONF_PRPENC_EN; + break; + case MEM_ROT_ENC_MEM: + ic_conf &= ~IC_CONF_PRPENC_ROT_EN; + break; + case MEM_PP_ADC: + case MEM_PP_MEM: + ic_conf &= ~IC_CONF_PP_EN; + break; + case MEM_ROT_PP_MEM: + ic_conf &= ~IC_CONF_PP_ROT_EN; + break; + case CSI_MEM: + ic_conf &= ~(IC_CONF_RWS_EN | IC_CONF_PRPENC_EN); + break; + default: + break; + } + __raw_writel(ic_conf, IC_CONF); +} + +void _ipu_ic_init_prpvf(ipu_channel_params_t *params, bool src_is_csi) +{ + uint32_t reg, ic_conf; + uint32_t downsizeCoeff, resizeCoeff; + ipu_color_space_t in_fmt, out_fmt; + + /* Setup vertical resizing */ + _calc_resize_coeffs(params->mem_prp_vf_mem.in_height, + params->mem_prp_vf_mem.out_height, + &resizeCoeff, &downsizeCoeff); + reg = (downsizeCoeff << 30) | (resizeCoeff << 16); + + /* Setup horizontal resizing */ + _calc_resize_coeffs(params->mem_prp_vf_mem.in_width, + params->mem_prp_vf_mem.out_width, + &resizeCoeff, &downsizeCoeff); + reg |= (downsizeCoeff << 14) | resizeCoeff; + + __raw_writel(reg, IC_PRP_VF_RSC); + + ic_conf = __raw_readl(IC_CONF); + + /* Setup color space conversion */ + in_fmt = format_to_colorspace(params->mem_prp_vf_mem.in_pixel_fmt); + out_fmt = format_to_colorspace(params->mem_prp_vf_mem.out_pixel_fmt); + if (in_fmt == RGB) { + if ((out_fmt == YCbCr) || (out_fmt == YUV)) { + _init_csc(IC_TASK_VIEWFINDER, RGB, out_fmt); + ic_conf |= IC_CONF_PRPVF_CSC1; /* Enable RGB->YCBCR CSC */ + } + } + if ((in_fmt == YCbCr) || (in_fmt == YUV)) { + if (out_fmt == RGB) { + _init_csc(IC_TASK_VIEWFINDER, YCbCr, RGB); + ic_conf |= IC_CONF_PRPVF_CSC1; /* Enable YCBCR->RGB CSC */ + } else { + /* TODO: Support YUV<->YCbCr conversion? */ + } + } + + if (params->mem_prp_vf_mem.graphics_combine_en) { + ic_conf |= IC_CONF_PRPVF_CMB; + + /* need transparent CSC1 conversion */ + _init_csc(IC_TASK_POST_PROCESSOR, RGB, RGB); + ic_conf |= IC_CONF_PRPVF_CSC1; /* Enable RGB->RGB CSC */ + + if (params->mem_prp_vf_mem.global_alpha_en) { + ic_conf |= IC_CONF_IC_GLB_LOC_A; + } else { + ic_conf &= ~IC_CONF_IC_GLB_LOC_A; + } + + if (params->mem_prp_vf_mem.key_color_en) { + ic_conf |= IC_CONF_KEY_COLOR_EN; + } else { + ic_conf &= ~IC_CONF_KEY_COLOR_EN; + } + } else { + ic_conf &= ~IC_CONF_PP_CMB; + } + +#ifndef CONFIG_VIRTIO_SUPPORT /* Setting RWS_EN doesn't work in Virtio */ + if (src_is_csi) { + ic_conf &= ~IC_CONF_RWS_EN; + } else { + ic_conf |= IC_CONF_RWS_EN; + } +#endif + __raw_writel(ic_conf, IC_CONF); +} + +void _ipu_ic_uninit_prpvf(void) +{ + uint32_t reg; + + reg = __raw_readl(IC_CONF); + reg &= ~(IC_CONF_PRPVF_EN | IC_CONF_PRPVF_CMB | + IC_CONF_PRPVF_CSC2 | IC_CONF_PRPVF_CSC1); + __raw_writel(reg, IC_CONF); +} + +void _ipu_ic_init_rotate_vf(ipu_channel_params_t *params) +{ +} + +void _ipu_ic_uninit_rotate_vf(void) +{ + uint32_t reg; + reg = __raw_readl(IC_CONF); + reg &= ~IC_CONF_PRPVF_ROT_EN; + __raw_writel(reg, IC_CONF); +} + +void _ipu_ic_init_csi(ipu_channel_params_t *params) +{ + uint32_t reg; + reg = __raw_readl(IC_CONF); + reg &= ~IC_CONF_CSI_MEM_WR_EN; + __raw_writel(reg, IC_CONF); +} + +void _ipu_ic_uninit_csi(void) +{ + uint32_t reg; + reg = __raw_readl(IC_CONF); + reg &= ~(IC_CONF_RWS_EN | IC_CONF_PRPENC_EN); + __raw_writel(reg, IC_CONF); +} + +void _ipu_ic_init_prpenc(ipu_channel_params_t *params, bool src_is_csi) +{ + uint32_t reg, ic_conf; + uint32_t downsizeCoeff, resizeCoeff; + ipu_color_space_t in_fmt, out_fmt; + + /* Setup vertical resizing */ + _calc_resize_coeffs(params->mem_prp_enc_mem.in_height, + params->mem_prp_enc_mem.out_height, + &resizeCoeff, &downsizeCoeff); + reg = (downsizeCoeff << 30) | (resizeCoeff << 16); + + /* Setup horizontal resizing */ + _calc_resize_coeffs(params->mem_prp_enc_mem.in_width, + params->mem_prp_enc_mem.out_width, + &resizeCoeff, &downsizeCoeff); + reg |= (downsizeCoeff << 14) | resizeCoeff; + + __raw_writel(reg, IC_PRP_ENC_RSC); + + ic_conf = __raw_readl(IC_CONF); + + /* Setup color space conversion */ + in_fmt = format_to_colorspace(params->mem_prp_enc_mem.in_pixel_fmt); + out_fmt = format_to_colorspace(params->mem_prp_enc_mem.out_pixel_fmt); + if (in_fmt == RGB) { + if ((out_fmt == YCbCr) || (out_fmt == YUV)) { + /* TODO: ERROR! */ + } + } + if ((in_fmt == YCbCr) || (in_fmt == YUV)) { + if (out_fmt == RGB) { + _init_csc(IC_TASK_ENCODER, YCbCr, RGB); + ic_conf |= IC_CONF_PRPENC_CSC1; /* Enable YCBCR->RGB CSC */ + } else { + /* TODO: Support YUV<->YCbCr conversion? */ + } + } + + if (src_is_csi) { + ic_conf &= ~IC_CONF_RWS_EN; + } else { + ic_conf |= IC_CONF_RWS_EN; + } + + __raw_writel(ic_conf, IC_CONF); +} + +void _ipu_ic_uninit_prpenc(void) +{ + uint32_t reg; + + reg = __raw_readl(IC_CONF); + reg &= ~(IC_CONF_PRPENC_EN | IC_CONF_PRPENC_CSC1); + __raw_writel(reg, IC_CONF); +} + +void _ipu_ic_init_rotate_enc(ipu_channel_params_t *params) +{ +} + +void _ipu_ic_uninit_rotate_enc(void) +{ + uint32_t reg; + + reg = __raw_readl(IC_CONF); + reg &= ~(IC_CONF_PRPENC_ROT_EN); + __raw_writel(reg, IC_CONF); +} + +void _ipu_ic_init_pp(ipu_channel_params_t *params) +{ + uint32_t reg, ic_conf; + uint32_t downsizeCoeff, resizeCoeff; + ipu_color_space_t in_fmt, out_fmt; + + /* Setup vertical resizing */ + _calc_resize_coeffs(params->mem_pp_mem.in_height, + params->mem_pp_mem.out_height, + &resizeCoeff, &downsizeCoeff); + reg = (downsizeCoeff << 30) | (resizeCoeff << 16); + + /* Setup horizontal resizing */ + _calc_resize_coeffs(params->mem_pp_mem.in_width, + params->mem_pp_mem.out_width, + &resizeCoeff, &downsizeCoeff); + reg |= (downsizeCoeff << 14) | resizeCoeff; + + __raw_writel(reg, IC_PP_RSC); + + ic_conf = __raw_readl(IC_CONF); + + /* Setup color space conversion */ + in_fmt = format_to_colorspace(params->mem_pp_mem.in_pixel_fmt); + out_fmt = format_to_colorspace(params->mem_pp_mem.out_pixel_fmt); + if (in_fmt == RGB) { + if ((out_fmt == YCbCr) || (out_fmt == YUV)) { + _init_csc(IC_TASK_POST_PROCESSOR, RGB, out_fmt); + ic_conf |= IC_CONF_PP_CSC2; /* Enable RGB->YCBCR CSC */ + } + } + if ((in_fmt == YCbCr) || (in_fmt == YUV)) { + if (out_fmt == RGB) { + _init_csc(IC_TASK_POST_PROCESSOR, YCbCr, RGB); + ic_conf |= IC_CONF_PP_CSC1; /* Enable YCBCR->RGB CSC */ + } else { + /* TODO: Support YUV<->YCbCr conversion? */ + } + } + + if (params->mem_pp_mem.graphics_combine_en) { + ic_conf |= IC_CONF_PP_CMB; + + /* need transparent CSC1 conversion */ + _init_csc(IC_TASK_POST_PROCESSOR, RGB, RGB); + ic_conf |= IC_CONF_PP_CSC1; /* Enable RGB->RGB CSC */ + + if (params->mem_pp_mem.global_alpha_en) { + ic_conf |= IC_CONF_IC_GLB_LOC_A; + } else { + ic_conf &= ~IC_CONF_IC_GLB_LOC_A; + } + + if (params->mem_pp_mem.key_color_en) { + ic_conf |= IC_CONF_KEY_COLOR_EN; + } else { + ic_conf &= ~IC_CONF_KEY_COLOR_EN; + } + } else { + ic_conf &= ~IC_CONF_PP_CMB; + } + + __raw_writel(ic_conf, IC_CONF); +} + +void _ipu_ic_uninit_pp(void) +{ + uint32_t reg; + + reg = __raw_readl(IC_CONF); + reg &= ~(IC_CONF_PP_EN | IC_CONF_PP_CSC1 | IC_CONF_PP_CSC2 | + IC_CONF_PP_CMB); + __raw_writel(reg, IC_CONF); +} + +void _ipu_ic_init_rotate_pp(ipu_channel_params_t *params) +{ +} + +void _ipu_ic_uninit_rotate_pp(void) +{ + uint32_t reg; + reg = __raw_readl(IC_CONF); + reg &= ~IC_CONF_PP_ROT_EN; + __raw_writel(reg, IC_CONF); +} + +static void _init_csc(uint8_t ic_task, ipu_color_space_t in_format, + ipu_color_space_t out_format) +{ +/* Y = R * .299 + G * .587 + B * .114; + U = R * -.169 + G * -.332 + B * .500 + 128.; + V = R * .500 + G * -.419 + B * -.0813 + 128.;*/ + static const uint32_t rgb2ycbcr_coeff[4][3] = { + {0x004D, 0x0096, 0x001D}, + {0x01D5, 0x01AB, 0x0080}, + {0x0080, 0x0195, 0x01EB}, + {0x0000, 0x0200, 0x0200}, /* A0, A1, A2 */ + }; + + /* transparent RGB->RGB matrix for combining + */ + static const uint32_t rgb2rgb_coeff[4][3] = { + {0x0080, 0x0000, 0x0000}, + {0x0000, 0x0080, 0x0000}, + {0x0000, 0x0000, 0x0080}, + {0x0000, 0x0000, 0x0000}, /* A0, A1, A2 */ + }; + +/* R = (1.164 * (Y - 16)) + (1.596 * (Cr - 128)); + G = (1.164 * (Y - 16)) - (0.392 * (Cb - 128)) - (0.813 * (Cr - 128)); + B = (1.164 * (Y - 16)) + (2.017 * (Cb - 128); */ + static const uint32_t ycbcr2rgb_coeff[4][3] = { + {149, 0, 204}, + {149, 462, 408}, + {149, 255, 0}, + {8192 - 446, 266, 8192 - 554}, /* A0, A1, A2 */ + }; + + uint32_t param[2]; + uint32_t address = 0; + + if (g_ipu_hw_rev > 1) { + if (ic_task == IC_TASK_VIEWFINDER) { + address = 0x645 << 3; + } else if (ic_task == IC_TASK_ENCODER) { + address = 0x321 << 3; + } else if (ic_task == IC_TASK_POST_PROCESSOR) { + address = 0x96C << 3; + } else { + BUG(); + } + } else { + if (ic_task == IC_TASK_VIEWFINDER) { + address = 0x5a5 << 3; + } else if (ic_task == IC_TASK_ENCODER) { + address = 0x2d1 << 3; + } else if (ic_task == IC_TASK_POST_PROCESSOR) { + address = 0x87c << 3; + } else { + BUG(); + } + } + + if ((in_format == YCbCr) && (out_format == RGB)) { + /* Init CSC1 (YCbCr->RGB) */ + param[0] = + (ycbcr2rgb_coeff[3][0] << 27) | (ycbcr2rgb_coeff[0][0] << + 18) | + (ycbcr2rgb_coeff[1][1] << 9) | ycbcr2rgb_coeff[2][2]; + /* scale = 2, sat = 0 */ + param[1] = (ycbcr2rgb_coeff[3][0] >> 5) | (2L << (40 - 32)); + _ipu_write_param_mem(address, param, 2); + dev_dbg(g_ipu_dev, + "addr 0x%04X: word0 = 0x%08X, word1 = 0x%08X\n", + address, param[0], param[1]); + + param[0] = + (ycbcr2rgb_coeff[3][1] << 27) | (ycbcr2rgb_coeff[0][1] << + 18) | + (ycbcr2rgb_coeff[1][0] << 9) | ycbcr2rgb_coeff[2][0]; + param[1] = (ycbcr2rgb_coeff[3][1] >> 5); + address += 1L << 3; + _ipu_write_param_mem(address, param, 2); + dev_dbg(g_ipu_dev, + "addr 0x%04X: word0 = 0x%08X, word1 = 0x%08X\n", + address, param[0], param[1]); + + param[0] = + (ycbcr2rgb_coeff[3][2] << 27) | (ycbcr2rgb_coeff[0][2] << + 18) | + (ycbcr2rgb_coeff[1][2] << 9) | ycbcr2rgb_coeff[2][1]; + param[1] = (ycbcr2rgb_coeff[3][2] >> 5); + address += 1L << 3; + _ipu_write_param_mem(address, param, 2); + dev_dbg(g_ipu_dev, + "addr 0x%04X: word0 = 0x%08X, word1 = 0x%08X\n", + address, param[0], param[1]); + } else if ((in_format == RGB) && (out_format == YCbCr)) { + /* Init CSC1 (RGB->YCbCr) */ + param[0] = + (rgb2ycbcr_coeff[3][0] << 27) | (rgb2ycbcr_coeff[0][0] << + 18) | + (rgb2ycbcr_coeff[1][1] << 9) | rgb2ycbcr_coeff[2][2]; + /* scale = 1, sat = 0 */ + param[1] = (rgb2ycbcr_coeff[3][0] >> 5) | (1UL << 8); + _ipu_write_param_mem(address, param, 2); + dev_dbg(g_ipu_dev, + "addr 0x%04X: word0 = 0x%08X, word1 = 0x%08X\n", + address, param[0], param[1]); + + param[0] = + (rgb2ycbcr_coeff[3][1] << 27) | (rgb2ycbcr_coeff[0][1] << + 18) | + (rgb2ycbcr_coeff[1][0] << 9) | rgb2ycbcr_coeff[2][0]; + param[1] = (rgb2ycbcr_coeff[3][1] >> 5); + address += 1L << 3; + _ipu_write_param_mem(address, param, 2); + dev_dbg(g_ipu_dev, + "addr 0x%04X: word0 = 0x%08X, word1 = 0x%08X\n", + address, param[0], param[1]); + + param[0] = + (rgb2ycbcr_coeff[3][2] << 27) | (rgb2ycbcr_coeff[0][2] << + 18) | + (rgb2ycbcr_coeff[1][2] << 9) | rgb2ycbcr_coeff[2][1]; + param[1] = (rgb2ycbcr_coeff[3][2] >> 5); + address += 1L << 3; + _ipu_write_param_mem(address, param, 2); + dev_dbg(g_ipu_dev, + "addr 0x%04X: word0 = 0x%08X, word1 = 0x%08X\n", + address, param[0], param[1]); + } else if ((in_format == RGB) && (out_format == RGB)) { + /* Init CSC1 */ + param[0] = + (rgb2rgb_coeff[3][0] << 27) | (rgb2rgb_coeff[0][0] << 18) | + (rgb2rgb_coeff[1][1] << 9) | rgb2rgb_coeff[2][2]; + /* scale = 2, sat = 0 */ + param[1] = (rgb2rgb_coeff[3][0] >> 5) | (2UL << 8); + + _ipu_write_param_mem(address, param, 2); + + dev_dbg(g_ipu_dev, + "addr 0x%04X: word0 = 0x%08X, word1 = 0x%08X\n", + address, param[0], param[1]); + + param[0] = + (rgb2rgb_coeff[3][1] << 27) | (rgb2rgb_coeff[0][1] << 18) | + (rgb2rgb_coeff[1][0] << 9) | rgb2rgb_coeff[2][0]; + param[1] = (rgb2rgb_coeff[3][1] >> 5); + + address += 1L << 3; + _ipu_write_param_mem(address, param, 2); + + dev_dbg(g_ipu_dev, + "addr 0x%04X: word0 = 0x%08X, word1 = 0x%08X\n", + address, param[0], param[1]); + + param[0] = + (rgb2rgb_coeff[3][2] << 27) | (rgb2rgb_coeff[0][2] << 18) | + (rgb2rgb_coeff[1][2] << 9) | rgb2rgb_coeff[2][1]; + param[1] = (rgb2rgb_coeff[3][2] >> 5); + + address += 1L << 3; + _ipu_write_param_mem(address, param, 2); + + dev_dbg(g_ipu_dev, + "addr 0x%04X: word0 = 0x%08X, word1 = 0x%08X\n", + address, param[0], param[1]); + } else { + dev_err(g_ipu_dev, "Unsupported color space conversion\n"); + } +} + +static bool _calc_resize_coeffs(uint32_t inSize, uint32_t outSize, + uint32_t *resizeCoeff, + uint32_t *downsizeCoeff) +{ + uint32_t tempSize; + uint32_t tempDownsize; + + /* Cannot downsize more than 8:1 */ + if ((outSize << 3) < inSize) { + return false; + } + /* compute downsizing coefficient */ + tempDownsize = 0; + tempSize = inSize; + while ((tempSize >= outSize * 2) && (tempDownsize < 2)) { + tempSize >>= 1; + tempDownsize++; + } + *downsizeCoeff = tempDownsize; + + /* compute resizing coefficient using the following equation: + resizeCoeff = M*(SI -1)/(SO - 1) + where M = 2^13, SI - input size, SO - output size */ + *resizeCoeff = (8192L * (tempSize - 1)) / (outSize - 1); + if (*resizeCoeff >= 16384L) { + dev_err(g_ipu_dev, "Warning! Overflow on resize coeff.\n"); + *resizeCoeff = 0x3FFF; + } + + dev_dbg(g_ipu_dev, "resizing from %u -> %u pixels, " + "downsize=%u, resize=%u.%lu (reg=%u)\n", inSize, outSize, + *downsizeCoeff, (*resizeCoeff >= 8192L) ? 1 : 0, + ((*resizeCoeff & 0x1FFF) * 10000L) / 8192L, *resizeCoeff); + + return true; +} diff --git a/drivers/mxc/ipu/ipu_param_mem.h b/drivers/mxc/ipu/ipu_param_mem.h new file mode 100644 index 000000000000..4f2d5cba6e42 --- /dev/null +++ b/drivers/mxc/ipu/ipu_param_mem.h @@ -0,0 +1,176 @@ +/* + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#ifndef __INCLUDE_IPU_PARAM_MEM_H__ +#define __INCLUDE_IPU_PARAM_MEM_H__ + +#include + +static __inline void _ipu_ch_param_set_size(uint32_t *params, + uint32_t pixel_fmt, uint16_t width, + uint16_t height, uint16_t stride, + uint32_t u, uint32_t v) +{ + uint32_t u_offset = 0; + uint32_t v_offset = 0; + memset(params, 0, 40); + + params[3] = + (uint32_t) ((width - 1) << 12) | ((uint32_t) (height - 1) << 24); + params[4] = (uint32_t) (height - 1) >> 8; + params[7] = (uint32_t) (stride - 1) << 3; + + switch (pixel_fmt) { + case IPU_PIX_FMT_GENERIC: + /*Represents 8-bit Generic data */ + params[7] |= 3 | (7UL << (81 - 64)) | (31L << (89 - 64)); /* BPP & PFS */ + params[8] = 2; /* SAT = use 32-bit access */ + break; + case IPU_PIX_FMT_GENERIC_32: + /*Represents 32-bit Generic data */ + params[7] |= (7UL << (81 - 64)) | (7L << (89 - 64)); /* BPP & PFS */ + params[8] = 2; /* SAT = use 32-bit access */ + break; + case IPU_PIX_FMT_RGB565: + params[7] |= 2L | (4UL << (81 - 64)) | (7L << (89 - 64)); /* BPP & PFS */ + params[8] = 2 | /* SAT = 32-bit access */ + (0UL << (99 - 96)) | /* Red bit offset */ + (5UL << (104 - 96)) | /* Green bit offset */ + (11UL << (109 - 96)) | /* Blue bit offset */ + (16UL << (114 - 96)) | /* Alpha bit offset */ + (4UL << (119 - 96)) | /* Red bit width - 1 */ + (5UL << (122 - 96)) | /* Green bit width - 1 */ + (4UL << (125 - 96)); /* Blue bit width - 1 */ + break; + case IPU_PIX_FMT_BGR24: /* 24 BPP & RGB PFS */ + params[7] |= 1 | (4UL << (81 - 64)) | (7L << (89 - 64)); + params[8] = 2 | /* SAT = 32-bit access */ + (8UL << (104 - 96)) | /* Green bit offset */ + (16UL << (109 - 96)) | /* Blue bit offset */ + (24UL << (114 - 96)) | /* Alpha bit offset */ + (7UL << (119 - 96)) | /* Red bit width - 1 */ + (7UL << (122 - 96)) | /* Green bit width - 1 */ + (uint32_t) (7UL << (125 - 96)); /* Blue bit width - 1 */ + break; + case IPU_PIX_FMT_RGB24: /* 24 BPP & RGB PFS */ + params[7] |= 1 | (4UL << (81 - 64)) | (7L << (89 - 64)); + params[8] = 2 | /* SAT = 32-bit access */ + (16UL << (99 - 96)) | /* Red bit offset */ + (8UL << (104 - 96)) | /* Green bit offset */ + (0UL << (109 - 96)) | /* Blue bit offset */ + (24UL << (114 - 96)) | /* Alpha bit offset */ + (7UL << (119 - 96)) | /* Red bit width - 1 */ + (7UL << (122 - 96)) | /* Green bit width - 1 */ + (uint32_t) (7UL << (125 - 96)); /* Blue bit width - 1 */ + break; + case IPU_PIX_FMT_BGRA32: + case IPU_PIX_FMT_BGR32: + /* BPP & pixel fmt */ + params[7] |= 0 | (4UL << (81 - 64)) | (7 << (89 - 64)); + params[8] = 2 | /* SAT = 32-bit access */ + (8UL << (99 - 96)) | /* Red bit offset */ + (16UL << (104 - 96)) | /* Green bit offset */ + (24UL << (109 - 96)) | /* Blue bit offset */ + (0UL << (114 - 96)) | /* Alpha bit offset */ + (7UL << (119 - 96)) | /* Red bit width - 1 */ + (7UL << (122 - 96)) | /* Green bit width - 1 */ + (uint32_t) (7UL << (125 - 96)); /* Blue bit width - 1 */ + params[9] = 7; /* Alpha bit width - 1 */ + break; + case IPU_PIX_FMT_RGBA32: + case IPU_PIX_FMT_RGB32: + /* BPP & pixel fmt */ + params[7] |= 0 | (4UL << (81 - 64)) | (7 << (89 - 64)); + params[8] = 2 | /* SAT = 32-bit access */ + (24UL << (99 - 96)) | /* Red bit offset */ + (16UL << (104 - 96)) | /* Green bit offset */ + (8UL << (109 - 96)) | /* Blue bit offset */ + (0UL << (114 - 96)) | /* Alpha bit offset */ + (7UL << (119 - 96)) | /* Red bit width - 1 */ + (7UL << (122 - 96)) | /* Green bit width - 1 */ + (uint32_t) (7UL << (125 - 96)); /* Blue bit width - 1 */ + params[9] = 7; /* Alpha bit width - 1 */ + break; + case IPU_PIX_FMT_ABGR32: + /* BPP & pixel fmt */ + params[7] |= 0 | (4UL << (81 - 64)) | (7 << (89 - 64)); + params[8] = 2 | /* SAT = 32-bit access */ + (0UL << (99 - 96)) | /* Alpha bit offset */ + (8UL << (104 - 96)) | /* Blue bit offset */ + (16UL << (109 - 96)) | /* Green bit offset */ + (24UL << (114 - 96)) | /* Red bit offset */ + (7UL << (119 - 96)) | /* Alpha bit width - 1 */ + (7UL << (122 - 96)) | /* Blue bit width - 1 */ + (uint32_t) (7UL << (125 - 96)); /* Green bit width - 1 */ + params[9] = 7; /* Red bit width - 1 */ + break; + case IPU_PIX_FMT_UYVY: + /* BPP & pixel format */ + params[7] |= 2 | (6UL << 17) | (7 << (89 - 64)); + params[8] = 2; /* SAT = 32-bit access */ + break; + case IPU_PIX_FMT_YUV420P2: + case IPU_PIX_FMT_YUV420P: + /* BPP & pixel format */ + params[7] |= 3 | (3UL << 17) | (7 << (89 - 64)); + params[8] = 2; /* SAT = 32-bit access */ + u_offset = (u == 0) ? stride * height : u; + v_offset = (v == 0) ? u_offset + u_offset / 4 : v; + break; + case IPU_PIX_FMT_YVU422P: + /* BPP & pixel format */ + params[7] |= 3 | (2UL << 17) | (7 << (89 - 64)); + params[8] = 2; /* SAT = 32-bit access */ + v_offset = (v == 0) ? stride * height : v; + u_offset = (u == 0) ? v_offset + v_offset / 2 : u; + break; + case IPU_PIX_FMT_YUV422P: + /* BPP & pixel format */ + params[7] |= 3 | (2UL << 17) | (7 << (89 - 64)); + params[8] = 2; /* SAT = 32-bit access */ + u_offset = (u == 0) ? stride * height : u; + v_offset = (v == 0) ? u_offset + u_offset / 2 : v; + break; + default: + dev_err(g_ipu_dev, "mxc ipu: unimplemented pixel format\n"); + break; + } + + params[1] = (1UL << (46 - 32)) | (u_offset << (53 - 32)); + params[2] = u_offset >> (64 - 53); + params[2] |= v_offset << (79 - 64); + params[3] |= v_offset >> (96 - 79); +} + +static __inline void _ipu_ch_param_set_burst_size(uint32_t *params, + uint16_t burst_pixels) +{ + params[7] &= ~(0x3FL << (89 - 64)); + params[7] |= (uint32_t) (burst_pixels - 1) << (89 - 64); +}; + +static __inline void _ipu_ch_param_set_buffer(uint32_t *params, + dma_addr_t buf0, dma_addr_t buf1) +{ + params[5] = buf0; + params[6] = buf1; +}; + +static __inline void _ipu_ch_param_set_rotation(uint32_t *params, + ipu_rotate_mode_t rot) +{ + params[7] |= (uint32_t) rot << (84 - 64); +}; + +void _ipu_write_param_mem(uint32_t addr, uint32_t *data, uint32_t numWords); + +#endif diff --git a/drivers/mxc/ipu/ipu_prv.h b/drivers/mxc/ipu/ipu_prv.h new file mode 100644 index 000000000000..03450de968e6 --- /dev/null +++ b/drivers/mxc/ipu/ipu_prv.h @@ -0,0 +1,59 @@ +/* + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#ifndef __INCLUDE_IPU_PRV_H__ +#define __INCLUDE_IPU_PRV_H__ + +#include +#include +#include +#include +#include + +/* Globals */ +extern struct device *g_ipu_dev; +extern spinlock_t ipu_lock; +extern struct clk *g_ipu_clk; +extern struct clk *g_ipu_csi_clk; + +int register_ipu_device(void); +ipu_color_space_t format_to_colorspace(uint32_t fmt); + +uint32_t _ipu_channel_status(ipu_channel_t channel); + +void _ipu_sdc_fg_init(ipu_channel_params_t *params); +uint32_t _ipu_sdc_fg_uninit(void); +void _ipu_sdc_bg_init(ipu_channel_params_t *params); +uint32_t _ipu_sdc_bg_uninit(void); + +void _ipu_ic_enable_task(ipu_channel_t channel); +void _ipu_ic_disable_task(ipu_channel_t channel); +void _ipu_ic_init_prpvf(ipu_channel_params_t *params, bool src_is_csi); +void _ipu_ic_uninit_prpvf(void); +void _ipu_ic_init_rotate_vf(ipu_channel_params_t *params); +void _ipu_ic_uninit_rotate_vf(void); +void _ipu_ic_init_csi(ipu_channel_params_t *params); +void _ipu_ic_uninit_csi(void); +void _ipu_ic_init_prpenc(ipu_channel_params_t *params, bool src_is_csi); +void _ipu_ic_uninit_prpenc(void); +void _ipu_ic_init_rotate_enc(ipu_channel_params_t *params); +void _ipu_ic_uninit_rotate_enc(void); +void _ipu_ic_init_pp(ipu_channel_params_t *params); +void _ipu_ic_uninit_pp(void); +void _ipu_ic_init_rotate_pp(ipu_channel_params_t *params); +void _ipu_ic_uninit_rotate_pp(void); + +int32_t _ipu_adc_init_channel(ipu_channel_t chan, display_port_t disp, + mcu_mode_t cmd, int16_t x_pos, int16_t y_pos); +int32_t _ipu_adc_uninit_channel(ipu_channel_t chan); + +#endif /* __INCLUDE_IPU_PRV_H__ */ diff --git a/drivers/mxc/ipu/ipu_regs.h b/drivers/mxc/ipu/ipu_regs.h new file mode 100644 index 000000000000..d78df52a9785 --- /dev/null +++ b/drivers/mxc/ipu/ipu_regs.h @@ -0,0 +1,396 @@ +/* + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/* + * @file ipu_regs.h + * + * @brief IPU Register definitions + * + * @ingroup IPU + */ +#ifndef __IPU_REGS_INCLUDED__ +#define __IPU_REGS_INCLUDED__ + +#define IPU_REG_BASE IO_ADDRESS(IPU_CTRL_BASE_ADDR) + +/* Register addresses */ +/* IPU Common registers */ +#define IPU_CONF (IPU_REG_BASE + 0x0000) +#define IPU_CHA_BUF0_RDY (IPU_REG_BASE + 0x0004) +#define IPU_CHA_BUF1_RDY (IPU_REG_BASE + 0x0008) +#define IPU_CHA_DB_MODE_SEL (IPU_REG_BASE + 0x000C) +#define IPU_CHA_CUR_BUF (IPU_REG_BASE + 0x0010) +#define IPU_FS_PROC_FLOW (IPU_REG_BASE + 0x0014) +#define IPU_FS_DISP_FLOW (IPU_REG_BASE + 0x0018) +#define IPU_TASKS_STAT (IPU_REG_BASE + 0x001C) +#define IPU_IMA_ADDR (IPU_REG_BASE + 0x0020) +#define IPU_IMA_DATA (IPU_REG_BASE + 0x0024) +#define IPU_INT_CTRL_1 (IPU_REG_BASE + 0x0028) +#define IPU_INT_CTRL_2 (IPU_REG_BASE + 0x002C) +#define IPU_INT_CTRL_3 (IPU_REG_BASE + 0x0030) +#define IPU_INT_CTRL_4 (IPU_REG_BASE + 0x0034) +#define IPU_INT_CTRL_5 (IPU_REG_BASE + 0x0038) +#define IPU_INT_STAT_1 (IPU_REG_BASE + 0x003C) +#define IPU_INT_STAT_2 (IPU_REG_BASE + 0x0040) +#define IPU_INT_STAT_3 (IPU_REG_BASE + 0x0044) +#define IPU_INT_STAT_4 (IPU_REG_BASE + 0x0048) +#define IPU_INT_STAT_5 (IPU_REG_BASE + 0x004C) +#define IPU_BRK_CTRL_1 (IPU_REG_BASE + 0x0050) +#define IPU_BRK_CTRL_2 (IPU_REG_BASE + 0x0054) +#define IPU_BRK_STAT (IPU_REG_BASE + 0x0058) +#define IPU_DIAGB_CTRL (IPU_REG_BASE + 0x005C) +/* CMOS Sensor Interface Registers */ +#define CSI_SENS_CONF (IPU_REG_BASE + 0x0060) +#define CSI_SENS_FRM_SIZE (IPU_REG_BASE + 0x0064) +#define CSI_ACT_FRM_SIZE (IPU_REG_BASE + 0x0068) +#define CSI_OUT_FRM_CTRL (IPU_REG_BASE + 0x006C) +#define CSI_TST_CTRL (IPU_REG_BASE + 0x0070) +#define CSI_CCIR_CODE_1 (IPU_REG_BASE + 0x0074) +#define CSI_CCIR_CODE_2 (IPU_REG_BASE + 0x0078) +#define CSI_CCIR_CODE_3 (IPU_REG_BASE + 0x007C) +#define CSI_FLASH_STROBE_1 (IPU_REG_BASE + 0x0080) +#define CSI_FLASH_STROBE_2 (IPU_REG_BASE + 0x0084) +/* Image Converter Registers */ +#define IC_CONF (IPU_REG_BASE + 0x0088) +#define IC_PRP_ENC_RSC (IPU_REG_BASE + 0x008C) +#define IC_PRP_VF_RSC (IPU_REG_BASE + 0x0090) +#define IC_PP_RSC (IPU_REG_BASE + 0x0094) +#define IC_CMBP_1 (IPU_REG_BASE + 0x0098) +#define IC_CMBP_2 (IPU_REG_BASE + 0x009C) +#define PF_CONF (IPU_REG_BASE + 0x00A0) +#define IDMAC_CONF (IPU_REG_BASE + 0x00A4) +#define IDMAC_CHA_EN (IPU_REG_BASE + 0x00A8) +#define IDMAC_CHA_PRI (IPU_REG_BASE + 0x00AC) +#define IDMAC_CHA_BUSY (IPU_REG_BASE + 0x00B0) +/* SDC Registers */ +#define SDC_COM_CONF (IPU_REG_BASE + 0x00B4) +#define SDC_GW_CTRL (IPU_REG_BASE + 0x00B8) +#define SDC_FG_POS (IPU_REG_BASE + 0x00BC) +#define SDC_BG_POS (IPU_REG_BASE + 0x00C0) +#define SDC_CUR_POS (IPU_REG_BASE + 0x00C4) +#define SDC_PWM_CTRL (IPU_REG_BASE + 0x00C8) +#define SDC_CUR_MAP (IPU_REG_BASE + 0x00CC) +#define SDC_HOR_CONF (IPU_REG_BASE + 0x00D0) +#define SDC_VER_CONF (IPU_REG_BASE + 0x00D4) +#define SDC_SHARP_CONF_1 (IPU_REG_BASE + 0x00D8) +#define SDC_SHARP_CONF_2 (IPU_REG_BASE + 0x00DC) +/* ADC Registers */ +#define ADC_CONF (IPU_REG_BASE + 0x00E0) +#define ADC_SYSCHA1_SA (IPU_REG_BASE + 0x00E4) +#define ADC_SYSCHA2_SA (IPU_REG_BASE + 0x00E8) +#define ADC_PRPCHAN_SA (IPU_REG_BASE + 0x00EC) +#define ADC_PPCHAN_SA (IPU_REG_BASE + 0x00F0) +#define ADC_DISP0_CONF (IPU_REG_BASE + 0x00F4) +#define ADC_DISP0_RD_AP (IPU_REG_BASE + 0x00F8) +#define ADC_DISP0_RDM (IPU_REG_BASE + 0x00FC) +#define ADC_DISP0_SS (IPU_REG_BASE + 0x0100) +#define ADC_DISP1_CONF (IPU_REG_BASE + 0x0104) +#define ADC_DISP1_RD_AP (IPU_REG_BASE + 0x0108) +#define ADC_DISP1_RDM (IPU_REG_BASE + 0x010C) +#define ADC_DISP12_SS (IPU_REG_BASE + 0x0110) +#define ADC_DISP2_CONF (IPU_REG_BASE + 0x0114) +#define ADC_DISP2_RD_AP (IPU_REG_BASE + 0x0118) +#define ADC_DISP2_RDM (IPU_REG_BASE + 0x011C) +#define ADC_DISP_VSYNC (IPU_REG_BASE + 0x0120) +/* Display Interface re(sters */ +#define DI_DISP_IF_CONF (IPU_REG_BASE + 0x0124) +#define DI_DISP_SIG_POL (IPU_REG_BASE + 0x0128) +#define DI_SER_DISP1_CONF (IPU_REG_BASE + 0x012C) +#define DI_SER_DISP2_CONF (IPU_REG_BASE + 0x0130) +#define DI_HSP_CLK_PER (IPU_REG_BASE + 0x0134) +#define DI_DISP0_TIME_CONF_1 (IPU_REG_BASE + 0x0138) +#define DI_DISP0_TIME_CONF_2 (IPU_REG_BASE + 0x013C) +#define DI_DISP0_TIME_CONF_3 (IPU_REG_BASE + 0x0140) +#define DI_DISP1_TIME_CONF_1 (IPU_REG_BASE + 0x0144) +#define DI_DISP1_TIME_CONF_2 (IPU_REG_BASE + 0x0148) +#define DI_DISP1_TIME_CONF_3 (IPU_REG_BASE + 0x014C) +#define DI_DISP2_TIME_CONF_1 (IPU_REG_BASE + 0x0150) +#define DI_DISP2_TIME_CONF_2 (IPU_REG_BASE + 0x0154) +#define DI_DISP2_TIME_CONF_3 (IPU_REG_BASE + 0x0158) +#define DI_DISP3_TIME_CONF (IPU_REG_BASE + 0x015C) +#define DI_DISP0_DB0_MAP (IPU_REG_BASE + 0x0160) +#define DI_DISP0_DB1_MAP (IPU_REG_BASE + 0x0164) +#define DI_DISP0_DB2_MAP (IPU_REG_BASE + 0x0168) +#define DI_DISP0_CB0_MAP (IPU_REG_BASE + 0x016C) +#define DI_DISP0_CB1_MAP (IPU_REG_BASE + 0x0170) +#define DI_DISP0_CB2_MAP (IPU_REG_BASE + 0x0174) +#define DI_DISP1_DB0_MAP (IPU_REG_BASE + 0x0178) +#define DI_DISP1_DB1_MAP (IPU_REG_BASE + 0x017C) +#define DI_DISP1_DB2_MAP (IPU_REG_BASE + 0x0180) +#define DI_DISP1_CB0_MAP (IPU_REG_BASE + 0x0184) +#define DI_DISP1_CB1_MAP (IPU_REG_BASE + 0x0188) +#define DI_DISP1_CB2_MAP (IPU_REG_BASE + 0x018C) +#define DI_DISP2_DB0_MAP (IPU_REG_BASE + 0x0190) +#define DI_DISP2_DB1_MAP (IPU_REG_BASE + 0x0194) +#define DI_DISP2_DB2_MAP (IPU_REG_BASE + 0x0198) +#define DI_DISP2_CB0_MAP (IPU_REG_BASE + 0x019C) +#define DI_DISP2_CB1_MAP (IPU_REG_BASE + 0x01A0) +#define DI_DISP2_CB2_MAP (IPU_REG_BASE + 0x01A4) +#define DI_DISP3_B0_MAP (IPU_REG_BASE + 0x01A8) +#define DI_DISP3_B1_MAP (IPU_REG_BASE + 0x01AC) +#define DI_DISP3_B2_MAP (IPU_REG_BASE + 0x01B0) +#define DI_DISP_ACC_CC (IPU_REG_BASE + 0x01B4) +#define DI_DISP_LLA_CONF (IPU_REG_BASE + 0x01B8) +#define DI_DISP_LLA_DATA (IPU_REG_BASE + 0x01BC) + +#define IPUIRQ_2_STATREG(int) (IPU_INT_STAT_1 + 4*(int>>5)) +#define IPUIRQ_2_CTRLREG(int) (IPU_INT_CTRL_1 + 4*(int>>5)) +#define IPUIRQ_2_MASK(int) (1UL << (int & 0x1F)) + +enum { + IPU_CONF_CSI_EN = 0x00000001, + IPU_CONF_IC_EN = 0x00000002, + IPU_CONF_ROT_EN = 0x00000004, + IPU_CONF_PF_EN = 0x00000008, + IPU_CONF_SDC_EN = 0x00000010, + IPU_CONF_ADC_EN = 0x00000020, + IPU_CONF_DI_EN = 0x00000040, + IPU_CONF_DU_EN = 0x00000080, + IPU_CONF_PXL_ENDIAN = 0x00000100, + + FS_PRPVF_ROT_SRC_SEL = 0x00000040, + FS_PRPENC_ROT_SRC_SEL = 0x00000020, + FS_PRPENC_DEST_SEL = 0x00000010, + FS_PP_SRC_SEL_MASK = 0x00000300, + FS_PP_SRC_SEL_OFFSET = 8, + FS_PP_ROT_SRC_SEL_MASK = 0x00000C00, + FS_PP_ROT_SRC_SEL_OFFSET = 10, + FS_PF_DEST_SEL_MASK = 0x00003000, + FS_PF_DEST_SEL_OFFSET = 12, + FS_PRPVF_DEST_SEL_MASK = 0x00070000, + FS_PRPVF_DEST_SEL_OFFSET = 16, + FS_PRPVF_ROT_DEST_SEL_MASK = 0x00700000, + FS_PRPVF_ROT_DEST_SEL_OFFSET = 20, + FS_PP_DEST_SEL_MASK = 0x07000000, + FS_PP_DEST_SEL_OFFSET = 24, + FS_PP_ROT_DEST_SEL_MASK = 0x70000000, + FS_PP_ROT_DEST_SEL_OFFSET = 28, + FS_VF_IN_VALID = 0x00000002, + FS_ENC_IN_VALID = 0x00000001, + + FS_SDC_BG_SRC_SEL_MASK = 0x00000007, + FS_SDC_BG_SRC_SEL_OFFSET = 0, + FS_SDC_FG_SRC_SEL_MASK = 0x00000070, + FS_SDC_FG_SRC_SEL_OFFSET = 4, + FS_ADC1_SRC_SEL_MASK = 0x00000700, + FS_ADC1_SRC_SEL_OFFSET = 8, + FS_ADC2_SRC_SEL_MASK = 0x00007000, + FS_ADC2_SRC_SEL_OFFSET = 12, + FS_AUTO_REF_PER_MASK = 0x03FF0000, + FS_AUTO_REF_PER_OFFSET = 16, + + FS_DEST_ARM = 0, + FS_DEST_ROT = 1, + FS_DEST_PP = 1, + FS_DEST_ADC1 = 2, + FS_DEST_ADC2 = 3, + FS_DEST_SDC_BG = 4, + FS_DEST_SDC_FG = 5, + FS_DEST_ADC = 6, + + FS_SRC_ARM = 0, + FS_PP_SRC_PF = 1, + FS_PP_SRC_ROT = 2, + + FS_ROT_SRC_PP = 1, + FS_ROT_SRC_PF = 2, + + FS_PF_DEST_PP = 1, + FS_PF_DEST_ROT = 2, + + FS_SRC_ROT_VF = 1, + FS_SRC_ROT_PP = 2, + FS_SRC_VF = 3, + FS_SRC_PP = 4, + FS_SRC_SNOOP = 5, + FS_SRC_AUTOREF = 6, + FS_SRC_AUTOREF_SNOOP = 7, + + TSTAT_PF_H264_PAUSE = 0x00000001, + TSTAT_CSI2MEM_MASK = 0x0000000C, + TSTAT_CSI2MEM_OFFSET = 2, + TSTAT_VF_MASK = 0x00000600, + TSTAT_VF_OFFSET = 9, + TSTAT_VF_ROT_MASK = 0x000C0000, + TSTAT_VF_ROT_OFFSET = 18, + TSTAT_ENC_MASK = 0x00000180, + TSTAT_ENC_OFFSET = 7, + TSTAT_ENC_ROT_MASK = 0x00030000, + TSTAT_ENC_ROT_OFFSET = 16, + TSTAT_PP_MASK = 0x00001800, + TSTAT_PP_OFFSET = 11, + TSTAT_PP_ROT_MASK = 0x00300000, + TSTAT_PP_ROT_OFFSET = 20, + TSTAT_PF_MASK = 0x00C00000, + TSTAT_PF_OFFSET = 22, + TSTAT_ADCSYS1_MASK = 0x03000000, + TSTAT_ADCSYS1_OFFSET = 24, + TSTAT_ADCSYS2_MASK = 0x0C000000, + TSTAT_ADCSYS2_OFFSET = 26, + + TASK_STAT_IDLE = 0, + TASK_STAT_ACTIVE = 1, + TASK_STAT_WAIT4READY = 2, + + /* Register bits */ + SDC_COM_TFT_COLOR = 0x00000001UL, + SDC_COM_FG_EN = 0x00000010UL, + SDC_COM_GWSEL = 0x00000020UL, + SDC_COM_GLB_A = 0x00000040UL, + SDC_COM_KEY_COLOR_G = 0x00000080UL, + SDC_COM_BG_EN = 0x00000200UL, + SDC_COM_SHARP = 0x00001000UL, + + SDC_V_SYNC_WIDTH_L = 0x00000001UL, + + ADC_CONF_PRP_EN = 0x00000001L, + ADC_CONF_PP_EN = 0x00000002L, + ADC_CONF_MCU_EN = 0x00000004L, + + ADC_DISP_CONF_SL_MASK = 0x00000FFFL, + ADC_DISP_CONF_TYPE_MASK = 0x00003000L, + ADC_DISP_CONF_TYPE_XY = 0x00002000L, + + ADC_DISP_VSYNC_D0_MODE_MASK = 0x00000003L, + ADC_DISP_VSYNC_D0_WIDTH_MASK = 0x003F0000L, + ADC_DISP_VSYNC_D12_MODE_MASK = 0x0000000CL, + ADC_DISP_VSYNC_D12_WIDTH_MASK = 0x3F000000L, + + /* Image Converter Register bits */ + IC_CONF_PRPENC_EN = 0x00000001, + IC_CONF_PRPENC_CSC1 = 0x00000002, + IC_CONF_PRPENC_ROT_EN = 0x00000004, + IC_CONF_PRPVF_EN = 0x00000100, + IC_CONF_PRPVF_CSC1 = 0x00000200, + IC_CONF_PRPVF_CSC2 = 0x00000400, + IC_CONF_PRPVF_CMB = 0x00000800, + IC_CONF_PRPVF_ROT_EN = 0x00001000, + IC_CONF_PP_EN = 0x00010000, + IC_CONF_PP_CSC1 = 0x00020000, + IC_CONF_PP_CSC2 = 0x00040000, + IC_CONF_PP_CMB = 0x00080000, + IC_CONF_PP_ROT_EN = 0x00100000, + IC_CONF_IC_GLB_LOC_A = 0x10000000, + IC_CONF_KEY_COLOR_EN = 0x20000000, + IC_CONF_RWS_EN = 0x40000000, + IC_CONF_CSI_MEM_WR_EN = 0x80000000, + + IDMA_CHAN_INVALID = 0x000000FF, + IDMA_IC_0 = 0x00000001, + IDMA_IC_1 = 0x00000002, + IDMA_IC_2 = 0x00000004, + IDMA_IC_3 = 0x00000008, + IDMA_IC_4 = 0x00000010, + IDMA_IC_5 = 0x00000020, + IDMA_IC_6 = 0x00000040, + IDMA_IC_7 = 0x00000080, + IDMA_IC_8 = 0x00000100, + IDMA_IC_9 = 0x00000200, + IDMA_IC_10 = 0x00000400, + IDMA_IC_11 = 0x00000800, + IDMA_IC_12 = 0x00001000, + IDMA_IC_13 = 0x00002000, + IDMA_SDC_BG = 0x00004000, + IDMA_SDC_FG = 0x00008000, + IDMA_SDC_MASK = 0x00010000, + IDMA_SDC_PARTIAL = 0x00020000, + IDMA_ADC_SYS1_WR = 0x00040000, + IDMA_ADC_SYS2_WR = 0x00080000, + IDMA_ADC_SYS1_CMD = 0x00100000, + IDMA_ADC_SYS2_CMD = 0x00200000, + IDMA_ADC_SYS1_RD = 0x00400000, + IDMA_ADC_SYS2_RD = 0x00800000, + IDMA_PF_QP = 0x01000000, + IDMA_PF_BSP = 0x02000000, + IDMA_PF_Y_IN = 0x04000000, + IDMA_PF_U_IN = 0x08000000, + IDMA_PF_V_IN = 0x10000000, + IDMA_PF_Y_OUT = 0x20000000, + IDMA_PF_U_OUT = 0x40000000, + IDMA_PF_V_OUT = 0x80000000, + + CSI_SENS_CONF_DATA_FMT_SHIFT = 8, + CSI_SENS_CONF_DATA_FMT_RGB_YUV444 = 0x00000000L, + CSI_SENS_CONF_DATA_FMT_YUV422 = 0x00000200L, + CSI_SENS_CONF_DATA_FMT_BAYER = 0x00000300L, + + CSI_SENS_CONF_VSYNC_POL_SHIFT = 0, + CSI_SENS_CONF_HSYNC_POL_SHIFT = 1, + CSI_SENS_CONF_DATA_POL_SHIFT = 2, + CSI_SENS_CONF_PIX_CLK_POL_SHIFT = 3, + CSI_SENS_CONF_SENS_PRTCL_SHIFT = 4, + CSI_SENS_CONF_SENS_CLKSRC_SHIFT = 7, + CSI_SENS_CONF_DATA_WIDTH_SHIFT = 10, + CSI_SENS_CONF_EXT_VSYNC_SHIFT = 15, + CSI_SENS_CONF_DIVRATIO_SHIFT = 16, + + PF_CONF_TYPE_MASK = 0x00000007, + PF_CONF_TYPE_SHIFT = 0, + PF_CONF_PAUSE_EN = 0x00000010, + PF_CONF_RESET = 0x00008000, + PF_CONF_PAUSE_ROW_MASK = 0x00FF0000, + PF_CONF_PAUSE_ROW_SHIFT = 16, + + /* DI_DISP_SIG_POL bits */ + DI_D3_VSYNC_POL_SHIFT = 28, + DI_D3_HSYNC_POL_SHIFT = 27, + DI_D3_DRDY_SHARP_POL_SHIFT = 26, + DI_D3_CLK_POL_SHIFT = 25, + DI_D3_DATA_POL_SHIFT = 24, + + /* DI_DISP_IF_CONF bits */ + DI_D3_CLK_IDLE_SHIFT = 26, + DI_D3_CLK_SEL_SHIFT = 25, + DI_D3_DATAMSK_SHIFT = 24, + + DISPx_IF_CLK_DOWN_OFFSET = 22, + DISPx_IF_CLK_UP_OFFSET = 12, + DISPx_IF_CLK_PER_OFFSET = 0, + DISPx_IF_CLK_READ_EN_OFFSET = 16, + DISPx_PIX_CLK_PER_OFFSET = 0, + + DI_CONF_DISP0_EN = 0x00000001L, + DI_CONF_DISP0_IF_MODE_OFFSET = 1, + DI_CONF_DISP0_BURST_MODE_OFFSET = 3, + DI_CONF_DISP1_EN = 0x00000100L, + DI_CONF_DISP1_IF_MODE_OFFSET = 9, + DI_CONF_DISP1_BURST_MODE_OFFSET = 12, + DI_CONF_DISP2_EN = 0x00010000L, + DI_CONF_DISP2_IF_MODE_OFFSET = 17, + DI_CONF_DISP2_BURST_MODE_OFFSET = 20, + + DI_SER_DISPx_CONF_SER_BIT_NUM_OFFSET = 16, + DI_SER_DISPx_CONF_PREAMBLE_OFFSET = 8, + DI_SER_DISPx_CONF_PREAMBLE_LEN_OFFSET = 4, + DI_SER_DISPx_CONF_RW_CFG_OFFSET = 1, + DI_SER_DISPx_CONF_BURST_MODE_EN = 0x01000000L, + DI_SER_DISPx_CONF_PREAMBLE_EN = 0x00000001L, + + /* DI_DISP_ACC_CC */ + DISP0_IF_CLK_CNT_D_MASK = 0x00000003L, + DISP0_IF_CLK_CNT_D_OFFSET = 0, + DISP0_IF_CLK_CNT_C_MASK = 0x0000000CL, + DISP0_IF_CLK_CNT_C_OFFSET = 2, + DISP1_IF_CLK_CNT_D_MASK = 0x00000030L, + DISP1_IF_CLK_CNT_D_OFFSET = 4, + DISP1_IF_CLK_CNT_C_MASK = 0x000000C0L, + DISP1_IF_CLK_CNT_C_OFFSET = 6, + DISP2_IF_CLK_CNT_D_MASK = 0x00000300L, + DISP2_IF_CLK_CNT_D_OFFSET = 8, + DISP2_IF_CLK_CNT_C_MASK = 0x00000C00L, + DISP2_IF_CLK_CNT_C_OFFSET = 10, + DISP3_IF_CLK_CNT_MASK = 0x00003000L, + DISP3_IF_CLK_CNT_OFFSET = 12, +}; + +#endif diff --git a/drivers/mxc/ipu/ipu_sdc.c b/drivers/mxc/ipu/ipu_sdc.c new file mode 100644 index 000000000000..946d793e30de --- /dev/null +++ b/drivers/mxc/ipu/ipu_sdc.c @@ -0,0 +1,357 @@ +/* + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file ipu_sdc.c + * + * @brief IPU SDC submodule API functions + * + * @ingroup IPU + */ +#include +#include +#include +#include +#include +#include "ipu_prv.h" +#include "ipu_regs.h" +#include "ipu_param_mem.h" + +static uint32_t g_h_start_width; +static uint32_t g_v_start_width; + +static const uint32_t di_mappings[] = { + 0x1600AAAA, 0x00E05555, 0x00070000, 3, /* RGB888 */ + 0x0005000F, 0x000B000F, 0x0011000F, 1, /* RGB666 */ + 0x0011000F, 0x000B000F, 0x0005000F, 1, /* BGR666 */ + 0x0004003F, 0x000A000F, 0x000F003F, 1 /* RGB565 */ +}; + +/*! + * This function is called to initialize a synchronous LCD panel. + * + * @param panel The type of panel. + * + * @param pixel_clk Desired pixel clock frequency in Hz. + * + * @param pixel_fmt Input parameter for pixel format of buffer. Pixel + * format is a FOURCC ASCII code. + * + * @param width The width of panel in pixels. + * + * @param height The height of panel in pixels. + * + * @param hStartWidth The number of pixel clocks between the HSYNC + * signal pulse and the start of valid data. + * + * @param hSyncWidth The width of the HSYNC signal in units of pixel + * clocks. + * + * @param hEndWidth The number of pixel clocks between the end of + * valid data and the HSYNC signal for next line. + * + * @param vStartWidth The number of lines between the VSYNC + * signal pulse and the start of valid data. + * + * @param vSyncWidth The width of the VSYNC signal in units of lines + * + * @param vEndWidth The number of lines between the end of valid + * data and the VSYNC signal for next frame. + * + * @param sig Bitfield of signal polarities for LCD interface. + * + * @return This function returns 0 on success or negative error code on + * fail. + */ +int32_t ipu_sdc_init_panel(ipu_panel_t panel, + uint32_t pixel_clk, + uint16_t width, uint16_t height, + uint32_t pixel_fmt, + uint16_t h_start_width, uint16_t h_sync_width, + uint16_t h_end_width, uint16_t v_start_width, + uint16_t v_sync_width, uint16_t v_end_width, + ipu_di_signal_cfg_t sig) +{ + unsigned long lock_flags; + uint32_t reg; + uint32_t old_conf; + uint32_t div; + + dev_dbg(g_ipu_dev, "panel size = %d x %d\n", width, height); + + if ((v_sync_width == 0) || (h_sync_width == 0)) + return EINVAL; + + /* Init panel size and blanking periods */ + reg = + ((uint32_t) (h_sync_width - 1) << 26) | + ((uint32_t) (width + h_sync_width + h_start_width + h_end_width - 1) + << 16); + __raw_writel(reg, SDC_HOR_CONF); + + reg = ((uint32_t) (v_sync_width - 1) << 26) | SDC_V_SYNC_WIDTH_L | + ((uint32_t) + (height + v_sync_width + v_start_width + v_end_width - 1) << 16); + __raw_writel(reg, SDC_VER_CONF); + + g_h_start_width = h_start_width + h_sync_width; + g_v_start_width = v_start_width + v_sync_width; + + switch (panel) { + case IPU_PANEL_SHARP_TFT: + __raw_writel(0x00FD0102L, SDC_SHARP_CONF_1); + __raw_writel(0x00F500F4L, SDC_SHARP_CONF_2); + __raw_writel(SDC_COM_SHARP | SDC_COM_TFT_COLOR, SDC_COM_CONF); + break; + case IPU_PANEL_TFT: + __raw_writel(SDC_COM_TFT_COLOR, SDC_COM_CONF); + break; + default: + return EINVAL; + } + + spin_lock_irqsave(&ipu_lock, lock_flags); + + /* Init clocking */ + + /* Calculate divider */ + /* fractional part is 4 bits so simply multiple by 2^4 to get fractional part */ + dev_dbg(g_ipu_dev, "pixel clk = %d\n", pixel_clk); + div = (clk_get_rate(g_ipu_clk) * 16) / pixel_clk; + if (div < 0x40) { /* Divider less than 4 */ + dev_dbg(g_ipu_dev, + "InitPanel() - Pixel clock divider less than 1\n"); + div = 0x40; + } + /* DISP3_IF_CLK_DOWN_WR is half the divider value and 2 less fraction bits */ + /* Subtract 1 extra from DISP3_IF_CLK_DOWN_WR based on timing debug */ + /* DISP3_IF_CLK_UP_WR is 0 */ + __raw_writel((((div / 8) - 1) << 22) | div, DI_DISP3_TIME_CONF); + + /* DI settings */ + old_conf = __raw_readl(DI_DISP_IF_CONF) & 0x78FFFFFF; + old_conf |= sig.datamask_en << DI_D3_DATAMSK_SHIFT | + sig.clksel_en << DI_D3_CLK_SEL_SHIFT | + sig.clkidle_en << DI_D3_CLK_IDLE_SHIFT; + __raw_writel(old_conf, DI_DISP_IF_CONF); + + old_conf = __raw_readl(DI_DISP_SIG_POL) & 0xE0FFFFFF; + old_conf |= sig.data_pol << DI_D3_DATA_POL_SHIFT | + sig.clk_pol << DI_D3_CLK_POL_SHIFT | + sig.enable_pol << DI_D3_DRDY_SHARP_POL_SHIFT | + sig.Hsync_pol << DI_D3_HSYNC_POL_SHIFT | + sig.Vsync_pol << DI_D3_VSYNC_POL_SHIFT; + __raw_writel(old_conf, DI_DISP_SIG_POL); + + switch (pixel_fmt) { + case IPU_PIX_FMT_RGB24: + __raw_writel(di_mappings[0], DI_DISP3_B0_MAP); + __raw_writel(di_mappings[1], DI_DISP3_B1_MAP); + __raw_writel(di_mappings[2], DI_DISP3_B2_MAP); + __raw_writel(__raw_readl(DI_DISP_ACC_CC) | + ((di_mappings[3] - 1) << 12), DI_DISP_ACC_CC); + break; + case IPU_PIX_FMT_RGB666: + __raw_writel(di_mappings[4], DI_DISP3_B0_MAP); + __raw_writel(di_mappings[5], DI_DISP3_B1_MAP); + __raw_writel(di_mappings[6], DI_DISP3_B2_MAP); + __raw_writel(__raw_readl(DI_DISP_ACC_CC) | + ((di_mappings[7] - 1) << 12), DI_DISP_ACC_CC); + break; + case IPU_PIX_FMT_BGR666: + __raw_writel(di_mappings[8], DI_DISP3_B0_MAP); + __raw_writel(di_mappings[9], DI_DISP3_B1_MAP); + __raw_writel(di_mappings[10], DI_DISP3_B2_MAP); + __raw_writel(__raw_readl(DI_DISP_ACC_CC) | + ((di_mappings[11] - 1) << 12), DI_DISP_ACC_CC); + break; + default: + __raw_writel(di_mappings[12], DI_DISP3_B0_MAP); + __raw_writel(di_mappings[13], DI_DISP3_B1_MAP); + __raw_writel(di_mappings[14], DI_DISP3_B2_MAP); + __raw_writel(__raw_readl(DI_DISP_ACC_CC) | + ((di_mappings[15] - 1) << 12), DI_DISP_ACC_CC); + break; + } + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + + dev_dbg(g_ipu_dev, "DI_DISP_IF_CONF = 0x%08X\n", + __raw_readl(DI_DISP_IF_CONF)); + dev_dbg(g_ipu_dev, "DI_DISP_SIG_POL = 0x%08X\n", + __raw_readl(DI_DISP_SIG_POL)); + dev_dbg(g_ipu_dev, "DI_DISP3_TIME_CONF = 0x%08X\n", + __raw_readl(DI_DISP3_TIME_CONF)); + + return 0; +} + +/*! + * This function sets the foreground and background plane global alpha blending + * modes. + * + * @param enable Boolean to enable or disable global alpha + * blending. If disabled, per pixel blending is used. + * + * @param alpha Global alpha value. + * + * @return This function returns 0 on success or negative error code on fail + */ +int32_t ipu_sdc_set_global_alpha(bool enable, uint8_t alpha) +{ + uint32_t reg; + unsigned long lock_flags; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + if (enable) { + reg = __raw_readl(SDC_GW_CTRL) & 0x00FFFFFFL; + __raw_writel(reg | ((uint32_t) alpha << 24), SDC_GW_CTRL); + + reg = __raw_readl(SDC_COM_CONF); + __raw_writel(reg | SDC_COM_GLB_A, SDC_COM_CONF); + } else { + reg = __raw_readl(SDC_COM_CONF); + __raw_writel(reg & ~SDC_COM_GLB_A, SDC_COM_CONF); + } + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + + return 0; +} + +/*! + * This function sets the transparent color key for SDC graphic plane. + * + * @param channel Input parameter for the logical channel ID. + * + * @param enable Boolean to enable or disable color key + * + * @param colorKey 24-bit RGB color to use as transparent color key. + * + * @return This function returns 0 on success or negative error code on fail + */ +int32_t ipu_sdc_set_color_key(ipu_channel_t channel, bool enable, + uint32_t color_key) +{ + uint32_t reg, sdc_conf; + unsigned long lock_flags; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + sdc_conf = __raw_readl(SDC_COM_CONF); + if (channel == MEM_SDC_BG) { + sdc_conf &= ~SDC_COM_GWSEL; + } else { + sdc_conf |= SDC_COM_GWSEL; + } + + if (enable) { + reg = __raw_readl(SDC_GW_CTRL) & 0xFF000000L; + __raw_writel(reg | (color_key & 0x00FFFFFFL), SDC_GW_CTRL); + + sdc_conf |= SDC_COM_KEY_COLOR_G; + } else { + sdc_conf &= ~SDC_COM_KEY_COLOR_G; + } + __raw_writel(sdc_conf, SDC_COM_CONF); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + + return 0; +} + +int32_t ipu_sdc_set_brightness(uint8_t value) +{ + __raw_writel(0x03000000UL | value << 16, SDC_PWM_CTRL); + return 0; +} + +/*! + * This function sets the window position of the foreground or background plane. + * modes. + * + * @param channel Input parameter for the logical channel ID. + * + * @param x_pos The X coordinate position to place window at. + * The position is relative to the top left corner. + * + * @param y_pos The Y coordinate position to place window at. + * The position is relative to the top left corner. + * + * @return This function returns 0 on success or negative error code on fail + */ +int32_t ipu_disp_set_window_pos(ipu_channel_t channel, int16_t x_pos, + int16_t y_pos) +{ + x_pos += g_h_start_width; + y_pos += g_v_start_width; + + if (channel == MEM_SDC_BG) { + __raw_writel((x_pos << 16) | y_pos, SDC_BG_POS); + } else if (channel == MEM_SDC_FG) { + __raw_writel((x_pos << 16) | y_pos, SDC_FG_POS); + } else { + return EINVAL; + } + return 0; +} + +void _ipu_sdc_fg_init(ipu_channel_params_t *params) +{ + uint32_t reg; + (void)params; + + /* Enable FG channel */ + reg = __raw_readl(SDC_COM_CONF); + __raw_writel(reg | SDC_COM_FG_EN | SDC_COM_BG_EN, SDC_COM_CONF); +} + +uint32_t _ipu_sdc_fg_uninit(void) +{ + uint32_t reg; + + /* Disable FG channel */ + reg = __raw_readl(SDC_COM_CONF); + __raw_writel(reg & ~SDC_COM_FG_EN, SDC_COM_CONF); + + return reg & SDC_COM_FG_EN; +} + +void _ipu_sdc_bg_init(ipu_channel_params_t *params) +{ + uint32_t reg; + (void)params; + + /* Enable FG channel */ + reg = __raw_readl(SDC_COM_CONF); + __raw_writel(reg | SDC_COM_BG_EN, SDC_COM_CONF); +} + +uint32_t _ipu_sdc_bg_uninit(void) +{ + uint32_t reg; + + /* Disable BG channel */ + reg = __raw_readl(SDC_COM_CONF); + __raw_writel(reg & ~SDC_COM_BG_EN, SDC_COM_CONF); + + return reg & SDC_COM_BG_EN; +} + +/* Exported symbols for modules. */ +EXPORT_SYMBOL(ipu_sdc_init_panel); +EXPORT_SYMBOL(ipu_sdc_set_global_alpha); +EXPORT_SYMBOL(ipu_sdc_set_color_key); +EXPORT_SYMBOL(ipu_sdc_set_brightness); +EXPORT_SYMBOL(ipu_disp_set_window_pos); diff --git a/drivers/mxc/ipu/pf/Kconfig b/drivers/mxc/ipu/pf/Kconfig new file mode 100644 index 000000000000..fa5a777cf727 --- /dev/null +++ b/drivers/mxc/ipu/pf/Kconfig @@ -0,0 +1,7 @@ +config MXC_IPU_PF + tristate "MXC MPEG4/H.264 Post Filter Driver" + depends on MXC_IPU_V1 + default y + help + Driver for MPEG4 dering and deblock and H.264 deblock + using MXC IPU h/w diff --git a/drivers/mxc/ipu/pf/Makefile b/drivers/mxc/ipu/pf/Makefile new file mode 100644 index 000000000000..641adf4be4bd --- /dev/null +++ b/drivers/mxc/ipu/pf/Makefile @@ -0,0 +1 @@ +obj-$(CONFIG_MXC_IPU_PF) += mxc_pf.o diff --git a/drivers/mxc/ipu/pf/mxc_pf.c b/drivers/mxc/ipu/pf/mxc_pf.c new file mode 100644 index 000000000000..e098e0d20510 --- /dev/null +++ b/drivers/mxc/ipu/pf/mxc_pf.c @@ -0,0 +1,991 @@ +/* + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mxc_pf.c + * + * @brief MXC IPU MPEG4/H.264 Post-filtering driver + * + * User-level API for IPU Hardware MPEG4/H.264 Post-filtering. + * + * @ingroup MXC_PF + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct mxc_pf_data { + pf_operation_t mode; + u32 pf_enabled; + u32 width; + u32 height; + u32 stride; + uint32_t qp_size; + dma_addr_t qp_paddr; + void *qp_vaddr; + pf_buf buf[PF_MAX_BUFFER_CNT]; + void *buf_vaddr[PF_MAX_BUFFER_CNT]; + wait_queue_head_t pf_wait; + volatile int done_mask; + volatile int wait_mask; + volatile int busy_flag; + struct semaphore busy_lock; +}; + +static struct mxc_pf_data pf_data; +static u8 open_count; +static struct class *mxc_pf_class; + +/* + * Function definitions + */ + +static irqreturn_t mxc_pf_irq_handler(int irq, void *dev_id) +{ + struct mxc_pf_data *pf = dev_id; + + if (irq == IPU_IRQ_PF_Y_OUT_EOF) { + pf->done_mask |= PF_WAIT_Y; + } else if (irq == IPU_IRQ_PF_U_OUT_EOF) { + pf->done_mask |= PF_WAIT_U; + } else if (irq == IPU_IRQ_PF_V_OUT_EOF) { + pf->done_mask |= PF_WAIT_V; + } else { + return IRQ_NONE; + } + + if (pf->wait_mask && ((pf->done_mask & pf->wait_mask) == pf->wait_mask)) { + wake_up_interruptible(&pf->pf_wait); + } + return IRQ_HANDLED; +} + +/*! + * This function handles PF_IOCTL_INIT calls. It initializes the PF channels, + * interrupt handlers, and channel buffers. + * + * @return This function returns 0 on success or negative error code on + * error. + */ +static int mxc_pf_init(pf_init_params *pf_init) +{ + int err; + ipu_channel_params_t params; + u32 w; + u32 stride; + u32 h; + u32 qp_size = 0; + u32 qp_stride; + + if ((pf_init->pf_mode > 4) || (pf_init->width > 1024) || + (pf_init->height > 1024) || (pf_init->stride < pf_init->width)) { + return -EINVAL; + } + + pf_data.mode = pf_init->pf_mode; + w = pf_data.width = pf_init->width; + h = pf_data.height = pf_init->height; + stride = pf_data.stride = pf_init->stride; + pf_data.qp_size = pf_init->qp_size; + + memset(¶ms, 0, sizeof(params)); + params.mem_pf_mem.operation = pf_data.mode; + err = ipu_init_channel(MEM_PF_Y_MEM, ¶ms); + if (err < 0) { + printk(KERN_ERR "mxc_pf: error initializing channel\n"); + goto err0; + } + + err = ipu_init_channel_buffer(MEM_PF_Y_MEM, IPU_INPUT_BUFFER, + IPU_PIX_FMT_GENERIC, w, h, stride, + IPU_ROTATE_NONE, 0, 0, 0, 0); + if (err < 0) { + printk(KERN_ERR "mxc_pf: error initializing Y input buffer\n"); + goto err0; + } + + err = ipu_init_channel_buffer(MEM_PF_Y_MEM, IPU_OUTPUT_BUFFER, + IPU_PIX_FMT_GENERIC, w, h, stride, + IPU_ROTATE_NONE, 0, 0, 0, 0); + if (err < 0) { + printk(KERN_ERR "mxc_pf: error initializing Y output buffer\n"); + goto err0; + } + + w = w / 2; + h = h / 2; + stride = stride / 2; + + if (pf_data.mode != PF_MPEG4_DERING) { + err = ipu_init_channel_buffer(MEM_PF_U_MEM, IPU_INPUT_BUFFER, + IPU_PIX_FMT_GENERIC, w, h, stride, + IPU_ROTATE_NONE, 0, 0, 0, 0); + if (err < 0) { + printk(KERN_ERR + "mxc_pf: error initializing U input buffer\n"); + goto err0; + } + + err = ipu_init_channel_buffer(MEM_PF_U_MEM, IPU_OUTPUT_BUFFER, + IPU_PIX_FMT_GENERIC, w, h, stride, + IPU_ROTATE_NONE, 0, 0, 0, 0); + if (err < 0) { + printk(KERN_ERR + "mxc_pf: error initializing U output buffer\n"); + goto err0; + } + + err = ipu_init_channel_buffer(MEM_PF_V_MEM, IPU_INPUT_BUFFER, + IPU_PIX_FMT_GENERIC, w, h, stride, + IPU_ROTATE_NONE, 0, 0, 0, 0); + if (err < 0) { + printk(KERN_ERR + "mxc_pf: error initializing V input buffer\n"); + goto err0; + } + + err = ipu_init_channel_buffer(MEM_PF_V_MEM, IPU_OUTPUT_BUFFER, + IPU_PIX_FMT_GENERIC, w, h, stride, + IPU_ROTATE_NONE, 0, 0, 0, 0); + if (err < 0) { + printk(KERN_ERR + "mxc_pf: error initializing V output buffer\n"); + goto err0; + } + } + + /*Setup Channel QF and BSC Params */ + if (pf_data.mode == PF_H264_DEBLOCK) { + w = ((pf_data.width + 15) / 16); + h = (pf_data.height + 15) / 16; + qp_stride = w; + qp_size = 4 * qp_stride * h; + pr_debug("H264 QP width = %d, height = %d\n", w, h); + err = ipu_init_channel_buffer(MEM_PF_Y_MEM, + IPU_SEC_INPUT_BUFFER, + IPU_PIX_FMT_GENERIC_32, w, h, + qp_stride, IPU_ROTATE_NONE, 0, 0, + 0, 0); + if (err < 0) { + printk(KERN_ERR + "mxc_pf: error initializing H264 QP buffer\n"); + goto err0; + } +/* w = (pf_data.width + 3) / 4; */ + w *= 4; + h *= 4; + qp_stride = w; + err = ipu_init_channel_buffer(MEM_PF_U_MEM, + IPU_SEC_INPUT_BUFFER, + IPU_PIX_FMT_GENERIC, w, h, + qp_stride, IPU_ROTATE_NONE, 0, 0, + 0, 0); + if (err < 0) { + printk(KERN_ERR + "mxc_pf: error initializing H264 BSB buffer\n"); + goto err0; + } + qp_size += qp_stride * h; + } else { /* MPEG4 mode */ + + w = (pf_data.width + 15) / 16; + h = (pf_data.height + 15) / 16; + qp_stride = (w + 3) & ~0x3UL; + pr_debug("MPEG4 QP width = %d, height = %d, stride = %d\n", + w, h, qp_stride); + err = ipu_init_channel_buffer(MEM_PF_Y_MEM, + IPU_SEC_INPUT_BUFFER, + IPU_PIX_FMT_GENERIC, w, h, + qp_stride, IPU_ROTATE_NONE, 0, 0, + 0, 0); + if (err < 0) { + printk(KERN_ERR + "mxc_pf: error initializing MPEG4 QP buffer\n"); + goto err0; + } + qp_size = qp_stride * h; + } + + /* Support 2 QP buffers */ + qp_size *= 2; + + if (pf_data.qp_size > qp_size) + qp_size = pf_data.qp_size; + else + pf_data.qp_size = qp_size; + + pf_data.qp_vaddr = dma_alloc_coherent(NULL, pf_data.qp_size, + &pf_data.qp_paddr, + GFP_KERNEL | GFP_DMA); + if (!pf_data.qp_vaddr) + return -ENOMEM; + + pf_init->qp_paddr = pf_data.qp_paddr; + pf_init->qp_size = pf_data.qp_size; + + return 0; + + err0: + return err; +} + +/*! + * This function handles PF_IOCTL_UNINIT calls. It uninitializes the PF + * channels and interrupt handlers. + * + * @return This function returns 0 on success or negative error code + * on error. + */ +static int mxc_pf_uninit(void) +{ + pf_data.pf_enabled = 0; + ipu_disable_irq(IPU_IRQ_PF_Y_OUT_EOF); + ipu_disable_irq(IPU_IRQ_PF_U_OUT_EOF); + ipu_disable_irq(IPU_IRQ_PF_V_OUT_EOF); + + ipu_disable_channel(MEM_PF_Y_MEM, true); + ipu_disable_channel(MEM_PF_U_MEM, true); + ipu_disable_channel(MEM_PF_V_MEM, true); + ipu_uninit_channel(MEM_PF_Y_MEM); + ipu_uninit_channel(MEM_PF_U_MEM); + ipu_uninit_channel(MEM_PF_V_MEM); + + if (pf_data.qp_vaddr) { + dma_free_coherent(NULL, pf_data.qp_size, pf_data.qp_vaddr, + pf_data.qp_paddr); + pf_data.qp_vaddr = NULL; + } + + return 0; +} + +/*! + * This function handles PF_IOCTL_REQBUFS calls. It initializes the PF channels + * and channel buffers. + * + * @param reqbufs Input/Output Structure containing buffer mode, + * type, offset, and size. The offset and size of + * the buffer are returned for PF_MEMORY_MMAP mode. + * + * @return This function returns 0 on success or negative error code + * on error. + */ +static int mxc_pf_reqbufs(pf_reqbufs_params *reqbufs) +{ + int err; + uint32_t buf_size; + int i; + int alloc_cnt = 0; + pf_buf *buf = pf_data.buf; + if (reqbufs->count > PF_MAX_BUFFER_CNT) { + reqbufs->count = PF_MAX_BUFFER_CNT; + } + /* Deallocate mmapped buffers */ + if (reqbufs->count == 0) { + for (i = 0; i < PF_MAX_BUFFER_CNT; i++) { + if (buf[i].index != -1) { + dma_free_coherent(NULL, buf[i].size, + pf_data.buf_vaddr[i], + buf[i].offset); + pf_data.buf_vaddr[i] = NULL; + buf[i].index = -1; + buf[i].size = 0; + } + } + return 0; + } + + buf_size = (pf_data.stride * pf_data.height * 3) / 2; + if (reqbufs->req_size > buf_size) { + buf_size = reqbufs->req_size; + pr_debug("using requested buffer size of %d\n", buf_size); + } else { + reqbufs->req_size = buf_size; + pr_debug("using default buffer size of %d\n", buf_size); + } + + for (i = 0; alloc_cnt < reqbufs->count; i++) { + buf[i].index = i; + buf[i].size = buf_size; + pf_data.buf_vaddr[i] = dma_alloc_coherent(NULL, buf[i].size, + &buf[i].offset, + GFP_KERNEL | GFP_DMA); + if (!pf_data.buf_vaddr[i] || !buf[i].offset) { + printk(KERN_ERR + "mxc_pf: unable to allocate IPU buffers.\n"); + err = -ENOMEM; + goto err0; + } + pr_debug("Allocated buffer %d at paddr 0x%08X, vaddr %p\n", + i, buf[i].offset, pf_data.buf_vaddr[i]); + + alloc_cnt++; + } + + return 0; + err0: + for (i = 0; i < alloc_cnt; i++) { + dma_free_coherent(NULL, buf[i].size, pf_data.buf_vaddr[i], + buf[i].offset); + pf_data.buf_vaddr[i] = NULL; + buf[i].index = -1; + buf[i].size = 0; + } + return err; +} + +/*! + * This function handles PF_IOCTL_START calls. It sets the PF channel buffers + * addresses and starts the channels + * + * @return This function returns 0 on success or negative error code on + * error. + */ +static int mxc_pf_start(pf_buf *in, pf_buf *out, int qp_buf) +{ + int err; + dma_addr_t y_in_paddr; + dma_addr_t u_in_paddr; + dma_addr_t v_in_paddr; + dma_addr_t p1_in_paddr; + dma_addr_t p2_in_paddr; + dma_addr_t y_out_paddr; + dma_addr_t u_out_paddr; + dma_addr_t v_out_paddr; + + /* H.264 requires output buffer equal to input */ + if (pf_data.mode == PF_H264_DEBLOCK) + out = in; + + y_in_paddr = in->offset + in->y_offset; + if (in->u_offset) + u_in_paddr = in->offset + in->u_offset; + else + u_in_paddr = y_in_paddr + (pf_data.stride * pf_data.height); + if (in->v_offset) + v_in_paddr = in->offset + in->v_offset; + else + v_in_paddr = u_in_paddr + (pf_data.stride * pf_data.height) / 4; + p1_in_paddr = pf_data.qp_paddr; + if (qp_buf) + p1_in_paddr += pf_data.qp_size / 2; + + if (pf_data.mode == PF_H264_DEBLOCK) { + p2_in_paddr = p1_in_paddr + + ((pf_data.width + 15) / 16) * + ((pf_data.height + 15) / 16) * 4; + } else { + p2_in_paddr = 0; + } + + pr_debug("y_in_paddr = 0x%08X\nu_in_paddr = 0x%08X\n" + "v_in_paddr = 0x%08X\n" + "qp_paddr = 0x%08X\nbsb_paddr = 0x%08X\n", + y_in_paddr, u_in_paddr, v_in_paddr, p1_in_paddr, p2_in_paddr); + + y_out_paddr = out->offset + out->y_offset; + if (out->u_offset) + u_out_paddr = out->offset + out->u_offset; + else + u_out_paddr = y_out_paddr + (pf_data.stride * pf_data.height); + if (out->v_offset) + v_out_paddr = out->offset + out->v_offset; + else + v_out_paddr = + u_out_paddr + (pf_data.stride * pf_data.height) / 4; + + pr_debug("y_out_paddr = 0x%08X\nu_out_paddr = 0x%08X\n" + "v_out_paddr = 0x%08X\n", + y_out_paddr, u_out_paddr, v_out_paddr); + + pf_data.done_mask = 0; + + ipu_enable_irq(IPU_IRQ_PF_Y_OUT_EOF); + if (pf_data.mode != PF_MPEG4_DERING) { + ipu_enable_irq(IPU_IRQ_PF_U_OUT_EOF); + ipu_enable_irq(IPU_IRQ_PF_V_OUT_EOF); + } + + err = ipu_update_channel_buffer(MEM_PF_Y_MEM, IPU_INPUT_BUFFER, 0, + y_in_paddr); + if (err < 0) { + printk(KERN_ERR "mxc_pf: error setting Y input buffer\n"); + goto err0; + } + + err = ipu_update_channel_buffer(MEM_PF_Y_MEM, IPU_OUTPUT_BUFFER, 0, + y_out_paddr); + if (err < 0) { + printk(KERN_ERR "mxc_pf: error setting Y output buffer\n"); + goto err0; + } + + if (pf_data.mode != PF_MPEG4_DERING) { + err = + ipu_update_channel_buffer(MEM_PF_U_MEM, IPU_INPUT_BUFFER, 0, + u_in_paddr); + if (err < 0) { + printk(KERN_ERR + "mxc_pf: error setting U input buffer\n"); + goto err0; + } + + err = + ipu_update_channel_buffer(MEM_PF_U_MEM, IPU_OUTPUT_BUFFER, + 0, u_out_paddr); + if (err < 0) { + printk(KERN_ERR + "mxc_pf: error setting U output buffer\n"); + goto err0; + } + + err = + ipu_update_channel_buffer(MEM_PF_V_MEM, IPU_INPUT_BUFFER, 0, + v_in_paddr); + if (err < 0) { + printk(KERN_ERR + "mxc_pf: error setting V input buffer\n"); + goto err0; + } + + err = + ipu_update_channel_buffer(MEM_PF_V_MEM, IPU_OUTPUT_BUFFER, + 0, v_out_paddr); + if (err < 0) { + printk(KERN_ERR + "mxc_pf: error setting V output buffer\n"); + goto err0; + } + } + + err = ipu_update_channel_buffer(MEM_PF_Y_MEM, IPU_SEC_INPUT_BUFFER, 0, + p1_in_paddr); + if (err < 0) { + printk(KERN_ERR "mxc_pf: error setting QP buffer\n"); + goto err0; + } + + if (pf_data.mode == PF_H264_DEBLOCK) { + + err = ipu_update_channel_buffer(MEM_PF_U_MEM, + IPU_SEC_INPUT_BUFFER, 0, + p2_in_paddr); + if (err < 0) { + printk(KERN_ERR + "mxc_pf: error setting H264 BSB buffer\n"); + goto err0; + } + ipu_select_buffer(MEM_PF_U_MEM, IPU_SEC_INPUT_BUFFER, 0); + } + + ipu_select_buffer(MEM_PF_Y_MEM, IPU_OUTPUT_BUFFER, 0); + ipu_select_buffer(MEM_PF_Y_MEM, IPU_SEC_INPUT_BUFFER, 0); + ipu_select_buffer(MEM_PF_Y_MEM, IPU_INPUT_BUFFER, 0); + if (pf_data.mode != PF_MPEG4_DERING) { + ipu_select_buffer(MEM_PF_U_MEM, IPU_OUTPUT_BUFFER, 0); + ipu_select_buffer(MEM_PF_V_MEM, IPU_OUTPUT_BUFFER, 0); + ipu_select_buffer(MEM_PF_U_MEM, IPU_INPUT_BUFFER, 0); + ipu_select_buffer(MEM_PF_V_MEM, IPU_INPUT_BUFFER, 0); + } + + if (!pf_data.pf_enabled) { + pf_data.pf_enabled = 1; + if (pf_data.mode != PF_MPEG4_DERING) { + ipu_enable_channel(MEM_PF_V_MEM); + ipu_enable_channel(MEM_PF_U_MEM); + } + ipu_enable_channel(MEM_PF_Y_MEM); + } + + return 0; + err0: + return err; +} + +/*! + * Post Filter driver open function. This function implements the Linux + * file_operations.open() API function. + * + * @param inode struct inode * + * + * @param filp struct file * + * + * @return This function returns 0 on success or negative error code on + * error. + */ +static int mxc_pf_open(struct inode *inode, struct file *filp) +{ + int i; + + if (open_count) { + return -EBUSY; + } + + open_count++; + + memset(&pf_data, 0, sizeof(pf_data)); + for (i = 0; i < PF_MAX_BUFFER_CNT; i++) { + pf_data.buf[i].index = -1; + } + init_waitqueue_head(&pf_data.pf_wait); + init_MUTEX(&pf_data.busy_lock); + + pf_data.busy_flag = 1; + + ipu_request_irq(IPU_IRQ_PF_Y_OUT_EOF, mxc_pf_irq_handler, + 0, "mxc_ipu_pf", &pf_data); + + ipu_request_irq(IPU_IRQ_PF_U_OUT_EOF, mxc_pf_irq_handler, + 0, "mxc_ipu_pf", &pf_data); + + ipu_request_irq(IPU_IRQ_PF_V_OUT_EOF, mxc_pf_irq_handler, + 0, "mxc_ipu_pf", &pf_data); + + ipu_disable_irq(IPU_IRQ_PF_Y_OUT_EOF); + ipu_disable_irq(IPU_IRQ_PF_U_OUT_EOF); + ipu_disable_irq(IPU_IRQ_PF_V_OUT_EOF); + + return 0; +} + +/*! + * Post Filter driver release function. This function implements the Linux + * file_operations.release() API function. + * + * @param inode struct inode * + * + * @param filp struct file * + * + * @return This function returns 0 on success or negative error code on + * error. + */ +static int mxc_pf_release(struct inode *inode, struct file *filp) +{ + pf_reqbufs_params req_buf; + + if (open_count) { + mxc_pf_uninit(); + + /* Free any allocated buffers */ + req_buf.count = 0; + mxc_pf_reqbufs(&req_buf); + + ipu_free_irq(IPU_IRQ_PF_V_OUT_EOF, &pf_data); + ipu_free_irq(IPU_IRQ_PF_U_OUT_EOF, &pf_data); + ipu_free_irq(IPU_IRQ_PF_Y_OUT_EOF, &pf_data); + open_count--; + } + return 0; +} + +/*! + * Post Filter driver ioctl function. This function implements the Linux + * file_operations.ioctl() API function. + * + * @param inode struct inode * + * + * @param filp struct file * + * + * @param cmd IOCTL command to handle + * + * @param arg Pointer to arguments for IOCTL + * + * @return This function returns 0 on success or negative error code on + * error. + */ +static int mxc_pf_ioctl(struct inode *inode, struct file *filp, + unsigned int cmd, unsigned long arg) +{ + int retval = 0; + + switch (cmd) { + case PF_IOCTL_INIT: + { + pf_init_params pf_init; + + pr_debug("PF_IOCTL_INIT\n"); + if (copy_from_user(&pf_init, (void *)arg, + _IOC_SIZE(cmd))) { + retval = -EFAULT; + break; + } + + retval = mxc_pf_init(&pf_init); + if (retval < 0) + break; + pf_init.qp_paddr = pf_data.qp_paddr; + pf_init.qp_size = pf_data.qp_size; + + /* Return size of memory allocated */ + if (copy_to_user((void *)arg, &pf_init, _IOC_SIZE(cmd))) { + retval = -EFAULT; + break; + } + + pf_data.busy_flag = 0; + break; + } + case PF_IOCTL_UNINIT: + pr_debug("PF_IOCTL_UNINIT\n"); + retval = mxc_pf_uninit(); + break; + case PF_IOCTL_REQBUFS: + { + pf_reqbufs_params reqbufs; + pr_debug("PF_IOCTL_REQBUFS\n"); + + if (copy_from_user + (&reqbufs, (void *)arg, _IOC_SIZE(cmd))) { + retval = -EFAULT; + break; + } + + retval = mxc_pf_reqbufs(&reqbufs); + + /* Return size of memory allocated */ + if (copy_to_user((void *)arg, &reqbufs, _IOC_SIZE(cmd))) { + retval = -EFAULT; + break; + } + + break; + } + case PF_IOCTL_QUERYBUF: + { + pf_buf buf; + pr_debug("PF_IOCTL_QUERYBUF\n"); + + if (copy_from_user(&buf, (void *)arg, _IOC_SIZE(cmd))) { + retval = -EFAULT; + break; + } + + if ((buf.index < 0) || + (buf.index >= PF_MAX_BUFFER_CNT) || + (pf_data.buf[buf.index].index != buf.index)) { + retval = -EINVAL; + break; + } + /* Return size of memory allocated */ + if (copy_to_user((void *)arg, &pf_data.buf[buf.index], + _IOC_SIZE(cmd))) { + retval = -EFAULT; + break; + } + + break; + } + case PF_IOCTL_START: + { + int index; + pf_start_params start_params; + pr_debug("PF_IOCTL_START\n"); + + if (pf_data.busy_flag) { + retval = -EBUSY; + break; + } + + if (copy_from_user(&start_params, (void *)arg, + _IOC_SIZE(cmd))) { + retval = -EFAULT; + break; + } + if (start_params.h264_pause_row >= + ((pf_data.height + 15) / 16)) { + retval = -EINVAL; + break; + } + + pf_data.busy_flag = 1; + + index = start_params.in.index; + if ((index >= 0) && (index < PF_MAX_BUFFER_CNT)) { + if (pf_data.buf[index].offset != + start_params.in.offset) { + retval = -EINVAL; + break; + } + } + + index = start_params.out.index; + if ((index >= 0) && (index < PF_MAX_BUFFER_CNT)) { + if (pf_data.buf[index].offset != + start_params.out.offset) { + retval = -EINVAL; + break; + } + } + + ipu_pf_set_pause_row(start_params.h264_pause_row); + + retval = mxc_pf_start(&start_params.in, &start_params.out, + start_params.qp_buf); + /*Update y, u, v buffers in DMA Channels */ + if ((retval < 0) + break; + + pr_debug("PF_IOCTL_START - processing started\n"); + + if (!start_params.wait) { + break; + } + + pr_debug("PF_IOCTL_START - waiting for completion\n"); + + pf_data.wait_mask = PF_WAIT_ALL; + /* Fall thru to wait */ + } + case PF_IOCTL_WAIT: + { + if (!pf_data.wait_mask) + pf_data.wait_mask = (u32) arg; + + if (pf_data.mode == PF_MPEG4_DERING) + pf_data.wait_mask &= PF_WAIT_Y; + + if (!pf_data.wait_mask) { + retval = -EINVAL; + break; + } + + if (!wait_event_interruptible_timeout(pf_data.pf_wait, + ((pf_data. + done_mask & + pf_data. + wait_mask) == + pf_data. + wait_mask), + 1 * HZ)) { + pr_debug + ("PF_IOCTL_WAIT: timeout, done_mask = %d\n", + pf_data.done_mask); + retval = -ETIME; + break; + } else if (signal_pending(current)) { + pr_debug("PF_IOCTL_WAIT: interrupt received\n"); + retval = -ERESTARTSYS; + break; + } + pf_data.busy_flag = 0; + pf_data.wait_mask = 0; + + pr_debug("PF_IOCTL_WAIT - finished\n"); + break; + } + case PF_IOCTL_RESUME: + { + int pause_row; + pr_debug("PF_IOCTL_RESUME\n"); + + if (pf_data.busy_flag == 0) { + retval = -EFAULT; + break; + } + + if (copy_from_user(&pause_row, (void *)arg, + _IOC_SIZE(cmd))) { + retval = -EFAULT; + break; + } + + if (pause_row >= ((pf_data.height + 15) / 16)) { + retval = -EINVAL; + break; + } + + ipu_pf_set_pause_row(pause_row); + break; + } + + default: + printk(KERN_ERR "ipu_pf_ioctl not supported ioctl\n"); + retval = -1; + } + + if (retval < 0) + pr_debug("return = %d\n", retval); + return retval; +} + +/*! + * Post Filter driver mmap function. This function implements the Linux + * file_operations.mmap() API function for mapping driver buffers to user space. + * + * @param file struct file * + * + * @param vma structure vm_area_struct * + * + * @return 0 Success, EINTR busy lock error, + * ENOBUFS remap_page error. + */ +static int mxc_pf_mmap(struct file *file, struct vm_area_struct *vma) +{ + unsigned long size = vma->vm_end - vma->vm_start; + int res = 0; + + pr_debug("pgoff=0x%lx, start=0x%lx, end=0x%lx\n", + vma->vm_pgoff, vma->vm_start, vma->vm_end); + + /* make this _really_ smp-safe */ + if (down_interruptible(&pf_data.busy_lock)) + return -EINTR; + + /* make buffers write-thru cacheable */ + vma->vm_page_prot = __pgprot(pgprot_val(vma->vm_page_prot) & + ~L_PTE_BUFFERABLE); + + if (remap_pfn_range(vma, vma->vm_start, + vma->vm_pgoff, size, vma->vm_page_prot)) { + printk(KERN_ERR "mxc_pf: remap_pfn_range failed\n"); + res = -ENOBUFS; + goto mmap_exit; + } + + vma->vm_flags &= ~VM_IO; /* using shared anonymous pages */ + + mmap_exit: + up(&pf_data.busy_lock); + return res; +} + +/*! + * Post Filter driver fsync function. This function implements the Linux + * file_operations.fsync() API function. + * + * The user must call fsync() before reading an output buffer. This + * call flushes the L1 and L2 caches + * + * @param filp structure file * + * + * @param dentry struct dentry * + * + * @param datasync unused + * + * @return status POLLIN | POLLRDNORM + */ +int mxc_pf_fsync(struct file *filp, struct dentry *dentry, int datasync) +{ + flush_cache_all(); + outer_flush_all(); + return 0; +} + +/*! + * Post Filter driver poll function. This function implements the Linux + * file_operations.poll() API function. + * + * @param file structure file * + * + * @param wait structure poll_table * + * + * @return status POLLIN | POLLRDNORM + */ +static unsigned int mxc_pf_poll(struct file *file, poll_table * wait) +{ + wait_queue_head_t *queue = NULL; + int res = POLLIN | POLLRDNORM; + + if (down_interruptible(&pf_data.busy_lock)) + return -EINTR; + + queue = &pf_data.pf_wait; + poll_wait(file, queue, wait); + + up(&pf_data.busy_lock); + + return res; +} + +/*! + * File operation structure functions pointers. + */ +static struct file_operations mxc_pf_fops = { + .owner = THIS_MODULE, + .open = mxc_pf_open, + .release = mxc_pf_release, + .ioctl = mxc_pf_ioctl, + .poll = mxc_pf_poll, + .mmap = mxc_pf_mmap, + .fsync = mxc_pf_fsync, +}; + +static int mxc_pf_major; + +/*! + * Post Filter driver module initialization function. + */ +int mxc_pf_dev_init(void) +{ + int ret = 0; + struct device *temp_class; + + mxc_pf_major = register_chrdev(0, "mxc_ipu_pf", &mxc_pf_fops); + + if (mxc_pf_major < 0) { + printk(KERN_INFO "Unable to get a major for mxc_ipu_pf"); + return mxc_pf_major; + } + + mxc_pf_class = class_create(THIS_MODULE, "mxc_ipu_pf"); + if (IS_ERR(mxc_pf_class)) { + printk(KERN_ERR "Error creating mxc_ipu_pf class.\n"); + ret = PTR_ERR(mxc_pf_class); + goto err_out1; + } + + temp_class = device_create(mxc_pf_class, NULL, MKDEV(mxc_pf_major, 0), NULL, + "mxc_ipu_pf"); + if (IS_ERR(temp_class)) { + printk(KERN_ERR "Error creating mxc_ipu_pf class device.\n"); + ret = PTR_ERR(temp_class); + goto err_out2; + } + + printk(KERN_INFO "IPU Post-filter loading\n"); + + return 0; + + err_out2: + class_destroy(mxc_pf_class); + err_out1: + unregister_chrdev(mxc_pf_major, "mxc_ipu_pf"); + return ret; +} + +/*! + * Post Filter driver module exit function. + */ +static void mxc_pf_exit(void) +{ + if (mxc_pf_major > 0) { + device_destroy(mxc_pf_class, MKDEV(mxc_pf_major, 0)); + class_destroy(mxc_pf_class); + unregister_chrdev(mxc_pf_major, "mxc_ipu_pf"); + } +} + +module_init(mxc_pf_dev_init); +module_exit(mxc_pf_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MXC MPEG4/H.264 Postfilter Driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/ipu3/Kconfig b/drivers/mxc/ipu3/Kconfig new file mode 100644 index 000000000000..0ae0ffa9e19d --- /dev/null +++ b/drivers/mxc/ipu3/Kconfig @@ -0,0 +1,5 @@ +config MXC_IPU_V3 + bool + +config MXC_IPU_V3D + bool diff --git a/drivers/mxc/ipu3/Makefile b/drivers/mxc/ipu3/Makefile new file mode 100644 index 000000000000..aa3e7b1bb501 --- /dev/null +++ b/drivers/mxc/ipu3/Makefile @@ -0,0 +1,4 @@ +obj-$(CONFIG_MXC_IPU_V3) = mxc_ipu.o + +mxc_ipu-objs := ipu_common.o ipu_ic.o ipu_disp.o ipu_capture.o ipu_device.o ipu_calc_stripes_sizes.o + diff --git a/drivers/mxc/ipu3/ipu_calc_stripes_sizes.c b/drivers/mxc/ipu3/ipu_calc_stripes_sizes.c new file mode 100644 index 000000000000..5d5e0b9155a0 --- /dev/null +++ b/drivers/mxc/ipu3/ipu_calc_stripes_sizes.c @@ -0,0 +1,373 @@ +/* + * Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/* + * @file ipu_calc_stripes_sizes.c + * + * @brief IPU IC functions + * + * @ingroup IPU + */ + +#include +#include +#include + +#define BPP_32 0 +#define BPP_16 3 +#define BPP_8 5 +#define BPP_24 1 +#define BPP_12 4 +#define BPP_18 2 + +static u64 _do_div(u64 a, u32 b) +{ + u64 div; + div = a; + do_div(div, b); + return div; +} + +static u32 truncate(u32 up, /* 0: down; else: up */ + u64 a, /* must be non-negative */ + u32 b) +{ + u32 d; + u64 div; + div = _do_div(a, b); + d = b * (div >> 32); + if (up && (a > (((u64)d) << 32))) + return d+b; + else + return d; +} + +static unsigned int f_calc(unsigned int pfs, unsigned int bpp, unsigned int *write) +{/* return input_f */ + unsigned int f_calculated = 0; + switch (pfs) { + case IPU_PIX_FMT_YVU422P: + case IPU_PIX_FMT_YUV422P: + case IPU_PIX_FMT_YUV420P2: + case IPU_PIX_FMT_YUV420P: + f_calculated = 16; + break; + + case IPU_PIX_FMT_NV12: + f_calculated = 8; + break; + + default: + f_calculated = 0; + break; + + } + if (!f_calculated) { + switch (bpp) { + case BPP_32: + f_calculated = 2; + break; + + case BPP_16: + f_calculated = 4; + break; + + case BPP_8: + case BPP_24: + f_calculated = 8; + break; + + case BPP_12: + f_calculated = 16; + break; + + case BPP_18: + f_calculated = 32; + break; + + default: + f_calculated = 0; + break; + } + } + return f_calculated; +} + + +static unsigned int m_calc(unsigned int pfs) +{ + unsigned int m_calculated = 0; + switch (pfs) { + case IPU_PIX_FMT_YUV420P2: + case IPU_PIX_FMT_YUV420P: + case IPU_PIX_FMT_YVU422P: + case IPU_PIX_FMT_YUV422P: + case IPU_PIX_FMT_YVU420P: + case IPU_PIX_FMT_NV12: + m_calculated = 8; + break; + + case IPU_PIX_FMT_YUYV: + case IPU_PIX_FMT_UYVY: + m_calculated = 2; + break; + + default: + m_calculated = 1; + break; + + } + return m_calculated; +} + + +/* Stripe parameters calculator */ +/************************************************************************** +Notes: +MSW = the maximal width allowed for a stripe + i.MX31: 720, i.MX35: 800, i.MX37/51/53: 1024 +cirr = the maximal inverse resizing ratio for which overlap in the input + is requested; typically cirr~2 +equal_stripes: + 0: each stripe is allowed to have independent parameters + for maximal image quality + 1: the stripes are requested to have identical parameters + (except the base address), for maximal performance +If performance is the top priority (above image quality) + Avoid overlap, by setting CIRR = 0 + This will also force effectively identical_stripes = 1 + Choose IF & OF that corresponds to the same IOX/SX for both stripes + Choose IFW & OFW such that + IFW/IM, IFW/IF, OFW/OM, OFW/OF are even integers + The function returns an error status: + 0: no error + 1: invalid input parameters -> aborted without result + Valid parameters should satisfy the following conditions + IFW <= OFW, otherwise downsizing is required + - which is not supported yet + 4 <= IFW,OFW, so some interpolation may be needed even without overlap + IM, OM, IF, OF should not vanish + 2*IF <= IFW + so the frame can be split to two equal stripes, even without overlap + 2*(OF+IF/irr_opt) <= OFW + so a valid positive INW exists even for equal stripes + OF <= MSW, otherwise, the left stripe cannot be sufficiently large + MSW < OFW, so splitting to stripes is required + OFW <= 2*MSW, so two stripes are sufficient + (this also implies that 2<=MSW) + 2: OF is not a multiple of OM - not fully-supported yet + Output is produced but OW is not guaranited to be a multiple of OM + 4: OFW reduced to be a multiple of OM + 8: CIRR > 1: truncated to 1 + Overlap is not supported (and not needed) y for upsizing) +**************************************************************************/ +int ipu_calc_stripes_sizes(const unsigned int input_frame_width, + /* input frame width;>1 */ + unsigned int output_frame_width, /* output frame width; >1 */ + const unsigned int maximal_stripe_width, + /* the maximal width allowed for a stripe */ + const unsigned long long cirr, /* see above */ + const unsigned int equal_stripes, /* see above */ + u32 input_pixelformat,/* pixel format after of read channel*/ + u32 output_pixelformat,/* pixel format after of write channel*/ + struct stripe_param *left, + struct stripe_param *right) +{ + const unsigned int irr_frac_bits = 13; + const unsigned long irr_steps = 1 << irr_frac_bits; + const u64 dirr = ((u64)1) << (32 - 2); + /* The maximum relative difference allowed between the irrs */ + const u64 cr = ((u64)4) << 32; + /* The importance ratio between the two terms in the cost function below */ + + unsigned int status; + unsigned int temp; + unsigned int onw_min; + unsigned int inw, onw, inw_best = 0; + /* number of pixels in the left stripe NOT hidden by the right stripe */ + u64 irr_opt; /* the optimal inverse resizing ratio */ + u64 rr_opt; /* the optimal resizing ratio = 1/irr_opt*/ + u64 dinw; /* the misalignment between the stripes */ + /* (measured in units of input columns) */ + u64 difwl, difwr; + /* The number of input columns not reflected in the output */ + /* the resizing ratio used for the right stripe is */ + /* left->irr and right->irr respectively */ + u64 cost, cost_min; + u64 div; /* result of division */ + + unsigned int input_m, input_f, output_m, output_f; /* parameters for upsizing by stripes */ + + status = 0; + + /* M, F calculations */ + /* read back pfs from params */ + + input_f = f_calc(input_pixelformat, 0, NULL); + input_m = 16; + /* BPP should be used in the out_F calc */ + /* Temporarily not used */ + /* out_F = F_calc(idmac->pfs, idmac->bpp, NULL); */ + + output_f = 16; + output_m = m_calc(output_pixelformat); + + + if ((input_frame_width < 4) || (output_frame_width < 4)) + return 1; + + irr_opt = _do_div((((u64)(input_frame_width - 1)) << 32), + (output_frame_width - 1)); + rr_opt = _do_div((((u64)(output_frame_width - 1)) << 32), + (input_frame_width - 1)); + + if ((input_m == 0) || (output_m == 0) || (input_f == 0) || (output_f == 0) + || (input_frame_width < (2 * input_f)) + || ((((u64)output_frame_width) << 32) < + (2 * ((((u64)output_f) << 32) + (input_f * rr_opt)))) + || (maximal_stripe_width < output_f) + || (output_frame_width <= maximal_stripe_width) + || ((2 * maximal_stripe_width) < output_frame_width)) + return 1; + + if (output_f % output_m) + status += 2; + + temp = truncate(0, (((u64)output_frame_width) << 32), output_m); + if (temp < output_frame_width) { + output_frame_width = temp; + status += 4; + } + + if (equal_stripes) { + if ((irr_opt > cirr) /* overlap in the input is not requested */ + && ((input_frame_width % (input_m << 1)) == 0) + && ((input_frame_width % (input_f << 1)) == 0) + && ((output_frame_width % (output_m << 1)) == 0) + && ((output_frame_width % (output_f << 1)) == 0)) { + /* without overlap */ + left->input_width = right->input_width = right->input_column = + input_frame_width >> 1; + left->output_width = right->output_width = right->output_column = + output_frame_width >> 1; + left->input_column = 0; + div = _do_div(((((u64)irr_steps) << 32) * + (right->input_width - 1)), (right->output_width - 1)); + left->irr = right->irr = truncate(0, div, 1); + } else { /* with overlap */ + onw = truncate(0, (((u64)output_frame_width - 1) << 32) >> 1, + output_f); + inw = truncate(0, onw * irr_opt, input_f); + /* this is the maximal inw which allows the same resizing ratio */ + /* in both stripes */ + onw = truncate(1, (inw * rr_opt), output_f); + div = _do_div((((u64)(irr_steps * inw)) << + 32), onw); + left->irr = right->irr = truncate(0, div, 1); + left->output_width = right->output_width = + output_frame_width - onw; + /* These are valid assignments for output_width, */ + /* assuming output_f is a multiple of output_m */ + div = (((u64)(left->output_width-1) * (left->irr)) << 32); + div = (((u64)1) << 32) + _do_div(div, irr_steps); + + left->input_width = right->input_width = truncate(1, div, input_m); + + div = _do_div((((u64)((right->output_width - 1) * right->irr)) << + 32), irr_steps); + difwr = (((u64)(input_frame_width - 1 - inw)) << 32) - div; + div = _do_div((difwr + (((u64)input_f) << 32)), 2); + left->input_column = truncate(0, div, input_f); + + + /* This splits the truncated input columns evenly */ + /* between the left and right margins */ + right->input_column = left->input_column + inw; + left->output_column = 0; + right->output_column = onw; + } + } else { /* independent stripes */ + onw_min = output_frame_width - maximal_stripe_width; + /* onw is a multiple of output_f, in the range */ + /* [max(output_f,output_frame_width-maximal_stripe_width),*/ + /*min(output_frame_width-2,maximal_stripe_width)] */ + /* definitely beyond the cost of any valid setting */ + cost_min = (((u64)input_frame_width) << 32) + cr; + onw = truncate(0, ((u64)maximal_stripe_width), output_f); + if (output_frame_width - onw == 1) + onw -= output_f; /* => onw and output_frame_width-1-onw are positive */ + inw = truncate(0, onw * irr_opt, input_f); + /* this is the maximal inw which allows the same resizing ratio */ + /* in both stripes */ + onw = truncate(1, inw * rr_opt, output_f); + do { + div = _do_div((((u64)(irr_steps * inw)) << 32), onw); + left->irr = truncate(0, div, 1); + div = _do_div((((u64)(onw * left->irr)) << 32), + irr_steps); + dinw = (((u64)inw) << 32) - div; + + div = _do_div((((u64)((output_frame_width - 1 - onw) * left->irr)) << + 32), irr_steps); + + difwl = (((u64)(input_frame_width - 1 - inw)) << 32) - div; + + cost = difwl + (((u64)(cr * dinw)) >> 32); + + if (cost < cost_min) { + inw_best = inw; + cost_min = cost; + } + + inw -= input_f; + onw = truncate(1, inw * rr_opt, output_f); + /* This is the minimal onw which allows the same resizing ratio */ + /* in both stripes */ + } while (onw >= onw_min); + + inw = inw_best; + onw = truncate(1, inw * rr_opt, output_f); + div = _do_div((((u64)(irr_steps * inw)) << 32), onw); + left->irr = truncate(0, div, 1); + + left->output_width = onw; + right->output_width = output_frame_width - onw; + /* These are valid assignments for output_width, */ + /* assuming output_f is a multiple of output_m */ + left->input_width = truncate(1, ((u64)(inw + 1)) << 32, input_m); + right->input_width = truncate(1, ((u64)(input_frame_width - inw)) << + 32, input_m); + + div = _do_div((((u64)(irr_steps * (input_frame_width - 1 - inw))) << + 32), (right->output_width - 1)); + right->irr = truncate(0, div, 1); + temp = truncate(0, ((u64)left->irr) * ((((u64)1) << 32) + dirr), 1); + if (temp < right->irr) + right->irr = temp; + div = _do_div(((u64)((right->output_width - 1) * right->irr) << + 32), irr_steps); + difwr = (u64)(input_frame_width - 1 - inw) - div; + + + div = _do_div((difwr + (((u64)input_f) << 32)), 2); + left->input_column = truncate(0, div, input_f); + + /* This splits the truncated input columns evenly */ + /* between the left and right margins */ + right->input_column = left->input_column + inw; + left->output_column = 0; + right->output_column = onw; + } + return status; +} +EXPORT_SYMBOL(ipu_calc_stripes_sizes); diff --git a/drivers/mxc/ipu3/ipu_capture.c b/drivers/mxc/ipu3/ipu_capture.c new file mode 100644 index 000000000000..391cc963ec9a --- /dev/null +++ b/drivers/mxc/ipu3/ipu_capture.c @@ -0,0 +1,719 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file ipu_capture.c + * + * @brief IPU capture dase functions + * + * @ingroup IPU + */ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ipu_prv.h" +#include "ipu_regs.h" + +/*! + * ipu_csi_init_interface + * Sets initial values for the CSI registers. + * The width and height of the sensor and the actual frame size will be + * set to the same values. + * @param width Sensor width + * @param height Sensor height + * @param pixel_fmt pixel format + * @param cfg_param ipu_csi_signal_cfg_t structure + * @param csi csi 0 or csi 1 + * + * @return 0 for success, -EINVAL for error + */ +int32_t +ipu_csi_init_interface(uint16_t width, uint16_t height, uint32_t pixel_fmt, + ipu_csi_signal_cfg_t cfg_param) +{ + uint32_t data = 0; + uint32_t csi = cfg_param.csi; + unsigned long lock_flags; + + /* Set SENS_DATA_FORMAT bits (8, 9 and 10) + RGB or YUV444 is 0 which is current value in data so not set + explicitly + This is also the default value if attempts are made to set it to + something invalid. */ + switch (pixel_fmt) { + case IPU_PIX_FMT_YUYV: + cfg_param.data_fmt = CSI_SENS_CONF_DATA_FMT_YUV422_YUYV; + break; + case IPU_PIX_FMT_UYVY: + cfg_param.data_fmt = CSI_SENS_CONF_DATA_FMT_YUV422_UYVY; + break; + case IPU_PIX_FMT_RGB24: + case IPU_PIX_FMT_BGR24: + cfg_param.data_fmt = CSI_SENS_CONF_DATA_FMT_RGB_YUV444; + break; + case IPU_PIX_FMT_GENERIC: + cfg_param.data_fmt = CSI_SENS_CONF_DATA_FMT_BAYER; + break; + case IPU_PIX_FMT_RGB565: + cfg_param.data_fmt = CSI_SENS_CONF_DATA_FMT_RGB565; + break; + case IPU_PIX_FMT_RGB555: + cfg_param.data_fmt = CSI_SENS_CONF_DATA_FMT_RGB555; + break; + default: + return -EINVAL; + } + + /* Set the CSI_SENS_CONF register remaining fields */ + data |= cfg_param.data_width << CSI_SENS_CONF_DATA_WIDTH_SHIFT | + cfg_param.data_fmt << CSI_SENS_CONF_DATA_FMT_SHIFT | + cfg_param.data_pol << CSI_SENS_CONF_DATA_POL_SHIFT | + cfg_param.Vsync_pol << CSI_SENS_CONF_VSYNC_POL_SHIFT | + cfg_param.Hsync_pol << CSI_SENS_CONF_HSYNC_POL_SHIFT | + cfg_param.pixclk_pol << CSI_SENS_CONF_PIX_CLK_POL_SHIFT | + cfg_param.ext_vsync << CSI_SENS_CONF_EXT_VSYNC_SHIFT | + cfg_param.clk_mode << CSI_SENS_CONF_SENS_PRTCL_SHIFT | + cfg_param.pack_tight << CSI_SENS_CONF_PACK_TIGHT_SHIFT | + cfg_param.force_eof << CSI_SENS_CONF_FORCE_EOF_SHIFT | + cfg_param.data_en_pol << CSI_SENS_CONF_DATA_EN_POL_SHIFT; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + __raw_writel(data, CSI_SENS_CONF(csi)); + + /* Setup sensor frame size */ + __raw_writel((width - 1) | (height - 1) << 16, CSI_SENS_FRM_SIZE(csi)); + + /* Set CCIR registers */ + if (cfg_param.clk_mode == IPU_CSI_CLK_MODE_CCIR656_PROGRESSIVE) { + __raw_writel(0x40030, CSI_CCIR_CODE_1(csi)); + __raw_writel(0xFF0000, CSI_CCIR_CODE_3(csi)); + } else if (cfg_param.clk_mode == IPU_CSI_CLK_MODE_CCIR656_INTERLACED) { + _ipu_csi_ccir_err_detection_enable(csi); + /* Field0BlankEnd = 0x7, Field0BlankStart = 0x3, + Field0ActiveEnd = 0x5, Field0ActiveStart = 0x1 */ + __raw_writel(0xD07DF, CSI_CCIR_CODE_1(csi)); + /* Field1BlankEnd = 0x6, Field1BlankStart = 0x2, + Field1ActiveEnd = 0x4, Field1ActiveStart = 0 */ + __raw_writel(0x40596, CSI_CCIR_CODE_2(csi)); + __raw_writel(0xFF0000, CSI_CCIR_CODE_3(csi)); + } else if ((cfg_param.clk_mode == + IPU_CSI_CLK_MODE_CCIR1120_PROGRESSIVE_DDR) || + (cfg_param.clk_mode == + IPU_CSI_CLK_MODE_CCIR1120_PROGRESSIVE_SDR) || + (cfg_param.clk_mode == + IPU_CSI_CLK_MODE_CCIR1120_INTERLACED_DDR) || + (cfg_param.clk_mode == + IPU_CSI_CLK_MODE_CCIR1120_INTERLACED_SDR)) { + _ipu_csi_ccir_err_detection_enable(csi); + __raw_writel(0x40030, CSI_CCIR_CODE_1(csi)); + __raw_writel(0xFF0000, CSI_CCIR_CODE_3(csi)); + } else if ((cfg_param.clk_mode == IPU_CSI_CLK_MODE_GATED_CLK) || + (cfg_param.clk_mode == IPU_CSI_CLK_MODE_NONGATED_CLK)) { + _ipu_csi_ccir_err_detection_disable(csi); + } + + dev_dbg(g_ipu_dev, "CSI_SENS_CONF = 0x%08X\n", + __raw_readl(CSI_SENS_CONF(csi))); + dev_dbg(g_ipu_dev, "CSI_ACT_FRM_SIZE = 0x%08X\n", + __raw_readl(CSI_ACT_FRM_SIZE(csi))); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + + return 0; +} +EXPORT_SYMBOL(ipu_csi_init_interface); + +/*! _ipu_csi_mclk_set + * + * @param pixel_clk desired pixel clock frequency in Hz + * @param csi csi 0 or csi 1 + * + * @return Returns 0 on success or negative error code on fail + */ +int _ipu_csi_mclk_set(uint32_t pixel_clk, uint32_t csi) +{ + uint32_t temp; + uint32_t div_ratio; + + div_ratio = (clk_get_rate(g_ipu_clk) / pixel_clk) - 1; + + if (div_ratio > 0xFF || div_ratio < 0) { + dev_dbg(g_ipu_dev, "The value of pixel_clk extends normal range\n"); + return -EINVAL; + } + + temp = __raw_readl(CSI_SENS_CONF(csi)); + temp &= ~CSI_SENS_CONF_DIVRATIO_MASK; + __raw_writel(temp | (div_ratio << CSI_SENS_CONF_DIVRATIO_SHIFT), + CSI_SENS_CONF(csi)); + + return 0; +} + +/*! + * ipu_csi_enable_mclk + * + * @param csi csi 0 or csi 1 + * @param flag true to enable mclk, false to disable mclk + * @param wait true to wait 100ms make clock stable, false not wait + * + * @return Returns 0 on success + */ +int ipu_csi_enable_mclk(int csi, bool flag, bool wait) +{ + if (flag) { + clk_enable(g_csi_clk[csi]); + if (wait == true) + msleep(10); + } else { + clk_disable(g_csi_clk[csi]); + } + + return 0; +} +EXPORT_SYMBOL(ipu_csi_enable_mclk); + +/*! + * ipu_csi_get_window_size + * + * @param width pointer to window width + * @param height pointer to window height + * @param csi csi 0 or csi 1 + */ +void ipu_csi_get_window_size(uint32_t *width, uint32_t *height, uint32_t csi) +{ + uint32_t reg; + unsigned long lock_flags; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + reg = __raw_readl(CSI_ACT_FRM_SIZE(csi)); + *width = (reg & 0xFFFF) + 1; + *height = (reg >> 16 & 0xFFFF) + 1; + + spin_unlock_irqrestore(&ipu_lock, lock_flags); +} +EXPORT_SYMBOL(ipu_csi_get_window_size); + +/*! + * ipu_csi_set_window_size + * + * @param width window width + * @param height window height + * @param csi csi 0 or csi 1 + */ +void ipu_csi_set_window_size(uint32_t width, uint32_t height, uint32_t csi) +{ + unsigned long lock_flags; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + __raw_writel((width - 1) | (height - 1) << 16, CSI_ACT_FRM_SIZE(csi)); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); +} +EXPORT_SYMBOL(ipu_csi_set_window_size); + +/*! + * ipu_csi_set_window_pos + * + * @param left uint32 window x start + * @param top uint32 window y start + * @param csi csi 0 or csi 1 + */ +void ipu_csi_set_window_pos(uint32_t left, uint32_t top, uint32_t csi) +{ + uint32_t temp; + unsigned long lock_flags; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + temp = __raw_readl(CSI_OUT_FRM_CTRL(csi)); + temp &= ~(CSI_HSC_MASK | CSI_VSC_MASK); + temp |= ((top << CSI_VSC_SHIFT) | (left << CSI_HSC_SHIFT)); + __raw_writel(temp, CSI_OUT_FRM_CTRL(csi)); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); +} +EXPORT_SYMBOL(ipu_csi_set_window_pos); + +/*! + * _ipu_csi_horizontal_downsize_enable + * Enable horizontal downsizing(decimation) by 2. + * + * @param csi csi 0 or csi 1 + */ +void _ipu_csi_horizontal_downsize_enable(uint32_t csi) +{ + uint32_t temp; + unsigned long lock_flags; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + temp = __raw_readl(CSI_OUT_FRM_CTRL(csi)); + temp |= CSI_HORI_DOWNSIZE_EN; + __raw_writel(temp, CSI_OUT_FRM_CTRL(csi)); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); +} + +/*! + * _ipu_csi_horizontal_downsize_disable + * Disable horizontal downsizing(decimation) by 2. + * + * @param csi csi 0 or csi 1 + */ +void _ipu_csi_horizontal_downsize_disable(uint32_t csi) +{ + uint32_t temp; + unsigned long lock_flags; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + temp = __raw_readl(CSI_OUT_FRM_CTRL(csi)); + temp &= ~CSI_HORI_DOWNSIZE_EN; + __raw_writel(temp, CSI_OUT_FRM_CTRL(csi)); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); +} + +/*! + * _ipu_csi_vertical_downsize_enable + * Enable vertical downsizing(decimation) by 2. + * + * @param csi csi 0 or csi 1 + */ +void _ipu_csi_vertical_downsize_enable(uint32_t csi) +{ + uint32_t temp; + unsigned long lock_flags; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + temp = __raw_readl(CSI_OUT_FRM_CTRL(csi)); + temp |= CSI_VERT_DOWNSIZE_EN; + __raw_writel(temp, CSI_OUT_FRM_CTRL(csi)); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); +} + +/*! + * _ipu_csi_vertical_downsize_disable + * Disable vertical downsizing(decimation) by 2. + * + * @param csi csi 0 or csi 1 + */ +void _ipu_csi_vertical_downsize_disable(uint32_t csi) +{ + uint32_t temp; + unsigned long lock_flags; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + temp = __raw_readl(CSI_OUT_FRM_CTRL(csi)); + temp &= ~CSI_VERT_DOWNSIZE_EN; + __raw_writel(temp, CSI_OUT_FRM_CTRL(csi)); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); +} + +/*! + * ipu_csi_set_test_generator + * + * @param active 1 for active and 0 for inactive + * @param r_value red value for the generated pattern of even pixel + * @param g_value green value for the generated pattern of even + * pixel + * @param b_value blue value for the generated pattern of even pixel + * @param pixel_clk desired pixel clock frequency in Hz + * @param csi csi 0 or csi 1 + */ +void ipu_csi_set_test_generator(bool active, uint32_t r_value, + uint32_t g_value, uint32_t b_value, uint32_t pix_clk, uint32_t csi) +{ + uint32_t temp; + unsigned long lock_flags; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + temp = __raw_readl(CSI_TST_CTRL(csi)); + + if (active == false) { + temp &= ~CSI_TEST_GEN_MODE_EN; + __raw_writel(temp, CSI_TST_CTRL(csi)); + } else { + /* Set sensb_mclk div_ratio*/ + _ipu_csi_mclk_set(pix_clk, csi); + + temp &= ~(CSI_TEST_GEN_R_MASK | CSI_TEST_GEN_G_MASK | + CSI_TEST_GEN_B_MASK); + temp |= CSI_TEST_GEN_MODE_EN; + temp |= (r_value << CSI_TEST_GEN_R_SHIFT) | + (g_value << CSI_TEST_GEN_G_SHIFT) | + (b_value << CSI_TEST_GEN_B_SHIFT); + __raw_writel(temp, CSI_TST_CTRL(csi)); + } + + spin_unlock_irqrestore(&ipu_lock, lock_flags); +} +EXPORT_SYMBOL(ipu_csi_set_test_generator); + +/*! + * _ipu_csi_ccir_err_detection_en + * Enable error detection and correction for + * CCIR interlaced mode with protection bit. + * + * @param csi csi 0 or csi 1 + */ +void _ipu_csi_ccir_err_detection_enable(uint32_t csi) +{ + uint32_t temp; + + temp = __raw_readl(CSI_CCIR_CODE_1(csi)); + temp |= CSI_CCIR_ERR_DET_EN; + __raw_writel(temp, CSI_CCIR_CODE_1(csi)); +} + +/*! + * _ipu_csi_ccir_err_detection_disable + * Disable error detection and correction for + * CCIR interlaced mode with protection bit. + * + * @param csi csi 0 or csi 1 + */ +void _ipu_csi_ccir_err_detection_disable(uint32_t csi) +{ + uint32_t temp; + + temp = __raw_readl(CSI_CCIR_CODE_1(csi)); + temp &= ~CSI_CCIR_ERR_DET_EN; + __raw_writel(temp, CSI_CCIR_CODE_1(csi)); +} + +/*! + * _ipu_csi_set_mipi_di + * + * @param num MIPI data identifier 0-3 handled by CSI + * @param di_val data identifier value + * @param csi csi 0 or csi 1 + * + * @return Returns 0 on success or negative error code on fail + */ +int _ipu_csi_set_mipi_di(uint32_t num, uint32_t di_val, uint32_t csi) +{ + uint32_t temp; + int retval = 0; + unsigned long lock_flags; + + if (di_val > 0xFFL) { + retval = -EINVAL; + goto err; + } + + spin_lock_irqsave(&ipu_lock, lock_flags); + + temp = __raw_readl(CSI_MIPI_DI(csi)); + + switch (num) { + case IPU_CSI_MIPI_DI0: + temp &= ~CSI_MIPI_DI0_MASK; + temp |= (di_val << CSI_MIPI_DI0_SHIFT); + __raw_writel(temp, CSI_MIPI_DI(csi)); + break; + case IPU_CSI_MIPI_DI1: + temp &= ~CSI_MIPI_DI1_MASK; + temp |= (di_val << CSI_MIPI_DI1_SHIFT); + __raw_writel(temp, CSI_MIPI_DI(csi)); + break; + case IPU_CSI_MIPI_DI2: + temp &= ~CSI_MIPI_DI2_MASK; + temp |= (di_val << CSI_MIPI_DI2_SHIFT); + __raw_writel(temp, CSI_MIPI_DI(csi)); + break; + case IPU_CSI_MIPI_DI3: + temp &= ~CSI_MIPI_DI3_MASK; + temp |= (di_val << CSI_MIPI_DI3_SHIFT); + __raw_writel(temp, CSI_MIPI_DI(csi)); + break; + default: + retval = -EINVAL; + goto err; + } + + spin_unlock_irqrestore(&ipu_lock, lock_flags); +err: + return retval; +} + +/*! + * _ipu_csi_set_skip_isp + * + * @param skip select frames to be skipped and set the + * correspond bits to 1 + * @param max_ratio number of frames in a skipping set and the + * maximum value of max_ratio is 5 + * @param csi csi 0 or csi 1 + * + * @return Returns 0 on success or negative error code on fail + */ +int _ipu_csi_set_skip_isp(uint32_t skip, uint32_t max_ratio, uint32_t csi) +{ + uint32_t temp; + int retval = 0; + unsigned long lock_flags; + + if (max_ratio > 5) { + retval = -EINVAL; + goto err; + } + + spin_lock_irqsave(&ipu_lock, lock_flags); + + temp = __raw_readl(CSI_SKIP(csi)); + temp &= ~(CSI_MAX_RATIO_SKIP_ISP_MASK | CSI_SKIP_ISP_MASK); + temp |= (max_ratio << CSI_MAX_RATIO_SKIP_ISP_SHIFT) | + (skip << CSI_SKIP_ISP_SHIFT); + __raw_writel(temp, CSI_SKIP(csi)); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); +err: + return retval; +} + +/*! + * _ipu_csi_set_skip_smfc + * + * @param skip select frames to be skipped and set the + * correspond bits to 1 + * @param max_ratio number of frames in a skipping set and the + * maximum value of max_ratio is 5 + * @param id csi to smfc skipping id + * @param csi csi 0 or csi 1 + * + * @return Returns 0 on success or negative error code on fail + */ +int _ipu_csi_set_skip_smfc(uint32_t skip, uint32_t max_ratio, + uint32_t id, uint32_t csi) +{ + uint32_t temp; + int retval = 0; + unsigned long lock_flags; + + if (max_ratio > 5 || id > 3) { + retval = -EINVAL; + goto err; + } + + spin_lock_irqsave(&ipu_lock, lock_flags); + + temp = __raw_readl(CSI_SKIP(csi)); + temp &= ~(CSI_MAX_RATIO_SKIP_SMFC_MASK | CSI_ID_2_SKIP_MASK | + CSI_SKIP_SMFC_MASK); + temp |= (max_ratio << CSI_MAX_RATIO_SKIP_SMFC_SHIFT) | + (id << CSI_ID_2_SKIP_SHIFT) | + (skip << CSI_SKIP_SMFC_SHIFT); + __raw_writel(temp, CSI_SKIP(csi)); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); +err: + return retval; +} + +/*! + * _ipu_smfc_init + * Map CSI frames to IDMAC channels. + * + * @param channel IDMAC channel 0-3 + * @param mipi_id mipi id number 0-3 + * @param csi csi0 or csi1 + */ +void _ipu_smfc_init(ipu_channel_t channel, uint32_t mipi_id, uint32_t csi) +{ + uint32_t temp; + + temp = __raw_readl(SMFC_MAP); + + switch (channel) { + case CSI_MEM0: + temp &= ~SMFC_MAP_CH0_MASK; + temp |= ((csi << 2) | mipi_id) << SMFC_MAP_CH0_SHIFT; + break; + case CSI_MEM1: + temp &= ~SMFC_MAP_CH1_MASK; + temp |= ((csi << 2) | mipi_id) << SMFC_MAP_CH1_SHIFT; + break; + case CSI_MEM2: + temp &= ~SMFC_MAP_CH2_MASK; + temp |= ((csi << 2) | mipi_id) << SMFC_MAP_CH2_SHIFT; + break; + case CSI_MEM3: + temp &= ~SMFC_MAP_CH3_MASK; + temp |= ((csi << 2) | mipi_id) << SMFC_MAP_CH3_SHIFT; + break; + default: + return; + } + + __raw_writel(temp, SMFC_MAP); +} + +/*! + * _ipu_smfc_set_wmc + * Caution: The number of required channels, the enabled channels + * and the FIFO size per channel are configured restrictedly. + * + * @param channel IDMAC channel 0-3 + * @param set set 1 or clear 0 + * @param level water mark level when FIFO is on the + * relative size + */ +void _ipu_smfc_set_wmc(ipu_channel_t channel, bool set, uint32_t level) +{ + uint32_t temp; + unsigned long lock_flags; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + temp = __raw_readl(SMFC_WMC); + + switch (channel) { + case CSI_MEM0: + if (set == true) { + temp &= ~SMFC_WM0_SET_MASK; + temp |= level << SMFC_WM0_SET_SHIFT; + } else { + temp &= ~SMFC_WM0_CLR_MASK; + temp |= level << SMFC_WM0_CLR_SHIFT; + } + break; + case CSI_MEM1: + if (set == true) { + temp &= ~SMFC_WM1_SET_MASK; + temp |= level << SMFC_WM1_SET_SHIFT; + } else { + temp &= ~SMFC_WM1_CLR_MASK; + temp |= level << SMFC_WM1_CLR_SHIFT; + } + break; + case CSI_MEM2: + if (set == true) { + temp &= ~SMFC_WM2_SET_MASK; + temp |= level << SMFC_WM2_SET_SHIFT; + } else { + temp &= ~SMFC_WM2_CLR_MASK; + temp |= level << SMFC_WM2_CLR_SHIFT; + } + break; + case CSI_MEM3: + if (set == true) { + temp &= ~SMFC_WM3_SET_MASK; + temp |= level << SMFC_WM3_SET_SHIFT; + } else { + temp &= ~SMFC_WM3_CLR_MASK; + temp |= level << SMFC_WM3_CLR_SHIFT; + } + break; + default: + return; + } + + __raw_writel(temp, SMFC_WMC); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); +} + +/*! + * _ipu_smfc_set_burst_size + * + * @param channel IDMAC channel 0-3 + * @param bs burst size of IDMAC channel, + * the value programmed here shoud be BURST_SIZE-1 + */ +void _ipu_smfc_set_burst_size(ipu_channel_t channel, uint32_t bs) +{ + uint32_t temp; + unsigned long lock_flags; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + temp = __raw_readl(SMFC_BS); + + switch (channel) { + case CSI_MEM0: + temp &= ~SMFC_BS0_MASK; + temp |= bs << SMFC_BS0_SHIFT; + break; + case CSI_MEM1: + temp &= ~SMFC_BS1_MASK; + temp |= bs << SMFC_BS1_SHIFT; + break; + case CSI_MEM2: + temp &= ~SMFC_BS2_MASK; + temp |= bs << SMFC_BS2_SHIFT; + break; + case CSI_MEM3: + temp &= ~SMFC_BS3_MASK; + temp |= bs << SMFC_BS3_SHIFT; + break; + default: + return; + } + + __raw_writel(temp, SMFC_BS); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); +} + +/*! + * _ipu_csi_init + * + * @param channel IDMAC channel + * @param csi csi 0 or csi 1 + * + * @return Returns 0 on success or negative error code on fail + */ +int _ipu_csi_init(ipu_channel_t channel, uint32_t csi) +{ + uint32_t csi_sens_conf, csi_dest; + int retval = 0; + + switch (channel) { + case CSI_MEM0: + case CSI_MEM1: + case CSI_MEM2: + case CSI_MEM3: + csi_dest = CSI_DATA_DEST_IDMAC; + break; + case CSI_PRP_ENC_MEM: + case CSI_PRP_VF_MEM: + csi_dest = CSI_DATA_DEST_IC; + break; + default: + retval = -EINVAL; + goto err; + } + + csi_sens_conf = __raw_readl(CSI_SENS_CONF(csi)); + csi_sens_conf &= ~CSI_SENS_CONF_DATA_DEST_MASK; + __raw_writel(csi_sens_conf | (csi_dest << + CSI_SENS_CONF_DATA_DEST_SHIFT), CSI_SENS_CONF(csi)); +err: + return retval; +} diff --git a/drivers/mxc/ipu3/ipu_common.c b/drivers/mxc/ipu3/ipu_common.c new file mode 100644 index 000000000000..5c5e76762f9e --- /dev/null +++ b/drivers/mxc/ipu3/ipu_common.c @@ -0,0 +1,2589 @@ +/* + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file ipu_common.c + * + * @brief This file contains the IPU driver common API functions. + * + * @ingroup IPU + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ipu_prv.h" +#include "ipu_regs.h" +#include "ipu_param_mem.h" + +struct ipu_irq_node { + irqreturn_t(*handler) (int, void *); /*!< the ISR */ + const char *name; /*!< device associated with the interrupt */ + void *dev_id; /*!< some unique information for the ISR */ + __u32 flags; /*!< not used */ +}; + +/* Globals */ +struct clk *g_ipu_clk; +bool g_ipu_clk_enabled; +struct clk *g_di_clk[2]; +struct clk *g_pixel_clk[2]; +struct clk *g_csi_clk[2]; +unsigned char g_dc_di_assignment[10]; +ipu_channel_t g_ipu_csi_channel[2]; +int g_ipu_irq[2]; +int g_ipu_hw_rev; +bool g_sec_chan_en[24]; +bool g_thrd_chan_en[24]; +uint32_t g_channel_init_mask; +uint32_t g_channel_enable_mask; +DEFINE_SPINLOCK(ipu_lock); +struct device *g_ipu_dev; + +static struct ipu_irq_node ipu_irq_list[IPU_IRQ_COUNT]; +static const char driver_name[] = "mxc_ipu"; + +static int ipu_dc_use_count; +static int ipu_dp_use_count; +static int ipu_dmfc_use_count; +static int ipu_smfc_use_count; +static int ipu_ic_use_count; +static int ipu_rot_use_count; +static int ipu_vdi_use_count; +static int ipu_di_use_count[2]; +static int ipu_csi_use_count[2]; +/* Set to the follow using IC direct channel, default non */ +static ipu_channel_t using_ic_dirct_ch; + +/* for power gating */ +static uint32_t ipu_conf_reg; +static uint32_t ic_conf_reg; +static uint32_t ipu_cha_db_mode_reg[4]; +static uint32_t ipu_cha_cur_buf_reg[4]; +static uint32_t idma_enable_reg[2]; +static uint32_t buf_ready_reg[8]; + +u32 *ipu_cm_reg; +u32 *ipu_idmac_reg; +u32 *ipu_dp_reg; +u32 *ipu_ic_reg; +u32 *ipu_dc_reg; +u32 *ipu_dc_tmpl_reg; +u32 *ipu_dmfc_reg; +u32 *ipu_di_reg[2]; +u32 *ipu_smfc_reg; +u32 *ipu_csi_reg[2]; +u32 *ipu_cpmem_base; +u32 *ipu_tpmem_base; +u32 *ipu_disp_base[2]; +u32 *ipu_vdi_reg; + +/* Static functions */ +static irqreturn_t ipu_irq_handler(int irq, void *desc); + +static inline uint32_t channel_2_dma(ipu_channel_t ch, ipu_buffer_t type) +{ + return ((uint32_t) ch >> (6 * type)) & 0x3F; +}; + +static inline int _ipu_is_ic_chan(uint32_t dma_chan) +{ + return ((dma_chan >= 11) && (dma_chan <= 22) && (dma_chan != 17) && (dma_chan != 18)); +} + +static inline int _ipu_is_ic_graphic_chan(uint32_t dma_chan) +{ + return (dma_chan == 14 || dma_chan == 15); +} + +/* Either DP BG or DP FG can be graphic window */ +static inline int _ipu_is_dp_graphic_chan(uint32_t dma_chan) +{ + return (dma_chan == 23 || dma_chan == 27); +} + +static inline int _ipu_is_irt_chan(uint32_t dma_chan) +{ + return ((dma_chan >= 45) && (dma_chan <= 50)); +} + +static inline int _ipu_is_dmfc_chan(uint32_t dma_chan) +{ + return ((dma_chan >= 23) && (dma_chan <= 29)); +} + +static inline int _ipu_is_smfc_chan(uint32_t dma_chan) +{ + return ((dma_chan >= 0) && (dma_chan <= 3)); +} + +#define idma_is_valid(ch) (ch != NO_DMA) +#define idma_mask(ch) (idma_is_valid(ch) ? (1UL << (ch & 0x1F)) : 0) +#define idma_is_set(reg, dma) (__raw_readl(reg(dma)) & idma_mask(dma)) + +static unsigned long _ipu_pixel_clk_get_rate(struct clk *clk) +{ + u32 div = __raw_readl(DI_BS_CLKGEN0(clk->id)); + if (div == 0) + return 0; + return (clk_get_rate(clk->parent) * 16) / div; +} + +static unsigned long _ipu_pixel_clk_round_rate(struct clk *clk, unsigned long rate) +{ + u32 div, div1; + u32 parent_rate = clk_get_rate(clk->parent) * 16; + /* + * Calculate divider + * Fractional part is 4 bits, + * so simply multiply by 2^4 to get fractional part. + */ + div = parent_rate / rate; + + if (div < 0x10) /* Min DI disp clock divider is 1 */ + div = 0x10; + if (div & ~0xFEF) + div &= 0xFF8; + else { + div1 = div & 0xFE0; + if ((parent_rate / div1 - parent_rate / div) < rate / 4) + div = div1; + else + div &= 0xFF8; + } + return parent_rate / div; +} + +static int _ipu_pixel_clk_set_rate(struct clk *clk, unsigned long rate) +{ + u32 div = (clk_get_rate(clk->parent) * 16) / rate; + + __raw_writel(div, DI_BS_CLKGEN0(clk->id)); + + /* Setup pixel clock timing */ + /* FIXME: needs to be more flexible */ + /* Down time is half of period */ + __raw_writel((div / 16) << 16, DI_BS_CLKGEN1(clk->id)); + + return 0; +} + +static int _ipu_pixel_clk_enable(struct clk *clk) +{ + u32 disp_gen = __raw_readl(IPU_DISP_GEN); + disp_gen |= clk->id ? DI1_COUNTER_RELEASE : DI0_COUNTER_RELEASE; + __raw_writel(disp_gen, IPU_DISP_GEN); + + start_dvfs_per(); + + return 0; +} + +static void _ipu_pixel_clk_disable(struct clk *clk) +{ + u32 disp_gen = __raw_readl(IPU_DISP_GEN); + disp_gen &= clk->id ? ~DI1_COUNTER_RELEASE : ~DI0_COUNTER_RELEASE; + __raw_writel(disp_gen, IPU_DISP_GEN); + + start_dvfs_per(); +} + +static int _ipu_pixel_clk_set_parent(struct clk *clk, struct clk *parent) +{ + u32 di_gen = __raw_readl(DI_GENERAL(clk->id)); + + if (parent == g_ipu_clk) + di_gen &= ~DI_GEN_DI_CLK_EXT; + else if (!IS_ERR(g_di_clk[clk->id]) && parent == g_di_clk[clk->id]) + di_gen |= DI_GEN_DI_CLK_EXT; + else + return -EINVAL; + + __raw_writel(di_gen, DI_GENERAL(clk->id)); + return 0; +} + +static struct clk pixel_clk[] = { + { + .id = 0, + .get_rate = _ipu_pixel_clk_get_rate, + .set_rate = _ipu_pixel_clk_set_rate, + .round_rate = _ipu_pixel_clk_round_rate, + .set_parent = _ipu_pixel_clk_set_parent, + .enable = _ipu_pixel_clk_enable, + .disable = _ipu_pixel_clk_disable, + }, + { + .id = 1, + .get_rate = _ipu_pixel_clk_get_rate, + .set_rate = _ipu_pixel_clk_set_rate, + .round_rate = _ipu_pixel_clk_round_rate, + .set_parent = _ipu_pixel_clk_set_parent, + .enable = _ipu_pixel_clk_enable, + .disable = _ipu_pixel_clk_disable, + }, +}; + +/*! + * This function is called by the driver framework to initialize the IPU + * hardware. + * + * @param dev The device structure for the IPU passed in by the + * driver framework. + * + * @return Returns 0 on success or negative error code on error + */ +static int ipu_probe(struct platform_device *pdev) +{ + struct resource *res; + struct mxc_ipu_config *plat_data = pdev->dev.platform_data; + unsigned long ipu_base; + + spin_lock_init(&ipu_lock); + + g_ipu_hw_rev = plat_data->rev; + + g_ipu_dev = &pdev->dev; + + /* Register IPU interrupts */ + g_ipu_irq[0] = platform_get_irq(pdev, 0); + if (g_ipu_irq[0] < 0) + return -EINVAL; + + if (request_irq(g_ipu_irq[0], ipu_irq_handler, 0, pdev->name, 0) != 0) { + dev_err(g_ipu_dev, "request SYNC interrupt failed\n"); + return -EBUSY; + } + /* Some platforms have 2 IPU interrupts */ + g_ipu_irq[1] = platform_get_irq(pdev, 1); + if (g_ipu_irq[1] >= 0) { + if (request_irq + (g_ipu_irq[1], ipu_irq_handler, 0, pdev->name, 0) != 0) { + dev_err(g_ipu_dev, "request ERR interrupt failed\n"); + return -EBUSY; + } + } + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (IS_ERR(res)) + return -ENODEV; + + ipu_base = res->start; + if (g_ipu_hw_rev == 3) /* IPUv3M */ + ipu_base += IPUV3M_REG_BASE; + else /* IPUv3D, v3E, v3EX */ + ipu_base += IPU_REG_BASE; + + ipu_cm_reg = ioremap(ipu_base + IPU_CM_REG_BASE, PAGE_SIZE); + ipu_ic_reg = ioremap(ipu_base + IPU_IC_REG_BASE, PAGE_SIZE); + ipu_idmac_reg = ioremap(ipu_base + IPU_IDMAC_REG_BASE, PAGE_SIZE); + /* DP Registers are accessed thru the SRM */ + ipu_dp_reg = ioremap(ipu_base + IPU_SRM_REG_BASE, PAGE_SIZE); + ipu_dc_reg = ioremap(ipu_base + IPU_DC_REG_BASE, PAGE_SIZE); + ipu_dmfc_reg = ioremap(ipu_base + IPU_DMFC_REG_BASE, PAGE_SIZE); + ipu_di_reg[0] = ioremap(ipu_base + IPU_DI0_REG_BASE, PAGE_SIZE); + ipu_di_reg[1] = ioremap(ipu_base + IPU_DI1_REG_BASE, PAGE_SIZE); + ipu_smfc_reg = ioremap(ipu_base + IPU_SMFC_REG_BASE, PAGE_SIZE); + ipu_csi_reg[0] = ioremap(ipu_base + IPU_CSI0_REG_BASE, PAGE_SIZE); + ipu_csi_reg[1] = ioremap(ipu_base + IPU_CSI1_REG_BASE, PAGE_SIZE); + ipu_cpmem_base = ioremap(ipu_base + IPU_CPMEM_REG_BASE, PAGE_SIZE); + ipu_tpmem_base = ioremap(ipu_base + IPU_TPM_REG_BASE, SZ_64K); + ipu_dc_tmpl_reg = ioremap(ipu_base + IPU_DC_TMPL_REG_BASE, SZ_128K); + ipu_disp_base[1] = ioremap(ipu_base + IPU_DISP1_BASE, SZ_4K); + ipu_vdi_reg = ioremap(ipu_base + IPU_VDI_REG_BASE, PAGE_SIZE); + + dev_dbg(g_ipu_dev, "IPU VDI Regs = %p\n", ipu_vdi_reg); + dev_dbg(g_ipu_dev, "IPU CM Regs = %p\n", ipu_cm_reg); + dev_dbg(g_ipu_dev, "IPU IC Regs = %p\n", ipu_ic_reg); + dev_dbg(g_ipu_dev, "IPU IDMAC Regs = %p\n", ipu_idmac_reg); + dev_dbg(g_ipu_dev, "IPU DP Regs = %p\n", ipu_dp_reg); + dev_dbg(g_ipu_dev, "IPU DC Regs = %p\n", ipu_dc_reg); + dev_dbg(g_ipu_dev, "IPU DMFC Regs = %p\n", ipu_dmfc_reg); + dev_dbg(g_ipu_dev, "IPU DI0 Regs = %p\n", ipu_di_reg[0]); + dev_dbg(g_ipu_dev, "IPU DI1 Regs = %p\n", ipu_di_reg[1]); + dev_dbg(g_ipu_dev, "IPU SMFC Regs = %p\n", ipu_smfc_reg); + dev_dbg(g_ipu_dev, "IPU CSI0 Regs = %p\n", ipu_csi_reg[0]); + dev_dbg(g_ipu_dev, "IPU CSI1 Regs = %p\n", ipu_csi_reg[1]); + dev_dbg(g_ipu_dev, "IPU CPMem = %p\n", ipu_cpmem_base); + dev_dbg(g_ipu_dev, "IPU TPMem = %p\n", ipu_tpmem_base); + dev_dbg(g_ipu_dev, "IPU DC Template Mem = %p\n", ipu_dc_tmpl_reg); + dev_dbg(g_ipu_dev, "IPU Display Region 1 Mem = %p\n", ipu_disp_base[1]); + + g_pixel_clk[0] = &pixel_clk[0]; + g_pixel_clk[1] = &pixel_clk[1]; + + /* Enable IPU and CSI clocks */ + /* Get IPU clock freq */ + g_ipu_clk = clk_get(&pdev->dev, "ipu_clk"); + dev_dbg(g_ipu_dev, "ipu_clk = %lu\n", clk_get_rate(g_ipu_clk)); + + if (plat_data->reset) + plat_data->reset(); + + clk_set_parent(g_pixel_clk[0], g_ipu_clk); + clk_set_parent(g_pixel_clk[1], g_ipu_clk); + clk_enable(g_ipu_clk); + + g_di_clk[0] = plat_data->di_clk[0]; + g_di_clk[1] = plat_data->di_clk[1]; + + g_csi_clk[0] = plat_data->csi_clk[0]; + g_csi_clk[1] = plat_data->csi_clk[1]; + + __raw_writel(0x807FFFFF, IPU_MEM_RST); + while (__raw_readl(IPU_MEM_RST) & 0x80000000) + ; + + _ipu_init_dc_mappings(); + + /* Enable error interrupts by default */ + __raw_writel(0xFFFFFFFF, IPU_INT_CTRL(5)); + __raw_writel(0xFFFFFFFF, IPU_INT_CTRL(6)); + __raw_writel(0xFFFFFFFF, IPU_INT_CTRL(9)); + __raw_writel(0xFFFFFFFF, IPU_INT_CTRL(10)); + + /* DMFC Init */ + _ipu_dmfc_init(DMFC_NORMAL, 1); + + /* Set sync refresh channels and CSI->mem channel as high priority */ + __raw_writel(0x18800001L, IDMAC_CHA_PRI(0)); + + /* Set MCU_T to divide MCU access window into 2 */ + __raw_writel(0x00400000L | (IPU_MCU_T_DEFAULT << 18), IPU_DISP_GEN); + + clk_disable(g_ipu_clk); + + register_ipu_device(); + + return 0; +} + +int ipu_remove(struct platform_device *pdev) +{ + if (g_ipu_irq[0]) + free_irq(g_ipu_irq[0], 0); + if (g_ipu_irq[1]) + free_irq(g_ipu_irq[1], 0); + + clk_put(g_ipu_clk); + + iounmap(ipu_cm_reg); + iounmap(ipu_ic_reg); + iounmap(ipu_idmac_reg); + iounmap(ipu_dc_reg); + iounmap(ipu_dp_reg); + iounmap(ipu_dmfc_reg); + iounmap(ipu_di_reg[0]); + iounmap(ipu_di_reg[1]); + iounmap(ipu_smfc_reg); + iounmap(ipu_csi_reg[0]); + iounmap(ipu_csi_reg[1]); + iounmap(ipu_cpmem_base); + iounmap(ipu_tpmem_base); + iounmap(ipu_dc_tmpl_reg); + iounmap(ipu_disp_base[1]); + iounmap(ipu_vdi_reg); + + return 0; +} + +void ipu_dump_registers(void) +{ + printk(KERN_DEBUG "IPU_CONF = \t0x%08X\n", __raw_readl(IPU_CONF)); + printk(KERN_DEBUG "IDMAC_CONF = \t0x%08X\n", __raw_readl(IDMAC_CONF)); + printk(KERN_DEBUG "IDMAC_CHA_EN1 = \t0x%08X\n", + __raw_readl(IDMAC_CHA_EN(0))); + printk(KERN_DEBUG "IDMAC_CHA_EN2 = \t0x%08X\n", + __raw_readl(IDMAC_CHA_EN(32))); + printk(KERN_DEBUG "IDMAC_CHA_PRI1 = \t0x%08X\n", + __raw_readl(IDMAC_CHA_PRI(0))); + printk(KERN_DEBUG "IDMAC_CHA_PRI2 = \t0x%08X\n", + __raw_readl(IDMAC_CHA_PRI(32))); + printk(KERN_DEBUG "IDMAC_BAND_EN1 = \t0x%08X\n", + __raw_readl(IDMAC_BAND_EN(0))); + printk(KERN_DEBUG "IDMAC_BAND_EN2 = \t0x%08X\n", + __raw_readl(IDMAC_BAND_EN(32))); + printk(KERN_DEBUG "IPU_CHA_DB_MODE_SEL0 = \t0x%08X\n", + __raw_readl(IPU_CHA_DB_MODE_SEL(0))); + printk(KERN_DEBUG "IPU_CHA_DB_MODE_SEL1 = \t0x%08X\n", + __raw_readl(IPU_CHA_DB_MODE_SEL(32))); + printk(KERN_DEBUG "DMFC_WR_CHAN = \t0x%08X\n", + __raw_readl(DMFC_WR_CHAN)); + printk(KERN_DEBUG "DMFC_WR_CHAN_DEF = \t0x%08X\n", + __raw_readl(DMFC_WR_CHAN_DEF)); + printk(KERN_DEBUG "DMFC_DP_CHAN = \t0x%08X\n", + __raw_readl(DMFC_DP_CHAN)); + printk(KERN_DEBUG "DMFC_DP_CHAN_DEF = \t0x%08X\n", + __raw_readl(DMFC_DP_CHAN_DEF)); + printk(KERN_DEBUG "DMFC_IC_CTRL = \t0x%08X\n", + __raw_readl(DMFC_IC_CTRL)); + printk(KERN_DEBUG "IPU_FS_PROC_FLOW1 = \t0x%08X\n", + __raw_readl(IPU_FS_PROC_FLOW1)); + printk(KERN_DEBUG "IPU_FS_PROC_FLOW2 = \t0x%08X\n", + __raw_readl(IPU_FS_PROC_FLOW2)); + printk(KERN_DEBUG "IPU_FS_PROC_FLOW3 = \t0x%08X\n", + __raw_readl(IPU_FS_PROC_FLOW3)); + printk(KERN_DEBUG "IPU_FS_DISP_FLOW1 = \t0x%08X\n", + __raw_readl(IPU_FS_DISP_FLOW1)); +} + +/*! + * This function is called to initialize a logical IPU channel. + * + * @param channel Input parameter for the logical channel ID to init. + * + * @param params Input parameter containing union of channel + * initialization parameters. + * + * @return Returns 0 on success or negative error code on fail + */ +int32_t ipu_init_channel(ipu_channel_t channel, ipu_channel_params_t *params) +{ + int ret = 0; + uint32_t ipu_conf; + uint32_t reg; + unsigned long lock_flags; + + dev_dbg(g_ipu_dev, "init channel = %d\n", IPU_CHAN_ID(channel)); + + /* re-enable error interrupts every time a channel is initialized */ + __raw_writel(0xFFFFFFFF, IPU_INT_CTRL(5)); + __raw_writel(0xFFFFFFFF, IPU_INT_CTRL(6)); + __raw_writel(0xFFFFFFFF, IPU_INT_CTRL(9)); + __raw_writel(0xFFFFFFFF, IPU_INT_CTRL(10)); + + if (g_ipu_clk_enabled == false) { + stop_dvfs_per(); + g_ipu_clk_enabled = true; + clk_enable(g_ipu_clk); + } + + spin_lock_irqsave(&ipu_lock, lock_flags); + + if (g_channel_init_mask & (1L << IPU_CHAN_ID(channel))) { + dev_err(g_ipu_dev, "Warning: channel already initialized %d\n", + IPU_CHAN_ID(channel)); + } + + ipu_conf = __raw_readl(IPU_CONF); + + switch (channel) { + case CSI_MEM0: + case CSI_MEM1: + case CSI_MEM2: + case CSI_MEM3: + if (params->csi_mem.csi > 1) { + ret = -EINVAL; + goto err; + } + + ipu_smfc_use_count++; + g_ipu_csi_channel[params->csi_mem.csi] = channel; + + /*SMFC setting*/ + if (params->csi_mem.mipi_en) { + ipu_conf |= (1 << (IPU_CONF_CSI0_DATA_SOURCE_OFFSET + + params->csi_mem.csi)); + _ipu_smfc_init(channel, params->csi_mem.mipi_id, + params->csi_mem.csi); + } else { + ipu_conf &= ~(1 << (IPU_CONF_CSI0_DATA_SOURCE_OFFSET + + params->csi_mem.csi)); + _ipu_smfc_init(channel, 0, params->csi_mem.csi); + } + + /*CSI data (include compander) dest*/ + _ipu_csi_init(channel, params->csi_mem.csi); + break; + case CSI_PRP_ENC_MEM: + if (params->csi_prp_enc_mem.csi > 1) { + ret = -EINVAL; + goto err; + } + if (using_ic_dirct_ch == MEM_VDI_PRP_VF_MEM) { + ret = -EINVAL; + goto err; + } + using_ic_dirct_ch = CSI_PRP_ENC_MEM; + + ipu_ic_use_count++; + g_ipu_csi_channel[params->csi_prp_enc_mem.csi] = channel; + + /*Without SMFC, CSI only support parallel data source*/ + ipu_conf &= ~(1 << (IPU_CONF_CSI0_DATA_SOURCE_OFFSET + + params->csi_prp_enc_mem.csi)); + + /*CSI0/1 feed into IC*/ + ipu_conf &= ~IPU_CONF_IC_INPUT; + if (params->csi_prp_enc_mem.csi) + ipu_conf |= IPU_CONF_CSI_SEL; + else + ipu_conf &= ~IPU_CONF_CSI_SEL; + + /*PRP skip buffer in memory, only valid when RWS_EN is true*/ + reg = __raw_readl(IPU_FS_PROC_FLOW1); + __raw_writel(reg & ~FS_ENC_IN_VALID, IPU_FS_PROC_FLOW1); + + /*CSI data (include compander) dest*/ + _ipu_csi_init(channel, params->csi_prp_enc_mem.csi); + _ipu_ic_init_prpenc(params, true); + break; + case CSI_PRP_VF_MEM: + if (params->csi_prp_vf_mem.csi > 1) { + ret = -EINVAL; + goto err; + } + if (using_ic_dirct_ch == MEM_VDI_PRP_VF_MEM) { + ret = -EINVAL; + goto err; + } + using_ic_dirct_ch = CSI_PRP_VF_MEM; + + ipu_ic_use_count++; + g_ipu_csi_channel[params->csi_prp_vf_mem.csi] = channel; + + /*Without SMFC, CSI only support parallel data source*/ + ipu_conf &= ~(1 << (IPU_CONF_CSI0_DATA_SOURCE_OFFSET + + params->csi_prp_vf_mem.csi)); + + /*CSI0/1 feed into IC*/ + ipu_conf &= ~IPU_CONF_IC_INPUT; + if (params->csi_prp_vf_mem.csi) + ipu_conf |= IPU_CONF_CSI_SEL; + else + ipu_conf &= ~IPU_CONF_CSI_SEL; + + /*PRP skip buffer in memory, only valid when RWS_EN is true*/ + reg = __raw_readl(IPU_FS_PROC_FLOW1); + __raw_writel(reg & ~FS_VF_IN_VALID, IPU_FS_PROC_FLOW1); + + /*CSI data (include compander) dest*/ + _ipu_csi_init(channel, params->csi_prp_vf_mem.csi); + _ipu_ic_init_prpvf(params, true); + break; + case MEM_PRP_VF_MEM: + ipu_ic_use_count++; + reg = __raw_readl(IPU_FS_PROC_FLOW1); + __raw_writel(reg | FS_VF_IN_VALID, IPU_FS_PROC_FLOW1); + + if (params->mem_prp_vf_mem.graphics_combine_en) + g_sec_chan_en[IPU_CHAN_ID(channel)] = true; + if (params->mem_prp_vf_mem.alpha_chan_en) + g_thrd_chan_en[IPU_CHAN_ID(channel)] = true; + + _ipu_ic_init_prpvf(params, false); + break; + case MEM_VDI_PRP_VF_MEM: + if ((using_ic_dirct_ch == CSI_PRP_VF_MEM) || + (using_ic_dirct_ch == CSI_PRP_ENC_MEM)) { + ret = -EINVAL; + goto err; + } + using_ic_dirct_ch = MEM_VDI_PRP_VF_MEM; + ipu_ic_use_count++; + ipu_vdi_use_count++; + reg = __raw_readl(IPU_FS_PROC_FLOW1); + reg &= ~FS_VDI_SRC_SEL_MASK; + __raw_writel(reg , IPU_FS_PROC_FLOW1); + + if (params->mem_prp_vf_mem.graphics_combine_en) + g_sec_chan_en[IPU_CHAN_ID(channel)] = true; + _ipu_ic_init_prpvf(params, false); + _ipu_vdi_init(channel, params); + break; + case MEM_VDI_PRP_VF_MEM_P: + _ipu_vdi_init(channel, params); + break; + case MEM_VDI_PRP_VF_MEM_N: + _ipu_vdi_init(channel, params); + break; + case MEM_ROT_VF_MEM: + ipu_ic_use_count++; + ipu_rot_use_count++; + _ipu_ic_init_rotate_vf(params); + break; + case MEM_PRP_ENC_MEM: + ipu_ic_use_count++; + reg = __raw_readl(IPU_FS_PROC_FLOW1); + __raw_writel(reg | FS_ENC_IN_VALID, IPU_FS_PROC_FLOW1); + _ipu_ic_init_prpenc(params, false); + break; + case MEM_ROT_ENC_MEM: + ipu_ic_use_count++; + ipu_rot_use_count++; + _ipu_ic_init_rotate_enc(params); + break; + case MEM_PP_MEM: + if (params->mem_pp_mem.graphics_combine_en) + g_sec_chan_en[IPU_CHAN_ID(channel)] = true; + if (params->mem_pp_mem.alpha_chan_en) + g_thrd_chan_en[IPU_CHAN_ID(channel)] = true; + _ipu_ic_init_pp(params); + ipu_ic_use_count++; + break; + case MEM_ROT_PP_MEM: + _ipu_ic_init_rotate_pp(params); + ipu_ic_use_count++; + ipu_rot_use_count++; + break; + case MEM_DC_SYNC: + if (params->mem_dc_sync.di > 1) { + ret = -EINVAL; + goto err; + } + + g_dc_di_assignment[1] = params->mem_dc_sync.di; + _ipu_dc_init(1, params->mem_dc_sync.di, + params->mem_dc_sync.interlaced, + params->mem_dc_sync.out_pixel_fmt); + ipu_di_use_count[params->mem_dc_sync.di]++; + ipu_dc_use_count++; + ipu_dmfc_use_count++; + break; + case MEM_BG_SYNC: + if (params->mem_dp_bg_sync.di > 1) { + ret = -EINVAL; + goto err; + } + + if (params->mem_dp_bg_sync.alpha_chan_en) + g_thrd_chan_en[IPU_CHAN_ID(channel)] = true; + + g_dc_di_assignment[5] = params->mem_dp_bg_sync.di; + _ipu_dp_init(channel, params->mem_dp_bg_sync.in_pixel_fmt, + params->mem_dp_bg_sync.out_pixel_fmt); + _ipu_dc_init(5, params->mem_dp_bg_sync.di, + params->mem_dp_bg_sync.interlaced, + params->mem_dp_bg_sync.out_pixel_fmt); + ipu_di_use_count[params->mem_dp_bg_sync.di]++; + ipu_dc_use_count++; + ipu_dp_use_count++; + ipu_dmfc_use_count++; + break; + case MEM_FG_SYNC: + _ipu_dp_init(channel, params->mem_dp_fg_sync.in_pixel_fmt, + params->mem_dp_fg_sync.out_pixel_fmt); + + if (params->mem_dp_fg_sync.alpha_chan_en) + g_thrd_chan_en[IPU_CHAN_ID(channel)] = true; + + ipu_dc_use_count++; + ipu_dp_use_count++; + ipu_dmfc_use_count++; + break; + case DIRECT_ASYNC0: + if (params->direct_async.di > 1) { + ret = -EINVAL; + goto err; + } + + g_dc_di_assignment[8] = params->direct_async.di; + _ipu_dc_init(8, params->direct_async.di, false, IPU_PIX_FMT_GENERIC); + ipu_di_use_count[params->direct_async.di]++; + ipu_dc_use_count++; + break; + case DIRECT_ASYNC1: + if (params->direct_async.di > 1) { + ret = -EINVAL; + goto err; + } + + g_dc_di_assignment[9] = params->direct_async.di; + _ipu_dc_init(9, params->direct_async.di, false, IPU_PIX_FMT_GENERIC); + ipu_di_use_count[params->direct_async.di]++; + ipu_dc_use_count++; + break; + default: + dev_err(g_ipu_dev, "Missing channel initialization\n"); + break; + } + + /* Enable IPU sub module */ + g_channel_init_mask |= 1L << IPU_CHAN_ID(channel); + + __raw_writel(ipu_conf, IPU_CONF); + +err: + spin_unlock_irqrestore(&ipu_lock, lock_flags); + return ret; +} +EXPORT_SYMBOL(ipu_init_channel); + +/*! + * This function is called to uninitialize a logical IPU channel. + * + * @param channel Input parameter for the logical channel ID to uninit. + */ +void ipu_uninit_channel(ipu_channel_t channel) +{ + unsigned long lock_flags; + uint32_t reg; + uint32_t in_dma, out_dma = 0; + uint32_t ipu_conf; + + if ((g_channel_init_mask & (1L << IPU_CHAN_ID(channel))) == 0) { + dev_err(g_ipu_dev, "Channel already uninitialized %d\n", + IPU_CHAN_ID(channel)); + return; + } + + /* Make sure channel is disabled */ + /* Get input and output dma channels */ + in_dma = channel_2_dma(channel, IPU_VIDEO_IN_BUFFER); + out_dma = channel_2_dma(channel, IPU_OUTPUT_BUFFER); + + if (idma_is_set(IDMAC_CHA_EN, in_dma) || + idma_is_set(IDMAC_CHA_EN, out_dma)) { + dev_err(g_ipu_dev, + "Channel %d is not disabled, disable first\n", + IPU_CHAN_ID(channel)); + return; + } + + spin_lock_irqsave(&ipu_lock, lock_flags); + + ipu_conf = __raw_readl(IPU_CONF); + + /* Reset the double buffer */ + reg = __raw_readl(IPU_CHA_DB_MODE_SEL(in_dma)); + __raw_writel(reg & ~idma_mask(in_dma), IPU_CHA_DB_MODE_SEL(in_dma)); + reg = __raw_readl(IPU_CHA_DB_MODE_SEL(out_dma)); + __raw_writel(reg & ~idma_mask(out_dma), IPU_CHA_DB_MODE_SEL(out_dma)); + + if (_ipu_is_ic_chan(in_dma) || _ipu_is_dp_graphic_chan(in_dma)) { + g_sec_chan_en[IPU_CHAN_ID(channel)] = false; + g_thrd_chan_en[IPU_CHAN_ID(channel)] = false; + } + + switch (channel) { + case CSI_MEM0: + case CSI_MEM1: + case CSI_MEM2: + case CSI_MEM3: + ipu_smfc_use_count--; + if (g_ipu_csi_channel[0] == channel) { + g_ipu_csi_channel[0] = CHAN_NONE; + } else if (g_ipu_csi_channel[1] == channel) { + g_ipu_csi_channel[1] = CHAN_NONE; + } + break; + case CSI_PRP_ENC_MEM: + ipu_ic_use_count--; + if (using_ic_dirct_ch == CSI_PRP_ENC_MEM) + using_ic_dirct_ch = 0; + _ipu_ic_uninit_prpenc(); + if (g_ipu_csi_channel[0] == channel) { + g_ipu_csi_channel[0] = CHAN_NONE; + } else if (g_ipu_csi_channel[1] == channel) { + g_ipu_csi_channel[1] = CHAN_NONE; + } + break; + case CSI_PRP_VF_MEM: + ipu_ic_use_count--; + if (using_ic_dirct_ch == CSI_PRP_VF_MEM) + using_ic_dirct_ch = 0; + _ipu_ic_uninit_prpvf(); + if (g_ipu_csi_channel[0] == channel) { + g_ipu_csi_channel[0] = CHAN_NONE; + } else if (g_ipu_csi_channel[1] == channel) { + g_ipu_csi_channel[1] = CHAN_NONE; + } + break; + case MEM_PRP_VF_MEM: + ipu_ic_use_count--; + _ipu_ic_uninit_prpvf(); + reg = __raw_readl(IPU_FS_PROC_FLOW1); + __raw_writel(reg & ~FS_VF_IN_VALID, IPU_FS_PROC_FLOW1); + break; + case MEM_VDI_PRP_VF_MEM: + ipu_ic_use_count--; + ipu_vdi_use_count--; + if (using_ic_dirct_ch == MEM_VDI_PRP_VF_MEM) + using_ic_dirct_ch = 0; + _ipu_ic_uninit_prpvf(); + _ipu_vdi_uninit(); + reg = __raw_readl(IPU_FS_PROC_FLOW1); + __raw_writel(reg & ~FS_VF_IN_VALID, IPU_FS_PROC_FLOW1); + break; + case MEM_VDI_PRP_VF_MEM_P: + case MEM_VDI_PRP_VF_MEM_N: + break; + case MEM_ROT_VF_MEM: + ipu_rot_use_count--; + ipu_ic_use_count--; + _ipu_ic_uninit_rotate_vf(); + break; + case MEM_PRP_ENC_MEM: + ipu_ic_use_count--; + _ipu_ic_uninit_prpenc(); + reg = __raw_readl(IPU_FS_PROC_FLOW1); + __raw_writel(reg & ~FS_ENC_IN_VALID, IPU_FS_PROC_FLOW1); + break; + case MEM_ROT_ENC_MEM: + ipu_rot_use_count--; + ipu_ic_use_count--; + _ipu_ic_uninit_rotate_enc(); + break; + case MEM_PP_MEM: + ipu_ic_use_count--; + _ipu_ic_uninit_pp(); + break; + case MEM_ROT_PP_MEM: + ipu_rot_use_count--; + ipu_ic_use_count--; + _ipu_ic_uninit_rotate_pp(); + break; + case MEM_DC_SYNC: + _ipu_dc_uninit(1); + ipu_di_use_count[g_dc_di_assignment[1]]--; + ipu_dc_use_count--; + ipu_dmfc_use_count--; + break; + case MEM_BG_SYNC: + _ipu_dp_uninit(channel); + _ipu_dc_uninit(5); + ipu_di_use_count[g_dc_di_assignment[5]]--; + ipu_dc_use_count--; + ipu_dp_use_count--; + ipu_dmfc_use_count--; + break; + case MEM_FG_SYNC: + _ipu_dp_uninit(channel); + ipu_dc_use_count--; + ipu_dp_use_count--; + ipu_dmfc_use_count--; + break; + case DIRECT_ASYNC0: + _ipu_dc_uninit(8); + ipu_di_use_count[g_dc_di_assignment[8]]--; + ipu_dc_use_count--; + break; + case DIRECT_ASYNC1: + _ipu_dc_uninit(9); + ipu_di_use_count[g_dc_di_assignment[9]]--; + ipu_dc_use_count--; + break; + default: + break; + } + + g_channel_init_mask &= ~(1L << IPU_CHAN_ID(channel)); + + if (ipu_ic_use_count == 0) + ipu_conf &= ~IPU_CONF_IC_EN; + if (ipu_vdi_use_count == 0) { + ipu_conf &= ~IPU_CONF_ISP_EN; + ipu_conf &= ~IPU_CONF_VDI_EN; + ipu_conf &= ~IPU_CONF_IC_INPUT; + } + if (ipu_rot_use_count == 0) + ipu_conf &= ~IPU_CONF_ROT_EN; + if (ipu_dc_use_count == 0) + ipu_conf &= ~IPU_CONF_DC_EN; + if (ipu_dp_use_count == 0) + ipu_conf &= ~IPU_CONF_DP_EN; + if (ipu_dmfc_use_count == 0) + ipu_conf &= ~IPU_CONF_DMFC_EN; + if (ipu_di_use_count[0] == 0) { + ipu_conf &= ~IPU_CONF_DI0_EN; + } + if (ipu_di_use_count[1] == 0) { + ipu_conf &= ~IPU_CONF_DI1_EN; + } + if (ipu_smfc_use_count == 0) + ipu_conf &= ~IPU_CONF_SMFC_EN; + + __raw_writel(ipu_conf, IPU_CONF); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + + if (ipu_conf == 0) { + clk_disable(g_ipu_clk); + g_ipu_clk_enabled = false; + } + + WARN_ON(ipu_ic_use_count < 0); + WARN_ON(ipu_vdi_use_count < 0); + WARN_ON(ipu_rot_use_count < 0); + WARN_ON(ipu_dc_use_count < 0); + WARN_ON(ipu_dp_use_count < 0); + WARN_ON(ipu_dmfc_use_count < 0); + WARN_ON(ipu_smfc_use_count < 0); +} +EXPORT_SYMBOL(ipu_uninit_channel); + +/*! + * This function is called to initialize a buffer for logical IPU channel. + * + * @param channel Input parameter for the logical channel ID. + * + * @param type Input parameter which buffer to initialize. + * + * @param pixel_fmt Input parameter for pixel format of buffer. + * Pixel format is a FOURCC ASCII code. + * + * @param width Input parameter for width of buffer in pixels. + * + * @param height Input parameter for height of buffer in pixels. + * + * @param stride Input parameter for stride length of buffer + * in pixels. + * + * @param rot_mode Input parameter for rotation setting of buffer. + * A rotation setting other than + * IPU_ROTATE_VERT_FLIP + * should only be used for input buffers of + * rotation channels. + * + * @param phyaddr_0 Input parameter buffer 0 physical address. + * + * @param phyaddr_1 Input parameter buffer 1 physical address. + * Setting this to a value other than NULL enables + * double buffering mode. + * + * @param u private u offset for additional cropping, + * zero if not used. + * + * @param v private v offset for additional cropping, + * zero if not used. + * + * @return Returns 0 on success or negative error code on fail + */ +int32_t ipu_init_channel_buffer(ipu_channel_t channel, ipu_buffer_t type, + uint32_t pixel_fmt, + uint16_t width, uint16_t height, + uint32_t stride, + ipu_rotate_mode_t rot_mode, + dma_addr_t phyaddr_0, dma_addr_t phyaddr_1, + uint32_t u, uint32_t v) +{ + unsigned long lock_flags; + uint32_t reg; + uint32_t dma_chan; + uint32_t burst_size; + + dma_chan = channel_2_dma(channel, type); + if (!idma_is_valid(dma_chan)) + return -EINVAL; + + if (stride < width * bytes_per_pixel(pixel_fmt)) + stride = width * bytes_per_pixel(pixel_fmt); + + if (stride % 4) { + dev_err(g_ipu_dev, + "Stride not 32-bit aligned, stride = %d\n", stride); + return -EINVAL; + } + /* IC & IRT channels' width must be multiple of 8 pixels */ + if ((_ipu_is_ic_chan(dma_chan) || _ipu_is_irt_chan(dma_chan)) + && (width % 8)) { + dev_err(g_ipu_dev, "Width must be 8 pixel multiple\n"); + return -EINVAL; + } + + /* Build parameter memory data for DMA channel */ + _ipu_ch_param_init(dma_chan, pixel_fmt, width, height, stride, u, v, 0, + phyaddr_0, phyaddr_1); + + /* Set correlative channel parameter of local alpha channel */ + if ((_ipu_is_ic_graphic_chan(dma_chan) || + _ipu_is_dp_graphic_chan(dma_chan)) && + (g_thrd_chan_en[IPU_CHAN_ID(channel)] == true)) { + _ipu_ch_param_set_alpha_use_separate_channel(dma_chan, true); + _ipu_ch_param_set_alpha_buffer_memory(dma_chan); + _ipu_ch_param_set_alpha_condition_read(dma_chan); + /* fix alpha width as 8 and burst size as 16*/ + _ipu_ch_params_set_alpha_width(dma_chan, 8); + _ipu_ch_param_set_burst_size(dma_chan, 16); + } else if (_ipu_is_ic_graphic_chan(dma_chan) && + ipu_pixel_format_has_alpha(pixel_fmt)) + _ipu_ch_param_set_alpha_use_separate_channel(dma_chan, false); + + if (rot_mode) + _ipu_ch_param_set_rotation(dma_chan, rot_mode); + + /* IC and ROT channels have restriction of 8 or 16 pix burst length */ + if (_ipu_is_ic_chan(dma_chan)) { + if ((width % 16) == 0) + _ipu_ch_param_set_burst_size(dma_chan, 16); + else + _ipu_ch_param_set_burst_size(dma_chan, 8); + } else if (_ipu_is_irt_chan(dma_chan)) { + _ipu_ch_param_set_burst_size(dma_chan, 8); + _ipu_ch_param_set_block_mode(dma_chan); + } else if (_ipu_is_dmfc_chan(dma_chan)) { + spin_lock_irqsave(&ipu_lock, lock_flags); + _ipu_dmfc_set_wait4eot(dma_chan, width); + spin_unlock_irqrestore(&ipu_lock, lock_flags); + } + + if (_ipu_chan_is_interlaced(channel)) { + _ipu_ch_param_set_interlaced_scan(dma_chan); + } + + if (_ipu_is_ic_chan(dma_chan) || _ipu_is_irt_chan(dma_chan)) { + burst_size = _ipu_ch_param_get_burst_size(dma_chan); + _ipu_ic_idma_init(dma_chan, width, height, burst_size, + rot_mode); + } else if (_ipu_is_smfc_chan(dma_chan)) { + burst_size = _ipu_ch_param_get_burst_size(dma_chan); + if ((pixel_fmt == IPU_PIX_FMT_GENERIC) && + ((_ipu_ch_param_get_bpp(dma_chan) == 5) || + (_ipu_ch_param_get_bpp(dma_chan) == 3))) + burst_size = burst_size >> 4; + else + burst_size = burst_size >> 2; + _ipu_smfc_set_burst_size(channel, burst_size-1); + } + + if (idma_is_set(IDMAC_CHA_PRI, dma_chan) && !cpu_is_mx53()) + _ipu_ch_param_set_high_priority(dma_chan); + + _ipu_ch_param_dump(dma_chan); + + spin_lock_irqsave(&ipu_lock, lock_flags); + + reg = __raw_readl(IPU_CHA_DB_MODE_SEL(dma_chan)); + if (phyaddr_1) + reg |= idma_mask(dma_chan); + else + reg &= ~idma_mask(dma_chan); + __raw_writel(reg, IPU_CHA_DB_MODE_SEL(dma_chan)); + + /* Reset to buffer 0 */ + __raw_writel(idma_mask(dma_chan), IPU_CHA_CUR_BUF(dma_chan)); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + + return 0; +} +EXPORT_SYMBOL(ipu_init_channel_buffer); + +/*! + * This function is called to update the physical address of a buffer for + * a logical IPU channel. + * + * @param channel Input parameter for the logical channel ID. + * + * @param type Input parameter which buffer to initialize. + * + * @param bufNum Input parameter for buffer number to update. + * 0 or 1 are the only valid values. + * + * @param phyaddr Input parameter buffer physical address. + * + * @return This function returns 0 on success or negative error code on + * fail. This function will fail if the buffer is set to ready. + */ +int32_t ipu_update_channel_buffer(ipu_channel_t channel, ipu_buffer_t type, + uint32_t bufNum, dma_addr_t phyaddr) +{ + uint32_t reg; + int ret = 0; + unsigned long lock_flags; + uint32_t dma_chan = channel_2_dma(channel, type); + if (dma_chan == IDMA_CHAN_INVALID) + return -EINVAL; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + if (bufNum == 0) + reg = __raw_readl(IPU_CHA_BUF0_RDY(dma_chan)); + else + reg = __raw_readl(IPU_CHA_BUF1_RDY(dma_chan)); + + if ((reg & idma_mask(dma_chan)) == 0) + _ipu_ch_param_set_buffer(dma_chan, bufNum, phyaddr); + else + ret = -EACCES; + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + return ret; +} +EXPORT_SYMBOL(ipu_update_channel_buffer); + + +/*! + * This function is called to initialize a buffer for logical IPU channel. + * + * @param channel Input parameter for the logical channel ID. + * + * @param type Input parameter which buffer to initialize. + * + * @param pixel_fmt Input parameter for pixel format of buffer. + * Pixel format is a FOURCC ASCII code. + * + * @param width Input parameter for width of buffer in pixels. + * + * @param height Input parameter for height of buffer in pixels. + * + * @param stride Input parameter for stride length of buffer + * in pixels. + * + * @param u predefined private u offset for additional cropping, + * zero if not used. + * + * @param v predefined private v offset for additional cropping, + * zero if not used. + * + * @param vertical_offset vertical offset for Y coordinate + * in the existed frame + * + * + * @param horizontal_offset horizontal offset for X coordinate + * in the existed frame + * + * + * @return Returns 0 on success or negative error code on fail + * This function will fail if any buffer is set to ready. + */ + +int32_t ipu_update_channel_offset(ipu_channel_t channel, ipu_buffer_t type, + uint32_t pixel_fmt, + uint16_t width, uint16_t height, + uint32_t stride, + uint32_t u, uint32_t v, + uint32_t vertical_offset, uint32_t horizontal_offset) +{ + int ret = 0; + unsigned long lock_flags; + uint32_t dma_chan = channel_2_dma(channel, type); + + if (dma_chan == IDMA_CHAN_INVALID) + return -EINVAL; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + if ((__raw_readl(IPU_CHA_BUF0_RDY(dma_chan)) & idma_mask(dma_chan)) || + (__raw_readl(IPU_CHA_BUF0_RDY(dma_chan)) & idma_mask(dma_chan))) + ret = -EACCES; + else + _ipu_ch_offset_update(dma_chan, pixel_fmt, width, height, stride, + u, v, 0, vertical_offset, horizontal_offset); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + return ret; +} +EXPORT_SYMBOL(ipu_update_channel_offset); + + +/*! + * This function is called to set a channel's buffer as ready. + * + * @param channel Input parameter for the logical channel ID. + * + * @param type Input parameter which buffer to initialize. + * + * @param bufNum Input parameter for which buffer number set to + * ready state. + * + * @return Returns 0 on success or negative error code on fail + */ +int32_t ipu_select_buffer(ipu_channel_t channel, ipu_buffer_t type, + uint32_t bufNum) +{ + uint32_t dma_chan = channel_2_dma(channel, type); + uint32_t reg; + + if (dma_chan == IDMA_CHAN_INVALID) + return -EINVAL; + + if (bufNum == 0) { + /*Mark buffer 0 as ready. */ + reg = __raw_readl(IPU_CHA_BUF0_RDY(dma_chan)); + __raw_writel(idma_mask(dma_chan) | reg, + IPU_CHA_BUF0_RDY(dma_chan)); + } else { + /*Mark buffer 1 as ready. */ + reg = __raw_readl(IPU_CHA_BUF1_RDY(dma_chan)); + __raw_writel(idma_mask(dma_chan) | reg, + IPU_CHA_BUF1_RDY(dma_chan)); + } + return 0; +} +EXPORT_SYMBOL(ipu_select_buffer); + +/*! + * This function is called to set a channel's buffer as ready. + * + * @param bufNum Input parameter for which buffer number set to + * ready state. + * + * @return Returns 0 on success or negative error code on fail + */ +int32_t ipu_select_multi_vdi_buffer(uint32_t bufNum) +{ + + uint32_t dma_chan = channel_2_dma(MEM_VDI_PRP_VF_MEM, IPU_INPUT_BUFFER); + uint32_t mask_bit = + idma_mask(channel_2_dma(MEM_VDI_PRP_VF_MEM_P, IPU_INPUT_BUFFER))| + idma_mask(dma_chan)| + idma_mask(channel_2_dma(MEM_VDI_PRP_VF_MEM_N, IPU_INPUT_BUFFER)); + uint32_t reg; + + if (bufNum == 0) { + /*Mark buffer 0 as ready. */ + reg = __raw_readl(IPU_CHA_BUF0_RDY(dma_chan)); + __raw_writel(mask_bit | reg, IPU_CHA_BUF0_RDY(dma_chan)); + } else { + /*Mark buffer 1 as ready. */ + reg = __raw_readl(IPU_CHA_BUF1_RDY(dma_chan)); + __raw_writel(mask_bit | reg, IPU_CHA_BUF1_RDY(dma_chan)); + } + return 0; +} +EXPORT_SYMBOL(ipu_select_multi_vdi_buffer); + +#define NA -1 +static int proc_dest_sel[] = { + 0, 1, 1, 3, 5, 5, 4, 7, 8, 9, 10, 11, 12, 14, 15, 16, + 0, 1, 1, 5, 5, 5, 5, 5, 7, 8, 9, 10, 11, 12, 14, 31 }; +static int proc_src_sel[] = { 0, 6, 7, 6, 7, 8, 5, NA, NA, NA, + NA, NA, NA, NA, NA, 1, 2, 3, 4, 7, 8, NA, 8, NA }; +static int disp_src_sel[] = { 0, 6, 7, 8, 3, 4, 5, NA, NA, NA, + NA, NA, NA, NA, NA, 1, NA, 2, NA, 3, 4, 4, 4, 4 }; + + +/*! + * This function links 2 channels together for automatic frame + * synchronization. The output of the source channel is linked to the input of + * the destination channel. + * + * @param src_ch Input parameter for the logical channel ID of + * the source channel. + * + * @param dest_ch Input parameter for the logical channel ID of + * the destination channel. + * + * @return This function returns 0 on success or negative error code on + * fail. + */ +int32_t ipu_link_channels(ipu_channel_t src_ch, ipu_channel_t dest_ch) +{ + int retval = 0; + unsigned long lock_flags; + uint32_t fs_proc_flow1; + uint32_t fs_proc_flow2; + uint32_t fs_proc_flow3; + uint32_t fs_disp_flow1; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + fs_proc_flow1 = __raw_readl(IPU_FS_PROC_FLOW1); + fs_proc_flow2 = __raw_readl(IPU_FS_PROC_FLOW2); + fs_proc_flow3 = __raw_readl(IPU_FS_PROC_FLOW3); + fs_disp_flow1 = __raw_readl(IPU_FS_DISP_FLOW1); + + switch (src_ch) { + case CSI_MEM0: + fs_proc_flow3 &= ~FS_SMFC0_DEST_SEL_MASK; + fs_proc_flow3 |= + proc_dest_sel[IPU_CHAN_ID(dest_ch)] << + FS_SMFC0_DEST_SEL_OFFSET; + break; + case CSI_MEM1: + fs_proc_flow3 &= ~FS_SMFC1_DEST_SEL_MASK; + fs_proc_flow3 |= + proc_dest_sel[IPU_CHAN_ID(dest_ch)] << + FS_SMFC1_DEST_SEL_OFFSET; + break; + case CSI_MEM2: + fs_proc_flow3 &= ~FS_SMFC2_DEST_SEL_MASK; + fs_proc_flow3 |= + proc_dest_sel[IPU_CHAN_ID(dest_ch)] << + FS_SMFC2_DEST_SEL_OFFSET; + break; + case CSI_MEM3: + fs_proc_flow3 &= ~FS_SMFC3_DEST_SEL_MASK; + fs_proc_flow3 |= + proc_dest_sel[IPU_CHAN_ID(dest_ch)] << + FS_SMFC3_DEST_SEL_OFFSET; + break; + case CSI_PRP_ENC_MEM: + fs_proc_flow2 &= ~FS_PRPENC_DEST_SEL_MASK; + fs_proc_flow2 |= + proc_dest_sel[IPU_CHAN_ID(dest_ch)] << + FS_PRPENC_DEST_SEL_OFFSET; + break; + case CSI_PRP_VF_MEM: + fs_proc_flow2 &= ~FS_PRPVF_DEST_SEL_MASK; + fs_proc_flow2 |= + proc_dest_sel[IPU_CHAN_ID(dest_ch)] << + FS_PRPVF_DEST_SEL_OFFSET; + break; + case MEM_PP_MEM: + fs_proc_flow2 &= ~FS_PP_DEST_SEL_MASK; + fs_proc_flow2 |= + proc_dest_sel[IPU_CHAN_ID(dest_ch)] << + FS_PP_DEST_SEL_OFFSET; + break; + case MEM_ROT_PP_MEM: + fs_proc_flow2 &= ~FS_PP_ROT_DEST_SEL_MASK; + fs_proc_flow2 |= + proc_dest_sel[IPU_CHAN_ID(dest_ch)] << + FS_PP_ROT_DEST_SEL_OFFSET; + break; + case MEM_PRP_ENC_MEM: + fs_proc_flow2 &= ~FS_PRPENC_DEST_SEL_MASK; + fs_proc_flow2 |= + proc_dest_sel[IPU_CHAN_ID(dest_ch)] << + FS_PRPENC_DEST_SEL_OFFSET; + break; + case MEM_ROT_ENC_MEM: + fs_proc_flow2 &= ~FS_PRPENC_ROT_DEST_SEL_MASK; + fs_proc_flow2 |= + proc_dest_sel[IPU_CHAN_ID(dest_ch)] << + FS_PRPENC_ROT_DEST_SEL_OFFSET; + break; + case MEM_PRP_VF_MEM: + fs_proc_flow2 &= ~FS_PRPVF_DEST_SEL_MASK; + fs_proc_flow2 |= + proc_dest_sel[IPU_CHAN_ID(dest_ch)] << + FS_PRPVF_DEST_SEL_OFFSET; + break; + case MEM_VDI_PRP_VF_MEM: + fs_proc_flow2 &= ~FS_PRPVF_DEST_SEL_MASK; + fs_proc_flow2 |= + proc_dest_sel[IPU_CHAN_ID(dest_ch)] << + FS_PRPVF_DEST_SEL_OFFSET; + break; + case MEM_ROT_VF_MEM: + fs_proc_flow2 &= ~FS_PRPVF_ROT_DEST_SEL_MASK; + fs_proc_flow2 |= + proc_dest_sel[IPU_CHAN_ID(dest_ch)] << + FS_PRPVF_ROT_DEST_SEL_OFFSET; + break; + default: + retval = -EINVAL; + goto err; + } + + switch (dest_ch) { + case MEM_PP_MEM: + fs_proc_flow1 &= ~FS_PP_SRC_SEL_MASK; + fs_proc_flow1 |= + proc_src_sel[IPU_CHAN_ID(src_ch)] << FS_PP_SRC_SEL_OFFSET; + break; + case MEM_ROT_PP_MEM: + fs_proc_flow1 &= ~FS_PP_ROT_SRC_SEL_MASK; + fs_proc_flow1 |= + proc_src_sel[IPU_CHAN_ID(src_ch)] << + FS_PP_ROT_SRC_SEL_OFFSET; + break; + case MEM_PRP_ENC_MEM: + fs_proc_flow1 &= ~FS_PRP_SRC_SEL_MASK; + fs_proc_flow1 |= + proc_src_sel[IPU_CHAN_ID(src_ch)] << FS_PRP_SRC_SEL_OFFSET; + break; + case MEM_ROT_ENC_MEM: + fs_proc_flow1 &= ~FS_PRPENC_ROT_SRC_SEL_MASK; + fs_proc_flow1 |= + proc_src_sel[IPU_CHAN_ID(src_ch)] << + FS_PRPENC_ROT_SRC_SEL_OFFSET; + break; + case MEM_PRP_VF_MEM: + fs_proc_flow1 &= ~FS_PRP_SRC_SEL_MASK; + fs_proc_flow1 |= + proc_src_sel[IPU_CHAN_ID(src_ch)] << FS_PRP_SRC_SEL_OFFSET; + break; + case MEM_VDI_PRP_VF_MEM: + fs_proc_flow1 &= ~FS_PRP_SRC_SEL_MASK; + fs_proc_flow1 |= + proc_src_sel[IPU_CHAN_ID(src_ch)] << FS_PRP_SRC_SEL_OFFSET; + break; + case MEM_ROT_VF_MEM: + fs_proc_flow1 &= ~FS_PRPVF_ROT_SRC_SEL_MASK; + fs_proc_flow1 |= + proc_src_sel[IPU_CHAN_ID(src_ch)] << + FS_PRPVF_ROT_SRC_SEL_OFFSET; + break; + case MEM_DC_SYNC: + fs_disp_flow1 &= ~FS_DC1_SRC_SEL_MASK; + fs_disp_flow1 |= + disp_src_sel[IPU_CHAN_ID(src_ch)] << FS_DC1_SRC_SEL_OFFSET; + break; + case MEM_BG_SYNC: + fs_disp_flow1 &= ~FS_DP_SYNC0_SRC_SEL_MASK; + fs_disp_flow1 |= + disp_src_sel[IPU_CHAN_ID(src_ch)] << + FS_DP_SYNC0_SRC_SEL_OFFSET; + break; + case MEM_FG_SYNC: + fs_disp_flow1 &= ~FS_DP_SYNC1_SRC_SEL_MASK; + fs_disp_flow1 |= + disp_src_sel[IPU_CHAN_ID(src_ch)] << + FS_DP_SYNC1_SRC_SEL_OFFSET; + break; + case MEM_DC_ASYNC: + fs_disp_flow1 &= ~FS_DC2_SRC_SEL_MASK; + fs_disp_flow1 |= + disp_src_sel[IPU_CHAN_ID(src_ch)] << FS_DC2_SRC_SEL_OFFSET; + break; + case MEM_BG_ASYNC0: + fs_disp_flow1 &= ~FS_DP_ASYNC0_SRC_SEL_MASK; + fs_disp_flow1 |= + disp_src_sel[IPU_CHAN_ID(src_ch)] << + FS_DP_ASYNC0_SRC_SEL_OFFSET; + break; + case MEM_FG_ASYNC0: + fs_disp_flow1 &= ~FS_DP_ASYNC1_SRC_SEL_MASK; + fs_disp_flow1 |= + disp_src_sel[IPU_CHAN_ID(src_ch)] << + FS_DP_ASYNC1_SRC_SEL_OFFSET; + break; + default: + retval = -EINVAL; + goto err; + } + + __raw_writel(fs_proc_flow1, IPU_FS_PROC_FLOW1); + __raw_writel(fs_proc_flow2, IPU_FS_PROC_FLOW2); + __raw_writel(fs_proc_flow3, IPU_FS_PROC_FLOW3); + __raw_writel(fs_disp_flow1, IPU_FS_DISP_FLOW1); + +err: + spin_unlock_irqrestore(&ipu_lock, lock_flags); + return retval; +} +EXPORT_SYMBOL(ipu_link_channels); + +/*! + * This function unlinks 2 channels and disables automatic frame + * synchronization. + * + * @param src_ch Input parameter for the logical channel ID of + * the source channel. + * + * @param dest_ch Input parameter for the logical channel ID of + * the destination channel. + * + * @return This function returns 0 on success or negative error code on + * fail. + */ +int32_t ipu_unlink_channels(ipu_channel_t src_ch, ipu_channel_t dest_ch) +{ + int retval = 0; + unsigned long lock_flags; + uint32_t fs_proc_flow1; + uint32_t fs_proc_flow2; + uint32_t fs_proc_flow3; + uint32_t fs_disp_flow1; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + fs_proc_flow1 = __raw_readl(IPU_FS_PROC_FLOW1); + fs_proc_flow2 = __raw_readl(IPU_FS_PROC_FLOW2); + fs_proc_flow3 = __raw_readl(IPU_FS_PROC_FLOW3); + fs_disp_flow1 = __raw_readl(IPU_FS_DISP_FLOW1); + + switch (src_ch) { + case CSI_MEM0: + fs_proc_flow3 &= ~FS_SMFC0_DEST_SEL_MASK; + break; + case CSI_MEM1: + fs_proc_flow3 &= ~FS_SMFC1_DEST_SEL_MASK; + break; + case CSI_MEM2: + fs_proc_flow3 &= ~FS_SMFC2_DEST_SEL_MASK; + break; + case CSI_MEM3: + fs_proc_flow3 &= ~FS_SMFC3_DEST_SEL_MASK; + break; + case CSI_PRP_ENC_MEM: + fs_proc_flow2 &= ~FS_PRPENC_DEST_SEL_MASK; + break; + case CSI_PRP_VF_MEM: + fs_proc_flow2 &= ~FS_PRPVF_DEST_SEL_MASK; + break; + case MEM_PP_MEM: + fs_proc_flow2 &= ~FS_PP_DEST_SEL_MASK; + break; + case MEM_ROT_PP_MEM: + fs_proc_flow2 &= ~FS_PP_ROT_DEST_SEL_MASK; + break; + case MEM_PRP_ENC_MEM: + fs_proc_flow2 &= ~FS_PRPENC_DEST_SEL_MASK; + break; + case MEM_ROT_ENC_MEM: + fs_proc_flow2 &= ~FS_PRPENC_ROT_DEST_SEL_MASK; + break; + case MEM_PRP_VF_MEM: + fs_proc_flow2 &= ~FS_PRPVF_DEST_SEL_MASK; + break; + case MEM_VDI_PRP_VF_MEM: + fs_proc_flow2 &= ~FS_PRPVF_DEST_SEL_MASK; + break; + case MEM_ROT_VF_MEM: + fs_proc_flow2 &= ~FS_PRPVF_ROT_DEST_SEL_MASK; + break; + default: + retval = -EINVAL; + goto err; + } + + switch (dest_ch) { + case MEM_PP_MEM: + fs_proc_flow1 &= ~FS_PP_SRC_SEL_MASK; + break; + case MEM_ROT_PP_MEM: + fs_proc_flow1 &= ~FS_PP_ROT_SRC_SEL_MASK; + break; + case MEM_PRP_ENC_MEM: + fs_proc_flow1 &= ~FS_PRP_SRC_SEL_MASK; + break; + case MEM_ROT_ENC_MEM: + fs_proc_flow1 &= ~FS_PRPENC_ROT_SRC_SEL_MASK; + break; + case MEM_PRP_VF_MEM: + fs_proc_flow1 &= ~FS_PRP_SRC_SEL_MASK; + break; + case MEM_VDI_PRP_VF_MEM: + fs_proc_flow1 &= ~FS_PRP_SRC_SEL_MASK; + break; + case MEM_ROT_VF_MEM: + fs_proc_flow1 &= ~FS_PRPVF_ROT_SRC_SEL_MASK; + break; + case MEM_DC_SYNC: + fs_disp_flow1 &= ~FS_DC1_SRC_SEL_MASK; + break; + case MEM_BG_SYNC: + fs_disp_flow1 &= ~FS_DP_SYNC0_SRC_SEL_MASK; + break; + case MEM_FG_SYNC: + fs_disp_flow1 &= ~FS_DP_SYNC1_SRC_SEL_MASK; + break; + case MEM_DC_ASYNC: + fs_disp_flow1 &= ~FS_DC2_SRC_SEL_MASK; + break; + case MEM_BG_ASYNC0: + fs_disp_flow1 &= ~FS_DP_ASYNC0_SRC_SEL_MASK; + break; + case MEM_FG_ASYNC0: + fs_disp_flow1 &= ~FS_DP_ASYNC1_SRC_SEL_MASK; + break; + default: + retval = -EINVAL; + goto err; + } + + __raw_writel(fs_proc_flow1, IPU_FS_PROC_FLOW1); + __raw_writel(fs_proc_flow2, IPU_FS_PROC_FLOW2); + __raw_writel(fs_proc_flow3, IPU_FS_PROC_FLOW3); + __raw_writel(fs_disp_flow1, IPU_FS_DISP_FLOW1); + +err: + spin_unlock_irqrestore(&ipu_lock, lock_flags); + return retval; +} +EXPORT_SYMBOL(ipu_unlink_channels); + +/*! + * This function check whether a logical channel was enabled. + * + * @param channel Input parameter for the logical channel ID. + * + * @return This function returns 1 while request channel is enabled or + * 0 for not enabled. + */ +int32_t ipu_is_channel_busy(ipu_channel_t channel) +{ + uint32_t reg; + uint32_t in_dma; + uint32_t out_dma; + + out_dma = channel_2_dma(channel, IPU_OUTPUT_BUFFER); + in_dma = channel_2_dma(channel, IPU_VIDEO_IN_BUFFER); + + reg = __raw_readl(IDMAC_CHA_EN(in_dma)); + if (reg & idma_mask(in_dma)) + return 1; + reg = __raw_readl(IDMAC_CHA_EN(out_dma)); + if (reg & idma_mask(out_dma)) + return 1; + return 0; +} +EXPORT_SYMBOL(ipu_is_channel_busy); + +/*! + * This function enables a logical channel. + * + * @param channel Input parameter for the logical channel ID. + * + * @return This function returns 0 on success or negative error code on + * fail. + */ +int32_t ipu_enable_channel(ipu_channel_t channel) +{ + uint32_t reg; + unsigned long lock_flags; + uint32_t ipu_conf; + uint32_t in_dma; + uint32_t out_dma; + uint32_t sec_dma; + uint32_t thrd_dma; + + if (g_channel_enable_mask & (1L << IPU_CHAN_ID(channel))) { + dev_err(g_ipu_dev, "Warning: channel already enabled %d\n", + IPU_CHAN_ID(channel)); + } + + /* Get input and output dma channels */ + out_dma = channel_2_dma(channel, IPU_OUTPUT_BUFFER); + in_dma = channel_2_dma(channel, IPU_VIDEO_IN_BUFFER); + + spin_lock_irqsave(&ipu_lock, lock_flags); + + ipu_conf = __raw_readl(IPU_CONF); + if (ipu_di_use_count[0] > 0) { + ipu_conf |= IPU_CONF_DI0_EN; + } + if (ipu_di_use_count[1] > 0) { + ipu_conf |= IPU_CONF_DI1_EN; + } + if (ipu_dp_use_count > 0) + ipu_conf |= IPU_CONF_DP_EN; + if (ipu_dc_use_count > 0) + ipu_conf |= IPU_CONF_DC_EN; + if (ipu_dmfc_use_count > 0) + ipu_conf |= IPU_CONF_DMFC_EN; + if (ipu_ic_use_count > 0) + ipu_conf |= IPU_CONF_IC_EN; + if (ipu_vdi_use_count > 0) { + ipu_conf |= IPU_CONF_ISP_EN; + ipu_conf |= IPU_CONF_VDI_EN; + ipu_conf |= IPU_CONF_IC_INPUT; + } + if (ipu_rot_use_count > 0) + ipu_conf |= IPU_CONF_ROT_EN; + if (ipu_smfc_use_count > 0) + ipu_conf |= IPU_CONF_SMFC_EN; + __raw_writel(ipu_conf, IPU_CONF); + + if (idma_is_valid(in_dma)) { + reg = __raw_readl(IDMAC_CHA_EN(in_dma)); + __raw_writel(reg | idma_mask(in_dma), IDMAC_CHA_EN(in_dma)); + } + if (idma_is_valid(out_dma)) { + reg = __raw_readl(IDMAC_CHA_EN(out_dma)); + __raw_writel(reg | idma_mask(out_dma), IDMAC_CHA_EN(out_dma)); + } + + if ((g_sec_chan_en[IPU_CHAN_ID(channel)]) && + ((channel == MEM_PP_MEM) || (channel == MEM_PRP_VF_MEM) || + (channel == MEM_VDI_PRP_VF_MEM))) { + sec_dma = channel_2_dma(channel, IPU_GRAPH_IN_BUFFER); + reg = __raw_readl(IDMAC_CHA_EN(sec_dma)); + __raw_writel(reg | idma_mask(sec_dma), IDMAC_CHA_EN(sec_dma)); + } + if ((g_thrd_chan_en[IPU_CHAN_ID(channel)]) && + ((channel == MEM_PP_MEM) || (channel == MEM_PRP_VF_MEM))) { + thrd_dma = channel_2_dma(channel, IPU_ALPHA_IN_BUFFER); + reg = __raw_readl(IDMAC_CHA_EN(thrd_dma)); + __raw_writel(reg | idma_mask(thrd_dma), IDMAC_CHA_EN(thrd_dma)); + + sec_dma = channel_2_dma(channel, IPU_GRAPH_IN_BUFFER); + reg = __raw_readl(IDMAC_SEP_ALPHA); + __raw_writel(reg | idma_mask(sec_dma), IDMAC_SEP_ALPHA); + } else if ((g_thrd_chan_en[IPU_CHAN_ID(channel)]) && + ((channel == MEM_BG_SYNC) || (channel == MEM_FG_SYNC))) { + thrd_dma = channel_2_dma(channel, IPU_ALPHA_IN_BUFFER); + reg = __raw_readl(IDMAC_CHA_EN(thrd_dma)); + __raw_writel(reg | idma_mask(thrd_dma), IDMAC_CHA_EN(thrd_dma)); + reg = __raw_readl(IDMAC_SEP_ALPHA); + __raw_writel(reg | idma_mask(in_dma), IDMAC_SEP_ALPHA); + } + + if ((channel == MEM_DC_SYNC) || (channel == MEM_BG_SYNC) || + (channel == MEM_FG_SYNC)) { + reg = __raw_readl(IDMAC_WM_EN(in_dma)); + __raw_writel(reg | idma_mask(in_dma), IDMAC_WM_EN(in_dma)); + + _ipu_dp_dc_enable(channel); + } + + if (_ipu_is_ic_chan(in_dma) || _ipu_is_ic_chan(out_dma) || + _ipu_is_irt_chan(in_dma) || _ipu_is_irt_chan(out_dma)) + _ipu_ic_enable_task(channel); + + g_channel_enable_mask |= 1L << IPU_CHAN_ID(channel); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + + return 0; +} +EXPORT_SYMBOL(ipu_enable_channel); + +/*! + * This function check buffer ready for a logical channel. + * + * @param channel Input parameter for the logical channel ID. + * + * @param type Input parameter which buffer to clear. + * + * @param bufNum Input parameter for which buffer number clear + * ready state. + * + */ +int32_t ipu_check_buffer_busy(ipu_channel_t channel, ipu_buffer_t type, + uint32_t bufNum) +{ + uint32_t dma_chan = channel_2_dma(channel, type); + uint32_t reg; + + if (dma_chan == IDMA_CHAN_INVALID) + return -EINVAL; + + if (bufNum == 0) + reg = __raw_readl(IPU_CHA_BUF0_RDY(dma_chan)); + else + reg = __raw_readl(IPU_CHA_BUF1_RDY(dma_chan)); + + if (reg & idma_mask(dma_chan)) + return 1; + else + return 0; +} +EXPORT_SYMBOL(ipu_check_buffer_busy); + +/*! + * This function clear buffer ready for a logical channel. + * + * @param channel Input parameter for the logical channel ID. + * + * @param type Input parameter which buffer to clear. + * + * @param bufNum Input parameter for which buffer number clear + * ready state. + * + */ +void ipu_clear_buffer_ready(ipu_channel_t channel, ipu_buffer_t type, + uint32_t bufNum) +{ + unsigned long lock_flags; + uint32_t dma_ch = channel_2_dma(channel, type); + + if (!idma_is_valid(dma_ch)) + return; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + __raw_writel(0xF0000000, IPU_GPR); /* write one to clear */ + if (bufNum == 0) { + if (idma_is_set(IPU_CHA_BUF0_RDY, dma_ch)) { + __raw_writel(idma_mask(dma_ch), + IPU_CHA_BUF0_RDY(dma_ch)); + } + } else { + if (idma_is_set(IPU_CHA_BUF1_RDY, dma_ch)) { + __raw_writel(idma_mask(dma_ch), + IPU_CHA_BUF1_RDY(dma_ch)); + } + } + __raw_writel(0x0, IPU_GPR); /* write one to set */ + spin_unlock_irqrestore(&ipu_lock, lock_flags); +} +EXPORT_SYMBOL(ipu_clear_buffer_ready); + +static irqreturn_t disable_chan_irq_handler(int irq, void *dev_id) +{ + struct completion *comp = dev_id; + + complete(comp); + return IRQ_HANDLED; +} + +/*! + * This function disables a logical channel. + * + * @param channel Input parameter for the logical channel ID. + * + * @param wait_for_stop Flag to set whether to wait for channel end + * of frame or return immediately. + * + * @return This function returns 0 on success or negative error code on + * fail. + */ +int32_t ipu_disable_channel(ipu_channel_t channel, bool wait_for_stop) +{ + uint32_t reg; + unsigned long lock_flags; + uint32_t in_dma; + uint32_t out_dma; + uint32_t sec_dma = NO_DMA; + uint32_t thrd_dma = NO_DMA; + + if ((g_channel_enable_mask & (1L << IPU_CHAN_ID(channel))) == 0) { + dev_err(g_ipu_dev, "Channel already disabled %d\n", + IPU_CHAN_ID(channel)); + return 0; + } + + /* Get input and output dma channels */ + out_dma = channel_2_dma(channel, IPU_OUTPUT_BUFFER); + in_dma = channel_2_dma(channel, IPU_VIDEO_IN_BUFFER); + + if ((idma_is_valid(in_dma) && + !idma_is_set(IDMAC_CHA_EN, in_dma)) + && (idma_is_valid(out_dma) && + !idma_is_set(IDMAC_CHA_EN, out_dma))) + return -EINVAL; + + if (g_sec_chan_en[IPU_CHAN_ID(channel)]) + sec_dma = channel_2_dma(channel, IPU_GRAPH_IN_BUFFER); + if (g_thrd_chan_en[IPU_CHAN_ID(channel)]) { + sec_dma = channel_2_dma(channel, IPU_GRAPH_IN_BUFFER); + thrd_dma = channel_2_dma(channel, IPU_ALPHA_IN_BUFFER); + } + + if ((channel == MEM_BG_SYNC) || (channel == MEM_FG_SYNC) || + (channel == MEM_DC_SYNC)) { + int timeout = 50; + int irq; + + _ipu_dp_dc_disable(channel, false); + + /* + * wait for display channel EOF then disable IDMAC, + * it avoid NFB4EOF error. + */ + if (channel == MEM_BG_SYNC) + irq = IPU_IRQ_BG_SYNC_EOF; + if (channel == MEM_FG_SYNC) + irq = IPU_IRQ_FG_SYNC_EOF; + else + irq = IPU_IRQ_DC_SYNC_EOF; + __raw_writel(IPUIRQ_2_MASK(irq), + IPUIRQ_2_STATREG(irq)); + while ((__raw_readl(IPUIRQ_2_STATREG(irq)) & + IPUIRQ_2_MASK(irq)) == 0) { + msleep(10); + timeout -= 10; + if (timeout <= 0) + break; + } + } else if (wait_for_stop) { + while (idma_is_set(IDMAC_CHA_BUSY, in_dma) || + idma_is_set(IDMAC_CHA_BUSY, out_dma) || + (g_sec_chan_en[IPU_CHAN_ID(channel)] && + idma_is_set(IDMAC_CHA_BUSY, sec_dma)) || + (g_thrd_chan_en[IPU_CHAN_ID(channel)] && + idma_is_set(IDMAC_CHA_BUSY, thrd_dma))) { + uint32_t ret, irq = 0xffffffff; + DECLARE_COMPLETION_ONSTACK(disable_comp); + + if (idma_is_set(IDMAC_CHA_BUSY, out_dma)) + irq = out_dma; + if (g_sec_chan_en[IPU_CHAN_ID(channel)] && + idma_is_set(IDMAC_CHA_BUSY, sec_dma)) + irq = sec_dma; + if (g_thrd_chan_en[IPU_CHAN_ID(channel)] && + idma_is_set(IDMAC_CHA_BUSY, thrd_dma)) + irq = thrd_dma; + if (idma_is_set(IDMAC_CHA_BUSY, in_dma)) + irq = in_dma; + + if (irq == 0xffffffff) { + dev_err(g_ipu_dev, "warning: no channel busy, break\n"); + break; + } + ret = ipu_request_irq(irq, disable_chan_irq_handler, 0, NULL, &disable_comp); + if (ret < 0) { + dev_err(g_ipu_dev, "irq %d in use\n", irq); + break; + } else { + ret = wait_for_completion_timeout(&disable_comp, msecs_to_jiffies(200)); + ipu_free_irq(irq, &disable_comp); + if (ret == 0) { + ipu_dump_registers(); + dev_err(g_ipu_dev, "warning: disable ipu dma channel %d during its busy state\n", irq); + break; + } + } + } + } + + spin_lock_irqsave(&ipu_lock, lock_flags); + + if ((channel == MEM_BG_SYNC) || (channel == MEM_FG_SYNC) || + (channel == MEM_DC_SYNC)) { + reg = __raw_readl(IDMAC_WM_EN(in_dma)); + __raw_writel(reg & ~idma_mask(in_dma), IDMAC_WM_EN(in_dma)); + } + + /* Disable IC task */ + if (_ipu_is_ic_chan(in_dma) || _ipu_is_ic_chan(out_dma) || + _ipu_is_irt_chan(in_dma) || _ipu_is_irt_chan(out_dma)) + _ipu_ic_disable_task(channel); + + /* Disable DMA channel(s) */ + if (idma_is_valid(in_dma)) { + reg = __raw_readl(IDMAC_CHA_EN(in_dma)); + __raw_writel(reg & ~idma_mask(in_dma), IDMAC_CHA_EN(in_dma)); + __raw_writel(idma_mask(in_dma), IPU_CHA_CUR_BUF(in_dma)); + } + if (idma_is_valid(out_dma)) { + reg = __raw_readl(IDMAC_CHA_EN(out_dma)); + __raw_writel(reg & ~idma_mask(out_dma), IDMAC_CHA_EN(out_dma)); + __raw_writel(idma_mask(out_dma), IPU_CHA_CUR_BUF(out_dma)); + } + if (g_sec_chan_en[IPU_CHAN_ID(channel)] && idma_is_valid(sec_dma)) { + reg = __raw_readl(IDMAC_CHA_EN(sec_dma)); + __raw_writel(reg & ~idma_mask(sec_dma), IDMAC_CHA_EN(sec_dma)); + __raw_writel(idma_mask(sec_dma), IPU_CHA_CUR_BUF(sec_dma)); + } + if (g_thrd_chan_en[IPU_CHAN_ID(channel)] && idma_is_valid(thrd_dma)) { + reg = __raw_readl(IDMAC_CHA_EN(thrd_dma)); + __raw_writel(reg & ~idma_mask(thrd_dma), IDMAC_CHA_EN(thrd_dma)); + if (channel == MEM_BG_SYNC || channel == MEM_FG_SYNC) { + reg = __raw_readl(IDMAC_SEP_ALPHA); + __raw_writel(reg & ~idma_mask(in_dma), IDMAC_SEP_ALPHA); + } else { + reg = __raw_readl(IDMAC_SEP_ALPHA); + __raw_writel(reg & ~idma_mask(sec_dma), IDMAC_SEP_ALPHA); + } + __raw_writel(idma_mask(thrd_dma), IPU_CHA_CUR_BUF(thrd_dma)); + } + + g_channel_enable_mask &= ~(1L << IPU_CHAN_ID(channel)); + + /* Set channel buffers NOT to be ready */ + if (idma_is_valid(in_dma)) { + ipu_clear_buffer_ready(channel, IPU_VIDEO_IN_BUFFER, 0); + ipu_clear_buffer_ready(channel, IPU_VIDEO_IN_BUFFER, 1); + } + if (idma_is_valid(out_dma)) { + ipu_clear_buffer_ready(channel, IPU_OUTPUT_BUFFER, 0); + ipu_clear_buffer_ready(channel, IPU_OUTPUT_BUFFER, 1); + } + if (g_sec_chan_en[IPU_CHAN_ID(channel)] && idma_is_valid(sec_dma)) { + ipu_clear_buffer_ready(channel, IPU_GRAPH_IN_BUFFER, 0); + ipu_clear_buffer_ready(channel, IPU_GRAPH_IN_BUFFER, 1); + } + if (g_thrd_chan_en[IPU_CHAN_ID(channel)] && idma_is_valid(thrd_dma)) { + ipu_clear_buffer_ready(channel, IPU_ALPHA_IN_BUFFER, 0); + ipu_clear_buffer_ready(channel, IPU_ALPHA_IN_BUFFER, 1); + } + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + + return 0; +} +EXPORT_SYMBOL(ipu_disable_channel); + +/*! + * This function enables CSI. + * + * @param csi csi num 0 or 1 + * + * @return This function returns 0 on success or negative error code on + * fail. + */ +int32_t ipu_enable_csi(uint32_t csi) +{ + uint32_t reg; + unsigned long lock_flags; + + if (csi > 1) { + dev_err(g_ipu_dev, "Wrong csi num_%d\n", csi); + return -EINVAL; + } + + spin_lock_irqsave(&ipu_lock, lock_flags); + ipu_csi_use_count[csi]++; + + if (ipu_csi_use_count[csi] == 1) { + reg = __raw_readl(IPU_CONF); + if (csi == 0) + __raw_writel(reg | IPU_CONF_CSI0_EN, IPU_CONF); + else + __raw_writel(reg | IPU_CONF_CSI1_EN, IPU_CONF); + } + spin_unlock_irqrestore(&ipu_lock, lock_flags); + return 0; +} +EXPORT_SYMBOL(ipu_enable_csi); + +/*! + * This function disables CSI. + * + * @param csi csi num 0 or 1 + * + * @return This function returns 0 on success or negative error code on + * fail. + */ +int32_t ipu_disable_csi(uint32_t csi) +{ + uint32_t reg; + unsigned long lock_flags; + + if (csi > 1) { + dev_err(g_ipu_dev, "Wrong csi num_%d\n", csi); + return -EINVAL; + } + + spin_lock_irqsave(&ipu_lock, lock_flags); + ipu_csi_use_count[csi]--; + + if (ipu_csi_use_count[csi] == 0) { + reg = __raw_readl(IPU_CONF); + if (csi == 0) + __raw_writel(reg & ~IPU_CONF_CSI0_EN, IPU_CONF); + else + __raw_writel(reg & ~IPU_CONF_CSI1_EN, IPU_CONF); + } + spin_unlock_irqrestore(&ipu_lock, lock_flags); + return 0; +} +EXPORT_SYMBOL(ipu_disable_csi); + +static irqreturn_t ipu_irq_handler(int irq, void *desc) +{ + int i; + uint32_t line; + irqreturn_t result = IRQ_NONE; + uint32_t int_stat; + const int err_reg[] = { 5, 6, 9, 10, 0 }; + const int int_reg[] = { 1, 2, 3, 4, 11, 12, 13, 14, 15, 0 }; + + for (i = 0;; i++) { + if (err_reg[i] == 0) + break; + int_stat = __raw_readl(IPU_INT_STAT(err_reg[i])); + int_stat &= __raw_readl(IPU_INT_CTRL(err_reg[i])); + if (int_stat) { + __raw_writel(int_stat, IPU_INT_STAT(err_reg[i])); + dev_err(g_ipu_dev, + "IPU Error - IPU_INT_STAT_%d = 0x%08X\n", + err_reg[i], int_stat); + /* Disable interrupts so we only get error once */ + int_stat = + __raw_readl(IPU_INT_CTRL(err_reg[i])) & ~int_stat; + __raw_writel(int_stat, IPU_INT_CTRL(err_reg[i])); + } + } + + for (i = 0;; i++) { + if (int_reg[i] == 0) + break; + int_stat = __raw_readl(IPU_INT_STAT(int_reg[i])); + int_stat &= __raw_readl(IPU_INT_CTRL(int_reg[i])); + __raw_writel(int_stat, IPU_INT_STAT(int_reg[i])); + while ((line = ffs(int_stat)) != 0) { + line--; + int_stat &= ~(1UL << line); + line += (int_reg[i] - 1) * 32; + result |= + ipu_irq_list[line].handler(line, + ipu_irq_list[line]. + dev_id); + } + } + + return result; +} + +/*! + * This function enables the interrupt for the specified interrupt line. + * The interrupt lines are defined in \b ipu_irq_line enum. + * + * @param irq Interrupt line to enable interrupt for. + * + */ +void ipu_enable_irq(uint32_t irq) +{ + uint32_t reg; + unsigned long lock_flags; + + if (!g_ipu_clk_enabled) + clk_enable(g_ipu_clk); + + spin_lock_irqsave(&ipu_lock, lock_flags); + + reg = __raw_readl(IPUIRQ_2_CTRLREG(irq)); + reg |= IPUIRQ_2_MASK(irq); + __raw_writel(reg, IPUIRQ_2_CTRLREG(irq)); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + if (!g_ipu_clk_enabled) + clk_disable(g_ipu_clk); +} +EXPORT_SYMBOL(ipu_enable_irq); + +/*! + * This function disables the interrupt for the specified interrupt line. + * The interrupt lines are defined in \b ipu_irq_line enum. + * + * @param irq Interrupt line to disable interrupt for. + * + */ +void ipu_disable_irq(uint32_t irq) +{ + uint32_t reg; + unsigned long lock_flags; + + if (!g_ipu_clk_enabled) + clk_enable(g_ipu_clk); + spin_lock_irqsave(&ipu_lock, lock_flags); + + reg = __raw_readl(IPUIRQ_2_CTRLREG(irq)); + reg &= ~IPUIRQ_2_MASK(irq); + __raw_writel(reg, IPUIRQ_2_CTRLREG(irq)); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + if (!g_ipu_clk_enabled) + clk_disable(g_ipu_clk); +} +EXPORT_SYMBOL(ipu_disable_irq); + +/*! + * This function clears the interrupt for the specified interrupt line. + * The interrupt lines are defined in \b ipu_irq_line enum. + * + * @param irq Interrupt line to clear interrupt for. + * + */ +void ipu_clear_irq(uint32_t irq) +{ + if (!g_ipu_clk_enabled) + clk_enable(g_ipu_clk); + + __raw_writel(IPUIRQ_2_MASK(irq), IPUIRQ_2_STATREG(irq)); + + if (!g_ipu_clk_enabled) + clk_disable(g_ipu_clk); +} +EXPORT_SYMBOL(ipu_clear_irq); + +/*! + * This function returns the current interrupt status for the specified + * interrupt line. The interrupt lines are defined in \b ipu_irq_line enum. + * + * @param irq Interrupt line to get status for. + * + * @return Returns true if the interrupt is pending/asserted or false if + * the interrupt is not pending. + */ +bool ipu_get_irq_status(uint32_t irq) +{ + uint32_t reg; + + if (!g_ipu_clk_enabled) + clk_enable(g_ipu_clk); + + reg = __raw_readl(IPUIRQ_2_STATREG(irq)); + + if (!g_ipu_clk_enabled) + clk_disable(g_ipu_clk); + + if (reg & IPUIRQ_2_MASK(irq)) + return true; + else + return false; +} +EXPORT_SYMBOL(ipu_get_irq_status); + +/*! + * This function registers an interrupt handler function for the specified + * interrupt line. The interrupt lines are defined in \b ipu_irq_line enum. + * + * @param irq Interrupt line to get status for. + * + * @param handler Input parameter for address of the handler + * function. + * + * @param irq_flags Flags for interrupt mode. Currently not used. + * + * @param devname Input parameter for string name of driver + * registering the handler. + * + * @param dev_id Input parameter for pointer of data to be + * passed to the handler. + * + * @return This function returns 0 on success or negative error code on + * fail. + */ +int ipu_request_irq(uint32_t irq, + irqreturn_t(*handler) (int, void *), + uint32_t irq_flags, const char *devname, void *dev_id) +{ + unsigned long lock_flags; + + BUG_ON(irq >= IPU_IRQ_COUNT); + + spin_lock_irqsave(&ipu_lock, lock_flags); + + if (ipu_irq_list[irq].handler != NULL) { + dev_err(g_ipu_dev, + "handler already installed on irq %d\n", irq); + spin_unlock_irqrestore(&ipu_lock, lock_flags); + return -EINVAL; + } + + ipu_irq_list[irq].handler = handler; + ipu_irq_list[irq].flags = irq_flags; + ipu_irq_list[irq].dev_id = dev_id; + ipu_irq_list[irq].name = devname; + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + + ipu_enable_irq(irq); /* enable the interrupt */ + + return 0; +} +EXPORT_SYMBOL(ipu_request_irq); + +/*! + * This function unregisters an interrupt handler for the specified interrupt + * line. The interrupt lines are defined in \b ipu_irq_line enum. + * + * @param irq Interrupt line to get status for. + * + * @param dev_id Input parameter for pointer of data to be passed + * to the handler. This must match value passed to + * ipu_request_irq(). + * + */ +void ipu_free_irq(uint32_t irq, void *dev_id) +{ + ipu_disable_irq(irq); /* disable the interrupt */ + + if (ipu_irq_list[irq].dev_id == dev_id) + ipu_irq_list[irq].handler = NULL; +} +EXPORT_SYMBOL(ipu_free_irq); + +uint32_t ipu_get_cur_buffer_idx(ipu_channel_t channel, ipu_buffer_t type) +{ + uint32_t reg, dma_chan; + + dma_chan = channel_2_dma(channel, type); + if (!idma_is_valid(dma_chan)) + return -EINVAL; + + reg = __raw_readl(IPU_CHA_CUR_BUF(dma_chan/32)); + if (reg & idma_mask(dma_chan)) + return 1; + else + return 0; +} +EXPORT_SYMBOL(ipu_get_cur_buffer_idx); + +uint32_t _ipu_channel_status(ipu_channel_t channel) +{ + uint32_t stat = 0; + uint32_t task_stat_reg = __raw_readl(IPU_PROC_TASK_STAT); + + switch (channel) { + case MEM_PRP_VF_MEM: + stat = (task_stat_reg & TSTAT_VF_MASK) >> TSTAT_VF_OFFSET; + break; + case MEM_VDI_PRP_VF_MEM: + stat = (task_stat_reg & TSTAT_VF_MASK) >> TSTAT_VF_OFFSET; + break; + case MEM_ROT_VF_MEM: + stat = + (task_stat_reg & TSTAT_VF_ROT_MASK) >> TSTAT_VF_ROT_OFFSET; + break; + case MEM_PRP_ENC_MEM: + stat = (task_stat_reg & TSTAT_ENC_MASK) >> TSTAT_ENC_OFFSET; + break; + case MEM_ROT_ENC_MEM: + stat = + (task_stat_reg & TSTAT_ENC_ROT_MASK) >> + TSTAT_ENC_ROT_OFFSET; + break; + case MEM_PP_MEM: + stat = (task_stat_reg & TSTAT_PP_MASK) >> TSTAT_PP_OFFSET; + break; + case MEM_ROT_PP_MEM: + stat = + (task_stat_reg & TSTAT_PP_ROT_MASK) >> TSTAT_PP_ROT_OFFSET; + break; + + default: + stat = TASK_STAT_IDLE; + break; + } + return stat; +} + +int32_t ipu_swap_channel(ipu_channel_t from_ch, ipu_channel_t to_ch) +{ + uint32_t reg; + unsigned long lock_flags; + + int from_dma = channel_2_dma(from_ch, IPU_INPUT_BUFFER); + int to_dma = channel_2_dma(to_ch, IPU_INPUT_BUFFER); + + /* enable target channel */ + spin_lock_irqsave(&ipu_lock, lock_flags); + + reg = __raw_readl(IDMAC_CHA_EN(to_dma)); + __raw_writel(reg | idma_mask(to_dma), IDMAC_CHA_EN(to_dma)); + + g_channel_enable_mask |= 1L << IPU_CHAN_ID(to_ch); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + + /* switch dp dc */ + _ipu_dp_dc_disable(from_ch, true); + + /* disable source channel */ + spin_lock_irqsave(&ipu_lock, lock_flags); + + reg = __raw_readl(IDMAC_CHA_EN(from_dma)); + __raw_writel(reg & ~idma_mask(from_dma), IDMAC_CHA_EN(from_dma)); + __raw_writel(idma_mask(from_dma), IPU_CHA_CUR_BUF(from_dma)); + + g_channel_enable_mask &= ~(1L << IPU_CHAN_ID(from_ch)); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + + return 0; +} +EXPORT_SYMBOL(ipu_swap_channel); + +uint32_t bytes_per_pixel(uint32_t fmt) +{ + switch (fmt) { + case IPU_PIX_FMT_GENERIC: /*generic data */ + case IPU_PIX_FMT_RGB332: + case IPU_PIX_FMT_YUV420P: + case IPU_PIX_FMT_YUV422P: + return 1; + break; + case IPU_PIX_FMT_RGB565: + case IPU_PIX_FMT_YUYV: + case IPU_PIX_FMT_UYVY: + return 2; + break; + case IPU_PIX_FMT_BGR24: + case IPU_PIX_FMT_RGB24: + return 3; + break; + case IPU_PIX_FMT_GENERIC_32: /*generic data */ + case IPU_PIX_FMT_BGR32: + case IPU_PIX_FMT_BGRA32: + case IPU_PIX_FMT_RGB32: + case IPU_PIX_FMT_RGBA32: + case IPU_PIX_FMT_ABGR32: + return 4; + break; + default: + return 1; + break; + } + return 0; +} +EXPORT_SYMBOL(bytes_per_pixel); + +ipu_color_space_t format_to_colorspace(uint32_t fmt) +{ + switch (fmt) { + case IPU_PIX_FMT_RGB666: + case IPU_PIX_FMT_RGB565: + case IPU_PIX_FMT_BGR24: + case IPU_PIX_FMT_RGB24: + case IPU_PIX_FMT_BGR32: + case IPU_PIX_FMT_BGRA32: + case IPU_PIX_FMT_RGB32: + case IPU_PIX_FMT_RGBA32: + case IPU_PIX_FMT_ABGR32: + case IPU_PIX_FMT_LVDS666: + case IPU_PIX_FMT_LVDS888: + return RGB; + break; + + default: + return YCbCr; + break; + } + return RGB; +} + +bool ipu_pixel_format_has_alpha(uint32_t fmt) +{ + switch (fmt) { + case IPU_PIX_FMT_RGBA32: + case IPU_PIX_FMT_BGRA32: + case IPU_PIX_FMT_ABGR32: + return true; + break; + default: + return false; + break; + } + return false; +} + +void ipu_set_csc_coefficients(ipu_channel_t channel, int32_t param[][3]) +{ + _ipu_dp_set_csc_coefficients(channel, param); +} +EXPORT_SYMBOL(ipu_set_csc_coefficients); + +static int ipu_suspend(struct platform_device *pdev, pm_message_t state) +{ + if (g_ipu_clk_enabled) { + /* save and disable enabled channels*/ + idma_enable_reg[0] = __raw_readl(IDMAC_CHA_EN(0)); + idma_enable_reg[1] = __raw_readl(IDMAC_CHA_EN(32)); + while ((__raw_readl(IDMAC_CHA_BUSY(0)) & idma_enable_reg[0]) + || (__raw_readl(IDMAC_CHA_BUSY(32)) & + idma_enable_reg[1])) { + /* disable channel not busy already */ + uint32_t chan_should_disable, timeout = 1000, time = 0; + + chan_should_disable = + __raw_readl(IDMAC_CHA_BUSY(0)) + ^ idma_enable_reg[0]; + __raw_writel((~chan_should_disable) & + idma_enable_reg[0], IDMAC_CHA_EN(0)); + chan_should_disable = + __raw_readl(IDMAC_CHA_BUSY(1)) + ^ idma_enable_reg[1]; + __raw_writel((~chan_should_disable) & + idma_enable_reg[1], IDMAC_CHA_EN(32)); + msleep(2); + time += 2; + if (time >= timeout) + return -1; + } + __raw_writel(0, IDMAC_CHA_EN(0)); + __raw_writel(0, IDMAC_CHA_EN(32)); + + /* save double buffer select regs */ + ipu_cha_db_mode_reg[0] = __raw_readl(IPU_CHA_DB_MODE_SEL(0)); + ipu_cha_db_mode_reg[1] = __raw_readl(IPU_CHA_DB_MODE_SEL(32)); + ipu_cha_db_mode_reg[2] = + __raw_readl(IPU_ALT_CHA_DB_MODE_SEL(0)); + ipu_cha_db_mode_reg[3] = + __raw_readl(IPU_ALT_CHA_DB_MODE_SEL(32)); + + /* save current buffer regs */ + ipu_cha_cur_buf_reg[0] = __raw_readl(IPU_CHA_CUR_BUF(0)); + ipu_cha_cur_buf_reg[1] = __raw_readl(IPU_CHA_CUR_BUF(32)); + ipu_cha_cur_buf_reg[2] = __raw_readl(IPU_ALT_CUR_BUF0); + ipu_cha_cur_buf_reg[3] = __raw_readl(IPU_ALT_CUR_BUF1); + + /* save sub-modules status and disable all */ + ic_conf_reg = __raw_readl(IC_CONF); + __raw_writel(0, IC_CONF); + ipu_conf_reg = __raw_readl(IPU_CONF); + __raw_writel(0, IPU_CONF); + + /* save buf ready regs */ + buf_ready_reg[0] = __raw_readl(IPU_CHA_BUF0_RDY(0)); + buf_ready_reg[1] = __raw_readl(IPU_CHA_BUF0_RDY(32)); + buf_ready_reg[2] = __raw_readl(IPU_CHA_BUF1_RDY(0)); + buf_ready_reg[3] = __raw_readl(IPU_CHA_BUF1_RDY(32)); + buf_ready_reg[4] = __raw_readl(IPU_ALT_CHA_BUF0_RDY(0)); + buf_ready_reg[5] = __raw_readl(IPU_ALT_CHA_BUF0_RDY(32)); + buf_ready_reg[6] = __raw_readl(IPU_ALT_CHA_BUF1_RDY(0)); + buf_ready_reg[7] = __raw_readl(IPU_ALT_CHA_BUF1_RDY(32)); + } + + mxc_pg_enable(pdev); + + return 0; +} + +static int ipu_resume(struct platform_device *pdev) +{ + mxc_pg_disable(pdev); + + if (g_ipu_clk_enabled) { + + /* restore buf ready regs */ + __raw_writel(buf_ready_reg[0], IPU_CHA_BUF0_RDY(0)); + __raw_writel(buf_ready_reg[1], IPU_CHA_BUF0_RDY(32)); + __raw_writel(buf_ready_reg[2], IPU_CHA_BUF1_RDY(0)); + __raw_writel(buf_ready_reg[3], IPU_CHA_BUF1_RDY(32)); + __raw_writel(buf_ready_reg[4], IPU_ALT_CHA_BUF0_RDY(0)); + __raw_writel(buf_ready_reg[5], IPU_ALT_CHA_BUF0_RDY(32)); + __raw_writel(buf_ready_reg[6], IPU_ALT_CHA_BUF1_RDY(0)); + __raw_writel(buf_ready_reg[7], IPU_ALT_CHA_BUF1_RDY(32)); + + /* re-enable sub-modules*/ + __raw_writel(ipu_conf_reg, IPU_CONF); + __raw_writel(ic_conf_reg, IC_CONF); + + /* restore double buffer select regs */ + __raw_writel(ipu_cha_db_mode_reg[0], IPU_CHA_DB_MODE_SEL(0)); + __raw_writel(ipu_cha_db_mode_reg[1], IPU_CHA_DB_MODE_SEL(32)); + __raw_writel(ipu_cha_db_mode_reg[2], + IPU_ALT_CHA_DB_MODE_SEL(0)); + __raw_writel(ipu_cha_db_mode_reg[3], + IPU_ALT_CHA_DB_MODE_SEL(32)); + + /* restore current buffer select regs */ + __raw_writel(~(ipu_cha_cur_buf_reg[0]), IPU_CHA_CUR_BUF(0)); + __raw_writel(~(ipu_cha_cur_buf_reg[1]), IPU_CHA_CUR_BUF(32)); + __raw_writel(~(ipu_cha_cur_buf_reg[2]), IPU_ALT_CUR_BUF0); + __raw_writel(~(ipu_cha_cur_buf_reg[3]), IPU_ALT_CUR_BUF1); + + /* restart idma channel*/ + __raw_writel(idma_enable_reg[0], IDMAC_CHA_EN(0)); + __raw_writel(idma_enable_reg[1], IDMAC_CHA_EN(32)); + } else { + clk_enable(g_ipu_clk); + _ipu_dmfc_init(dmfc_type_setup, 1); + _ipu_init_dc_mappings(); + + /* Set sync refresh channels as high priority */ + __raw_writel(0x18800000L, IDMAC_CHA_PRI(0)); + clk_disable(g_ipu_clk); + } + + return 0; +} + +/*! + * This structure contains pointers to the power management callback functions. + */ +static struct platform_driver mxcipu_driver = { + .driver = { + .name = "mxc_ipu", + }, + .probe = ipu_probe, + .remove = ipu_remove, + .suspend = ipu_suspend, + .resume = ipu_resume, +}; + +int32_t __init ipu_gen_init(void) +{ + int32_t ret; + + ret = platform_driver_register(&mxcipu_driver); + return 0; +} + +subsys_initcall(ipu_gen_init); + +static void __exit ipu_gen_uninit(void) +{ + platform_driver_unregister(&mxcipu_driver); +} + +module_exit(ipu_gen_uninit); diff --git a/drivers/mxc/ipu3/ipu_device.c b/drivers/mxc/ipu3/ipu_device.c new file mode 100644 index 000000000000..c7c032d85d52 --- /dev/null +++ b/drivers/mxc/ipu3/ipu_device.c @@ -0,0 +1,510 @@ +/* + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file ipu_device.c + * + * @brief This file contains the IPUv3 driver device interface and fops functions. + * + * @ingroup IPU + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ipu_prv.h" +#include "ipu_regs.h" +#include "ipu_param_mem.h" + +/* Strucutures and variables for exporting MXC IPU as device*/ + +static int mxc_ipu_major; +static struct class *mxc_ipu_class; + +DEFINE_SPINLOCK(event_lock); + +struct ipu_dev_irq_info { + wait_queue_head_t waitq; + int irq_pending; +} irq_info[480]; + +int register_ipu_device(void); + +/* Static functions */ + +int get_events(ipu_event_info *p) +{ + unsigned long flags; + int ret = 0; + + spin_lock_irqsave(&event_lock, flags); + if (irq_info[p->irq].irq_pending > 0) + irq_info[p->irq].irq_pending--; + else + ret = -1; + spin_unlock_irqrestore(&event_lock, flags); + + return ret; +} + +static irqreturn_t mxc_ipu_generic_handler(int irq, void *dev_id) +{ + irq_info[irq].irq_pending++; + + /* Wakeup any blocking user context */ + wake_up_interruptible(&(irq_info[irq].waitq)); + return IRQ_HANDLED; +} + +static int mxc_ipu_open(struct inode *inode, struct file *file) +{ + int ret = 0; + return ret; +} +static int mxc_ipu_ioctl(struct inode *inode, struct file *file, + unsigned int cmd, unsigned long arg) +{ + int ret = 0; + + switch (cmd) { + case IPU_INIT_CHANNEL: + { + ipu_channel_parm parm; + + if (copy_from_user + (&parm, (ipu_channel_parm *) arg, + sizeof(ipu_channel_parm))) + return -EFAULT; + + if (!parm.flag) { + ret = + ipu_init_channel(parm.channel, + &parm.params); + } else { + ret = ipu_init_channel(parm.channel, NULL); + } + } + break; + case IPU_UNINIT_CHANNEL: + { + ipu_channel_t ch; + int __user *argp = (void __user *)arg; + if (get_user(ch, argp)) + return -EFAULT; + ipu_uninit_channel(ch); + } + break; + case IPU_INIT_CHANNEL_BUFFER: + { + ipu_channel_buf_parm parm; + if (copy_from_user + (&parm, (ipu_channel_buf_parm *) arg, + sizeof(ipu_channel_buf_parm))) + return -EFAULT; + + ret = + ipu_init_channel_buffer( + parm.channel, parm.type, + parm.pixel_fmt, + parm.width, parm.height, + parm.stride, + parm.rot_mode, + parm.phyaddr_0, + parm.phyaddr_1, + parm.u_offset, + parm.v_offset); + + } + break; + case IPU_UPDATE_CHANNEL_BUFFER: + { + ipu_channel_buf_parm parm; + if (copy_from_user + (&parm, (ipu_channel_buf_parm *) arg, + sizeof(ipu_channel_buf_parm))) + return -EFAULT; + + if ((parm.phyaddr_0 != (dma_addr_t) NULL) + && (parm.phyaddr_1 == (dma_addr_t) NULL)) { + ret = + ipu_update_channel_buffer( + parm.channel, + parm.type, + parm.bufNum, + parm.phyaddr_0); + } else if ((parm.phyaddr_0 == (dma_addr_t) NULL) + && (parm.phyaddr_1 != (dma_addr_t) NULL)) { + ret = + ipu_update_channel_buffer( + parm.channel, + parm.type, + parm.bufNum, + parm.phyaddr_1); + } else { + ret = -1; + } + + } + break; + case IPU_SELECT_CHANNEL_BUFFER: + { + ipu_channel_buf_parm parm; + if (copy_from_user + (&parm, (ipu_channel_buf_parm *) arg, + sizeof(ipu_channel_buf_parm))) + return -EFAULT; + + ret = + ipu_select_buffer(parm.channel, + parm.type, parm.bufNum); + + } + break; + case IPU_SELECT_MULTI_VDI_BUFFER: + { + uint32_t parm; + if (copy_from_user + (&parm, (uint32_t *) arg, + sizeof(uint32_t))) + return -EFAULT; + + ret = ipu_select_multi_vdi_buffer(parm); + } + break; + case IPU_LINK_CHANNELS: + { + ipu_channel_link link; + if (copy_from_user + (&link, (ipu_channel_link *) arg, + sizeof(ipu_channel_link))) + return -EFAULT; + + ret = ipu_link_channels(link.src_ch, + link.dest_ch); + + } + break; + case IPU_UNLINK_CHANNELS: + { + ipu_channel_link link; + if (copy_from_user + (&link, (ipu_channel_link *) arg, + sizeof(ipu_channel_link))) + return -EFAULT; + + ret = ipu_unlink_channels(link.src_ch, + link.dest_ch); + + } + break; + case IPU_ENABLE_CHANNEL: + { + ipu_channel_t ch; + int __user *argp = (void __user *)arg; + if (get_user(ch, argp)) + return -EFAULT; + ipu_enable_channel(ch); + } + break; + case IPU_DISABLE_CHANNEL: + { + ipu_channel_info info; + if (copy_from_user + (&info, (ipu_channel_info *) arg, + sizeof(ipu_channel_info))) + return -EFAULT; + + ret = ipu_disable_channel(info.channel, + info.stop); + } + break; + case IPU_ENABLE_IRQ: + { + uint32_t irq; + int __user *argp = (void __user *)arg; + if (get_user(irq, argp)) + return -EFAULT; + ipu_enable_irq(irq); + } + break; + case IPU_DISABLE_IRQ: + { + uint32_t irq; + int __user *argp = (void __user *)arg; + if (get_user(irq, argp)) + return -EFAULT; + ipu_disable_irq(irq); + } + break; + case IPU_CLEAR_IRQ: + { + uint32_t irq; + int __user *argp = (void __user *)arg; + if (get_user(irq, argp)) + return -EFAULT; + ipu_clear_irq(irq); + } + break; + case IPU_FREE_IRQ: + { + ipu_irq_info info; + + if (copy_from_user + (&info, (ipu_irq_info *) arg, + sizeof(ipu_irq_info))) + return -EFAULT; + + ipu_free_irq(info.irq, info.dev_id); + irq_info[info.irq].irq_pending = 0; + } + break; + case IPU_REQUEST_IRQ_STATUS: + { + uint32_t irq; + int __user *argp = (void __user *)arg; + if (get_user(irq, argp)) + return -EFAULT; + ret = ipu_get_irq_status(irq); + } + break; + case IPU_REGISTER_GENERIC_ISR: + { + ipu_event_info info; + if (copy_from_user + (&info, (ipu_event_info *) arg, + sizeof(ipu_event_info))) + return -EFAULT; + + ret = + ipu_request_irq(info.irq, + mxc_ipu_generic_handler, + 0, "video_sink", info.dev); + if (ret == 0) + init_waitqueue_head(&(irq_info[info.irq].waitq)); + } + break; + case IPU_GET_EVENT: + /* User will have to allocate event_type + structure and pass the pointer in arg */ + { + ipu_event_info info; + int r = -1; + + if (copy_from_user + (&info, (ipu_event_info *) arg, + sizeof(ipu_event_info))) + return -EFAULT; + + r = get_events(&info); + if (r == -1) { + if ((file->f_flags & O_NONBLOCK) && + (irq_info[info.irq].irq_pending == 0)) + return -EAGAIN; + wait_event_interruptible_timeout(irq_info[info.irq].waitq, + (irq_info[info.irq].irq_pending != 0), 2 * HZ); + r = get_events(&info); + } + ret = -1; + if (r == 0) { + if (!copy_to_user((ipu_event_info *) arg, + &info, sizeof(ipu_event_info))) + ret = 0; + } + } + break; + case IPU_ALOC_MEM: + { + ipu_mem_info info; + if (copy_from_user + (&info, (ipu_mem_info *) arg, + sizeof(ipu_mem_info))) + return -EFAULT; + + info.vaddr = dma_alloc_coherent(0, + PAGE_ALIGN(info.size), + &info.paddr, + GFP_DMA | GFP_KERNEL); + if (info.vaddr == 0) { + printk(KERN_ERR "dma alloc failed!\n"); + return -ENOBUFS; + } + if (copy_to_user((ipu_mem_info *) arg, &info, + sizeof(ipu_mem_info)) > 0) + return -EFAULT; + } + break; + case IPU_FREE_MEM: + { + ipu_mem_info info; + if (copy_from_user + (&info, (ipu_mem_info *) arg, + sizeof(ipu_mem_info))) + return -EFAULT; + + if (info.vaddr) + dma_free_coherent(0, PAGE_ALIGN(info.size), + info.vaddr, info.paddr); + else + return -EFAULT; + } + break; + case IPU_IS_CHAN_BUSY: + { + ipu_channel_t chan; + if (copy_from_user + (&chan, (ipu_channel_t *)arg, + sizeof(ipu_channel_t))) + return -EFAULT; + + if (ipu_is_channel_busy(chan)) + ret = 1; + else + ret = 0; + } + break; + case IPU_CALC_STRIPES_SIZE: + { + ipu_stripe_parm stripe_parm; + + if (copy_from_user (&stripe_parm, (ipu_stripe_parm *)arg, + sizeof(ipu_stripe_parm))) + return -EFAULT; + ipu_calc_stripes_sizes(stripe_parm.input_width, + stripe_parm.output_width, + stripe_parm.maximal_stripe_width, + stripe_parm.cirr, + stripe_parm.equal_stripes, + stripe_parm.input_pixelformat, + stripe_parm.output_pixelformat, + &stripe_parm.left, + &stripe_parm.right); + if (copy_to_user((ipu_stripe_parm *) arg, &stripe_parm, + sizeof(ipu_stripe_parm)) > 0) + return -EFAULT; + } + break; + case IPU_UPDATE_BUF_OFFSET: + { + ipu_buf_offset_parm offset_parm; + + if (copy_from_user (&offset_parm, (ipu_buf_offset_parm *)arg, + sizeof(ipu_buf_offset_parm))) + return -EFAULT; + ret = ipu_update_channel_offset(offset_parm.channel, + offset_parm.type, + offset_parm.pixel_fmt, + offset_parm.width, + offset_parm.height, + offset_parm.stride, + offset_parm.u_offset, + offset_parm.v_offset, + offset_parm.vertical_offset, + offset_parm.horizontal_offset); + } + break; + case IPU_CSC_UPDATE: + { + int param[5][3]; + ipu_csc_update csc; + if (copy_from_user(&csc, (void *) arg, + sizeof(ipu_csc_update))) + return -EFAULT; + if (copy_from_user(¶m[0][0], (void *) csc.param, + sizeof(param))) + return -EFAULT; + ipu_set_csc_coefficients(csc.channel, param); + } + break; + default: + break; + } + return ret; +} + +static int mxc_ipu_mmap(struct file *file, struct vm_area_struct *vma) +{ + vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot); + + if (remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff, + vma->vm_end - vma->vm_start, + vma->vm_page_prot)) { + printk(KERN_ERR + "mmap failed!\n"); + return -ENOBUFS; + } + return 0; +} + +static int mxc_ipu_release(struct inode *inode, struct file *file) +{ + return 0; +} + +static struct file_operations mxc_ipu_fops = { + .owner = THIS_MODULE, + .open = mxc_ipu_open, + .mmap = mxc_ipu_mmap, + .release = mxc_ipu_release, + .ioctl = mxc_ipu_ioctl, +}; + +int register_ipu_device() +{ + int ret = 0; + struct device *temp; + mxc_ipu_major = register_chrdev(0, "mxc_ipu", &mxc_ipu_fops); + if (mxc_ipu_major < 0) { + printk(KERN_ERR + "Unable to register Mxc Ipu as a char device\n"); + return mxc_ipu_major; + } + + mxc_ipu_class = class_create(THIS_MODULE, "mxc_ipu"); + if (IS_ERR(mxc_ipu_class)) { + printk(KERN_ERR "Unable to create class for Mxc Ipu\n"); + ret = PTR_ERR(mxc_ipu_class); + goto err1; + } + + temp = device_create(mxc_ipu_class, NULL, MKDEV(mxc_ipu_major, 0), + NULL, "mxc_ipu"); + + if (IS_ERR(temp)) { + printk(KERN_ERR "Unable to create class device for Mxc Ipu\n"); + ret = PTR_ERR(temp); + goto err2; + } + spin_lock_init(&event_lock); + + return ret; + +err2: + class_destroy(mxc_ipu_class); +err1: + unregister_chrdev(mxc_ipu_major, "mxc_ipu"); + return ret; + +} diff --git a/drivers/mxc/ipu3/ipu_disp.c b/drivers/mxc/ipu3/ipu_disp.c new file mode 100644 index 000000000000..ce2c2bc72dc2 --- /dev/null +++ b/drivers/mxc/ipu3/ipu_disp.c @@ -0,0 +1,1805 @@ +/* + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file ipu_disp.c + * + * @brief IPU display submodule API functions + * + * @ingroup IPU + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "ipu_prv.h" +#include "ipu_regs.h" +#include "ipu_param_mem.h" + +enum csc_type_t { + RGB2YUV = 0, + YUV2RGB, + RGB2RGB, + YUV2YUV, + CSC_NONE, + CSC_NUM +}; + +struct dp_csc_param_t { + int mode; + void *coeff; +}; + +#define SYNC_WAVE 0 +#define ASYNC_SER_WAVE 6 + +/* DC display ID assignments */ +#define DC_DISP_ID_SYNC(di) (di) +#define DC_DISP_ID_SERIAL 2 +#define DC_DISP_ID_ASYNC 3 + +int dmfc_type_setup; +static int dmfc_size_28, dmfc_size_29, dmfc_size_24, dmfc_size_27, dmfc_size_23; + +void _ipu_dmfc_init(int dmfc_type, int first) +{ + u32 dmfc_wr_chan, dmfc_dp_chan; + + if (first) { + if (dmfc_type_setup > dmfc_type) + dmfc_type = dmfc_type_setup; + else + dmfc_type_setup = dmfc_type; + + /* disable DMFC-IC channel*/ + __raw_writel(0x2, DMFC_IC_CTRL); + } else if (dmfc_type_setup >= DMFC_HIGH_RESOLUTION_DC) { + printk(KERN_DEBUG "DMFC high resolution has set, will not change\n"); + return; + } else + dmfc_type_setup = dmfc_type; + + if (dmfc_type == DMFC_HIGH_RESOLUTION_DC) { + /* 1 - segment 0~3; + * 5B - segement 4, 5; + * 5F - segement 6, 7; + * 1C, 2C and 6B, 6F unused; + */ + printk(KERN_INFO "IPU DMFC DC HIGH RESOLUTION: 1(0~3), 5B(4,5), 5F(6,7)\n"); + dmfc_wr_chan = 0x00000088; + dmfc_dp_chan = 0x00009694; + dmfc_size_28 = 256*4; + dmfc_size_29 = 0; + dmfc_size_24 = 0; + dmfc_size_27 = 128*4; + dmfc_size_23 = 128*4; + } else if (dmfc_type == DMFC_HIGH_RESOLUTION_DP) { + /* 1 - segment 0, 1; + * 5B - segement 2~5; + * 5F - segement 6,7; + * 1C, 2C and 6B, 6F unused; + */ + printk(KERN_INFO "IPU DMFC DP HIGH RESOLUTION: 1(0,1), 5B(2~5), 5F(6,7)\n"); + dmfc_wr_chan = 0x00000090; + dmfc_dp_chan = 0x0000968a; + dmfc_size_28 = 128*4; + dmfc_size_29 = 0; + dmfc_size_24 = 0; + dmfc_size_27 = 128*4; + dmfc_size_23 = 256*4; + } else if (dmfc_type == DMFC_HIGH_RESOLUTION_ONLY_DP) { + /* 5B - segement 0~3; + * 5F - segement 4~7; + * 1, 1C, 2C and 6B, 6F unused; + */ + printk(KERN_INFO "IPU DMFC ONLY-DP HIGH RESOLUTION: 5B(0~3), 5F(4~7)\n"); + dmfc_wr_chan = 0x00000000; + dmfc_dp_chan = 0x00008c88; + dmfc_size_28 = 0; + dmfc_size_29 = 0; + dmfc_size_24 = 0; + dmfc_size_27 = 256*4; + dmfc_size_23 = 256*4; + } else { + /* 1 - segment 0, 1; + * 5B - segement 4, 5; + * 5F - segement 6, 7; + * 1C, 2C and 6B, 6F unused; + */ + printk(KERN_INFO "IPU DMFC NORMAL mode: 1(0~1), 5B(4,5), 5F(6,7)\n"); + dmfc_wr_chan = 0x00000090; + dmfc_dp_chan = 0x00009694; + dmfc_size_28 = 128*4; + dmfc_size_29 = 0; + dmfc_size_24 = 0; + dmfc_size_27 = 128*4; + dmfc_size_23 = 128*4; + } + __raw_writel(dmfc_wr_chan, DMFC_WR_CHAN); + __raw_writel(0x202020F6, DMFC_WR_CHAN_DEF); + __raw_writel(dmfc_dp_chan, DMFC_DP_CHAN); + /* Enable chan 5 watermark set at 5 bursts and clear at 7 bursts */ + __raw_writel(0x2020F6F6, DMFC_DP_CHAN_DEF); +} + +static int __init dmfc_setup(char *options) +{ + get_option(&options, &dmfc_type_setup); + if (dmfc_type_setup > DMFC_HIGH_RESOLUTION_ONLY_DP) + dmfc_type_setup = DMFC_HIGH_RESOLUTION_ONLY_DP; + return 1; +} +__setup("dmfc=", dmfc_setup); + +void _ipu_dmfc_set_wait4eot(int dma_chan, int width) +{ + u32 dmfc_gen1 = __raw_readl(DMFC_GENERAL1); + + if (width >= HIGH_RESOLUTION_WIDTH) { + if (dma_chan == 23) + _ipu_dmfc_init(DMFC_HIGH_RESOLUTION_DP, 0); + else if (dma_chan == 28) + _ipu_dmfc_init(DMFC_HIGH_RESOLUTION_DC, 0); + } + + if (dma_chan == 23) { /*5B*/ + if (dmfc_size_23/width > 3) + dmfc_gen1 |= 1UL << 20; + else + dmfc_gen1 &= ~(1UL << 20); + } else if (dma_chan == 24) { /*6B*/ + if (dmfc_size_24/width > 1) + dmfc_gen1 |= 1UL << 22; + else + dmfc_gen1 &= ~(1UL << 22); + } else if (dma_chan == 27) { /*5F*/ + if (dmfc_size_27/width > 2) + dmfc_gen1 |= 1UL << 21; + else + dmfc_gen1 &= ~(1UL << 21); + } else if (dma_chan == 28) { /*1*/ + if (dmfc_size_28/width > 2) + dmfc_gen1 |= 1UL << 16; + else + dmfc_gen1 &= ~(1UL << 16); + } else if (dma_chan == 29) { /*6F*/ + if (dmfc_size_29/width > 1) + dmfc_gen1 |= 1UL << 23; + else + dmfc_gen1 &= ~(1UL << 23); + } + + __raw_writel(dmfc_gen1, DMFC_GENERAL1); +} + +static void _ipu_di_data_wave_config(int di, + int wave_gen, + int access_size, int component_size) +{ + u32 reg; + reg = (access_size << DI_DW_GEN_ACCESS_SIZE_OFFSET) | + (component_size << DI_DW_GEN_COMPONENT_SIZE_OFFSET); + __raw_writel(reg, DI_DW_GEN(di, wave_gen)); +} + +static void _ipu_di_data_pin_config(int di, int wave_gen, int di_pin, int set, + int up, int down) +{ + u32 reg; + + reg = __raw_readl(DI_DW_GEN(di, wave_gen)); + reg &= ~(0x3 << (di_pin * 2)); + reg |= set << (di_pin * 2); + __raw_writel(reg, DI_DW_GEN(di, wave_gen)); + + __raw_writel((down << 16) | up, DI_DW_SET(di, wave_gen, set)); +} + +static void _ipu_di_sync_config(int di, int wave_gen, + int run_count, int run_src, + int offset_count, int offset_src, + int repeat_count, int cnt_clr_src, + int cnt_polarity_gen_en, + int cnt_polarity_clr_src, + int cnt_polarity_trigger_src, + int cnt_up, int cnt_down) +{ + u32 reg; + + if ((run_count >= 0x1000) || (offset_count >= 0x1000) || (repeat_count >= 0x1000) || + (cnt_up >= 0x400) || (cnt_down >= 0x400)) { + dev_err(g_ipu_dev, "DI%d counters out of range.\n", di); + return; + } + + reg = (run_count << 19) | (++run_src << 16) | + (offset_count << 3) | ++offset_src; + __raw_writel(reg, DI_SW_GEN0(di, wave_gen)); + reg = (cnt_polarity_gen_en << 29) | (++cnt_clr_src << 25) | + (++cnt_polarity_trigger_src << 12) | (++cnt_polarity_clr_src << 9); + reg |= (cnt_down << 16) | cnt_up; + if (repeat_count == 0) { + /* Enable auto reload */ + reg |= 0x10000000; + } + __raw_writel(reg, DI_SW_GEN1(di, wave_gen)); + reg = __raw_readl(DI_STP_REP(di, wave_gen)); + reg &= ~(0xFFFF << (16 * ((wave_gen - 1) & 0x1))); + reg |= repeat_count << (16 * ((wave_gen - 1) & 0x1)); + __raw_writel(reg, DI_STP_REP(di, wave_gen)); +} + +static void _ipu_dc_map_link(int current_map, + int base_map_0, int buf_num_0, + int base_map_1, int buf_num_1, + int base_map_2, int buf_num_2) +{ + int ptr_0 = base_map_0 * 3 + buf_num_0; + int ptr_1 = base_map_1 * 3 + buf_num_1; + int ptr_2 = base_map_2 * 3 + buf_num_2; + int ptr; + u32 reg; + ptr = (ptr_2 << 10) + (ptr_1 << 5) + ptr_0; + + reg = __raw_readl(DC_MAP_CONF_PTR(current_map)); + reg &= ~(0x1F << ((16 * (current_map & 0x1)))); + reg |= ptr << ((16 * (current_map & 0x1))); + __raw_writel(reg, DC_MAP_CONF_PTR(current_map)); +} + +static void _ipu_dc_map_config(int map, int byte_num, int offset, int mask) +{ + int ptr = map * 3 + byte_num; + u32 reg; + + reg = __raw_readl(DC_MAP_CONF_VAL(ptr)); + reg &= ~(0xFFFF << (16 * (ptr & 0x1))); + reg |= ((offset << 8) | mask) << (16 * (ptr & 0x1)); + __raw_writel(reg, DC_MAP_CONF_VAL(ptr)); + + reg = __raw_readl(DC_MAP_CONF_PTR(map)); + reg &= ~(0x1F << ((16 * (map & 0x1)) + (5 * byte_num))); + reg |= ptr << ((16 * (map & 0x1)) + (5 * byte_num)); + __raw_writel(reg, DC_MAP_CONF_PTR(map)); +} + +static void _ipu_dc_map_clear(int map) +{ + u32 reg = __raw_readl(DC_MAP_CONF_PTR(map)); + __raw_writel(reg & ~(0xFFFF << (16 * (map & 0x1))), + DC_MAP_CONF_PTR(map)); +} + +static void _ipu_dc_write_tmpl(int word, u32 opcode, u32 operand, int map, + int wave, int glue, int sync) +{ + u32 reg; + int stop = 1; + + reg = sync; + reg |= (glue << 4); + reg |= (++wave << 11); + reg |= (++map << 15); + reg |= (operand << 20) & 0xFFF00000; + __raw_writel(reg, ipu_dc_tmpl_reg + word * 2); + + reg = (operand >> 12); + reg |= opcode << 4; + reg |= (stop << 9); + __raw_writel(reg, ipu_dc_tmpl_reg + word * 2 + 1); +} + +static void _ipu_dc_link_event(int chan, int event, int addr, int priority) +{ + u32 reg; + u32 address_shift; + if (event < DC_EVEN_UGDE0) { + reg = __raw_readl(DC_RL_CH(chan, event)); + reg &= ~(0xFFFF << (16 * (event & 0x1))); + reg |= ((addr << 8) | priority) << (16 * (event & 0x1)); + __raw_writel(reg, DC_RL_CH(chan, event)); + } else { + reg = __raw_readl(DC_UGDE_0((event - DC_EVEN_UGDE0) / 2)); + if ((event - DC_EVEN_UGDE0) & 0x1) { + reg &= ~(0x2FF << 16); + reg |= (addr << 16); + reg |= priority ? (2 << 24) : 0x0; + } else { + reg &= ~0xFC00FFFF; + if (priority) + chan = (chan >> 1) + + ((((chan & 0x1) + ((chan & 0x2) >> 1))) | (chan >> 3)); + else + chan = 0x7; + address_shift = ((event - DC_EVEN_UGDE0) >> 1) ? 7 : 8; + reg |= (addr << address_shift) | (priority << 3) | chan; + } + __raw_writel(reg, DC_UGDE_0((event - DC_EVEN_UGDE0) / 2)); + } +} + +/* Y = R * 1.200 + G * 2.343 + B * .453 + 0.250; + U = R * -.672 + G * -1.328 + B * 2.000 + 512.250.; + V = R * 2.000 + G * -1.672 + B * -.328 + 512.250.;*/ +static const int rgb2ycbcr_coeff[5][3] = { + {0x4D, 0x96, 0x1D}, + {-0x2B, -0x55, 0x80}, + {0x80, -0x6B, -0x15}, + {0x0000, 0x0200, 0x0200}, /* B0, B1, B2 */ + {0x2, 0x2, 0x2}, /* S0, S1, S2 */ +}; + +/* R = (1.164 * (Y - 16)) + (1.596 * (Cr - 128)); + G = (1.164 * (Y - 16)) - (0.392 * (Cb - 128)) - (0.813 * (Cr - 128)); + B = (1.164 * (Y - 16)) + (2.017 * (Cb - 128); */ +static const int ycbcr2rgb_coeff[5][3] = { + {0x095, 0x000, 0x0CC}, + {0x095, 0x3CE, 0x398}, + {0x095, 0x0FF, 0x000}, + {0x3E42, 0x010A, 0x3DD6}, /*B0,B1,B2 */ + {0x1, 0x1, 0x1}, /*S0,S1,S2 */ +}; + +#define mask_a(a) ((u32)(a) & 0x3FF) +#define mask_b(b) ((u32)(b) & 0x3FFF) + +/* Pls keep S0, S1 and S2 as 0x2 by using this convertion */ +static int _rgb_to_yuv(int n, int red, int green, int blue) +{ + int c; + c = red * rgb2ycbcr_coeff[n][0]; + c += green * rgb2ycbcr_coeff[n][1]; + c += blue * rgb2ycbcr_coeff[n][2]; + c /= 16; + c += rgb2ycbcr_coeff[3][n] * 4; + c += 8; + c /= 16; + if (c < 0) + c = 0; + if (c > 255) + c = 255; + return c; +} + +/* + * Row is for BG: RGB2YUV YUV2RGB RGB2RGB YUV2YUV CSC_NONE + * Column is for FG: RGB2YUV YUV2RGB RGB2RGB YUV2YUV CSC_NONE + */ +static struct dp_csc_param_t dp_csc_array[CSC_NUM][CSC_NUM] = { +{{DP_COM_CONF_CSC_DEF_BOTH, &rgb2ycbcr_coeff}, {0, 0}, {0, 0}, {DP_COM_CONF_CSC_DEF_BG, &rgb2ycbcr_coeff}, {DP_COM_CONF_CSC_DEF_BG, &rgb2ycbcr_coeff} }, +{{0, 0}, {DP_COM_CONF_CSC_DEF_BOTH, &ycbcr2rgb_coeff}, {DP_COM_CONF_CSC_DEF_BG, &ycbcr2rgb_coeff}, {0, 0}, {DP_COM_CONF_CSC_DEF_BG, &ycbcr2rgb_coeff} }, +{{0, 0}, {DP_COM_CONF_CSC_DEF_FG, &ycbcr2rgb_coeff}, {0, 0}, {0, 0}, {0, 0} }, +{{DP_COM_CONF_CSC_DEF_FG, &rgb2ycbcr_coeff}, {0, 0}, {0, 0}, {0, 0}, {0, 0} }, +{{DP_COM_CONF_CSC_DEF_FG, &rgb2ycbcr_coeff}, {DP_COM_CONF_CSC_DEF_FG, &ycbcr2rgb_coeff}, {0, 0}, {0, 0}, {0, 0} } +}; + +static enum csc_type_t fg_csc_type = CSC_NONE, bg_csc_type = CSC_NONE; +static int color_key_4rgb = 1; + +void __ipu_dp_csc_setup(int dp, struct dp_csc_param_t dp_csc_param, + bool srm_mode_update) +{ + u32 reg; + const int (*coeff)[5][3]; + + if (dp_csc_param.mode >= 0) { + reg = __raw_readl(DP_COM_CONF(dp)); + reg &= ~DP_COM_CONF_CSC_DEF_MASK; + reg |= dp_csc_param.mode; + __raw_writel(reg, DP_COM_CONF(dp)); + } + + coeff = dp_csc_param.coeff; + + if (coeff) { + __raw_writel(mask_a((*coeff)[0][0]) | + (mask_a((*coeff)[0][1]) << 16), DP_CSC_A_0(dp)); + __raw_writel(mask_a((*coeff)[0][2]) | + (mask_a((*coeff)[1][0]) << 16), DP_CSC_A_1(dp)); + __raw_writel(mask_a((*coeff)[1][1]) | + (mask_a((*coeff)[1][2]) << 16), DP_CSC_A_2(dp)); + __raw_writel(mask_a((*coeff)[2][0]) | + (mask_a((*coeff)[2][1]) << 16), DP_CSC_A_3(dp)); + __raw_writel(mask_a((*coeff)[2][2]) | + (mask_b((*coeff)[3][0]) << 16) | + ((*coeff)[4][0] << 30), DP_CSC_0(dp)); + __raw_writel(mask_b((*coeff)[3][1]) | ((*coeff)[4][1] << 14) | + (mask_b((*coeff)[3][2]) << 16) | + ((*coeff)[4][2] << 30), DP_CSC_1(dp)); + } + + if (srm_mode_update) { + reg = __raw_readl(IPU_SRM_PRI2) | 0x8; + __raw_writel(reg, IPU_SRM_PRI2); + } +} + +int _ipu_dp_init(ipu_channel_t channel, uint32_t in_pixel_fmt, + uint32_t out_pixel_fmt) +{ + int in_fmt, out_fmt; + int dp; + int partial = false; + uint32_t reg; + + if (channel == MEM_FG_SYNC) { + dp = DP_SYNC; + partial = true; + } else if (channel == MEM_BG_SYNC) { + dp = DP_SYNC; + partial = false; + } else if (channel == MEM_BG_ASYNC0) { + dp = DP_ASYNC0; + partial = false; + } else { + return -EINVAL; + } + + in_fmt = format_to_colorspace(in_pixel_fmt); + out_fmt = format_to_colorspace(out_pixel_fmt); + + if (partial) { + if (in_fmt == RGB) { + if (out_fmt == RGB) + fg_csc_type = RGB2RGB; + else + fg_csc_type = RGB2YUV; + } else { + if (out_fmt == RGB) + fg_csc_type = YUV2RGB; + else + fg_csc_type = YUV2YUV; + } + } else { + if (in_fmt == RGB) { + if (out_fmt == RGB) + bg_csc_type = RGB2RGB; + else + bg_csc_type = RGB2YUV; + } else { + if (out_fmt == RGB) + bg_csc_type = YUV2RGB; + else + bg_csc_type = YUV2YUV; + } + } + + /* Transform color key from rgb to yuv if CSC is enabled */ + reg = __raw_readl(DP_COM_CONF(dp)); + if (color_key_4rgb && (reg & DP_COM_CONF_GWCKE) && + (((fg_csc_type == RGB2YUV) && (bg_csc_type == YUV2YUV)) || + ((fg_csc_type == YUV2YUV) && (bg_csc_type == RGB2YUV)) || + ((fg_csc_type == YUV2YUV) && (bg_csc_type == YUV2YUV)) || + ((fg_csc_type == YUV2RGB) && (bg_csc_type == YUV2RGB)))) { + int red, green, blue; + int y, u, v; + uint32_t color_key = __raw_readl(DP_GRAPH_WIND_CTRL(dp)) & 0xFFFFFFL; + + dev_dbg(g_ipu_dev, "_ipu_dp_init color key 0x%x need change to yuv fmt!\n", color_key); + + red = (color_key >> 16) & 0xFF; + green = (color_key >> 8) & 0xFF; + blue = color_key & 0xFF; + + y = _rgb_to_yuv(0, red, green, blue); + u = _rgb_to_yuv(1, red, green, blue); + v = _rgb_to_yuv(2, red, green, blue); + color_key = (y << 16) | (u << 8) | v; + + reg = __raw_readl(DP_GRAPH_WIND_CTRL(dp)) & 0xFF000000L; + __raw_writel(reg | color_key, DP_GRAPH_WIND_CTRL(dp)); + color_key_4rgb = 0; + + dev_dbg(g_ipu_dev, "_ipu_dp_init color key change to yuv fmt 0x%x!\n", color_key); + } + + __ipu_dp_csc_setup(dp, dp_csc_array[bg_csc_type][fg_csc_type], true); + + return 0; +} + +void _ipu_dp_uninit(ipu_channel_t channel) +{ + int dp; + int partial = false; + + if (channel == MEM_FG_SYNC) { + dp = DP_SYNC; + partial = true; + } else if (channel == MEM_BG_SYNC) { + dp = DP_SYNC; + partial = false; + } else if (channel == MEM_BG_ASYNC0) { + dp = DP_ASYNC0; + partial = false; + } else { + return; + } + + if (partial) + fg_csc_type = CSC_NONE; + else + bg_csc_type = CSC_NONE; + + __ipu_dp_csc_setup(dp, dp_csc_array[bg_csc_type][fg_csc_type], false); +} + +void _ipu_dc_init(int dc_chan, int di, bool interlaced, uint32_t pixel_fmt) +{ + u32 reg = 0; + + if ((dc_chan == 1) || (dc_chan == 5)) { + if (interlaced) { + _ipu_dc_link_event(dc_chan, DC_EVT_NL, 0, 3); + _ipu_dc_link_event(dc_chan, DC_EVT_EOL, 0, 2); + _ipu_dc_link_event(dc_chan, DC_EVT_NEW_DATA, 0, 1); + } else { + if (di) { + _ipu_dc_link_event(dc_chan, DC_EVT_NL, 2, 3); + _ipu_dc_link_event(dc_chan, DC_EVT_EOL, 3, 2); + _ipu_dc_link_event(dc_chan, DC_EVT_NEW_DATA, 4, 1); + if ((pixel_fmt == IPU_PIX_FMT_YUYV) || + (pixel_fmt == IPU_PIX_FMT_UYVY) || + (pixel_fmt == IPU_PIX_FMT_YVYU) || + (pixel_fmt == IPU_PIX_FMT_VYUY)) { + _ipu_dc_link_event(dc_chan, DC_ODD_UGDE1, 9, 5); + _ipu_dc_link_event(dc_chan, DC_EVEN_UGDE1, 8, 5); + } + } else { + _ipu_dc_link_event(dc_chan, DC_EVT_NL, 5, 3); + _ipu_dc_link_event(dc_chan, DC_EVT_EOL, 6, 2); + _ipu_dc_link_event(dc_chan, DC_EVT_NEW_DATA, 7, 1); + if ((pixel_fmt == IPU_PIX_FMT_YUYV) || + (pixel_fmt == IPU_PIX_FMT_UYVY) || + (pixel_fmt == IPU_PIX_FMT_YVYU) || + (pixel_fmt == IPU_PIX_FMT_VYUY)) { + _ipu_dc_link_event(dc_chan, DC_ODD_UGDE0, 10, 5); + _ipu_dc_link_event(dc_chan, DC_EVEN_UGDE0, 11, 5); + } + } + } + _ipu_dc_link_event(dc_chan, DC_EVT_NF, 0, 0); + _ipu_dc_link_event(dc_chan, DC_EVT_NFIELD, 0, 0); + _ipu_dc_link_event(dc_chan, DC_EVT_EOF, 0, 0); + _ipu_dc_link_event(dc_chan, DC_EVT_EOFIELD, 0, 0); + _ipu_dc_link_event(dc_chan, DC_EVT_NEW_CHAN, 0, 0); + _ipu_dc_link_event(dc_chan, DC_EVT_NEW_ADDR, 0, 0); + + reg = 0x2; + reg |= DC_DISP_ID_SYNC(di) << DC_WR_CH_CONF_PROG_DISP_ID_OFFSET; + reg |= di << 2; + if (interlaced) + reg |= DC_WR_CH_CONF_FIELD_MODE; + } else if ((dc_chan == 8) || (dc_chan == 9)) { + /* async channels */ + _ipu_dc_link_event(dc_chan, DC_EVT_NEW_DATA_W_0, 0x64, 1); + _ipu_dc_link_event(dc_chan, DC_EVT_NEW_DATA_W_1, 0x64, 1); + + reg = 0x3; + reg |= DC_DISP_ID_SERIAL << DC_WR_CH_CONF_PROG_DISP_ID_OFFSET; + } + __raw_writel(reg, DC_WR_CH_CONF(dc_chan)); + + __raw_writel(0x00000000, DC_WR_CH_ADDR(dc_chan)); + + __raw_writel(0x00000084, DC_GEN); +} + +void _ipu_dc_uninit(int dc_chan) +{ + if ((dc_chan == 1) || (dc_chan == 5)) { + _ipu_dc_link_event(dc_chan, DC_EVT_NL, 0, 0); + _ipu_dc_link_event(dc_chan, DC_EVT_EOL, 0, 0); + _ipu_dc_link_event(dc_chan, DC_EVT_NEW_DATA, 0, 0); + _ipu_dc_link_event(dc_chan, DC_EVT_NF, 0, 0); + _ipu_dc_link_event(dc_chan, DC_EVT_NFIELD, 0, 0); + _ipu_dc_link_event(dc_chan, DC_EVT_EOF, 0, 0); + _ipu_dc_link_event(dc_chan, DC_EVT_EOFIELD, 0, 0); + _ipu_dc_link_event(dc_chan, DC_EVT_NEW_CHAN, 0, 0); + _ipu_dc_link_event(dc_chan, DC_EVT_NEW_ADDR, 0, 0); + _ipu_dc_link_event(dc_chan, DC_ODD_UGDE0, 0, 0); + _ipu_dc_link_event(dc_chan, DC_EVEN_UGDE0, 0, 0); + _ipu_dc_link_event(dc_chan, DC_ODD_UGDE1, 0, 0); + _ipu_dc_link_event(dc_chan, DC_EVEN_UGDE1, 0, 0); + } else if ((dc_chan == 8) || (dc_chan == 9)) { + _ipu_dc_link_event(dc_chan, DC_EVT_NEW_ADDR_W_0, 0, 0); + _ipu_dc_link_event(dc_chan, DC_EVT_NEW_ADDR_W_1, 0, 0); + _ipu_dc_link_event(dc_chan, DC_EVT_NEW_CHAN_W_0, 0, 0); + _ipu_dc_link_event(dc_chan, DC_EVT_NEW_CHAN_W_1, 0, 0); + _ipu_dc_link_event(dc_chan, DC_EVT_NEW_DATA_W_0, 0, 0); + _ipu_dc_link_event(dc_chan, DC_EVT_NEW_DATA_W_1, 0, 0); + _ipu_dc_link_event(dc_chan, DC_EVT_NEW_ADDR_R_0, 0, 0); + _ipu_dc_link_event(dc_chan, DC_EVT_NEW_ADDR_R_1, 0, 0); + _ipu_dc_link_event(dc_chan, DC_EVT_NEW_CHAN_R_0, 0, 0); + _ipu_dc_link_event(dc_chan, DC_EVT_NEW_CHAN_R_1, 0, 0); + _ipu_dc_link_event(dc_chan, DC_EVT_NEW_DATA_R_0, 0, 0); + _ipu_dc_link_event(dc_chan, DC_EVT_NEW_DATA_R_1, 0, 0); + } +} + +int _ipu_chan_is_interlaced(ipu_channel_t channel) +{ + if (channel == MEM_DC_SYNC) + return !!(__raw_readl(DC_WR_CH_CONF_1) & + DC_WR_CH_CONF_FIELD_MODE); + else if ((channel == MEM_BG_SYNC) || (channel == MEM_FG_SYNC)) + return !!(__raw_readl(DC_WR_CH_CONF_5) & + DC_WR_CH_CONF_FIELD_MODE); + return 0; +} + +void _ipu_dp_dc_enable(ipu_channel_t channel) +{ + int di; + uint32_t reg; + uint32_t dc_chan; + int irq = 0; + + if (channel == MEM_FG_SYNC) + irq = IPU_IRQ_DP_SF_END; + else if (channel == MEM_DC_SYNC) + dc_chan = 1; + else if (channel == MEM_BG_SYNC) + dc_chan = 5; + else + return; + + if (channel == MEM_FG_SYNC) { + /* Enable FG channel */ + reg = __raw_readl(DP_COM_CONF(DP_SYNC)); + __raw_writel(reg | DP_COM_CONF_FG_EN, DP_COM_CONF(DP_SYNC)); + + reg = __raw_readl(IPU_SRM_PRI2) | 0x8; + __raw_writel(reg, IPU_SRM_PRI2); + return; + } + + di = g_dc_di_assignment[dc_chan]; + + /* Make sure other DC sync channel is not assigned same DI */ + reg = __raw_readl(DC_WR_CH_CONF(6 - dc_chan)); + if ((di << 2) == (reg & DC_WR_CH_CONF_PROG_DI_ID)) { + reg &= ~DC_WR_CH_CONF_PROG_DI_ID; + reg |= di ? 0 : DC_WR_CH_CONF_PROG_DI_ID; + __raw_writel(reg, DC_WR_CH_CONF(6 - dc_chan)); + } + + reg = __raw_readl(DC_WR_CH_CONF(dc_chan)); + reg |= 4 << DC_WR_CH_CONF_PROG_TYPE_OFFSET; + __raw_writel(reg, DC_WR_CH_CONF(dc_chan)); + + clk_enable(g_pixel_clk[di]); +} + +static bool dc_swap; + +static irqreturn_t dc_irq_handler(int irq, void *dev_id) +{ + struct completion *comp = dev_id; + + complete(comp); + return IRQ_HANDLED; +} + +void _ipu_dp_dc_disable(ipu_channel_t channel, bool swap) +{ + int ret; + unsigned long lock_flags; + uint32_t reg; + uint32_t csc; + uint32_t dc_chan; + int irq = 0; + int timeout = 50; + DECLARE_COMPLETION_ONSTACK(dc_comp); + + dc_swap = swap; + + if (channel == MEM_DC_SYNC) { + dc_chan = 1; + irq = IPU_IRQ_DC_FC_1; + } else if (channel == MEM_BG_SYNC) { + dc_chan = 5; + irq = IPU_IRQ_DP_SF_END; + } else if (channel == MEM_FG_SYNC) { + /* Disable FG channel */ + dc_chan = 5; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + reg = __raw_readl(DP_COM_CONF(DP_SYNC)); + csc = reg & DP_COM_CONF_CSC_DEF_MASK; + if (csc == DP_COM_CONF_CSC_DEF_FG) + reg &= ~DP_COM_CONF_CSC_DEF_MASK; + + reg &= ~DP_COM_CONF_FG_EN; + __raw_writel(reg, DP_COM_CONF(DP_SYNC)); + + reg = __raw_readl(IPU_SRM_PRI2) | 0x8; + __raw_writel(reg, IPU_SRM_PRI2); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + + __raw_writel(IPUIRQ_2_MASK(IPU_IRQ_DP_SF_END), + IPUIRQ_2_STATREG(IPU_IRQ_DP_SF_END)); + while ((__raw_readl(IPUIRQ_2_STATREG(IPU_IRQ_DP_SF_END)) & + IPUIRQ_2_MASK(IPU_IRQ_DP_SF_END)) == 0) { + msleep(2); + timeout -= 2; + if (timeout <= 0) + break; + } + return; + } else { + return; + } + + if (!dc_swap) + __raw_writel(IPUIRQ_2_MASK(IPU_IRQ_VSYNC_PRE_0 + + g_dc_di_assignment[dc_chan]), + IPUIRQ_2_STATREG(IPU_IRQ_VSYNC_PRE_0 + + g_dc_di_assignment[dc_chan])); + ipu_clear_irq(irq); + ret = ipu_request_irq(irq, dc_irq_handler, 0, NULL, &dc_comp); + if (ret < 0) { + dev_err(g_ipu_dev, "DC irq %d in use\n", irq); + return; + } + ret = wait_for_completion_timeout(&dc_comp, msecs_to_jiffies(50)); + + dev_dbg(g_ipu_dev, "DC stop timeout - %d * 10ms\n", 5 - ret); + ipu_free_irq(irq, &dc_comp); + + if (dc_swap) { + spin_lock_irqsave(&ipu_lock, lock_flags); + /* Swap DC channel 1 and 5 settings, and disable old dc chan */ + reg = __raw_readl(DC_WR_CH_CONF(dc_chan)); + __raw_writel(reg, DC_WR_CH_CONF(6 - dc_chan)); + reg &= ~DC_WR_CH_CONF_PROG_TYPE_MASK; + reg ^= DC_WR_CH_CONF_PROG_DI_ID; + __raw_writel(reg, DC_WR_CH_CONF(dc_chan)); + spin_unlock_irqrestore(&ipu_lock, lock_flags); + } else { + spin_lock_irqsave(&ipu_lock, lock_flags); + reg = __raw_readl(DC_WR_CH_CONF(dc_chan)); + reg &= ~DC_WR_CH_CONF_PROG_TYPE_MASK; + __raw_writel(reg, DC_WR_CH_CONF(dc_chan)); + + reg = __raw_readl(IPU_DISP_GEN); + if (g_dc_di_assignment[dc_chan]) + reg &= ~DI1_COUNTER_RELEASE; + else + reg &= ~DI0_COUNTER_RELEASE; + __raw_writel(reg, IPU_DISP_GEN); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + /* Clock is already off because it must be done quickly, but + we need to fix the ref count */ + clk_disable(g_pixel_clk[g_dc_di_assignment[dc_chan]]); + + if (__raw_readl(IPUIRQ_2_STATREG(IPU_IRQ_VSYNC_PRE_0 + + g_dc_di_assignment[dc_chan])) & + IPUIRQ_2_MASK(IPU_IRQ_VSYNC_PRE_0 + + g_dc_di_assignment[dc_chan])) + dev_dbg(g_ipu_dev, + "VSyncPre occurred before DI%d disable\n", + g_dc_di_assignment[dc_chan]); + } +} + +void _ipu_init_dc_mappings(void) +{ + /* IPU_PIX_FMT_RGB24 */ + _ipu_dc_map_clear(0); + _ipu_dc_map_config(0, 0, 7, 0xFF); + _ipu_dc_map_config(0, 1, 15, 0xFF); + _ipu_dc_map_config(0, 2, 23, 0xFF); + + /* IPU_PIX_FMT_RGB666 */ + _ipu_dc_map_clear(1); + _ipu_dc_map_config(1, 0, 5, 0xFC); + _ipu_dc_map_config(1, 1, 11, 0xFC); + _ipu_dc_map_config(1, 2, 17, 0xFC); + + /* IPU_PIX_FMT_YUV444 */ + _ipu_dc_map_clear(2); + _ipu_dc_map_config(2, 0, 15, 0xFF); + _ipu_dc_map_config(2, 1, 23, 0xFF); + _ipu_dc_map_config(2, 2, 7, 0xFF); + + /* IPU_PIX_FMT_RGB565 */ + _ipu_dc_map_clear(3); + _ipu_dc_map_config(3, 0, 4, 0xF8); + _ipu_dc_map_config(3, 1, 10, 0xFC); + _ipu_dc_map_config(3, 2, 15, 0xF8); + + /* IPU_PIX_FMT_LVDS666 */ + _ipu_dc_map_clear(4); + _ipu_dc_map_config(4, 0, 5, 0xFC); + _ipu_dc_map_config(4, 1, 13, 0xFC); + _ipu_dc_map_config(4, 2, 21, 0xFC); + + /* IPU_PIX_FMT_VYUY 16bit width */ + _ipu_dc_map_clear(5); + _ipu_dc_map_config(5, 0, 7, 0xFF); + _ipu_dc_map_config(5, 1, 0, 0x0); + _ipu_dc_map_config(5, 2, 15, 0xFF); + _ipu_dc_map_clear(6); + _ipu_dc_map_config(6, 0, 0, 0x0); + _ipu_dc_map_config(6, 1, 7, 0xFF); + _ipu_dc_map_config(6, 2, 15, 0xFF); + + /* IPU_PIX_FMT_UYUV 16bit width */ + _ipu_dc_map_clear(7); + _ipu_dc_map_link(7, 6, 0, 6, 1, 6, 2); + _ipu_dc_map_clear(8); + _ipu_dc_map_link(8, 5, 0, 5, 1, 5, 2); + + /* IPU_PIX_FMT_YUYV 16bit width */ + _ipu_dc_map_clear(9); + _ipu_dc_map_link(9, 5, 2, 5, 1, 5, 0); + _ipu_dc_map_clear(10); + _ipu_dc_map_link(10, 5, 1, 5, 2, 5, 0); + + /* IPU_PIX_FMT_YVYU 16bit width */ + _ipu_dc_map_clear(11); + _ipu_dc_map_link(11, 5, 1, 5, 2, 5, 0); + _ipu_dc_map_clear(12); + _ipu_dc_map_link(12, 5, 2, 5, 1, 5, 0); +} + +int _ipu_pixfmt_to_map(uint32_t fmt) +{ + switch (fmt) { + case IPU_PIX_FMT_GENERIC: + case IPU_PIX_FMT_RGB24: + return 0; + case IPU_PIX_FMT_RGB666: + return 1; + case IPU_PIX_FMT_YUV444: + return 2; + case IPU_PIX_FMT_RGB565: + return 3; + case IPU_PIX_FMT_LVDS666: + return 4; + case IPU_PIX_FMT_VYUY: + return 6; + case IPU_PIX_FMT_UYVY: + return 8; + case IPU_PIX_FMT_YUYV: + return 10; + case IPU_PIX_FMT_YVYU: + return 12; + } + + return -1; +} + +/*! + * This function sets the colorspace for of dp. + * modes. + * + * @param channel Input parameter for the logical channel ID. + * + * @param param If it's not NULL, update the csc table + * with this parameter. + * + * @return N/A + */ +void _ipu_dp_set_csc_coefficients(ipu_channel_t channel, int32_t param[][3]) +{ + int dp; + struct dp_csc_param_t dp_csc_param; + + if (channel == MEM_FG_SYNC) + dp = DP_SYNC; + else if (channel == MEM_BG_SYNC) + dp = DP_SYNC; + else if (channel == MEM_BG_ASYNC0) + dp = DP_ASYNC0; + else + return; + + dp_csc_param.mode = -1; + dp_csc_param.coeff = param; + __ipu_dp_csc_setup(dp, dp_csc_param, true); +} + +/*! + * This function is called to adapt synchronous LCD panel to IPU restriction. + * + */ +void adapt_panel_to_ipu_restricitions(uint32_t *pixel_clk, + uint16_t width, uint16_t height, + uint16_t h_start_width, + uint16_t h_end_width, + uint16_t v_start_width, + uint16_t *v_end_width) +{ + if (*v_end_width < 2) { + uint16_t total_width = width + h_start_width + h_end_width; + uint16_t total_height_old = height + v_start_width + (*v_end_width); + uint16_t total_height_new = height + v_start_width + 2; + *v_end_width = 2; + *pixel_clk = (*pixel_clk) * total_width * total_height_new / + (total_width * total_height_old); + dev_err(g_ipu_dev, "WARNING: adapt panel end blank lines\n"); + } +} + +/*! + * This function is called to initialize a synchronous LCD panel. + * + * @param disp The DI the panel is attached to. + * + * @param pixel_clk Desired pixel clock frequency in Hz. + * + * @param pixel_fmt Input parameter for pixel format of buffer. + * Pixel format is a FOURCC ASCII code. + * + * @param width The width of panel in pixels. + * + * @param height The height of panel in pixels. + * + * @param hStartWidth The number of pixel clocks between the HSYNC + * signal pulse and the start of valid data. + * + * @param hSyncWidth The width of the HSYNC signal in units of pixel + * clocks. + * + * @param hEndWidth The number of pixel clocks between the end of + * valid data and the HSYNC signal for next line. + * + * @param vStartWidth The number of lines between the VSYNC + * signal pulse and the start of valid data. + * + * @param vSyncWidth The width of the VSYNC signal in units of lines + * + * @param vEndWidth The number of lines between the end of valid + * data and the VSYNC signal for next frame. + * + * @param sig Bitfield of signal polarities for LCD interface. + * + * @return This function returns 0 on success or negative error code on + * fail. + */ +int32_t ipu_init_sync_panel(int disp, uint32_t pixel_clk, + uint16_t width, uint16_t height, + uint32_t pixel_fmt, + uint16_t h_start_width, uint16_t h_sync_width, + uint16_t h_end_width, uint16_t v_start_width, + uint16_t v_sync_width, uint16_t v_end_width, + uint32_t v_to_h_sync, ipu_di_signal_cfg_t sig) +{ + unsigned long lock_flags; + uint32_t field0_offset = 0; + uint32_t field1_offset; + uint32_t reg; + uint32_t di_gen, vsync_cnt; + uint32_t div, rounded_pixel_clk; + uint32_t h_total, v_total; + int map; + int ipu_freq_scaling_enabled = 0; + struct clk *di_parent; + + dev_dbg(g_ipu_dev, "panel size = %d x %d\n", width, height); + + if ((v_sync_width == 0) || (h_sync_width == 0)) + return EINVAL; + + adapt_panel_to_ipu_restricitions(&pixel_clk, width, height, + h_start_width, h_end_width, + v_start_width, &v_end_width); + h_total = width + h_sync_width + h_start_width + h_end_width; + v_total = height + v_sync_width + v_start_width + v_end_width; + + /* Init clocking */ + dev_dbg(g_ipu_dev, "pixel clk = %d\n", pixel_clk); + + if (sig.ext_clk) { + /* Set the PLL to be an even multiple of the pixel clock. not round div for tvout*/ + if ((clk_get_usecount(g_pixel_clk[0]) == 0) && + (clk_get_usecount(g_pixel_clk[1]) == 0)) { + di_parent = clk_get_parent(g_di_clk[disp]); + if (clk_get(NULL, "tve_clk") != di_parent && + clk_get(NULL, "ldb_di0_clk") != di_parent && + clk_get(NULL, "ldb_di1_clk") != di_parent) { + rounded_pixel_clk = pixel_clk * 2; + while (rounded_pixel_clk < 150000000) + rounded_pixel_clk += pixel_clk * 2; + clk_set_rate(di_parent, rounded_pixel_clk); + clk_set_rate(g_di_clk[disp], pixel_clk); + } + } + clk_set_parent(g_pixel_clk[disp], g_di_clk[disp]); + } else { + if (clk_get_usecount(g_pixel_clk[disp]) != 0) + clk_set_parent(g_pixel_clk[disp], g_ipu_clk); + } + rounded_pixel_clk = clk_round_rate(g_pixel_clk[disp], pixel_clk); + clk_set_rate(g_pixel_clk[disp], rounded_pixel_clk); + msleep(5); + /* Get integer portion of divider */ + div = clk_get_rate(clk_get_parent(g_pixel_clk[disp])) / rounded_pixel_clk; + + ipu_freq_scaling_enabled = dvfs_per_pixel_clk_limit(); + + if (ipu_freq_scaling_enabled) { + /* Enable for a divide by 2 clock change. */ + reg = __raw_readl(IPU_PM); + reg &= ~(0x7f << 7); + reg |= 0x20 << 7; + reg &= ~(0x7f << 23); + reg |= 0x20 << 23; + __raw_writel(reg, IPU_PM); + } + spin_lock_irqsave(&ipu_lock, lock_flags); + + _ipu_di_data_wave_config(disp, SYNC_WAVE, div - 1, div - 1); + _ipu_di_data_pin_config(disp, SYNC_WAVE, DI_PIN15, 3, 0, div * 2); + + map = _ipu_pixfmt_to_map(pixel_fmt); + if (map < 0) { + dev_dbg(g_ipu_dev, "IPU_DISP: No MAP\n"); + spin_unlock_irqrestore(&ipu_lock, lock_flags); + return -EINVAL; + } + + di_gen = __raw_readl(DI_GENERAL(disp)); + + if (sig.interlaced) { + if (g_ipu_hw_rev >= 2) { + /* Setup internal HSYNC waveform */ + _ipu_di_sync_config( + disp, /* display */ + 1, /* counter */ + h_total/2 - 1, /* run count */ + DI_SYNC_CLK, /* run_resolution */ + 0, /* offset */ + DI_SYNC_NONE, /* offset resolution */ + 0, /* repeat count */ + DI_SYNC_NONE, /* CNT_CLR_SEL */ + 0, /* CNT_POLARITY_GEN_EN */ + DI_SYNC_NONE, /* CNT_POLARITY_CLR_SEL */ + DI_SYNC_NONE, /* CNT_POLARITY_TRIGGER_SEL */ + 0, /* COUNT UP */ + 0 /* COUNT DOWN */ + ); + + /* Field 1 VSYNC waveform */ + _ipu_di_sync_config( + disp, /* display */ + 2, /* counter */ + h_total - 1, /* run count */ + DI_SYNC_CLK, /* run_resolution */ + 0, /* offset */ + DI_SYNC_NONE, /* offset resolution */ + 0, /* repeat count */ + DI_SYNC_NONE, /* CNT_CLR_SEL */ + 0, /* CNT_POLARITY_GEN_EN */ + DI_SYNC_NONE, /* CNT_POLARITY_CLR_SEL */ + DI_SYNC_NONE, /* CNT_POLARITY_TRIGGER_SEL */ + 0, /* COUNT UP */ + 4 /* COUNT DOWN */ + ); + + /* Setup internal HSYNC waveform */ + _ipu_di_sync_config( + disp, /* display */ + 3, /* counter */ + v_total*2 - 1, /* run count */ + DI_SYNC_INT_HSYNC, /* run_resolution */ + 1, /* offset */ + DI_SYNC_INT_HSYNC, /* offset resolution */ + 0, /* repeat count */ + DI_SYNC_NONE, /* CNT_CLR_SEL */ + 0, /* CNT_POLARITY_GEN_EN */ + DI_SYNC_NONE, /* CNT_POLARITY_CLR_SEL */ + DI_SYNC_NONE, /* CNT_POLARITY_TRIGGER_SEL */ + 0, /* COUNT UP */ + 4 /* COUNT DOWN */ + ); + + /* Active Field ? */ + _ipu_di_sync_config( + disp, /* display */ + 4, /* counter */ + v_total/2 - 1, /* run count */ + DI_SYNC_HSYNC, /* run_resolution */ + v_start_width, /* offset */ + DI_SYNC_HSYNC, /* offset resolution */ + 2, /* repeat count */ + DI_SYNC_VSYNC, /* CNT_CLR_SEL */ + 0, /* CNT_POLARITY_GEN_EN */ + DI_SYNC_NONE, /* CNT_POLARITY_CLR_SEL */ + DI_SYNC_NONE, /* CNT_POLARITY_TRIGGER_SEL */ + 0, /* COUNT UP */ + 0 /* COUNT DOWN */ + ); + + /* Active Line */ + _ipu_di_sync_config( + disp, /* display */ + 5, /* counter */ + 0, /* run count */ + DI_SYNC_HSYNC, /* run_resolution */ + 0, /* offset */ + DI_SYNC_NONE, /* offset resolution */ + height/2, /* repeat count */ + 4, /* CNT_CLR_SEL */ + 0, /* CNT_POLARITY_GEN_EN */ + DI_SYNC_NONE, /* CNT_POLARITY_CLR_SEL */ + DI_SYNC_NONE, /* CNT_POLARITY_TRIGGER_SEL */ + 0, /* COUNT UP */ + 0 /* COUNT DOWN */ + ); + + /* Field 0 VSYNC waveform */ + _ipu_di_sync_config( + disp, /* display */ + 6, /* counter */ + v_total - 1, /* run count */ + DI_SYNC_HSYNC, /* run_resolution */ + 0, /* offset */ + DI_SYNC_NONE, /* offset resolution */ + 0, /* repeat count */ + DI_SYNC_NONE, /* CNT_CLR_SEL */ + 0, /* CNT_POLARITY_GEN_EN */ + DI_SYNC_NONE, /* CNT_POLARITY_CLR_SEL */ + DI_SYNC_NONE, /* CNT_POLARITY_TRIGGER_SEL */ + 0, /* COUNT UP */ + 0 /* COUNT DOWN */ + ); + + /* DC VSYNC waveform */ + vsync_cnt = 7; + _ipu_di_sync_config( + disp, /* display */ + 7, /* counter */ + v_total/2 - 1, /* run count */ + DI_SYNC_HSYNC, /* run_resolution */ + 9, /* offset */ + DI_SYNC_HSYNC, /* offset resolution */ + 2, /* repeat count */ + DI_SYNC_VSYNC, /* CNT_CLR_SEL */ + 0, /* CNT_POLARITY_GEN_EN */ + DI_SYNC_NONE, /* CNT_POLARITY_CLR_SEL */ + DI_SYNC_NONE, /* CNT_POLARITY_TRIGGER_SEL */ + 0, /* COUNT UP */ + 0 /* COUNT DOWN */ + ); + + /* active pixel waveform */ + _ipu_di_sync_config( + disp, /* display */ + 8, /* counter */ + 0, /* run count */ + DI_SYNC_CLK, /* run_resolution */ + h_start_width, /* offset */ + DI_SYNC_CLK, /* offset resolution */ + width, /* repeat count */ + 5, /* CNT_CLR_SEL */ + 0, /* CNT_POLARITY_GEN_EN */ + DI_SYNC_NONE, /* CNT_POLARITY_CLR_SEL */ + DI_SYNC_NONE, /* CNT_POLARITY_TRIGGER_SEL */ + 0, /* COUNT UP */ + 0 /* COUNT DOWN */ + ); + + /* ??? */ + _ipu_di_sync_config( + disp, /* display */ + 9, /* counter */ + v_total - 1, /* run count */ + DI_SYNC_INT_HSYNC, /* run_resolution */ + v_total/2, /* offset */ + DI_SYNC_INT_HSYNC, /* offset resolution */ + 0, /* repeat count */ + DI_SYNC_HSYNC, /* CNT_CLR_SEL */ + 0, /* CNT_POLARITY_GEN_EN */ + DI_SYNC_NONE, /* CNT_POLARITY_CLR_SEL */ + DI_SYNC_NONE, /* CNT_POLARITY_TRIGGER_SEL */ + 0, /* COUNT UP */ + 4 /* COUNT DOWN */ + ); + + /* set gentime select and tag sel */ + reg = __raw_readl(DI_SW_GEN1(disp, 9)); + reg &= 0x1FFFFFFF; + reg |= (3-1)<<29 | 0x00008000; + __raw_writel(reg, DI_SW_GEN1(disp, 9)); + + __raw_writel(v_total / 2 - 1, DI_SCR_CONF(disp)); + + /* set y_sel = 1 */ + di_gen |= 0x10000000; + di_gen |= DI_GEN_POLARITY_5; + di_gen |= DI_GEN_POLARITY_8; + } else { + /* Setup internal HSYNC waveform */ + _ipu_di_sync_config(disp, 1, h_total - 1, DI_SYNC_CLK, + 0, DI_SYNC_NONE, 0, DI_SYNC_NONE, 0, DI_SYNC_NONE, + DI_SYNC_NONE, 0, 0); + + field1_offset = v_sync_width + v_start_width + height / 2 + + v_end_width; + if (sig.odd_field_first) { + field0_offset = field1_offset - 1; + field1_offset = 0; + } + v_total += v_start_width + v_end_width; + + /* Field 1 VSYNC waveform */ + _ipu_di_sync_config(disp, 2, v_total - 1, 1, + field0_offset, + field0_offset ? 1 : DI_SYNC_NONE, + 0, DI_SYNC_NONE, 0, + DI_SYNC_NONE, DI_SYNC_NONE, 0, 4); + + /* Setup internal HSYNC waveform */ + _ipu_di_sync_config(disp, 3, h_total - 1, DI_SYNC_CLK, + 0, DI_SYNC_NONE, 0, DI_SYNC_NONE, 0, + DI_SYNC_NONE, DI_SYNC_NONE, 0, 4); + + /* Active Field ? */ + _ipu_di_sync_config(disp, 4, + field0_offset ? + field0_offset : field1_offset - 2, + 1, v_start_width + v_sync_width, 1, 2, 2, + 0, DI_SYNC_NONE, DI_SYNC_NONE, 0, 0); + + /* Active Line */ + _ipu_di_sync_config(disp, 5, 0, 1, + 0, DI_SYNC_NONE, + height / 2, 4, 0, DI_SYNC_NONE, + DI_SYNC_NONE, 0, 0); + + /* Field 0 VSYNC waveform */ + _ipu_di_sync_config(disp, 6, v_total - 1, 1, + 0, DI_SYNC_NONE, + 0, DI_SYNC_NONE, 0, DI_SYNC_NONE, + DI_SYNC_NONE, 0, 0); + + /* DC VSYNC waveform */ + vsync_cnt = 7; + _ipu_di_sync_config(disp, 7, 0, 1, + field1_offset, + field1_offset ? 1 : DI_SYNC_NONE, + 1, 2, 0, DI_SYNC_NONE, DI_SYNC_NONE, 0, 0); + + /* active pixel waveform */ + _ipu_di_sync_config(disp, 8, 0, DI_SYNC_CLK, + h_sync_width + h_start_width, DI_SYNC_CLK, + width, 5, 0, DI_SYNC_NONE, DI_SYNC_NONE, + 0, 0); + + /* ??? */ + _ipu_di_sync_config(disp, 9, v_total - 1, 2, + 0, DI_SYNC_NONE, + 0, DI_SYNC_NONE, 6, DI_SYNC_NONE, + DI_SYNC_NONE, 0, 0); + + reg = __raw_readl(DI_SW_GEN1(disp, 9)); + reg |= 0x8000; + __raw_writel(reg, DI_SW_GEN1(disp, 9)); + + __raw_writel(v_sync_width + v_start_width + + v_end_width + height / 2 - 1, DI_SCR_CONF(disp)); + } + + /* Init template microcode */ + _ipu_dc_write_tmpl(0, WROD(0), 0, map, SYNC_WAVE, 0, 8); + + if (sig.Hsync_pol) + di_gen |= DI_GEN_POLARITY_3; + if (sig.Vsync_pol) + di_gen |= DI_GEN_POLARITY_2; + } else { + /* Setup internal HSYNC waveform */ + _ipu_di_sync_config(disp, 1, h_total - 1, DI_SYNC_CLK, + 0, DI_SYNC_NONE, 0, DI_SYNC_NONE, 0, DI_SYNC_NONE, + DI_SYNC_NONE, 0, 0); + + /* Setup external (delayed) HSYNC waveform */ + _ipu_di_sync_config(disp, DI_SYNC_HSYNC, h_total - 1, + DI_SYNC_CLK, div * v_to_h_sync, DI_SYNC_CLK, + 0, DI_SYNC_NONE, 1, DI_SYNC_NONE, + DI_SYNC_CLK, 0, h_sync_width * 2); + /* Setup VSYNC waveform */ + vsync_cnt = DI_SYNC_VSYNC; + _ipu_di_sync_config(disp, DI_SYNC_VSYNC, v_total - 1, + DI_SYNC_INT_HSYNC, 0, DI_SYNC_NONE, 0, + DI_SYNC_NONE, 1, DI_SYNC_NONE, + DI_SYNC_INT_HSYNC, 0, v_sync_width * 2); + __raw_writel(v_total - 1, DI_SCR_CONF(disp)); + + /* Setup active data waveform to sync with DC */ + _ipu_di_sync_config(disp, 4, 0, DI_SYNC_HSYNC, + v_sync_width + v_start_width, DI_SYNC_HSYNC, height, + DI_SYNC_VSYNC, 0, DI_SYNC_NONE, + DI_SYNC_NONE, 0, 0); + _ipu_di_sync_config(disp, 5, 0, DI_SYNC_CLK, + h_sync_width + h_start_width, DI_SYNC_CLK, + width, 4, 0, DI_SYNC_NONE, DI_SYNC_NONE, 0, + 0); + + /* reset all unused counters */ + __raw_writel(0, DI_SW_GEN0(disp, 6)); + __raw_writel(0, DI_SW_GEN1(disp, 6)); + __raw_writel(0, DI_SW_GEN0(disp, 7)); + __raw_writel(0, DI_SW_GEN1(disp, 7)); + __raw_writel(0, DI_SW_GEN0(disp, 8)); + __raw_writel(0, DI_SW_GEN1(disp, 8)); + __raw_writel(0, DI_SW_GEN0(disp, 9)); + __raw_writel(0, DI_SW_GEN1(disp, 9)); + + reg = __raw_readl(DI_STP_REP(disp, 6)); + reg &= 0x0000FFFF; + __raw_writel(reg, DI_STP_REP(disp, 6)); + __raw_writel(0, DI_STP_REP(disp, 7)); + __raw_writel(0, DI_STP_REP(disp, 9)); + + if (ipu_freq_scaling_enabled) { + h_total = ((width + h_start_width + + h_sync_width) / 2) - 2; + _ipu_di_sync_config(disp, 6, 1, 0, + 2, DI_SYNC_CLK, + h_total, + DI_SYNC_INT_HSYNC, 0, DI_SYNC_NONE, + DI_SYNC_NONE, 0, 0); + } + + /* Init template microcode */ + if (disp) { + if ((pixel_fmt == IPU_PIX_FMT_YUYV) || + (pixel_fmt == IPU_PIX_FMT_UYVY) || + (pixel_fmt == IPU_PIX_FMT_YVYU) || + (pixel_fmt == IPU_PIX_FMT_VYUY)) { + _ipu_dc_write_tmpl(8, WROD(0), 0, (map - 1), SYNC_WAVE, 0, 5); + _ipu_dc_write_tmpl(9, WROD(0), 0, map, SYNC_WAVE, 0, 5); + /* configure user events according to DISP NUM */ + __raw_writel((width - 1), DC_UGDE_3(disp)); + } + _ipu_dc_write_tmpl(2, WROD(0), 0, map, SYNC_WAVE, 8, 5); + _ipu_dc_write_tmpl(3, WROD(0), 0, map, SYNC_WAVE, 4, 5); + _ipu_dc_write_tmpl(4, WROD(0), 0, map, SYNC_WAVE, 0, 5); + } else { + if ((pixel_fmt == IPU_PIX_FMT_YUYV) || + (pixel_fmt == IPU_PIX_FMT_UYVY) || + (pixel_fmt == IPU_PIX_FMT_YVYU) || + (pixel_fmt == IPU_PIX_FMT_VYUY)) { + _ipu_dc_write_tmpl(10, WROD(0), 0, (map - 1), SYNC_WAVE, 0, 5); + _ipu_dc_write_tmpl(11, WROD(0), 0, map, SYNC_WAVE, 0, 5); + /* configure user events according to DISP NUM */ + __raw_writel(width - 1, DC_UGDE_3(disp)); + } + _ipu_dc_write_tmpl(5, WROD(0), 0, map, SYNC_WAVE, 8, 5); + _ipu_dc_write_tmpl(6, WROD(0), 0, map, SYNC_WAVE, 4, 5); + _ipu_dc_write_tmpl(7, WROD(0), 0, map, SYNC_WAVE, 0, 5); + } + + if (sig.Hsync_pol) + di_gen |= DI_GEN_POLARITY_2; + if (sig.Vsync_pol) + di_gen |= DI_GEN_POLARITY_3; + + if (ipu_freq_scaling_enabled) + /* Set the clock to stop at counter 6. */ + di_gen |= 0x6000000; + } + /* changinc DISP_CLK polarity: it can be wrong for some applications */ + if ((pixel_fmt == IPU_PIX_FMT_YUYV) || + (pixel_fmt == IPU_PIX_FMT_UYVY) || + (pixel_fmt == IPU_PIX_FMT_YVYU) || + (pixel_fmt == IPU_PIX_FMT_VYUY)) + di_gen |= 0x00020000; + + __raw_writel(di_gen, DI_GENERAL(disp)); + + if (!ipu_freq_scaling_enabled) + __raw_writel((--vsync_cnt << DI_VSYNC_SEL_OFFSET) | + 0x00000002, DI_SYNC_AS_GEN(disp)); + else { + if (sig.interlaced) + __raw_writel((--vsync_cnt << DI_VSYNC_SEL_OFFSET) | + 0x00000002, DI_SYNC_AS_GEN(disp)); + else + __raw_writel((--vsync_cnt << DI_VSYNC_SEL_OFFSET), + DI_SYNC_AS_GEN(disp)); + } + + reg = __raw_readl(DI_POL(disp)); + reg &= ~(DI_POL_DRDY_DATA_POLARITY | DI_POL_DRDY_POLARITY_15); + if (sig.enable_pol) + reg |= DI_POL_DRDY_POLARITY_15; + if (sig.data_pol) + reg |= DI_POL_DRDY_DATA_POLARITY; + __raw_writel(reg, DI_POL(disp)); + + __raw_writel(width, DC_DISP_CONF2(DC_DISP_ID_SYNC(disp))); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + + return 0; +} +EXPORT_SYMBOL(ipu_init_sync_panel); + + +int ipu_init_async_panel(int disp, int type, uint32_t cycle_time, + uint32_t pixel_fmt, ipu_adc_sig_cfg_t sig) +{ + unsigned long lock_flags; + int map; + u32 ser_conf = 0; + u32 div; + u32 di_clk = clk_get_rate(g_ipu_clk); + + /* round up cycle_time, then calcalate the divider using scaled math */ + cycle_time += (1000000000UL / di_clk) - 1; + div = (cycle_time * (di_clk / 256UL)) / (1000000000UL / 256UL); + + map = _ipu_pixfmt_to_map(pixel_fmt); + if (map < 0) + return -EINVAL; + + spin_lock_irqsave(&ipu_lock, lock_flags); + + if (type == IPU_PANEL_SERIAL) { + __raw_writel((div << 24) | ((sig.ifc_width - 1) << 4), + DI_DW_GEN(disp, ASYNC_SER_WAVE)); + + _ipu_di_data_pin_config(disp, ASYNC_SER_WAVE, DI_PIN_CS, + 0, 0, (div * 2) + 1); + _ipu_di_data_pin_config(disp, ASYNC_SER_WAVE, DI_PIN_SER_CLK, + 1, div, div * 2); + _ipu_di_data_pin_config(disp, ASYNC_SER_WAVE, DI_PIN_SER_RS, + 2, 0, 0); + + _ipu_dc_write_tmpl(0x64, WROD(0), 0, map, ASYNC_SER_WAVE, 0, 0); + + /* Configure DC for serial panel */ + __raw_writel(0x14, DC_DISP_CONF1(DC_DISP_ID_SERIAL)); + + if (sig.clk_pol) + ser_conf |= DI_SER_CONF_SERIAL_CLK_POL; + if (sig.data_pol) + ser_conf |= DI_SER_CONF_SERIAL_DATA_POL; + if (sig.rs_pol) + ser_conf |= DI_SER_CONF_SERIAL_RS_POL; + if (sig.cs_pol) + ser_conf |= DI_SER_CONF_SERIAL_CS_POL; + __raw_writel(ser_conf, DI_SER_CONF(disp)); + } + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + return 0; +} +EXPORT_SYMBOL(ipu_init_async_panel); + +/*! + * This function sets the foreground and background plane global alpha blending + * modes. This function also sets the DP graphic plane according to the + * parameter of IPUv3 DP channel. + * + * @param channel IPUv3 DP channel + * + * @param enable Boolean to enable or disable global alpha + * blending. If disabled, local blending is used. + * + * @param alpha Global alpha value. + * + * @return Returns 0 on success or negative error code on fail + */ +int32_t ipu_disp_set_global_alpha(ipu_channel_t channel, bool enable, + uint8_t alpha) +{ + uint32_t reg; + uint32_t flow; + unsigned long lock_flags; + bool bg_chan; + + if (channel == MEM_BG_SYNC || channel == MEM_FG_SYNC) + flow = DP_SYNC; + else if (channel == MEM_BG_ASYNC0 || channel == MEM_FG_ASYNC0) + flow = DP_ASYNC0; + else if (channel == MEM_BG_ASYNC1 || channel == MEM_FG_ASYNC1) + flow = DP_ASYNC1; + else + return -EINVAL; + + if (channel == MEM_BG_SYNC || channel == MEM_BG_ASYNC0 || + channel == MEM_BG_ASYNC1) + bg_chan = true; + else + bg_chan = false; + + if (!g_ipu_clk_enabled) + clk_enable(g_ipu_clk); + spin_lock_irqsave(&ipu_lock, lock_flags); + + if (bg_chan) { + reg = __raw_readl(DP_COM_CONF(flow)); + __raw_writel(reg & ~DP_COM_CONF_GWSEL, DP_COM_CONF(flow)); + } else { + reg = __raw_readl(DP_COM_CONF(flow)); + __raw_writel(reg | DP_COM_CONF_GWSEL, DP_COM_CONF(flow)); + } + + if (enable) { + reg = __raw_readl(DP_GRAPH_WIND_CTRL(flow)) & 0x00FFFFFFL; + __raw_writel(reg | ((uint32_t) alpha << 24), + DP_GRAPH_WIND_CTRL(flow)); + + reg = __raw_readl(DP_COM_CONF(flow)); + __raw_writel(reg | DP_COM_CONF_GWAM, DP_COM_CONF(flow)); + } else { + reg = __raw_readl(DP_COM_CONF(flow)); + __raw_writel(reg & ~DP_COM_CONF_GWAM, DP_COM_CONF(flow)); + } + + reg = __raw_readl(IPU_SRM_PRI2) | 0x8; + __raw_writel(reg, IPU_SRM_PRI2); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + if (!g_ipu_clk_enabled) + clk_disable(g_ipu_clk); + + return 0; +} +EXPORT_SYMBOL(ipu_disp_set_global_alpha); + +/*! + * This function sets the transparent color key for SDC graphic plane. + * + * @param channel Input parameter for the logical channel ID. + * + * @param enable Boolean to enable or disable color key + * + * @param colorKey 24-bit RGB color for transparent color key. + * + * @return Returns 0 on success or negative error code on fail + */ +int32_t ipu_disp_set_color_key(ipu_channel_t channel, bool enable, + uint32_t color_key) +{ + uint32_t reg, flow; + int y, u, v; + int red, green, blue; + unsigned long lock_flags; + + if (channel == MEM_BG_SYNC || channel == MEM_FG_SYNC) + flow = DP_SYNC; + else if (channel == MEM_BG_ASYNC0 || channel == MEM_FG_ASYNC0) + flow = DP_ASYNC0; + else if (channel == MEM_BG_ASYNC1 || channel == MEM_FG_ASYNC1) + flow = DP_ASYNC1; + else + return -EINVAL; + + if (!g_ipu_clk_enabled) + clk_enable(g_ipu_clk); + + spin_lock_irqsave(&ipu_lock, lock_flags); + + color_key_4rgb = 1; + /* Transform color key from rgb to yuv if CSC is enabled */ + if (((fg_csc_type == RGB2YUV) && (bg_csc_type == YUV2YUV)) || + ((fg_csc_type == YUV2YUV) && (bg_csc_type == RGB2YUV)) || + ((fg_csc_type == YUV2YUV) && (bg_csc_type == YUV2YUV)) || + ((fg_csc_type == YUV2RGB) && (bg_csc_type == YUV2RGB))) { + + dev_dbg(g_ipu_dev, "color key 0x%x need change to yuv fmt\n", color_key); + + red = (color_key >> 16) & 0xFF; + green = (color_key >> 8) & 0xFF; + blue = color_key & 0xFF; + + y = _rgb_to_yuv(0, red, green, blue); + u = _rgb_to_yuv(1, red, green, blue); + v = _rgb_to_yuv(2, red, green, blue); + color_key = (y << 16) | (u << 8) | v; + + color_key_4rgb = 0; + + dev_dbg(g_ipu_dev, "color key change to yuv fmt 0x%x\n", color_key); + } + + if (enable) { + reg = __raw_readl(DP_GRAPH_WIND_CTRL(flow)) & 0xFF000000L; + __raw_writel(reg | color_key, DP_GRAPH_WIND_CTRL(flow)); + + reg = __raw_readl(DP_COM_CONF(flow)); + __raw_writel(reg | DP_COM_CONF_GWCKE, DP_COM_CONF(flow)); + } else { + reg = __raw_readl(DP_COM_CONF(flow)); + __raw_writel(reg & ~DP_COM_CONF_GWCKE, DP_COM_CONF(flow)); + } + + reg = __raw_readl(IPU_SRM_PRI2) | 0x8; + __raw_writel(reg, IPU_SRM_PRI2); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + if (!g_ipu_clk_enabled) + clk_disable(g_ipu_clk); + + return 0; +} +EXPORT_SYMBOL(ipu_disp_set_color_key); + +/*! + * This function sets the gamma correction for DP output. + * + * @param channel Input parameter for the logical channel ID. + * + * @param enable Boolean to enable or disable gamma correction. + * + * @param constk Gamma piecewise linear approximation constk coeff. + * + * @param slopek Gamma piecewise linear approximation slopek coeff. + * + * @return Returns 0 on success or negative error code on fail + */ +int32_t ipu_disp_set_gamma_correction(ipu_channel_t channel, bool enable, int constk[], int slopek[]) +{ + uint32_t reg, flow, i; + unsigned long lock_flags; + + if (channel == MEM_BG_SYNC || channel == MEM_FG_SYNC) + flow = DP_SYNC; + else if (channel == MEM_BG_ASYNC0 || channel == MEM_FG_ASYNC0) + flow = DP_ASYNC0; + else if (channel == MEM_BG_ASYNC1 || channel == MEM_FG_ASYNC1) + flow = DP_ASYNC1; + else + return -EINVAL; + + if (!g_ipu_clk_enabled) + clk_enable(g_ipu_clk); + spin_lock_irqsave(&ipu_lock, lock_flags); + + for (i = 0; i < 8; i++) + __raw_writel((constk[2*i] & 0x1ff) | ((constk[2*i+1] & 0x1ff) << 16), DP_GAMMA_C(flow, i)); + for (i = 0; i < 4; i++) + __raw_writel((slopek[4*i] & 0xff) | ((slopek[4*i+1] & 0xff) << 8) | + ((slopek[4*i+2] & 0xff) << 16) | ((slopek[4*i+3] & 0xff) << 24), DP_GAMMA_S(flow, i)); + + reg = __raw_readl(DP_COM_CONF(flow)); + if (enable) { + if ((bg_csc_type == RGB2YUV) || (bg_csc_type == YUV2YUV)) + reg |= DP_COM_CONF_GAMMA_YUV_EN; + else + reg &= ~DP_COM_CONF_GAMMA_YUV_EN; + __raw_writel(reg | DP_COM_CONF_GAMMA_EN, DP_COM_CONF(flow)); + } else + __raw_writel(reg & ~DP_COM_CONF_GAMMA_EN, DP_COM_CONF(flow)); + + reg = __raw_readl(IPU_SRM_PRI2) | 0x8; + __raw_writel(reg, IPU_SRM_PRI2); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + if (!g_ipu_clk_enabled) + clk_disable(g_ipu_clk); + + return 0; +} +EXPORT_SYMBOL(ipu_disp_set_gamma_correction); + +/*! + * This function sets the window position of the foreground or background plane. + * modes. + * + * @param channel Input parameter for the logical channel ID. + * + * @param x_pos The X coordinate position to place window at. + * The position is relative to the top left corner. + * + * @param y_pos The Y coordinate position to place window at. + * The position is relative to the top left corner. + * + * @return Returns 0 on success or negative error code on fail + */ +int32_t ipu_disp_set_window_pos(ipu_channel_t channel, int16_t x_pos, + int16_t y_pos) +{ + u32 reg; + unsigned long lock_flags; + uint32_t flow = 0; + + if (channel == MEM_FG_SYNC) + flow = DP_SYNC; + else if (channel == MEM_FG_ASYNC0) + flow = DP_ASYNC0; + else if (channel == MEM_FG_ASYNC1) + flow = DP_ASYNC1; + else + return -EINVAL; + + if (!g_ipu_clk_enabled) + clk_enable(g_ipu_clk); + + spin_lock_irqsave(&ipu_lock, lock_flags); + + __raw_writel((x_pos << 16) | y_pos, DP_FG_POS(flow)); + + reg = __raw_readl(IPU_SRM_PRI2) | 0x8; + __raw_writel(reg, IPU_SRM_PRI2); + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + if (!g_ipu_clk_enabled) + clk_disable(g_ipu_clk); + + return 0; +} +EXPORT_SYMBOL(ipu_disp_set_window_pos); + +int32_t ipu_disp_get_window_pos(ipu_channel_t channel, int16_t *x_pos, + int16_t *y_pos) +{ + u32 reg; + unsigned long lock_flags; + uint32_t flow = 0; + + if (channel == MEM_FG_SYNC) + flow = DP_SYNC; + else if (channel == MEM_FG_ASYNC0) + flow = DP_ASYNC0; + else if (channel == MEM_FG_ASYNC1) + flow = DP_ASYNC1; + else + return -EINVAL; + + if (!g_ipu_clk_enabled) + clk_enable(g_ipu_clk); + spin_lock_irqsave(&ipu_lock, lock_flags); + + reg = __raw_readl(DP_FG_POS(flow)); + + *x_pos = (reg >> 16) & 0x7FF; + *y_pos = reg & 0x7FF; + + spin_unlock_irqrestore(&ipu_lock, lock_flags); + if (!g_ipu_clk_enabled) + clk_disable(g_ipu_clk); + + return 0; +} +EXPORT_SYMBOL(ipu_disp_get_window_pos); + +void ipu_disp_direct_write(ipu_channel_t channel, u32 value, u32 offset) +{ + if (channel == DIRECT_ASYNC0) + __raw_writel(value, ipu_disp_base[0] + offset); + else if (channel == DIRECT_ASYNC1) + __raw_writel(value, ipu_disp_base[1] + offset); +} +EXPORT_SYMBOL(ipu_disp_direct_write); + +void ipu_reset_disp_panel(void) +{ + uint32_t tmp; + + tmp = __raw_readl(DI_GENERAL(1)); + __raw_writel(tmp | 0x08, DI_GENERAL(1)); + msleep(10); /* tRES >= 100us */ + tmp = __raw_readl(DI_GENERAL(1)); + __raw_writel(tmp & ~0x08, DI_GENERAL(1)); + msleep(60); + + return; +} +EXPORT_SYMBOL(ipu_reset_disp_panel); diff --git a/drivers/mxc/ipu3/ipu_ic.c b/drivers/mxc/ipu3/ipu_ic.c new file mode 100644 index 000000000000..8bb28c929620 --- /dev/null +++ b/drivers/mxc/ipu3/ipu_ic.c @@ -0,0 +1,826 @@ +/* + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/* + * @file ipu_ic.c + * + * @brief IPU IC functions + * + * @ingroup IPU + */ +#include +#include +#include +#include +#include +#include +#include + +#include "ipu_prv.h" +#include "ipu_regs.h" +#include "ipu_param_mem.h" + +enum { + IC_TASK_VIEWFINDER, + IC_TASK_ENCODER, + IC_TASK_POST_PROCESSOR +}; + +static void _init_csc(uint8_t ic_task, ipu_color_space_t in_format, + ipu_color_space_t out_format, int csc_index); +static bool _calc_resize_coeffs(uint32_t inSize, uint32_t outSize, + uint32_t *resizeCoeff, + uint32_t *downsizeCoeff); + +void _ipu_vdi_set_top_field_man(bool top_field_0) +{ + uint32_t reg; + + reg = __raw_readl(VDI_C); + if (top_field_0) + reg &= ~VDI_C_TOP_FIELD_MAN_1; + else + reg |= VDI_C_TOP_FIELD_MAN_1; + __raw_writel(reg, VDI_C); +} + +void _ipu_vdi_set_motion(ipu_motion_sel motion_sel) +{ + uint32_t reg; + + reg = __raw_readl(VDI_C); + reg &= ~(VDI_C_MOT_SEL_FULL | VDI_C_MOT_SEL_MED | VDI_C_MOT_SEL_LOW); + if (motion_sel == HIGH_MOTION) + reg |= VDI_C_MOT_SEL_FULL; + else if (motion_sel == MED_MOTION) + reg |= VDI_C_MOT_SEL_MED; + else + reg |= VDI_C_MOT_SEL_LOW; + + __raw_writel(reg, VDI_C); +} + +void ic_dump_register(void) +{ + printk(KERN_DEBUG "IC_CONF = \t0x%08X\n", __raw_readl(IC_CONF)); + printk(KERN_DEBUG "IC_PRP_ENC_RSC = \t0x%08X\n", + __raw_readl(IC_PRP_ENC_RSC)); + printk(KERN_DEBUG "IC_PRP_VF_RSC = \t0x%08X\n", + __raw_readl(IC_PRP_VF_RSC)); + printk(KERN_DEBUG "IC_PP_RSC = \t0x%08X\n", __raw_readl(IC_PP_RSC)); + printk(KERN_DEBUG "IC_IDMAC_1 = \t0x%08X\n", __raw_readl(IC_IDMAC_1)); + printk(KERN_DEBUG "IC_IDMAC_2 = \t0x%08X\n", __raw_readl(IC_IDMAC_2)); + printk(KERN_DEBUG "IC_IDMAC_3 = \t0x%08X\n", __raw_readl(IC_IDMAC_3)); +} + +void _ipu_ic_enable_task(ipu_channel_t channel) +{ + uint32_t ic_conf; + + ic_conf = __raw_readl(IC_CONF); + switch (channel) { + case CSI_PRP_VF_MEM: + case MEM_PRP_VF_MEM: + ic_conf |= IC_CONF_PRPVF_EN; + break; + case MEM_VDI_PRP_VF_MEM: + ic_conf |= IC_CONF_PRPVF_EN; + break; + case MEM_ROT_VF_MEM: + ic_conf |= IC_CONF_PRPVF_ROT_EN; + break; + case CSI_PRP_ENC_MEM: + case MEM_PRP_ENC_MEM: + ic_conf |= IC_CONF_PRPENC_EN; + break; + case MEM_ROT_ENC_MEM: + ic_conf |= IC_CONF_PRPENC_ROT_EN; + break; + case MEM_PP_MEM: + ic_conf |= IC_CONF_PP_EN; + break; + case MEM_ROT_PP_MEM: + ic_conf |= IC_CONF_PP_ROT_EN; + break; + default: + break; + } + __raw_writel(ic_conf, IC_CONF); +} + +void _ipu_ic_disable_task(ipu_channel_t channel) +{ + uint32_t ic_conf; + + ic_conf = __raw_readl(IC_CONF); + switch (channel) { + case CSI_PRP_VF_MEM: + case MEM_PRP_VF_MEM: + ic_conf &= ~IC_CONF_PRPVF_EN; + break; + case MEM_VDI_PRP_VF_MEM: + ic_conf &= ~IC_CONF_PRPVF_EN; + break; + case MEM_ROT_VF_MEM: + ic_conf &= ~IC_CONF_PRPVF_ROT_EN; + break; + case CSI_PRP_ENC_MEM: + case MEM_PRP_ENC_MEM: + ic_conf &= ~IC_CONF_PRPENC_EN; + break; + case MEM_ROT_ENC_MEM: + ic_conf &= ~IC_CONF_PRPENC_ROT_EN; + break; + case MEM_PP_MEM: + ic_conf &= ~IC_CONF_PP_EN; + break; + case MEM_ROT_PP_MEM: + ic_conf &= ~IC_CONF_PP_ROT_EN; + break; + default: + break; + } + __raw_writel(ic_conf, IC_CONF); +} + +void _ipu_vdi_init(ipu_channel_t channel, ipu_channel_params_t *params) +{ + uint32_t reg; + uint32_t pixel_fmt; + + reg = ((params->mem_prp_vf_mem.in_height-1) << 16) | + (params->mem_prp_vf_mem.in_width-1); + __raw_writel(reg, VDI_FSIZE); + + /* Full motion, only vertical filter is used + Burst size is 4 accesses */ + pixel_fmt = + (params->mem_prp_vf_mem.in_pixel_fmt == + V4L2_PIX_FMT_YUV422P) ? VDI_C_CH_422 : VDI_C_CH_420; + + reg = __raw_readl(VDI_C); + reg |= pixel_fmt; + switch (channel) { + case MEM_VDI_PRP_VF_MEM: + reg |= VDI_C_BURST_SIZE2_4; + break; + case MEM_VDI_PRP_VF_MEM_P: + reg |= VDI_C_BURST_SIZE1_4 | VDI_C_VWM1_SET_1 | VDI_C_VWM1_CLR_2; + break; + case MEM_VDI_PRP_VF_MEM_N: + reg |= VDI_C_BURST_SIZE3_4 | VDI_C_VWM3_SET_1 | VDI_C_VWM3_CLR_2; + break; + default: + break; + } + __raw_writel(reg, VDI_C); + + _ipu_vdi_set_top_field_man(false); + + _ipu_vdi_set_motion(params->mem_prp_vf_mem.motion_sel); + + reg = __raw_readl(IC_CONF); + reg &= ~IC_CONF_RWS_EN; + __raw_writel(reg, IC_CONF); +} + +void _ipu_vdi_uninit(void) +{ + __raw_writel(0, VDI_FSIZE); + __raw_writel(0, VDI_C); +} + +void _ipu_ic_init_prpvf(ipu_channel_params_t *params, bool src_is_csi) +{ + uint32_t reg, ic_conf; + uint32_t downsizeCoeff, resizeCoeff; + ipu_color_space_t in_fmt, out_fmt; + + /* Setup vertical resizing */ + _calc_resize_coeffs(params->mem_prp_vf_mem.in_height, + params->mem_prp_vf_mem.out_height, + &resizeCoeff, &downsizeCoeff); + reg = (downsizeCoeff << 30) | (resizeCoeff << 16); + + /* Setup horizontal resizing */ + /* Upadeted for IC split case */ + if (!(params->mem_prp_vf_mem.outh_resize_ratio)) { + _calc_resize_coeffs(params->mem_prp_vf_mem.in_width, + params->mem_prp_vf_mem.out_width, + &resizeCoeff, &downsizeCoeff); + reg |= (downsizeCoeff << 14) | resizeCoeff; + } else + reg |= params->mem_prp_vf_mem.outh_resize_ratio; + + __raw_writel(reg, IC_PRP_VF_RSC); + + ic_conf = __raw_readl(IC_CONF); + + /* Setup color space conversion */ + in_fmt = format_to_colorspace(params->mem_prp_vf_mem.in_pixel_fmt); + out_fmt = format_to_colorspace(params->mem_prp_vf_mem.out_pixel_fmt); + if (in_fmt == RGB) { + if ((out_fmt == YCbCr) || (out_fmt == YUV)) { + /* Enable RGB->YCBCR CSC1 */ + _init_csc(IC_TASK_VIEWFINDER, RGB, out_fmt, 1); + ic_conf |= IC_CONF_PRPVF_CSC1; + } + } + if ((in_fmt == YCbCr) || (in_fmt == YUV)) { + if (out_fmt == RGB) { + /* Enable YCBCR->RGB CSC1 */ + _init_csc(IC_TASK_VIEWFINDER, YCbCr, RGB, 1); + ic_conf |= IC_CONF_PRPVF_CSC1; + } else { + /* TODO: Support YUV<->YCbCr conversion? */ + } + } + + if (params->mem_prp_vf_mem.graphics_combine_en) { + ic_conf |= IC_CONF_PRPVF_CMB; + + if (!(ic_conf & IC_CONF_PRPVF_CSC1)) { + /* need transparent CSC1 conversion */ + _init_csc(IC_TASK_VIEWFINDER, RGB, RGB, 1); + ic_conf |= IC_CONF_PRPVF_CSC1; /* Enable RGB->RGB CSC */ + } + in_fmt = format_to_colorspace(params->mem_prp_vf_mem.in_g_pixel_fmt); + out_fmt = format_to_colorspace(params->mem_prp_vf_mem.out_pixel_fmt); + if (in_fmt == RGB) { + if ((out_fmt == YCbCr) || (out_fmt == YUV)) { + /* Enable RGB->YCBCR CSC2 */ + _init_csc(IC_TASK_VIEWFINDER, RGB, out_fmt, 2); + ic_conf |= IC_CONF_PRPVF_CSC2; + } + } + if ((in_fmt == YCbCr) || (in_fmt == YUV)) { + if (out_fmt == RGB) { + /* Enable YCBCR->RGB CSC2 */ + _init_csc(IC_TASK_VIEWFINDER, YCbCr, RGB, 2); + ic_conf |= IC_CONF_PRPVF_CSC2; + } else { + /* TODO: Support YUV<->YCbCr conversion? */ + } + } + + if (params->mem_prp_vf_mem.global_alpha_en) { + ic_conf |= IC_CONF_IC_GLB_LOC_A; + reg = __raw_readl(IC_CMBP_1); + reg &= ~(0xff); + reg |= params->mem_prp_vf_mem.alpha; + __raw_writel(reg, IC_CMBP_1); + } else + ic_conf &= ~IC_CONF_IC_GLB_LOC_A; + + if (params->mem_prp_vf_mem.key_color_en) { + ic_conf |= IC_CONF_KEY_COLOR_EN; + __raw_writel(params->mem_prp_vf_mem.key_color, + IC_CMBP_2); + } else + ic_conf &= ~IC_CONF_KEY_COLOR_EN; + } else { + ic_conf &= ~IC_CONF_PRPVF_CMB; + } + + if (src_is_csi) + ic_conf &= ~IC_CONF_RWS_EN; + else + ic_conf |= IC_CONF_RWS_EN; + + __raw_writel(ic_conf, IC_CONF); +} + +void _ipu_ic_uninit_prpvf(void) +{ + uint32_t reg; + + reg = __raw_readl(IC_CONF); + reg &= ~(IC_CONF_PRPVF_EN | IC_CONF_PRPVF_CMB | + IC_CONF_PRPVF_CSC2 | IC_CONF_PRPVF_CSC1); + __raw_writel(reg, IC_CONF); +} + +void _ipu_ic_init_rotate_vf(ipu_channel_params_t *params) +{ +} + +void _ipu_ic_uninit_rotate_vf(void) +{ + uint32_t reg; + reg = __raw_readl(IC_CONF); + reg &= ~IC_CONF_PRPVF_ROT_EN; + __raw_writel(reg, IC_CONF); +} + +void _ipu_ic_init_prpenc(ipu_channel_params_t *params, bool src_is_csi) +{ + uint32_t reg, ic_conf; + uint32_t downsizeCoeff, resizeCoeff; + ipu_color_space_t in_fmt, out_fmt; + + /* Setup vertical resizing */ + _calc_resize_coeffs(params->mem_prp_enc_mem.in_height, + params->mem_prp_enc_mem.out_height, + &resizeCoeff, &downsizeCoeff); + reg = (downsizeCoeff << 30) | (resizeCoeff << 16); + + /* Setup horizontal resizing */ + /* Upadeted for IC split case */ + if (!(params->mem_prp_enc_mem.outh_resize_ratio)) { + _calc_resize_coeffs(params->mem_prp_enc_mem.in_width, + params->mem_prp_enc_mem.out_width, + &resizeCoeff, &downsizeCoeff); + reg |= (downsizeCoeff << 14) | resizeCoeff; + } else + reg |= params->mem_prp_enc_mem.outh_resize_ratio; + + __raw_writel(reg, IC_PRP_ENC_RSC); + + ic_conf = __raw_readl(IC_CONF); + + /* Setup color space conversion */ + in_fmt = format_to_colorspace(params->mem_prp_enc_mem.in_pixel_fmt); + out_fmt = format_to_colorspace(params->mem_prp_enc_mem.out_pixel_fmt); + if (in_fmt == RGB) { + if ((out_fmt == YCbCr) || (out_fmt == YUV)) { + /* Enable RGB->YCBCR CSC1 */ + _init_csc(IC_TASK_ENCODER, RGB, out_fmt, 1); + ic_conf |= IC_CONF_PRPENC_CSC1; + } + } + if ((in_fmt == YCbCr) || (in_fmt == YUV)) { + if (out_fmt == RGB) { + /* Enable YCBCR->RGB CSC1 */ + _init_csc(IC_TASK_ENCODER, YCbCr, RGB, 1); + ic_conf |= IC_CONF_PRPENC_CSC1; + } else { + /* TODO: Support YUV<->YCbCr conversion? */ + } + } + + if (src_is_csi) + ic_conf &= ~IC_CONF_RWS_EN; + else + ic_conf |= IC_CONF_RWS_EN; + + __raw_writel(ic_conf, IC_CONF); +} + +void _ipu_ic_uninit_prpenc(void) +{ + uint32_t reg; + + reg = __raw_readl(IC_CONF); + reg &= ~(IC_CONF_PRPENC_EN | IC_CONF_PRPENC_CSC1); + __raw_writel(reg, IC_CONF); +} + +void _ipu_ic_init_rotate_enc(ipu_channel_params_t *params) +{ +} + +void _ipu_ic_uninit_rotate_enc(void) +{ + uint32_t reg; + + reg = __raw_readl(IC_CONF); + reg &= ~(IC_CONF_PRPENC_ROT_EN); + __raw_writel(reg, IC_CONF); +} + +void _ipu_ic_init_pp(ipu_channel_params_t *params) +{ + uint32_t reg, ic_conf; + uint32_t downsizeCoeff, resizeCoeff; + ipu_color_space_t in_fmt, out_fmt; + + /* Setup vertical resizing */ + if (!(params->mem_pp_mem.outv_resize_ratio)) { + _calc_resize_coeffs(params->mem_pp_mem.in_height, + params->mem_pp_mem.out_height, + &resizeCoeff, &downsizeCoeff); + reg = (downsizeCoeff << 30) | (resizeCoeff << 16); + } else { + reg = (params->mem_pp_mem.outv_resize_ratio) << 16; + } + + /* Setup horizontal resizing */ + /* Upadeted for IC split case */ + if (!(params->mem_pp_mem.outh_resize_ratio)) { + _calc_resize_coeffs(params->mem_pp_mem.in_width, + params->mem_pp_mem.out_width, + &resizeCoeff, &downsizeCoeff); + reg |= (downsizeCoeff << 14) | resizeCoeff; + } else { + reg |= params->mem_pp_mem.outh_resize_ratio; + } + + __raw_writel(reg, IC_PP_RSC); + + ic_conf = __raw_readl(IC_CONF); + + /* Setup color space conversion */ + in_fmt = format_to_colorspace(params->mem_pp_mem.in_pixel_fmt); + out_fmt = format_to_colorspace(params->mem_pp_mem.out_pixel_fmt); + if (in_fmt == RGB) { + if ((out_fmt == YCbCr) || (out_fmt == YUV)) { + /* Enable RGB->YCBCR CSC1 */ + _init_csc(IC_TASK_POST_PROCESSOR, RGB, out_fmt, 1); + ic_conf |= IC_CONF_PP_CSC1; + } + } + if ((in_fmt == YCbCr) || (in_fmt == YUV)) { + if (out_fmt == RGB) { + /* Enable YCBCR->RGB CSC1 */ + _init_csc(IC_TASK_POST_PROCESSOR, YCbCr, RGB, 1); + ic_conf |= IC_CONF_PP_CSC1; + } else { + /* TODO: Support YUV<->YCbCr conversion? */ + } + } + + if (params->mem_pp_mem.graphics_combine_en) { + ic_conf |= IC_CONF_PP_CMB; + + if (!(ic_conf & IC_CONF_PP_CSC1)) { + /* need transparent CSC1 conversion */ + _init_csc(IC_TASK_POST_PROCESSOR, RGB, RGB, 1); + ic_conf |= IC_CONF_PP_CSC1; /* Enable RGB->RGB CSC */ + } + + in_fmt = format_to_colorspace(params->mem_pp_mem.in_g_pixel_fmt); + out_fmt = format_to_colorspace(params->mem_pp_mem.out_pixel_fmt); + if (in_fmt == RGB) { + if ((out_fmt == YCbCr) || (out_fmt == YUV)) { + /* Enable RGB->YCBCR CSC2 */ + _init_csc(IC_TASK_POST_PROCESSOR, RGB, out_fmt, 2); + ic_conf |= IC_CONF_PP_CSC2; + } + } + if ((in_fmt == YCbCr) || (in_fmt == YUV)) { + if (out_fmt == RGB) { + /* Enable YCBCR->RGB CSC2 */ + _init_csc(IC_TASK_POST_PROCESSOR, YCbCr, RGB, 2); + ic_conf |= IC_CONF_PP_CSC2; + } else { + /* TODO: Support YUV<->YCbCr conversion? */ + } + } + + if (params->mem_pp_mem.global_alpha_en) { + ic_conf |= IC_CONF_IC_GLB_LOC_A; + reg = __raw_readl(IC_CMBP_1); + reg &= ~(0xff00); + reg |= (params->mem_pp_mem.alpha << 8); + __raw_writel(reg, IC_CMBP_1); + } else + ic_conf &= ~IC_CONF_IC_GLB_LOC_A; + + if (params->mem_pp_mem.key_color_en) { + ic_conf |= IC_CONF_KEY_COLOR_EN; + __raw_writel(params->mem_pp_mem.key_color, + IC_CMBP_2); + } else + ic_conf &= ~IC_CONF_KEY_COLOR_EN; + } else { + ic_conf &= ~IC_CONF_PP_CMB; + } + + __raw_writel(ic_conf, IC_CONF); +} + +void _ipu_ic_uninit_pp(void) +{ + uint32_t reg; + + reg = __raw_readl(IC_CONF); + reg &= ~(IC_CONF_PP_EN | IC_CONF_PP_CSC1 | IC_CONF_PP_CSC2 | + IC_CONF_PP_CMB); + __raw_writel(reg, IC_CONF); +} + +void _ipu_ic_init_rotate_pp(ipu_channel_params_t *params) +{ +} + +void _ipu_ic_uninit_rotate_pp(void) +{ + uint32_t reg; + reg = __raw_readl(IC_CONF); + reg &= ~IC_CONF_PP_ROT_EN; + __raw_writel(reg, IC_CONF); +} + +int _ipu_ic_idma_init(int dma_chan, uint16_t width, uint16_t height, + int burst_size, ipu_rotate_mode_t rot) +{ + u32 ic_idmac_1, ic_idmac_2, ic_idmac_3; + u32 temp_rot = bitrev8(rot) >> 5; + bool need_hor_flip = false; + + if ((burst_size != 8) && (burst_size != 16)) { + dev_dbg(g_ipu_dev, "Illegal burst length for IC\n"); + return -EINVAL; + } + + width--; + height--; + + if (temp_rot & 0x2) /* Need horizontal flip */ + need_hor_flip = true; + + ic_idmac_1 = __raw_readl(IC_IDMAC_1); + ic_idmac_2 = __raw_readl(IC_IDMAC_2); + ic_idmac_3 = __raw_readl(IC_IDMAC_3); + if (dma_chan == 22) { /* PP output - CB2 */ + if (burst_size == 16) + ic_idmac_1 |= IC_IDMAC_1_CB2_BURST_16; + else + ic_idmac_1 &= ~IC_IDMAC_1_CB2_BURST_16; + + if (need_hor_flip) + ic_idmac_1 |= IC_IDMAC_1_PP_FLIP_RS; + else + ic_idmac_1 &= ~IC_IDMAC_1_PP_FLIP_RS; + + ic_idmac_2 &= ~IC_IDMAC_2_PP_HEIGHT_MASK; + ic_idmac_2 |= height << IC_IDMAC_2_PP_HEIGHT_OFFSET; + + ic_idmac_3 &= ~IC_IDMAC_3_PP_WIDTH_MASK; + ic_idmac_3 |= width << IC_IDMAC_3_PP_WIDTH_OFFSET; + + } else if (dma_chan == 11) { /* PP Input - CB5 */ + if (burst_size == 16) + ic_idmac_1 |= IC_IDMAC_1_CB5_BURST_16; + else + ic_idmac_1 &= ~IC_IDMAC_1_CB5_BURST_16; + } else if (dma_chan == 47) { /* PP Rot input */ + ic_idmac_1 &= ~IC_IDMAC_1_PP_ROT_MASK; + ic_idmac_1 |= temp_rot << IC_IDMAC_1_PP_ROT_OFFSET; + } + + if (dma_chan == 12) { /* PRP Input - CB6 */ + if (burst_size == 16) + ic_idmac_1 |= IC_IDMAC_1_CB6_BURST_16; + else + ic_idmac_1 &= ~IC_IDMAC_1_CB6_BURST_16; + } + + if (dma_chan == 20) { /* PRP ENC output - CB0 */ + if (burst_size == 16) + ic_idmac_1 |= IC_IDMAC_1_CB0_BURST_16; + else + ic_idmac_1 &= ~IC_IDMAC_1_CB0_BURST_16; + + if (need_hor_flip) + ic_idmac_1 |= IC_IDMAC_1_PRPENC_FLIP_RS; + else + ic_idmac_1 &= ~IC_IDMAC_1_PRPENC_FLIP_RS; + + ic_idmac_2 &= ~IC_IDMAC_2_PRPENC_HEIGHT_MASK; + ic_idmac_2 |= height << IC_IDMAC_2_PRPENC_HEIGHT_OFFSET; + + ic_idmac_3 &= ~IC_IDMAC_3_PRPENC_WIDTH_MASK; + ic_idmac_3 |= width << IC_IDMAC_3_PRPENC_WIDTH_OFFSET; + + } else if (dma_chan == 45) { /* PRP ENC Rot input */ + ic_idmac_1 &= ~IC_IDMAC_1_PRPENC_ROT_MASK; + ic_idmac_1 |= temp_rot << IC_IDMAC_1_PRPENC_ROT_OFFSET; + } + + if (dma_chan == 21) { /* PRP VF output - CB1 */ + if (burst_size == 16) + ic_idmac_1 |= IC_IDMAC_1_CB1_BURST_16; + else + ic_idmac_1 &= ~IC_IDMAC_1_CB1_BURST_16; + + if (need_hor_flip) + ic_idmac_1 |= IC_IDMAC_1_PRPVF_FLIP_RS; + else + ic_idmac_1 &= ~IC_IDMAC_1_PRPVF_FLIP_RS; + + ic_idmac_2 &= ~IC_IDMAC_2_PRPVF_HEIGHT_MASK; + ic_idmac_2 |= height << IC_IDMAC_2_PRPVF_HEIGHT_OFFSET; + + ic_idmac_3 &= ~IC_IDMAC_3_PRPVF_WIDTH_MASK; + ic_idmac_3 |= width << IC_IDMAC_3_PRPVF_WIDTH_OFFSET; + + } else if (dma_chan == 46) { /* PRP VF Rot input */ + ic_idmac_1 &= ~IC_IDMAC_1_PRPVF_ROT_MASK; + ic_idmac_1 |= temp_rot << IC_IDMAC_1_PRPVF_ROT_OFFSET; + } + + if (dma_chan == 14) { /* PRP VF graphics combining input - CB3 */ + if (burst_size == 16) + ic_idmac_1 |= IC_IDMAC_1_CB3_BURST_16; + else + ic_idmac_1 &= ~IC_IDMAC_1_CB3_BURST_16; + } else if (dma_chan == 15) { /* PP graphics combining input - CB4 */ + if (burst_size == 16) + ic_idmac_1 |= IC_IDMAC_1_CB4_BURST_16; + else + ic_idmac_1 &= ~IC_IDMAC_1_CB4_BURST_16; + } + + __raw_writel(ic_idmac_1, IC_IDMAC_1); + __raw_writel(ic_idmac_2, IC_IDMAC_2); + __raw_writel(ic_idmac_3, IC_IDMAC_3); + + return 0; +} + +static void _init_csc(uint8_t ic_task, ipu_color_space_t in_format, + ipu_color_space_t out_format, int csc_index) +{ + +/* Y = R * .299 + G * .587 + B * .114; + U = R * -.169 + G * -.332 + B * .500 + 128.; + V = R * .500 + G * -.419 + B * -.0813 + 128.;*/ + static const uint32_t rgb2ycbcr_coeff[4][3] = { + {0x004D, 0x0096, 0x001D}, + {0x01D5, 0x01AB, 0x0080}, + {0x0080, 0x0195, 0x01EB}, + {0x0000, 0x0200, 0x0200}, /* A0, A1, A2 */ + }; + + /* transparent RGB->RGB matrix for combining + */ + static const uint32_t rgb2rgb_coeff[4][3] = { + {0x0080, 0x0000, 0x0000}, + {0x0000, 0x0080, 0x0000}, + {0x0000, 0x0000, 0x0080}, + {0x0000, 0x0000, 0x0000}, /* A0, A1, A2 */ + }; + +/* R = (1.164 * (Y - 16)) + (1.596 * (Cr - 128)); + G = (1.164 * (Y - 16)) - (0.392 * (Cb - 128)) - (0.813 * (Cr - 128)); + B = (1.164 * (Y - 16)) + (2.017 * (Cb - 128); */ + static const uint32_t ycbcr2rgb_coeff[4][3] = { + {149, 0, 204}, + {149, 462, 408}, + {149, 255, 0}, + {8192 - 446, 266, 8192 - 554}, /* A0, A1, A2 */ + }; + + uint32_t param; + uint32_t *base = NULL; + + if (ic_task == IC_TASK_ENCODER) { + base = ipu_tpmem_base + 0x2008 / 4; + } else if (ic_task == IC_TASK_VIEWFINDER) { + if (csc_index == 1) + base = ipu_tpmem_base + 0x4028 / 4; + else + base = ipu_tpmem_base + 0x4040 / 4; + } else if (ic_task == IC_TASK_POST_PROCESSOR) { + if (csc_index == 1) + base = ipu_tpmem_base + 0x6060 / 4; + else + base = ipu_tpmem_base + 0x6078 / 4; + } else { + BUG(); + } + + if ((in_format == YCbCr) && (out_format == RGB)) { + /* Init CSC (YCbCr->RGB) */ + param = (ycbcr2rgb_coeff[3][0] << 27) | + (ycbcr2rgb_coeff[0][0] << 18) | + (ycbcr2rgb_coeff[1][1] << 9) | ycbcr2rgb_coeff[2][2]; + __raw_writel(param, base++); + /* scale = 2, sat = 0 */ + param = (ycbcr2rgb_coeff[3][0] >> 5) | (2L << (40 - 32)); + __raw_writel(param, base++); + + param = (ycbcr2rgb_coeff[3][1] << 27) | + (ycbcr2rgb_coeff[0][1] << 18) | + (ycbcr2rgb_coeff[1][0] << 9) | ycbcr2rgb_coeff[2][0]; + __raw_writel(param, base++); + param = (ycbcr2rgb_coeff[3][1] >> 5); + __raw_writel(param, base++); + + param = (ycbcr2rgb_coeff[3][2] << 27) | + (ycbcr2rgb_coeff[0][2] << 18) | + (ycbcr2rgb_coeff[1][2] << 9) | ycbcr2rgb_coeff[2][1]; + __raw_writel(param, base++); + param = (ycbcr2rgb_coeff[3][2] >> 5); + __raw_writel(param, base++); + } else if ((in_format == RGB) && (out_format == YCbCr)) { + /* Init CSC (RGB->YCbCr) */ + param = (rgb2ycbcr_coeff[3][0] << 27) | + (rgb2ycbcr_coeff[0][0] << 18) | + (rgb2ycbcr_coeff[1][1] << 9) | rgb2ycbcr_coeff[2][2]; + __raw_writel(param, base++); + /* scale = 1, sat = 0 */ + param = (rgb2ycbcr_coeff[3][0] >> 5) | (1UL << 8); + __raw_writel(param, base++); + + param = (rgb2ycbcr_coeff[3][1] << 27) | + (rgb2ycbcr_coeff[0][1] << 18) | + (rgb2ycbcr_coeff[1][0] << 9) | rgb2ycbcr_coeff[2][0]; + __raw_writel(param, base++); + param = (rgb2ycbcr_coeff[3][1] >> 5); + __raw_writel(param, base++); + + param = (rgb2ycbcr_coeff[3][2] << 27) | + (rgb2ycbcr_coeff[0][2] << 18) | + (rgb2ycbcr_coeff[1][2] << 9) | rgb2ycbcr_coeff[2][1]; + __raw_writel(param, base++); + param = (rgb2ycbcr_coeff[3][2] >> 5); + __raw_writel(param, base++); + } else if ((in_format == RGB) && (out_format == RGB)) { + /* Init CSC */ + param = + (rgb2rgb_coeff[3][0] << 27) | (rgb2rgb_coeff[0][0] << 18) | + (rgb2rgb_coeff[1][1] << 9) | rgb2rgb_coeff[2][2]; + __raw_writel(param, base++); + /* scale = 2, sat = 0 */ + param = (rgb2rgb_coeff[3][0] >> 5) | (2UL << 8); + __raw_writel(param, base++); + + param = + (rgb2rgb_coeff[3][1] << 27) | (rgb2rgb_coeff[0][1] << 18) | + (rgb2rgb_coeff[1][0] << 9) | rgb2rgb_coeff[2][0]; + __raw_writel(param, base++); + param = (rgb2rgb_coeff[3][1] >> 5); + __raw_writel(param, base++); + + param = + (rgb2rgb_coeff[3][2] << 27) | (rgb2rgb_coeff[0][2] << 18) | + (rgb2rgb_coeff[1][2] << 9) | rgb2rgb_coeff[2][1]; + __raw_writel(param, base++); + param = (rgb2rgb_coeff[3][2] >> 5); + __raw_writel(param, base++); + } else { + dev_err(g_ipu_dev, "Unsupported color space conversion\n"); + } +} + +static bool _calc_resize_coeffs(uint32_t inSize, uint32_t outSize, + uint32_t *resizeCoeff, + uint32_t *downsizeCoeff) +{ + uint32_t tempSize; + uint32_t tempDownsize; + + /* Input size cannot be more than 4096 */ + /* Output size cannot be more than 1024 */ + if ((inSize > 4096) || (outSize > 1024)) + return false; + + /* Cannot downsize more than 8:1 */ + if ((outSize << 3) < inSize) + return false; + + /* Compute downsizing coefficient */ + /* Output of downsizing unit cannot be more than 1024 */ + tempDownsize = 0; + tempSize = inSize; + while (((tempSize > 1024) || (tempSize >= outSize * 2)) && + (tempDownsize < 2)) { + tempSize >>= 1; + tempDownsize++; + } + *downsizeCoeff = tempDownsize; + + /* compute resizing coefficient using the following equation: + resizeCoeff = M*(SI -1)/(SO - 1) + where M = 2^13, SI - input size, SO - output size */ + *resizeCoeff = (8192L * (tempSize - 1)) / (outSize - 1); + if (*resizeCoeff >= 16384L) { + dev_err(g_ipu_dev, "Warning! Overflow on resize coeff.\n"); + *resizeCoeff = 0x3FFF; + } + + dev_dbg(g_ipu_dev, "resizing from %u -> %u pixels, " + "downsize=%u, resize=%u.%lu (reg=%u)\n", inSize, outSize, + *downsizeCoeff, (*resizeCoeff >= 8192L) ? 1 : 0, + ((*resizeCoeff & 0x1FFF) * 10000L) / 8192L, *resizeCoeff); + + return true; +} + +void _ipu_vdi_toggle_top_field_man() +{ + uint32_t reg; + uint32_t mask_reg; + + reg = __raw_readl(VDI_C); + mask_reg = reg & VDI_C_TOP_FIELD_MAN_1; + if (mask_reg == VDI_C_TOP_FIELD_MAN_1) + reg &= ~VDI_C_TOP_FIELD_MAN_1; + else + reg |= VDI_C_TOP_FIELD_MAN_1; + + __raw_writel(reg, VDI_C); +} + diff --git a/drivers/mxc/ipu3/ipu_param_mem.h b/drivers/mxc/ipu3/ipu_param_mem.h new file mode 100644 index 000000000000..30e6dc1005ba --- /dev/null +++ b/drivers/mxc/ipu3/ipu_param_mem.h @@ -0,0 +1,562 @@ +/* + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#ifndef __INCLUDE_IPU_PARAM_MEM_H__ +#define __INCLUDE_IPU_PARAM_MEM_H__ + +#include +#include + +extern u32 *ipu_cpmem_base; + +struct ipu_ch_param_word { + uint32_t data[5]; + uint32_t res[3]; +}; + +struct ipu_ch_param { + struct ipu_ch_param_word word[2]; +}; + +#define ipu_ch_param_addr(ch) (((struct ipu_ch_param *)ipu_cpmem_base) + (ch)) + +#define _param_word(base, w) \ + (((struct ipu_ch_param *)(base))->word[(w)].data) + +#define ipu_ch_param_set_field(base, w, bit, size, v) { \ + int i = (bit) / 32; \ + int off = (bit) % 32; \ + _param_word(base, w)[i] |= (v) << off; \ + if (((bit)+(size)-1)/32 > i) { \ + _param_word(base, w)[i + 1] |= (v) >> (off ? (32 - off) : 0); \ + } \ +} + +#define ipu_ch_param_mod_field(base, w, bit, size, v) { \ + int i = (bit) / 32; \ + int off = (bit) % 32; \ + u32 mask = (1UL << size) - 1; \ + u32 temp = _param_word(base, w)[i]; \ + temp &= ~(mask << off); \ + _param_word(base, w)[i] = temp | (v) << off; \ + if (((bit)+(size)-1)/32 > i) { \ + temp = _param_word(base, w)[i + 1]; \ + temp &= ~(mask >> (32 - off)); \ + _param_word(base, w)[i + 1] = \ + temp | ((v) >> (off ? (32 - off) : 0)); \ + } \ +} + +#define ipu_ch_param_read_field(base, w, bit, size) ({ \ + u32 temp2; \ + int i = (bit) / 32; \ + int off = (bit) % 32; \ + u32 mask = (1UL << size) - 1; \ + u32 temp1 = _param_word(base, w)[i]; \ + temp1 = mask & (temp1 >> off); \ + if (((bit)+(size)-1)/32 > i) { \ + temp2 = _param_word(base, w)[i + 1]; \ + temp2 &= mask >> (off ? (32 - off) : 0); \ + temp1 |= temp2 << (off ? (32 - off) : 0); \ + } \ + temp1; \ +}) + +static inline void _ipu_ch_params_set_packing(struct ipu_ch_param *p, + int red_width, int red_offset, + int green_width, int green_offset, + int blue_width, int blue_offset, + int alpha_width, int alpha_offset) +{ + /* Setup red width and offset */ + ipu_ch_param_set_field(p, 1, 116, 3, red_width - 1); + ipu_ch_param_set_field(p, 1, 128, 5, red_offset); + /* Setup green width and offset */ + ipu_ch_param_set_field(p, 1, 119, 3, green_width - 1); + ipu_ch_param_set_field(p, 1, 133, 5, green_offset); + /* Setup blue width and offset */ + ipu_ch_param_set_field(p, 1, 122, 3, blue_width - 1); + ipu_ch_param_set_field(p, 1, 138, 5, blue_offset); + /* Setup alpha width and offset */ + ipu_ch_param_set_field(p, 1, 125, 3, alpha_width - 1); + ipu_ch_param_set_field(p, 1, 143, 5, alpha_offset); +} + +static inline void _ipu_ch_param_dump(int ch) +{ + struct ipu_ch_param *p = ipu_ch_param_addr(ch); + pr_debug("ch %d word 0 - %08X %08X %08X %08X %08X\n", ch, + p->word[0].data[0], p->word[0].data[1], p->word[0].data[2], + p->word[0].data[3], p->word[0].data[4]); + pr_debug("ch %d word 1 - %08X %08X %08X %08X %08X\n", ch, + p->word[1].data[0], p->word[1].data[1], p->word[1].data[2], + p->word[1].data[3], p->word[1].data[4]); + pr_debug("PFS 0x%x, ", + ipu_ch_param_read_field(ipu_ch_param_addr(ch), 1, 85, 4)); + pr_debug("BPP 0x%x, ", + ipu_ch_param_read_field(ipu_ch_param_addr(ch), 0, 107, 3)); + pr_debug("NPB 0x%x\n", + ipu_ch_param_read_field(ipu_ch_param_addr(ch), 1, 78, 7)); + + pr_debug("FW %d, ", + ipu_ch_param_read_field(ipu_ch_param_addr(ch), 0, 125, 13)); + pr_debug("FH %d, ", + ipu_ch_param_read_field(ipu_ch_param_addr(ch), 0, 138, 12)); + pr_debug("Stride %d\n", + ipu_ch_param_read_field(ipu_ch_param_addr(ch), 1, 102, 14)); + + pr_debug("Width0 %d+1, ", + ipu_ch_param_read_field(ipu_ch_param_addr(ch), 1, 116, 3)); + pr_debug("Width1 %d+1, ", + ipu_ch_param_read_field(ipu_ch_param_addr(ch), 1, 119, 3)); + pr_debug("Width2 %d+1, ", + ipu_ch_param_read_field(ipu_ch_param_addr(ch), 1, 122, 3)); + pr_debug("Width3 %d+1, ", + ipu_ch_param_read_field(ipu_ch_param_addr(ch), 1, 125, 3)); + pr_debug("Offset0 %d, ", + ipu_ch_param_read_field(ipu_ch_param_addr(ch), 1, 128, 5)); + pr_debug("Offset1 %d, ", + ipu_ch_param_read_field(ipu_ch_param_addr(ch), 1, 133, 5)); + pr_debug("Offset2 %d, ", + ipu_ch_param_read_field(ipu_ch_param_addr(ch), 1, 138, 5)); + pr_debug("Offset3 %d\n", + ipu_ch_param_read_field(ipu_ch_param_addr(ch), 1, 143, 5)); +} + +static inline void _ipu_ch_param_init(int ch, + uint32_t pixel_fmt, uint32_t width, + uint32_t height, uint32_t stride, + uint32_t u, uint32_t v, + uint32_t uv_stride, dma_addr_t addr0, + dma_addr_t addr1) +{ + uint32_t u_offset = 0; + uint32_t v_offset = 0; + struct ipu_ch_param params; + + memset(¶ms, 0, sizeof(params)); + + ipu_ch_param_set_field(¶ms, 0, 125, 13, width - 1); + + if ((ch == 8) || (ch == 9) || (ch == 10)) { + ipu_ch_param_set_field(¶ms, 0, 138, 12, (height / 2) - 1); + ipu_ch_param_set_field(¶ms, 1, 102, 14, (stride * 2) - 1); + } else { + ipu_ch_param_set_field(¶ms, 0, 138, 12, height - 1); + ipu_ch_param_set_field(¶ms, 1, 102, 14, stride - 1); + } + + /* EBA is 8-byte aligned */ + ipu_ch_param_set_field(¶ms, 1, 0, 29, addr0 >> 3); + ipu_ch_param_set_field(¶ms, 1, 29, 29, addr1 >> 3); + if (addr0%8) + dev_warn(g_ipu_dev, + "IDMAC%d's EBA0 is not 8-byte aligned\n", ch); + if (addr1%8) + dev_warn(g_ipu_dev, + "IDMAC%d's EBA1 is not 8-byte aligned\n", ch); + + switch (pixel_fmt) { + case IPU_PIX_FMT_GENERIC: + /*Represents 8-bit Generic data */ + ipu_ch_param_set_field(¶ms, 0, 107, 3, 5); /* bits/pixel */ + ipu_ch_param_set_field(¶ms, 1, 85, 4, 6); /* pix format */ + ipu_ch_param_set_field(¶ms, 1, 78, 7, 63); /* burst size */ + + break; + case IPU_PIX_FMT_GENERIC_32: + /*Represents 32-bit Generic data */ + break; + case IPU_PIX_FMT_RGB565: + ipu_ch_param_set_field(¶ms, 0, 107, 3, 3); /* bits/pixel */ + ipu_ch_param_set_field(¶ms, 1, 85, 4, 7); /* pix format */ + ipu_ch_param_set_field(¶ms, 1, 78, 7, 15); /* burst size */ + + _ipu_ch_params_set_packing(¶ms, 5, 0, 6, 5, 5, 11, 8, 16); + break; + case IPU_PIX_FMT_BGR24: + ipu_ch_param_set_field(¶ms, 0, 107, 3, 1); /* bits/pixel */ + ipu_ch_param_set_field(¶ms, 1, 85, 4, 7); /* pix format */ + ipu_ch_param_set_field(¶ms, 1, 78, 7, 19); /* burst size */ + + _ipu_ch_params_set_packing(¶ms, 8, 0, 8, 8, 8, 16, 8, 24); + break; + case IPU_PIX_FMT_RGB24: + case IPU_PIX_FMT_YUV444: + ipu_ch_param_set_field(¶ms, 0, 107, 3, 1); /* bits/pixel */ + ipu_ch_param_set_field(¶ms, 1, 85, 4, 7); /* pix format */ + ipu_ch_param_set_field(¶ms, 1, 78, 7, 19); /* burst size */ + + _ipu_ch_params_set_packing(¶ms, 8, 16, 8, 8, 8, 0, 8, 24); + break; + case IPU_PIX_FMT_BGRA32: + case IPU_PIX_FMT_BGR32: + ipu_ch_param_set_field(¶ms, 0, 107, 3, 0); /* bits/pixel */ + ipu_ch_param_set_field(¶ms, 1, 85, 4, 7); /* pix format */ + ipu_ch_param_set_field(¶ms, 1, 78, 7, 15); /* burst size */ + + _ipu_ch_params_set_packing(¶ms, 8, 8, 8, 16, 8, 24, 8, 0); + break; + case IPU_PIX_FMT_RGBA32: + case IPU_PIX_FMT_RGB32: + ipu_ch_param_set_field(¶ms, 0, 107, 3, 0); /* bits/pixel */ + ipu_ch_param_set_field(¶ms, 1, 85, 4, 7); /* pix format */ + ipu_ch_param_set_field(¶ms, 1, 78, 7, 15); /* burst size */ + + _ipu_ch_params_set_packing(¶ms, 8, 24, 8, 16, 8, 8, 8, 0); + break; + case IPU_PIX_FMT_ABGR32: + ipu_ch_param_set_field(¶ms, 0, 107, 3, 0); /* bits/pixel */ + ipu_ch_param_set_field(¶ms, 1, 85, 4, 7); /* pix format */ + ipu_ch_param_set_field(¶ms, 1, 78, 7, 15); /* burst size */ + + _ipu_ch_params_set_packing(¶ms, 8, 0, 8, 8, 8, 16, 8, 24); + break; + case IPU_PIX_FMT_UYVY: + ipu_ch_param_set_field(¶ms, 0, 107, 3, 3); /* bits/pixel */ + ipu_ch_param_set_field(¶ms, 1, 85, 4, 0xA); /* pix format */ + ipu_ch_param_set_field(¶ms, 1, 78, 7, 31); /* burst size */ + break; + case IPU_PIX_FMT_YUYV: + ipu_ch_param_set_field(¶ms, 0, 107, 3, 3); /* bits/pixel */ + ipu_ch_param_set_field(¶ms, 1, 85, 4, 0x8); /* pix format */ + ipu_ch_param_set_field(¶ms, 1, 78, 7, 31); /* burst size */ + break; + case IPU_PIX_FMT_YUV420P2: + case IPU_PIX_FMT_YUV420P: + ipu_ch_param_set_field(¶ms, 1, 85, 4, 2); /* pix format */ + + if (uv_stride < stride / 2) + uv_stride = stride / 2; + + u_offset = stride * height; + v_offset = u_offset + (uv_stride * height / 2); + if ((ch == 8) || (ch == 9) || (ch == 10)) { + ipu_ch_param_set_field(¶ms, 1, 78, 7, 15); /* burst size */ + uv_stride = uv_stride*2; + } else { + ipu_ch_param_set_field(¶ms, 1, 78, 7, 31); /* burst size */ + } + break; + case IPU_PIX_FMT_YVU422P: + /* BPP & pixel format */ + ipu_ch_param_set_field(¶ms, 1, 85, 4, 1); /* pix format */ + ipu_ch_param_set_field(¶ms, 1, 78, 7, 31); /* burst size */ + + if (uv_stride < stride / 2) + uv_stride = stride / 2; + + v_offset = (v == 0) ? stride * height : v; + u_offset = (u == 0) ? v_offset + v_offset / 2 : u; + break; + case IPU_PIX_FMT_YUV422P: + /* BPP & pixel format */ + ipu_ch_param_set_field(¶ms, 1, 85, 4, 1); /* pix format */ + ipu_ch_param_set_field(¶ms, 1, 78, 7, 31); /* burst size */ + + if (uv_stride < stride / 2) + uv_stride = stride / 2; + + u_offset = (u == 0) ? stride * height : u; + v_offset = (v == 0) ? u_offset + u_offset / 2 : v; + break; + case IPU_PIX_FMT_NV12: + /* BPP & pixel format */ + ipu_ch_param_set_field(¶ms, 1, 85, 4, 4); /* pix format */ + uv_stride = stride; + u_offset = (u == 0) ? stride * height : u; + if ((ch == 8) || (ch == 9) || (ch == 10)) { + ipu_ch_param_set_field(¶ms, 1, 78, 7, 15); /* burst size */ + uv_stride = uv_stride*2; + } else { + ipu_ch_param_set_field(¶ms, 1, 78, 7, 31); /* burst size */ + } + break; + default: + dev_err(g_ipu_dev, "mxc ipu: unimplemented pixel format\n"); + break; + } + /*set burst size to 16*/ + + + if (uv_stride) + ipu_ch_param_set_field(¶ms, 1, 128, 14, uv_stride - 1); + + /* Get the uv offset from user when need cropping */ + if (u || v) { + u_offset = u; + v_offset = v; + } + + /* UBO and VBO are 22-bit and 8-byte aligned */ + if (u_offset/8 > 0x3fffff) + dev_warn(g_ipu_dev, + "IDMAC%d's U offset exceeds IPU limitation\n", ch); + if (v_offset/8 > 0x3fffff) + dev_warn(g_ipu_dev, + "IDMAC%d's V offset exceeds IPU limitation\n", ch); + if (u_offset%8) + dev_warn(g_ipu_dev, + "IDMAC%d's U offset is not 8-byte aligned\n", ch); + if (v_offset%8) + dev_warn(g_ipu_dev, + "IDMAC%d's V offset is not 8-byte aligned\n", ch); + + ipu_ch_param_set_field(¶ms, 0, 46, 22, u_offset / 8); + ipu_ch_param_set_field(¶ms, 0, 68, 22, v_offset / 8); + + pr_debug("initializing idma ch %d @ %p\n", ch, ipu_ch_param_addr(ch)); + memcpy(ipu_ch_param_addr(ch), ¶ms, sizeof(params)); +}; + +static inline void _ipu_ch_param_set_burst_size(uint32_t ch, + uint16_t burst_pixels) +{ + ipu_ch_param_mod_field(ipu_ch_param_addr(ch), 1, 78, 7, + burst_pixels - 1); +}; + +static inline int _ipu_ch_param_get_burst_size(uint32_t ch) +{ + return ipu_ch_param_read_field(ipu_ch_param_addr(ch), 1, 78, 7) + 1; +}; + +static inline int _ipu_ch_param_get_bpp(uint32_t ch) +{ + return ipu_ch_param_read_field(ipu_ch_param_addr(ch), 0, 107, 3); +}; + +static inline void _ipu_ch_param_set_buffer(uint32_t ch, int bufNum, + dma_addr_t phyaddr) +{ + ipu_ch_param_mod_field(ipu_ch_param_addr(ch), 1, 29 * bufNum, 29, + phyaddr / 8); +}; + +static inline void _ipu_ch_param_set_rotation(uint32_t ch, + ipu_rotate_mode_t rot) +{ + u32 temp_rot = bitrev8(rot) >> 5; + ipu_ch_param_mod_field(ipu_ch_param_addr(ch), 0, 119, 3, temp_rot); +}; + +static inline void _ipu_ch_param_set_block_mode(uint32_t ch) +{ + ipu_ch_param_mod_field(ipu_ch_param_addr(ch), 0, 117, 2, 1); +}; + +static inline void _ipu_ch_param_set_alpha_use_separate_channel(uint32_t ch, + bool option) +{ + if (option) { + ipu_ch_param_mod_field(ipu_ch_param_addr(ch), 1, 89, 1, 1); + } else { + ipu_ch_param_mod_field(ipu_ch_param_addr(ch), 1, 89, 1, 0); + } +}; + +static inline void _ipu_ch_param_set_alpha_condition_read(uint32_t ch) +{ + ipu_ch_param_mod_field(ipu_ch_param_addr(ch), 1, 149, 1, 1); +}; + +static inline void _ipu_ch_param_set_alpha_buffer_memory(uint32_t ch) +{ + int alp_mem_idx; + + switch (ch) { + case 14: /* PRP graphic */ + alp_mem_idx = 0; + break; + case 15: /* PP graphic */ + alp_mem_idx = 1; + break; + case 23: /* DP BG SYNC graphic */ + alp_mem_idx = 4; + break; + case 27: /* DP FG SYNC graphic */ + alp_mem_idx = 2; + break; + default: + dev_err(g_ipu_dev, "unsupported correlative channel of local " + "alpha channel\n"); + return; + } + + ipu_ch_param_mod_field(ipu_ch_param_addr(ch), 1, 90, 3, alp_mem_idx); +}; + +static inline void _ipu_ch_param_set_interlaced_scan(uint32_t ch) +{ + u32 stride; + ipu_ch_param_set_field(ipu_ch_param_addr(ch), 0, 113, 1, 1); + stride = ipu_ch_param_read_field(ipu_ch_param_addr(ch), 1, 102, 14) + 1; + /* ILO is 20-bit and 8-byte aligned */ + if (stride/8 > 0xfffff) + dev_warn(g_ipu_dev, + "IDMAC%d's ILO exceeds IPU limitation\n", ch); + if (stride%8) + dev_warn(g_ipu_dev, + "IDMAC%d's ILO is not 8-byte aligned\n", ch); + ipu_ch_param_mod_field(ipu_ch_param_addr(ch), 1, 58, 20, stride / 8); + stride *= 2; + ipu_ch_param_mod_field(ipu_ch_param_addr(ch), 1, 102, 14, stride - 1); +}; + +static inline void _ipu_ch_param_set_high_priority(uint32_t ch) +{ + ipu_ch_param_mod_field(ipu_ch_param_addr(ch), 1, 93, 2, 1); +}; + +/* IDMAC U/V offset changing support */ +/* U and V input is not affected, */ +/* the update is done by new calculation according to */ +/* vertical_offset and horizontal_offset */ +static inline void _ipu_ch_offset_update(int ch, + uint32_t pixel_fmt, + uint32_t width, + uint32_t height, + uint32_t stride, + uint32_t u, + uint32_t v, + uint32_t uv_stride, + uint32_t vertical_offset, + uint32_t horizontal_offset) +{ + uint32_t u_offset = 0; + uint32_t v_offset = 0; + uint32_t u_fix = 0; + uint32_t v_fix = 0; + + switch (pixel_fmt) { + case IPU_PIX_FMT_GENERIC: + case IPU_PIX_FMT_GENERIC_32: + case IPU_PIX_FMT_RGB565: + case IPU_PIX_FMT_BGR24: + case IPU_PIX_FMT_RGB24: + case IPU_PIX_FMT_YUV444: + case IPU_PIX_FMT_BGRA32: + case IPU_PIX_FMT_BGR32: + case IPU_PIX_FMT_RGBA32: + case IPU_PIX_FMT_RGB32: + case IPU_PIX_FMT_ABGR32: + case IPU_PIX_FMT_UYVY: + case IPU_PIX_FMT_YUYV: + break; + + case IPU_PIX_FMT_YUV420P2: + case IPU_PIX_FMT_YUV420P: + if (uv_stride < stride / 2) + uv_stride = stride / 2; + + u_offset = stride * (height - vertical_offset - 1) + + (stride - horizontal_offset) + + (uv_stride * vertical_offset / 2) + + horizontal_offset / 2; + v_offset = u_offset + (uv_stride * height / 2); + u_fix = u ? (u + (uv_stride * vertical_offset / 2) + + (horizontal_offset / 2) - + (stride * vertical_offset) - (horizontal_offset)) : + u_offset; + v_fix = v ? (v + (uv_stride * vertical_offset / 2) + + (horizontal_offset / 2) - + (stride * vertical_offset) - (horizontal_offset)) : + v_offset; + + break; + case IPU_PIX_FMT_YVU422P: + if (uv_stride < stride / 2) + uv_stride = stride / 2; + + v_offset = stride * (height - vertical_offset - 1) + + (stride - horizontal_offset) + + (uv_stride * vertical_offset) + + horizontal_offset / 2; + u_offset = v_offset + uv_stride * height; + u_fix = u ? (u + (uv_stride * vertical_offset) + + horizontal_offset / 2 - + (stride * vertical_offset) - (horizontal_offset)) : + u_offset; + v_fix = v ? (v + (uv_stride * vertical_offset) + + horizontal_offset / 2 - + (stride * vertical_offset) - (horizontal_offset)) : + v_offset; + break; + case IPU_PIX_FMT_YUV422P: + if (uv_stride < stride / 2) + uv_stride = stride / 2; + + u_offset = stride * (height - vertical_offset - 1) + + (stride - horizontal_offset) + + (uv_stride * vertical_offset) + + horizontal_offset / 2; + v_offset = u_offset + uv_stride * height; + u_fix = u ? (u + (uv_stride * vertical_offset) + + horizontal_offset / 2 - + (stride * vertical_offset) - (horizontal_offset)) : + u_offset; + v_fix = v ? (v + (uv_stride * vertical_offset) + + horizontal_offset / 2 - + (stride * vertical_offset) - (horizontal_offset)) : + v_offset; + break; + + case IPU_PIX_FMT_NV12: + uv_stride = stride; + u_offset = stride * (height - vertical_offset - 1) + + (stride - horizontal_offset) + + (uv_stride * vertical_offset / 2) + + horizontal_offset; + u_fix = u ? (u + (uv_stride * vertical_offset / 2) + + horizontal_offset - + (stride * vertical_offset) - (horizontal_offset)) : + u_offset; + + break; + default: + dev_err(g_ipu_dev, "mxc ipu: unimplemented pixel format\n"); + break; + } + + + + if (u_fix > u_offset) + u_offset = u_fix; + + if (v_fix > v_offset) + v_offset = v_fix; + + /* UBO and VBO are 22-bit and 8-byte aligned */ + if (u_offset/8 > 0x3fffff) + dev_warn(g_ipu_dev, + "IDMAC%d's U offset exceeds IPU limitation\n", ch); + if (v_offset/8 > 0x3fffff) + dev_warn(g_ipu_dev, + "IDMAC%d's V offset exceeds IPU limitation\n", ch); + if (u_offset%8) + dev_warn(g_ipu_dev, + "IDMAC%d's U offset is not 8-byte aligned\n", ch); + if (v_offset%8) + dev_warn(g_ipu_dev, + "IDMAC%d's V offset is not 8-byte aligned\n", ch); + + ipu_ch_param_mod_field(ipu_ch_param_addr(ch), 0, 46, 22, u_offset / 8); + ipu_ch_param_mod_field(ipu_ch_param_addr(ch), 0, 68, 22, v_offset / 8); + +}; + +static inline void _ipu_ch_params_set_alpha_width(uint32_t ch, int alpha_width) +{ + ipu_ch_param_set_field(ipu_ch_param_addr(ch), 1, 125, 3, alpha_width - 1); +}; + +#endif diff --git a/drivers/mxc/ipu3/ipu_prv.h b/drivers/mxc/ipu3/ipu_prv.h new file mode 100644 index 000000000000..d3bc23b2b220 --- /dev/null +++ b/drivers/mxc/ipu3/ipu_prv.h @@ -0,0 +1,102 @@ +/* + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#ifndef __INCLUDE_IPU_PRV_H__ +#define __INCLUDE_IPU_PRV_H__ + +#include +#include +#include +#include +#include + +/* Globals */ +extern struct device *g_ipu_dev; +extern spinlock_t ipu_lock; +extern bool g_ipu_clk_enabled; +extern struct clk *g_ipu_clk; +extern struct clk *g_di_clk[2]; +extern struct clk *g_pixel_clk[2]; +extern struct clk *g_csi_clk[2]; +extern unsigned char g_dc_di_assignment[]; +extern int g_ipu_hw_rev; +extern int dmfc_type_setup; + +#define IDMA_CHAN_INVALID 0xFF +#define HIGH_RESOLUTION_WIDTH 1024 + +struct ipu_channel { + u8 video_in_dma; + u8 alpha_in_dma; + u8 graph_in_dma; + u8 out_dma; +}; + +enum ipu_dmfc_type { + DMFC_NORMAL = 0, + DMFC_HIGH_RESOLUTION_DC, + DMFC_HIGH_RESOLUTION_DP, + DMFC_HIGH_RESOLUTION_ONLY_DP, +}; + +int register_ipu_device(void); +ipu_color_space_t format_to_colorspace(uint32_t fmt); +bool ipu_pixel_format_has_alpha(uint32_t fmt); + +void ipu_dump_registers(void); + +uint32_t _ipu_channel_status(ipu_channel_t channel); + +void _ipu_init_dc_mappings(void); +int _ipu_dp_init(ipu_channel_t channel, uint32_t in_pixel_fmt, + uint32_t out_pixel_fmt); +void _ipu_dp_uninit(ipu_channel_t channel); +void _ipu_dc_init(int dc_chan, int di, bool interlaced, uint32_t pixel_fmt); +void _ipu_dc_uninit(int dc_chan); +void _ipu_dp_dc_enable(ipu_channel_t channel); +void _ipu_dp_dc_disable(ipu_channel_t channel, bool swap); +void _ipu_dmfc_init(int dmfc_type, int first); +void _ipu_dmfc_set_wait4eot(int dma_chan, int width); +int _ipu_chan_is_interlaced(ipu_channel_t channel); + +void _ipu_ic_enable_task(ipu_channel_t channel); +void _ipu_ic_disable_task(ipu_channel_t channel); +void _ipu_ic_init_prpvf(ipu_channel_params_t *params, bool src_is_csi); +void _ipu_vdi_init(ipu_channel_t channel, ipu_channel_params_t *params); +void _ipu_vdi_uninit(void); +void _ipu_ic_uninit_prpvf(void); +void _ipu_ic_init_rotate_vf(ipu_channel_params_t *params); +void _ipu_ic_uninit_rotate_vf(void); +void _ipu_ic_init_csi(ipu_channel_params_t *params); +void _ipu_ic_uninit_csi(void); +void _ipu_ic_init_prpenc(ipu_channel_params_t *params, bool src_is_csi); +void _ipu_ic_uninit_prpenc(void); +void _ipu_ic_init_rotate_enc(ipu_channel_params_t *params); +void _ipu_ic_uninit_rotate_enc(void); +void _ipu_ic_init_pp(ipu_channel_params_t *params); +void _ipu_ic_uninit_pp(void); +void _ipu_ic_init_rotate_pp(ipu_channel_params_t *params); +void _ipu_ic_uninit_rotate_pp(void); +int _ipu_ic_idma_init(int dma_chan, uint16_t width, uint16_t height, + int burst_size, ipu_rotate_mode_t rot); +void _ipu_vdi_toggle_top_field_man(void); +int _ipu_csi_init(ipu_channel_t channel, uint32_t csi); +void ipu_csi_set_test_generator(bool active, uint32_t r_value, + uint32_t g_value, uint32_t b_value, + uint32_t pix_clk, uint32_t csi); +void _ipu_csi_ccir_err_detection_enable(uint32_t csi); +void _ipu_csi_ccir_err_detection_disable(uint32_t csi); +void _ipu_smfc_init(ipu_channel_t channel, uint32_t mipi_id, uint32_t csi); +void _ipu_smfc_set_burst_size(ipu_channel_t channel, uint32_t bs); +void _ipu_dp_set_csc_coefficients(ipu_channel_t channel, int32_t param[][3]); + +#endif /* __INCLUDE_IPU_PRV_H__ */ diff --git a/drivers/mxc/ipu3/ipu_regs.h b/drivers/mxc/ipu3/ipu_regs.h new file mode 100644 index 000000000000..668b08269e2c --- /dev/null +++ b/drivers/mxc/ipu3/ipu_regs.h @@ -0,0 +1,666 @@ +/* + * Copyright (C) 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/* + * @file ipu_regs.h + * + * @brief IPU Register definitions + * + * @ingroup IPU + */ +#ifndef __IPU_REGS_INCLUDED__ +#define __IPU_REGS_INCLUDED__ + +#define IPU_DISP0_BASE 0x00000000 +#define IPU_MCU_T_DEFAULT 8 +#define IPU_DISP1_BASE (IPU_MCU_T_DEFAULT << 25) +#define IPU_REG_BASE 0x1E000000 +#define IPUV3M_REG_BASE 0x06000000 + +#define IPU_CM_REG_BASE 0x00000000 +#define IPU_IDMAC_REG_BASE 0x00008000 +#define IPU_ISP_REG_BASE 0x00010000 +#define IPU_DP_REG_BASE 0x00018000 +#define IPU_IC_REG_BASE 0x00020000 +#define IPU_IRT_REG_BASE 0x00028000 +#define IPU_CSI0_REG_BASE 0x00030000 +#define IPU_CSI1_REG_BASE 0x00038000 +#define IPU_DI0_REG_BASE 0x00040000 +#define IPU_DI1_REG_BASE 0x00048000 +#define IPU_SMFC_REG_BASE 0x00050000 +#define IPU_DC_REG_BASE 0x00058000 +#define IPU_DMFC_REG_BASE 0x00060000 +#define IPU_VDI_REG_BASE 0x00068000 +#define IPU_CPMEM_REG_BASE 0x01000000 +#define IPU_LUT_REG_BASE 0x01020000 +#define IPU_SRM_REG_BASE 0x01040000 +#define IPU_TPM_REG_BASE 0x01060000 +#define IPU_DC_TMPL_REG_BASE 0x01080000 +#define IPU_ISP_TBPR_REG_BASE 0x010C0000 + + +extern u32 *ipu_cm_reg; +extern u32 *ipu_idmac_reg; +extern u32 *ipu_dp_reg; +extern u32 *ipu_ic_reg; +extern u32 *ipu_dc_reg; +extern u32 *ipu_dc_tmpl_reg; +extern u32 *ipu_dmfc_reg; +extern u32 *ipu_di_reg[]; +extern u32 *ipu_smfc_reg; +extern u32 *ipu_csi_reg[]; +extern u32 *ipu_tpmem_base; +extern u32 *ipu_disp_base[]; +extern u32 *ipu_vdi_reg; + +/* Register addresses */ +/* IPU Common registers */ +#define IPU_CONF (ipu_cm_reg) + +#define IPU_SRM_PRI1 (ipu_cm_reg + 0x00A0/4) +#define IPU_SRM_PRI2 (ipu_cm_reg + 0x00A4/4) +#define IPU_FS_PROC_FLOW1 (ipu_cm_reg + 0x00A8/4) +#define IPU_FS_PROC_FLOW2 (ipu_cm_reg + 0x00AC/4) +#define IPU_FS_PROC_FLOW3 (ipu_cm_reg + 0x00B0/4) +#define IPU_FS_DISP_FLOW1 (ipu_cm_reg + 0x00B4/4) +#define IPU_FS_DISP_FLOW2 (ipu_cm_reg + 0x00B8/4) +#define IPU_SKIP (ipu_cm_reg + 0x00BC/4) +#define IPU_DISP_ALT_CONF (ipu_cm_reg + 0x00C0/4) +#define IPU_DISP_GEN (ipu_cm_reg + 0x00C4/4) +#define IPU_DISP_ALT1 (ipu_cm_reg + 0x00C8/4) +#define IPU_DISP_ALT2 (ipu_cm_reg + 0x00CC/4) +#define IPU_DISP_ALT3 (ipu_cm_reg + 0x00D0/4) +#define IPU_DISP_ALT4 (ipu_cm_reg + 0x00D4/4) +#define IPU_SNOOP (ipu_cm_reg + 0x00D8/4) +#define IPU_MEM_RST (ipu_cm_reg + 0x00DC/4) +#define IPU_PM (ipu_cm_reg + 0x00E0/4) +#define IPU_GPR (ipu_cm_reg + 0x00E4/4) +#define IPU_CHA_DB_MODE_SEL(ch) (ipu_cm_reg + 0x0150/4 + (ch / 32)) +#define IPU_ALT_CHA_DB_MODE_SEL(ch) (ipu_cm_reg + 0x0168/4 + (ch / 32)) +#define IPU_CHA_CUR_BUF(ch) ({g_ipu_hw_rev >= 2 ? \ + (ipu_cm_reg + 0x023C/4 + (ch / 32)) : \ + (ipu_cm_reg + 0x0124/4 + (ch / 32)); }) +#define IPU_ALT_CUR_BUF0 ({g_ipu_hw_rev >= 2 ? \ + (ipu_cm_reg + 0x0244/4) : \ + (ipu_cm_reg + 0x012C/4); }) +#define IPU_ALT_CUR_BUF1 ({g_ipu_hw_rev >= 2 ? \ + (ipu_cm_reg + 0x0248/4) : \ + (ipu_cm_reg + 0x0130/4); }) +#define IPU_SRM_STAT ({g_ipu_hw_rev >= 2 ? \ + (ipu_cm_reg + 0x024C/4) : \ + (ipu_cm_reg + 0x0134/4); }) +#define IPU_PROC_TASK_STAT ({g_ipu_hw_rev >= 2 ? \ + (ipu_cm_reg + 0x0250/4) : \ + (ipu_cm_reg + 0x0138/4); }) +#define IPU_DISP_TASK_STAT ({g_ipu_hw_rev >= 2 ? \ + (ipu_cm_reg + 0x0254/4) : \ + (ipu_cm_reg + 0x013C/4); }) +#define IPU_CHA_BUF0_RDY(ch) ({g_ipu_hw_rev >= 2 ? \ + (ipu_cm_reg + 0x0268/4 + (ch / 32)) : \ + (ipu_cm_reg + 0x0140/4 + (ch / 32)); }) +#define IPU_CHA_BUF1_RDY(ch) ({g_ipu_hw_rev >= 2 ? \ + (ipu_cm_reg + 0x0270/4 + (ch / 32)) : \ + (ipu_cm_reg + 0x0148/4 + (ch / 32)); }) +#define IPU_ALT_CHA_BUF0_RDY(ch) ({g_ipu_hw_rev >= 2 ? \ + (ipu_cm_reg + 0x0278/4 + (ch / 32)) : \ + (ipu_cm_reg + 0x0158/4 + (ch / 32)); }) +#define IPU_ALT_CHA_BUF1_RDY(ch) ({g_ipu_hw_rev >= 2 ? \ + (ipu_cm_reg + 0x0280/4 + (ch / 32)) : \ + (ipu_cm_reg + 0x0160/4 + (ch / 32)); }) + +#define IPU_INT_CTRL(n) (ipu_cm_reg + 0x003C/4 + ((n) - 1)) +#define IPU_INT_CTRL_IRQ(irq) IPU_INT_CTRL(((irq) / 32)) +#define IPU_INT_STAT_IRQ(irq) IPU_INT_STAT(((irq) / 32)) +#define IPU_INT_STAT(n) ({g_ipu_hw_rev >= 2 ? \ + (ipu_cm_reg + 0x0200/4 + ((n) - 1)) : \ + (ipu_cm_reg + 0x00E8/4 + ((n) - 1)); }) + +#define IPUIRQ_2_STATREG(irq) (IPU_INT_STAT(1) + ((irq) / 32)) +#define IPUIRQ_2_CTRLREG(irq) (IPU_INT_CTRL(1) + ((irq) / 32)) +#define IPUIRQ_2_MASK(irq) (1UL << ((irq) & 0x1F)) + +#define VDI_FSIZE (ipu_vdi_reg) +#define VDI_C (ipu_vdi_reg + 0x0004/4) + +/* CMOS Sensor Interface Registers */ +#define CSI_SENS_CONF(csi) (ipu_csi_reg[csi]) +#define CSI_SENS_FRM_SIZE(csi) (ipu_csi_reg[csi] + 0x0004/4) +#define CSI_ACT_FRM_SIZE(csi) (ipu_csi_reg[csi] + 0x0008/4) +#define CSI_OUT_FRM_CTRL(csi) (ipu_csi_reg[csi] + 0x000C/4) +#define CSI_TST_CTRL(csi) (ipu_csi_reg[csi] + 0x0010/4) +#define CSI_CCIR_CODE_1(csi) (ipu_csi_reg[csi] + 0x0014/4) +#define CSI_CCIR_CODE_2(csi) (ipu_csi_reg[csi] + 0x0018/4) +#define CSI_CCIR_CODE_3(csi) (ipu_csi_reg[csi] + 0x001C/4) +#define CSI_MIPI_DI(csi) (ipu_csi_reg[csi] + 0x0020/4) +#define CSI_SKIP(csi) (ipu_csi_reg[csi] + 0x0024/4) +#define CSI_CPD_CTRL(csi) (ipu_csi_reg[csi] + 0x0028/4) +#define CSI_CPD_RC(csi, n) (ipu_csi_reg[csi] + 0x002C/4 + n) +#define CSI_CPD_RS(csi, n) (ipu_csi_reg[csi] + 0x004C/4 + n) +#define CSI_CPD_GRC(csi, n) (ipu_csi_reg[csi] + 0x005C/4 + n) +#define CSI_CPD_GRS(csi, n) (ipu_csi_reg[csi] + 0x007C/4 + n) +#define CSI_CPD_GBC(csi, n) (ipu_csi_reg[csi] + 0x008C/4 + n) +#define CSI_CPD_GBS(csi, n) (ipu_csi_reg[csi] + 0x00AC/4 + n) +#define CSI_CPD_BC(csi, n) (ipu_csi_reg[csi] + 0x00BC/4 + n) +#define CSI_CPD_BS(csi, n) (ipu_csi_reg[csi] + 0x00DC/4 + n) +#define CSI_CPD_OFFSET1(csi) (ipu_csi_reg[csi] + 0x00EC/4) +#define CSI_CPD_OFFSET2(csi) (ipu_csi_reg[csi] + 0x00F0/4) + +/*SMFC Registers */ +#define SMFC_MAP (ipu_smfc_reg) +#define SMFC_WMC (ipu_smfc_reg + 0x0004/4) +#define SMFC_BS (ipu_smfc_reg + 0x0008/4) + +/* Image Converter Registers */ +#define IC_CONF (ipu_ic_reg) +#define IC_PRP_ENC_RSC (ipu_ic_reg + 0x0004/4) +#define IC_PRP_VF_RSC (ipu_ic_reg + 0x0008/4) +#define IC_PP_RSC (ipu_ic_reg + 0x000C/4) +#define IC_CMBP_1 (ipu_ic_reg + 0x0010/4) +#define IC_CMBP_2 (ipu_ic_reg + 0x0014/4) +#define IC_IDMAC_1 (ipu_ic_reg + 0x0018/4) +#define IC_IDMAC_2 (ipu_ic_reg + 0x001C/4) +#define IC_IDMAC_3 (ipu_ic_reg + 0x0020/4) +#define IC_IDMAC_4 (ipu_ic_reg + 0x0024/4) + +#define IDMAC_CONF (ipu_idmac_reg + 0x0000) +#define IDMAC_CHA_EN(ch) (ipu_idmac_reg + 0x0004/4 + (ch/32)) +#define IDMAC_SEP_ALPHA (ipu_idmac_reg + 0x000C/4) +#define IDMAC_ALT_SEP_ALPHA (ipu_idmac_reg + 0x0010/4) +#define IDMAC_CHA_PRI(ch) (ipu_idmac_reg + 0x0014/4 + (ch/32)) +#define IDMAC_WM_EN(ch) (ipu_idmac_reg + 0x001C/4 + (ch/32)) +#define IDMAC_CH_LOCK_EN_1 ({g_ipu_hw_rev >= 2 ? \ + (ipu_idmac_reg + 0x0024/4) : 0; }) +#define IDMAC_CH_LOCK_EN_2 ({g_ipu_hw_rev >= 2 ? \ + (ipu_idmac_reg + 0x0028/4) : \ + (ipu_idmac_reg + 0x0024/4); }) +#define IDMAC_SUB_ADDR_0 ({g_ipu_hw_rev >= 2 ? \ + (ipu_idmac_reg + 0x002C/4) : \ + (ipu_idmac_reg + 0x0028/4); }) +#define IDMAC_SUB_ADDR_1 ({g_ipu_hw_rev >= 2 ? \ + (ipu_idmac_reg + 0x0030/4) : \ + (ipu_idmac_reg + 0x002C/4); }) +#define IDMAC_SUB_ADDR_2 ({g_ipu_hw_rev >= 2 ? \ + (ipu_idmac_reg + 0x0034/4) : \ + (ipu_idmac_reg + 0x0030/4); }) +#define IDMAC_BAND_EN(ch) ({g_ipu_hw_rev >= 2 ? \ + (ipu_idmac_reg + 0x0040/4 + (ch/32)) : \ + (ipu_idmac_reg + 0x0034/4 + (ch/32)); }) +#define IDMAC_CHA_BUSY(ch) ({g_ipu_hw_rev >= 2 ? \ + (ipu_idmac_reg + 0x0100/4 + (ch/32)) : \ + (ipu_idmac_reg + 0x0040/4 + (ch/32)); }) + +#define DI_GENERAL(di) (ipu_di_reg[di]) +#define DI_BS_CLKGEN0(di) (ipu_di_reg[di] + 0x0004/4) +#define DI_BS_CLKGEN1(di) (ipu_di_reg[di] + 0x0008/4) + +#define DI_SW_GEN0(di, gen) (ipu_di_reg[di] + 0x000C/4 + (gen - 1)) +#define DI_SW_GEN1(di, gen) (ipu_di_reg[di] + 0x0030/4 + (gen - 1)) +#define DI_STP_REP(di, gen) (ipu_di_reg[di] + 0x0148/4 + (gen - 1)/2) +#define DI_SYNC_AS_GEN(di) (ipu_di_reg[di] + 0x0054/4) +#define DI_DW_GEN(di, gen) (ipu_di_reg[di] + 0x0058/4 + gen) +#define DI_DW_SET(di, gen, set) (ipu_di_reg[di] + 0x0088/4 + gen + 0xC*set) +#define DI_SER_CONF(di) (ipu_di_reg[di] + 0x015C/4) +#define DI_SSC(di) (ipu_di_reg[di] + 0x0160/4) +#define DI_POL(di) (ipu_di_reg[di] + 0x0164/4) +#define DI_AW0(di) (ipu_di_reg[di] + 0x0168/4) +#define DI_AW1(di) (ipu_di_reg[di] + 0x016C/4) +#define DI_SCR_CONF(di) (ipu_di_reg[di] + 0x0170/4) +#define DI_STAT(di) (ipu_di_reg[di] + 0x0174/4) + +#define DMFC_RD_CHAN (ipu_dmfc_reg) +#define DMFC_WR_CHAN (ipu_dmfc_reg + 0x0004/4) +#define DMFC_WR_CHAN_DEF (ipu_dmfc_reg + 0x0008/4) +#define DMFC_DP_CHAN (ipu_dmfc_reg + 0x000C/4) +#define DMFC_DP_CHAN_DEF (ipu_dmfc_reg + 0x0010/4) +#define DMFC_GENERAL1 (ipu_dmfc_reg + 0x0014/4) +#define DMFC_GENERAL2 (ipu_dmfc_reg + 0x0018/4) +#define DMFC_IC_CTRL (ipu_dmfc_reg + 0x001C/4) +#define DMFC_STAT (ipu_dmfc_reg + 0x0020/4) + +#define DC_MAP_CONF_PTR(n) (ipu_dc_reg + 0x0108/4 + n/2) +#define DC_MAP_CONF_VAL(n) (ipu_dc_reg + 0x0144/4 + n/2) + +#define _RL_CH_2_OFFSET(ch) ((ch == 0) ? 8 : ( \ + (ch == 1) ? 0x24 : ( \ + (ch == 2) ? 0x40 : ( \ + (ch == 5) ? 0x64 : ( \ + (ch == 6) ? 0x80 : ( \ + (ch == 8) ? 0x9C : ( \ + (ch == 9) ? 0xBC : (-1)))))))) +#define DC_RL_CH(ch, evt) (ipu_dc_reg + _RL_CH_2_OFFSET(ch)/4 + evt/2) + +#define DC_EVT_NF 0 +#define DC_EVT_NL 1 +#define DC_EVT_EOF 2 +#define DC_EVT_NFIELD 3 +#define DC_EVT_EOL 4 +#define DC_EVT_EOFIELD 5 +#define DC_EVT_NEW_ADDR 6 +#define DC_EVT_NEW_CHAN 7 +#define DC_EVT_NEW_DATA 8 + +#define DC_EVT_NEW_ADDR_W_0 0 +#define DC_EVT_NEW_ADDR_W_1 1 +#define DC_EVT_NEW_CHAN_W_0 2 +#define DC_EVT_NEW_CHAN_W_1 3 +#define DC_EVT_NEW_DATA_W_0 4 +#define DC_EVT_NEW_DATA_W_1 5 +#define DC_EVT_NEW_ADDR_R_0 6 +#define DC_EVT_NEW_ADDR_R_1 7 +#define DC_EVT_NEW_CHAN_R_0 8 +#define DC_EVT_NEW_CHAN_R_1 9 +#define DC_EVT_NEW_DATA_R_0 10 +#define DC_EVT_NEW_DATA_R_1 11 +#define DC_EVEN_UGDE0 12 +#define DC_ODD_UGDE0 13 +#define DC_EVEN_UGDE1 14 +#define DC_ODD_UGDE1 15 +#define DC_EVEN_UGDE2 16 +#define DC_ODD_UGDE2 17 +#define DC_EVEN_UGDE3 18 +#define DC_ODD_UGDE3 19 + +#define dc_ch_offset(ch) \ +({ \ + const u8 _offset[] = { \ + 0, 0x1C, 0x38, 0x54, 0x58, 0x5C, 0x78, 0, 0x94, 0xB4}; \ + _offset[ch]; \ +}) +#define DC_WR_CH_CONF(ch) (ipu_dc_reg + dc_ch_offset(ch)/4) +#define DC_WR_CH_ADDR(ch) (ipu_dc_reg + dc_ch_offset(ch)/4 + 4/4) + +#define DC_WR_CH_CONF_1 (ipu_dc_reg + 0x001C/4) +#define DC_WR_CH_ADDR_1 (ipu_dc_reg + 0x0020/4) +#define DC_WR_CH_CONF_5 (ipu_dc_reg + 0x005C/4) +#define DC_WR_CH_ADDR_5 (ipu_dc_reg + 0x0060/4) +#define DC_GEN (ipu_dc_reg + 0x00D4/4) +#define DC_DISP_CONF1(disp) (ipu_dc_reg + 0x00D8/4 + disp) +#define DC_DISP_CONF2(disp) (ipu_dc_reg + 0x00E8/4 + disp) +#define DC_STAT (ipu_dc_reg + 0x01C8/4) +#define DC_UGDE_0(evt) (ipu_dc_reg + 0x0174/4 + evt*4) +#define DC_UGDE_1(evt) (ipu_dc_reg + 0x0178/4 + evt*4) +#define DC_UGDE_2(evt) (ipu_dc_reg + 0x017C/4 + evt*4) +#define DC_UGDE_3(evt) (ipu_dc_reg + 0x0180/4 + evt*4) + +#define DP_SYNC 0 +#define DP_ASYNC0 0x60 +#define DP_ASYNC1 0xBC +#define DP_COM_CONF(flow) (ipu_dp_reg + flow/4) +#define DP_GRAPH_WIND_CTRL(flow) (ipu_dp_reg + 0x0004/4 + flow/4) +#define DP_FG_POS(flow) (ipu_dp_reg + 0x0008/4 + flow/4) +#define DP_GAMMA_C(flow, i) (ipu_dp_reg + 0x0014/4 + flow/4 + i) +#define DP_GAMMA_S(flow, i) (ipu_dp_reg + 0x0034/4 + flow/4 + i) +#define DP_CSC_A_0(flow) (ipu_dp_reg + 0x0044/4 + flow/4) +#define DP_CSC_A_1(flow) (ipu_dp_reg + 0x0048/4 + flow/4) +#define DP_CSC_A_2(flow) (ipu_dp_reg + 0x004C/4 + flow/4) +#define DP_CSC_A_3(flow) (ipu_dp_reg + 0x0050/4 + flow/4) +#define DP_CSC_0(flow) (ipu_dp_reg + 0x0054/4 + flow/4) +#define DP_CSC_1(flow) (ipu_dp_reg + 0x0058/4 + flow/4) + +enum { + IPU_CONF_CSI0_EN = 0x00000001, + IPU_CONF_CSI1_EN = 0x00000002, + IPU_CONF_IC_EN = 0x00000004, + IPU_CONF_ROT_EN = 0x00000008, + IPU_CONF_ISP_EN = 0x00000010, + IPU_CONF_DP_EN = 0x00000020, + IPU_CONF_DI0_EN = 0x00000040, + IPU_CONF_DI1_EN = 0x00000080, + IPU_CONF_DMFC_EN = 0x00000400, + IPU_CONF_SMFC_EN = 0x00000100, + IPU_CONF_DC_EN = 0x00000200, + IPU_CONF_VDI_EN = 0x00001000, + IPU_CONF_IDMAC_DIS = 0x00400000, + IPU_CONF_IC_DMFC_SEL = 0x02000000, + IPU_CONF_IC_DMFC_SYNC = 0x04000000, + IPU_CONF_VDI_DMFC_SYNC = 0x08000000, + IPU_CONF_CSI0_DATA_SOURCE = 0x10000000, + IPU_CONF_CSI0_DATA_SOURCE_OFFSET = 28, + IPU_CONF_CSI1_DATA_SOURCE = 0x20000000, + IPU_CONF_IC_INPUT = 0x40000000, + IPU_CONF_CSI_SEL = 0x80000000, + + DI0_COUNTER_RELEASE = 0x01000000, + DI1_COUNTER_RELEASE = 0x02000000, + + FS_PRPVF_ROT_SRC_SEL_MASK = 0x00000F00, + FS_PRPVF_ROT_SRC_SEL_OFFSET = 8, + FS_PRPENC_ROT_SRC_SEL_MASK = 0x0000000F, + FS_PRPENC_ROT_SRC_SEL_OFFSET = 0, + FS_PP_ROT_SRC_SEL_MASK = 0x000F0000, + FS_PP_ROT_SRC_SEL_OFFSET = 16, + FS_PP_SRC_SEL_MASK = 0x0000F000, + FS_PP_SRC_SEL_OFFSET = 12, + FS_PRP_SRC_SEL_MASK = 0x0F000000, + FS_PRP_SRC_SEL_OFFSET = 24, + FS_VF_IN_VALID = 0x80000000, + FS_ENC_IN_VALID = 0x40000000, + FS_VDI_SRC_SEL_MASK = 0x30000000, + FS_VDI_SRC_SEL_OFFSET = 28, + + + FS_PRPENC_DEST_SEL_MASK = 0x0000000F, + FS_PRPENC_DEST_SEL_OFFSET = 0, + FS_PRPVF_DEST_SEL_MASK = 0x000000F0, + FS_PRPVF_DEST_SEL_OFFSET = 4, + FS_PRPVF_ROT_DEST_SEL_MASK = 0x00000F00, + FS_PRPVF_ROT_DEST_SEL_OFFSET = 8, + FS_PP_DEST_SEL_MASK = 0x0000F000, + FS_PP_DEST_SEL_OFFSET = 12, + FS_PP_ROT_DEST_SEL_MASK = 0x000F0000, + FS_PP_ROT_DEST_SEL_OFFSET = 16, + FS_PRPENC_ROT_DEST_SEL_MASK = 0x00F00000, + FS_PRPENC_ROT_DEST_SEL_OFFSET = 20, + + FS_SMFC0_DEST_SEL_MASK = 0x0000000F, + FS_SMFC0_DEST_SEL_OFFSET = 0, + FS_SMFC1_DEST_SEL_MASK = 0x00000070, + FS_SMFC1_DEST_SEL_OFFSET = 4, + FS_SMFC2_DEST_SEL_MASK = 0x00000780, + FS_SMFC2_DEST_SEL_OFFSET = 7, + FS_SMFC3_DEST_SEL_MASK = 0x00003800, + FS_SMFC3_DEST_SEL_OFFSET = 11, + + FS_DC1_SRC_SEL_MASK = 0x00F00000, + FS_DC1_SRC_SEL_OFFSET = 20, + FS_DC2_SRC_SEL_MASK = 0x000F0000, + FS_DC2_SRC_SEL_OFFSET = 16, + FS_DP_SYNC0_SRC_SEL_MASK = 0x0000000F, + FS_DP_SYNC0_SRC_SEL_OFFSET = 0, + FS_DP_SYNC1_SRC_SEL_MASK = 0x000000F0, + FS_DP_SYNC1_SRC_SEL_OFFSET = 4, + FS_DP_ASYNC0_SRC_SEL_MASK = 0x00000F00, + FS_DP_ASYNC0_SRC_SEL_OFFSET = 8, + FS_DP_ASYNC1_SRC_SEL_MASK = 0x0000F000, + FS_DP_ASYNC1_SRC_SEL_OFFSET = 12, + + FS_AUTO_REF_PER_MASK = 0, + FS_AUTO_REF_PER_OFFSET = 16, + + TSTAT_VF_MASK = 0x0000000C, + TSTAT_VF_OFFSET = 2, + TSTAT_VF_ROT_MASK = 0x00000300, + TSTAT_VF_ROT_OFFSET = 8, + TSTAT_ENC_MASK = 0x00000003, + TSTAT_ENC_OFFSET = 0, + TSTAT_ENC_ROT_MASK = 0x000000C0, + TSTAT_ENC_ROT_OFFSET = 6, + TSTAT_PP_MASK = 0x00000030, + TSTAT_PP_OFFSET = 4, + TSTAT_PP_ROT_MASK = 0x00000C00, + TSTAT_PP_ROT_OFFSET = 10, + + TASK_STAT_IDLE = 0, + TASK_STAT_ACTIVE = 1, + TASK_STAT_WAIT4READY = 2, + + /* Image Converter Register bits */ + IC_CONF_PRPENC_EN = 0x00000001, + IC_CONF_PRPENC_CSC1 = 0x00000002, + IC_CONF_PRPENC_ROT_EN = 0x00000004, + IC_CONF_PRPVF_EN = 0x00000100, + IC_CONF_PRPVF_CSC1 = 0x00000200, + IC_CONF_PRPVF_CSC2 = 0x00000400, + IC_CONF_PRPVF_CMB = 0x00000800, + IC_CONF_PRPVF_ROT_EN = 0x00001000, + IC_CONF_PP_EN = 0x00010000, + IC_CONF_PP_CSC1 = 0x00020000, + IC_CONF_PP_CSC2 = 0x00040000, + IC_CONF_PP_CMB = 0x00080000, + IC_CONF_PP_ROT_EN = 0x00100000, + IC_CONF_IC_GLB_LOC_A = 0x10000000, + IC_CONF_KEY_COLOR_EN = 0x20000000, + IC_CONF_RWS_EN = 0x40000000, + IC_CONF_CSI_MEM_WR_EN = 0x80000000, + + IC_IDMAC_1_CB0_BURST_16 = 0x00000001, + IC_IDMAC_1_CB1_BURST_16 = 0x00000002, + IC_IDMAC_1_CB2_BURST_16 = 0x00000004, + IC_IDMAC_1_CB3_BURST_16 = 0x00000008, + IC_IDMAC_1_CB4_BURST_16 = 0x00000010, + IC_IDMAC_1_CB5_BURST_16 = 0x00000020, + IC_IDMAC_1_CB6_BURST_16 = 0x00000040, + IC_IDMAC_1_CB7_BURST_16 = 0x00000080, + IC_IDMAC_1_PRPENC_ROT_MASK = 0x00003800, + IC_IDMAC_1_PRPENC_ROT_OFFSET = 11, + IC_IDMAC_1_PRPVF_ROT_MASK = 0x0001C000, + IC_IDMAC_1_PRPVF_ROT_OFFSET = 14, + IC_IDMAC_1_PP_ROT_MASK = 0x000E0000, + IC_IDMAC_1_PP_ROT_OFFSET = 17, + IC_IDMAC_1_PP_FLIP_RS = 0x00400000, + IC_IDMAC_1_PRPVF_FLIP_RS = 0x00200000, + IC_IDMAC_1_PRPENC_FLIP_RS = 0x00100000, + + IC_IDMAC_2_PRPENC_HEIGHT_MASK = 0x000003FF, + IC_IDMAC_2_PRPENC_HEIGHT_OFFSET = 0, + IC_IDMAC_2_PRPVF_HEIGHT_MASK = 0x000FFC00, + IC_IDMAC_2_PRPVF_HEIGHT_OFFSET = 10, + IC_IDMAC_2_PP_HEIGHT_MASK = 0x3FF00000, + IC_IDMAC_2_PP_HEIGHT_OFFSET = 20, + + IC_IDMAC_3_PRPENC_WIDTH_MASK = 0x000003FF, + IC_IDMAC_3_PRPENC_WIDTH_OFFSET = 0, + IC_IDMAC_3_PRPVF_WIDTH_MASK = 0x000FFC00, + IC_IDMAC_3_PRPVF_WIDTH_OFFSET = 10, + IC_IDMAC_3_PP_WIDTH_MASK = 0x3FF00000, + IC_IDMAC_3_PP_WIDTH_OFFSET = 20, + + CSI_SENS_CONF_DATA_FMT_SHIFT = 8, + CSI_SENS_CONF_DATA_FMT_MASK = 0x00000700, + CSI_SENS_CONF_DATA_FMT_RGB_YUV444 = 0L, + CSI_SENS_CONF_DATA_FMT_YUV422_YUYV = 1L, + CSI_SENS_CONF_DATA_FMT_YUV422_UYVY = 2L, + CSI_SENS_CONF_DATA_FMT_BAYER = 3L, + CSI_SENS_CONF_DATA_FMT_RGB565 = 4L, + CSI_SENS_CONF_DATA_FMT_RGB555 = 5L, + CSI_SENS_CONF_DATA_FMT_RGB444 = 6L, + CSI_SENS_CONF_DATA_FMT_JPEG = 7L, + + CSI_SENS_CONF_VSYNC_POL_SHIFT = 0, + CSI_SENS_CONF_HSYNC_POL_SHIFT = 1, + CSI_SENS_CONF_DATA_POL_SHIFT = 2, + CSI_SENS_CONF_PIX_CLK_POL_SHIFT = 3, + CSI_SENS_CONF_SENS_PRTCL_SHIFT = 4, + CSI_SENS_CONF_PACK_TIGHT_SHIFT = 7, + CSI_SENS_CONF_DATA_WIDTH_SHIFT = 11, + CSI_SENS_CONF_EXT_VSYNC_SHIFT = 15, + CSI_SENS_CONF_DIVRATIO_SHIFT = 16, + + CSI_SENS_CONF_DIVRATIO_MASK = 0x00FF0000L, + CSI_SENS_CONF_DATA_DEST_SHIFT = 24, + CSI_SENS_CONF_DATA_DEST_MASK = 0x07000000L, + CSI_SENS_CONF_JPEG8_EN_SHIFT = 27, + CSI_SENS_CONF_JPEG_EN_SHIFT = 28, + CSI_SENS_CONF_FORCE_EOF_SHIFT = 29, + CSI_SENS_CONF_DATA_EN_POL_SHIFT = 31, + + CSI_DATA_DEST_ISP = 1L, + CSI_DATA_DEST_IC = 2L, + CSI_DATA_DEST_IDMAC = 4L, + + CSI_CCIR_ERR_DET_EN = 0x01000000L, + CSI_HORI_DOWNSIZE_EN = 0x80000000L, + CSI_VERT_DOWNSIZE_EN = 0x40000000L, + CSI_TEST_GEN_MODE_EN = 0x01000000L, + + CSI_HSC_MASK = 0x1FFF0000, + CSI_HSC_SHIFT = 16, + CSI_VSC_MASK = 0x00000FFF, + CSI_VSC_SHIFT = 0, + + CSI_TEST_GEN_R_MASK = 0x000000FFL, + CSI_TEST_GEN_R_SHIFT = 0, + CSI_TEST_GEN_G_MASK = 0x0000FF00L, + CSI_TEST_GEN_G_SHIFT = 8, + CSI_TEST_GEN_B_MASK = 0x00FF0000L, + CSI_TEST_GEN_B_SHIFT = 16, + + CSI_MIPI_DI0_MASK = 0x000000FFL, + CSI_MIPI_DI0_SHIFT = 0, + CSI_MIPI_DI1_MASK = 0x0000FF00L, + CSI_MIPI_DI1_SHIFT = 8, + CSI_MIPI_DI2_MASK = 0x00FF0000L, + CSI_MIPI_DI2_SHIFT = 16, + CSI_MIPI_DI3_MASK = 0xFF000000L, + CSI_MIPI_DI3_SHIFT = 24, + + CSI_MAX_RATIO_SKIP_ISP_MASK = 0x00070000L, + CSI_MAX_RATIO_SKIP_ISP_SHIFT = 16, + CSI_SKIP_ISP_MASK = 0x00F80000L, + CSI_SKIP_ISP_SHIFT = 19, + CSI_MAX_RATIO_SKIP_SMFC_MASK = 0x00000007L, + CSI_MAX_RATIO_SKIP_SMFC_SHIFT = 0, + CSI_SKIP_SMFC_MASK = 0x000000F8L, + CSI_SKIP_SMFC_SHIFT = 3, + CSI_ID_2_SKIP_MASK = 0x00000300L, + CSI_ID_2_SKIP_SHIFT = 8, + + CSI_COLOR_FIRST_ROW_MASK = 0x00000002L, + CSI_COLOR_FIRST_COMP_MASK = 0x00000001L, + + SMFC_MAP_CH0_MASK = 0x00000007L, + SMFC_MAP_CH0_SHIFT = 0, + SMFC_MAP_CH1_MASK = 0x00000038L, + SMFC_MAP_CH1_SHIFT = 3, + SMFC_MAP_CH2_MASK = 0x000001C0L, + SMFC_MAP_CH2_SHIFT = 6, + SMFC_MAP_CH3_MASK = 0x00000E00L, + SMFC_MAP_CH3_SHIFT = 9, + + SMFC_WM0_SET_MASK = 0x00000007L, + SMFC_WM0_SET_SHIFT = 0, + SMFC_WM1_SET_MASK = 0x000001C0L, + SMFC_WM1_SET_SHIFT = 6, + SMFC_WM2_SET_MASK = 0x00070000L, + SMFC_WM2_SET_SHIFT = 16, + SMFC_WM3_SET_MASK = 0x01C00000L, + SMFC_WM3_SET_SHIFT = 22, + + SMFC_WM0_CLR_MASK = 0x00000038L, + SMFC_WM0_CLR_SHIFT = 3, + SMFC_WM1_CLR_MASK = 0x00000E00L, + SMFC_WM1_CLR_SHIFT = 9, + SMFC_WM2_CLR_MASK = 0x00380000L, + SMFC_WM2_CLR_SHIFT = 19, + SMFC_WM3_CLR_MASK = 0x0E000000L, + SMFC_WM3_CLR_SHIFT = 25, + + SMFC_BS0_MASK = 0x0000000FL, + SMFC_BS0_SHIFT = 0, + SMFC_BS1_MASK = 0x000000F0L, + SMFC_BS1_SHIFT = 4, + SMFC_BS2_MASK = 0x00000F00L, + SMFC_BS2_SHIFT = 8, + SMFC_BS3_MASK = 0x0000F000L, + SMFC_BS3_SHIFT = 12, + + PF_CONF_TYPE_MASK = 0x00000007, + PF_CONF_TYPE_SHIFT = 0, + PF_CONF_PAUSE_EN = 0x00000010, + PF_CONF_RESET = 0x00008000, + PF_CONF_PAUSE_ROW_MASK = 0x00FF0000, + PF_CONF_PAUSE_ROW_SHIFT = 16, + + DI_DW_GEN_ACCESS_SIZE_OFFSET = 24, + DI_DW_GEN_COMPONENT_SIZE_OFFSET = 16, + + DI_GEN_DI_CLK_EXT = 0x100000, + DI_GEN_POLARITY_1 = 0x00000001, + DI_GEN_POLARITY_2 = 0x00000002, + DI_GEN_POLARITY_3 = 0x00000004, + DI_GEN_POLARITY_4 = 0x00000008, + DI_GEN_POLARITY_5 = 0x00000010, + DI_GEN_POLARITY_6 = 0x00000020, + DI_GEN_POLARITY_7 = 0x00000040, + DI_GEN_POLARITY_8 = 0x00000080, + + DI_POL_DRDY_DATA_POLARITY = 0x00000080, + DI_POL_DRDY_POLARITY_15 = 0x00000010, + + DI_VSYNC_SEL_OFFSET = 13, + + DC_WR_CH_CONF_FIELD_MODE = 0x00000200, + DC_WR_CH_CONF_PROG_TYPE_OFFSET = 5, + DC_WR_CH_CONF_PROG_TYPE_MASK = 0x000000E0, + DC_WR_CH_CONF_PROG_DI_ID = 0x00000004, + DC_WR_CH_CONF_PROG_DISP_ID_OFFSET = 3, + DC_WR_CH_CONF_PROG_DISP_ID_MASK = 0x00000018, + + DC_UGDE_0_ODD_EN = 0x02000000, + DC_UGDE_0_ID_CODED_MASK = 0x00000007, + DC_UGDE_0_ID_CODED_OFFSET = 0, + DC_UGDE_0_EV_PRIORITY_MASK = 0x00000078, + DC_UGDE_0_EV_PRIORITY_OFFSET = 3, + + DP_COM_CONF_FG_EN = 0x00000001, + DP_COM_CONF_GWSEL = 0x00000002, + DP_COM_CONF_GWAM = 0x00000004, + DP_COM_CONF_GWCKE = 0x00000008, + DP_COM_CONF_CSC_DEF_MASK = 0x00000300, + DP_COM_CONF_CSC_DEF_OFFSET = 8, + DP_COM_CONF_CSC_DEF_FG = 0x00000300, + DP_COM_CONF_CSC_DEF_BG = 0x00000200, + DP_COM_CONF_CSC_DEF_BOTH = 0x00000100, + DP_COM_CONF_GAMMA_EN = 0x00001000, + DP_COM_CONF_GAMMA_YUV_EN = 0x00002000, + + DI_SER_CONF_LLA_SER_ACCESS = 0x00000020, + DI_SER_CONF_SERIAL_CLK_POL = 0x00000010, + DI_SER_CONF_SERIAL_DATA_POL = 0x00000008, + DI_SER_CONF_SERIAL_RS_POL = 0x00000004, + DI_SER_CONF_SERIAL_CS_POL = 0x00000002, + DI_SER_CONF_WAIT4SERIAL = 0x00000001, + + VDI_C_CH_420 = 0x00000000, + VDI_C_CH_422 = 0x00000002, + VDI_C_MOT_SEL_FULL = 0x00000008, + VDI_C_MOT_SEL_LOW = 0x00000004, + VDI_C_MOT_SEL_MED = 0x00000000, + VDI_C_BURST_SIZE1_4 = 0x00000030, + VDI_C_BURST_SIZE2_4 = 0x00000300, + VDI_C_BURST_SIZE3_4 = 0x00003000, + VDI_C_VWM1_SET_1 = 0x00000000, + VDI_C_VWM1_CLR_2 = 0x00080000, + VDI_C_VWM3_SET_1 = 0x00000000, + VDI_C_VWM3_CLR_2 = 0x02000000, + VDI_C_TOP_FIELD_MAN_1 = 0x40000000, + VDI_C_TOP_FIELD_AUTO_1 = 0x80000000, +}; + +enum di_pins { + DI_PIN11 = 0, + DI_PIN12 = 1, + DI_PIN13 = 2, + DI_PIN14 = 3, + DI_PIN15 = 4, + DI_PIN16 = 5, + DI_PIN17 = 6, + DI_PIN_CS = 7, + + DI_PIN_SER_CLK = 0, + DI_PIN_SER_RS = 1, +}; + +enum di_sync_wave { + DI_SYNC_NONE = -1, + DI_SYNC_CLK = 0, + DI_SYNC_INT_HSYNC = 1, + DI_SYNC_HSYNC = 2, + DI_SYNC_VSYNC = 3, + DI_SYNC_DE = 5, +}; + +/* DC template opcodes */ +#define WROD(lf) (0x18 | (lf << 1)) + +#endif diff --git a/drivers/mxc/mcu_pmic/Kconfig b/drivers/mxc/mcu_pmic/Kconfig new file mode 100644 index 000000000000..cb6815e92d86 --- /dev/null +++ b/drivers/mxc/mcu_pmic/Kconfig @@ -0,0 +1,17 @@ +# +# PMIC Modules configuration +# + +config MXC_PMIC_MC9S08DZ60 + tristate "MC9S08DZ60 PMIC" + depends on ARCH_MXC && I2C + ---help--- + This is the MXC MC9S08DZ60(MCU) PMIC support. + +config MXC_MC9SDZ60_RTC + tristate "MC9SDZ60 Real Time Clock (RTC) support" + depends on MXC_PMIC_MC9SDZ60 + ---help--- + This is the MC9SDZ60 RTC module driver. This module provides kernel API + for RTC part of MC9SDZ60. + If you want MC9SDZ60 RTC support, you should say Y here diff --git a/drivers/mxc/mcu_pmic/Makefile b/drivers/mxc/mcu_pmic/Makefile new file mode 100644 index 000000000000..96aae94d5290 --- /dev/null +++ b/drivers/mxc/mcu_pmic/Makefile @@ -0,0 +1,6 @@ +# +# Makefile for the mc9sdz60 pmic drivers. +# + +obj-$(CONFIG_MXC_PMIC_MC9SDZ60) += pmic_mc9sdz60_mod.o +pmic_mc9sdz60_mod-objs := mcu_pmic_core.o max8660.o mc9s08dz60.o mcu_pmic_gpio.o diff --git a/drivers/mxc/mcu_pmic/max8660.c b/drivers/mxc/mcu_pmic/max8660.c new file mode 100644 index 000000000000..17fe22958ca9 --- /dev/null +++ b/drivers/mxc/mcu_pmic/max8660.c @@ -0,0 +1,154 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file max8660.c + * @brief Driver for max8660 + * + * @ingroup pmic + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "mcu_pmic_core.h" +#include "max8660.h" + +/* I2C bus id and device address of mcu */ +#define I2C1_BUS 0 +#define MAX8660_I2C_ADDR 0x68 + +static struct i2c_client *max8660_i2c_client; + + /* reg names for max8660 + REG_MAX8660_OUTPUT_ENABLE_1, + REG_MAX8660_OUTPUT_ENABLE_2, + REG_MAX8660_VOLT__CHANGE_1, + REG_MAX8660_V3_TARGET_VOLT_1, + REG_MAX8660_V3_TARGET_VOLT_2, + REG_MAX8660_V4_TARGET_VOLT_1, + REG_MAX8660_V4_TARGET_VOLT_2, + REG_MAX8660_V5_TARGET_VOLT_1, + REG_MAX8660_V5_TARGET_VOLT_2, + REG_MAX8660_V6V7_TARGET_VOLT, + REG_MAX8660_FORCE_PWM + */ + + /* save down the reg values for the device is write only */ +static u8 max8660_reg_value_table[] = { + 0x0, 0x0, 0x0, 0x17, 0x17, 0x1F, 0x1F, 0x04, 0x04, 0x0, 0x0 +}; +static int max8660_dev_present; + +int is_max8660_present(void) +{ + return max8660_dev_present; +} + +int max8660_get_buffered_reg_val(int reg_name, u8 *value) +{ + if (!max8660_dev_present) + return -1; + /* outof range */ + if (reg_name < REG_MAX8660_OUTPUT_ENABLE_1 + || reg_name > REG_MAX8660_FORCE_PWM) + return -1; + *value = + max8660_reg_value_table[reg_name - REG_MAX8660_OUTPUT_ENABLE_1]; + return 0; +} +int max8660_save_buffered_reg_val(int reg_name, u8 value) +{ + + /* outof range */ + if (reg_name < REG_MAX8660_OUTPUT_ENABLE_1 + || reg_name > REG_MAX8660_FORCE_PWM) + return -1; + max8660_reg_value_table[reg_name - REG_MAX8660_OUTPUT_ENABLE_1] = value; + return 0; +} + +int max8660_write_reg(u8 reg, u8 value) +{ + if (max8660_dev_present && (i2c_smbus_write_byte_data( + max8660_i2c_client, reg, value) >= 0)) + return 0; + return -1; +} + +/*! + * max8660 I2C attach function + * + * @param adapter struct i2c_client * + * @return 0 for max8660 successfully detected + */ +static int max8660_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + int retval; + max8660_i2c_client = client; + retval = i2c_smbus_write_byte_data(max8660_i2c_client, + MAX8660_OUTPUT_ENABLE_1, 0); + if (retval == 0) { + max8660_dev_present = 1; + pr_info("max8660 probed !\n"); + } else { + max8660_dev_present = 0; + pr_info("max8660 not detected!\n"); + } + return retval; +} + +/*! + * max8660 I2C detach function + * + * @param client struct i2c_client * + * @return 0 + */ +static int max8660_remove(struct i2c_client *client) +{ + return 0; +} + +static const struct i2c_device_id max8660_id[] = { + { "max8660", 0 }, + {}, +}; +MODULE_DEVICE_TABLE(i2c, max8660_id); + +static struct i2c_driver max8660_i2c_driver = { + .driver = { + .owner = THIS_MODULE, + .name = "max8660",}, + .probe = max8660_probe, + .remove = max8660_remove, + .id_table = max8660_id, +}; + +/* called by pmic core when init*/ +int max8660_init(void) +{ + int err; + err = i2c_add_driver(&max8660_i2c_driver); + return err; +} +void max8660_exit(void) +{ + i2c_del_driver(&max8660_i2c_driver); +} diff --git a/drivers/mxc/mcu_pmic/max8660.h b/drivers/mxc/mcu_pmic/max8660.h new file mode 100644 index 000000000000..370ca5f66a28 --- /dev/null +++ b/drivers/mxc/mcu_pmic/max8660.h @@ -0,0 +1,49 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file max8660.h + * @brief Driver for max8660 + * + * @ingroup pmic + */ +#ifndef _MAX8660_H_ +#define _MAX8660_H_ + +#ifdef __KERNEL__ + +#define MAX8660_OUTPUT_ENABLE_1 0x10 +#define MAX8660_OUTPUT_ENABLE_2 0x12 +#define MAX8660_VOLT_CHANGE_CONTROL 0x20 +#define MAX8660_V3_TARGET_VOLT_1 0x23 +#define MAX8660_V3_TARGET_VOLT_2 0x24 +#define MAX8660_V4_TARGET_VOLT_1 0x29 +#define MAX8660_V4_TARGET_VOLT_2 0x2A +#define MAX8660_V5_TARGET_VOLT_1 0x32 +#define MAX8660_V5_TARGET_VOLT_2 0x33 +#define MAX8660_V6V7_TARGET_VOLT 0x39 +#define MAX8660_FORCE_PWM 0x80 + +int is_max8660_present(void); +int max8660_write_reg(u8 reg, u8 value); +int max8660_save_buffered_reg_val(int reg_name, u8 value); +int max8660_get_buffered_reg_val(int reg_name, u8 *value); +int max8660_init(void); +void max8660_exit(void); + +extern int reg_max8660_probe(void); +extern int reg_max8660_remove(void); + +#endif /* __KERNEL__ */ + +#endif /* _MAX8660_H_ */ diff --git a/drivers/mxc/mcu_pmic/mc9s08dz60.c b/drivers/mxc/mcu_pmic/mc9s08dz60.c new file mode 100644 index 000000000000..c51ffcd5ba7d --- /dev/null +++ b/drivers/mxc/mcu_pmic/mc9s08dz60.c @@ -0,0 +1,197 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + + /*! + * @file mc9s08dz60.c + * @brief Driver for MC9sdz60 + * + * @ingroup pmic + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include "mc9s08dz60.h" + +/* I2C bus id and device address of mcu */ +#define I2C1_BUS 0 +#define MC9S08DZ60_I2C_ADDR 0xD2 /* 7bits I2C address */ +static struct i2c_client *mc9s08dz60_i2c_client; + +int mc9s08dz60_read_reg(u8 reg, u8 *value) +{ + *value = (u8) i2c_smbus_read_byte_data(mc9s08dz60_i2c_client, reg); + return 0; +} + +int mc9s08dz60_write_reg(u8 reg, u8 value) +{ + if (i2c_smbus_write_byte_data(mc9s08dz60_i2c_client, reg, value) < 0) + return -1; + return 0; +} + +static ssize_t mc9s08dz60_show(struct device *dev, + struct device_attribute *attr, char *buf) +{ + unsigned int i; + u8 value; + int offset = 7; + + for (i = 0; i < 7; i++) { + mc9s08dz60_read_reg(i, &value); + pr_info("reg%02x: %02x\t", i, value); + mc9s08dz60_read_reg(i + offset, &value); + pr_info("reg%02x: %02x\t", i + offset, value); + mc9s08dz60_read_reg(i + offset * 2, &value); + pr_info("reg%02x: %02x\t", i + offset * 2, value); + mc9s08dz60_read_reg(i + offset * 3, &value); + pr_info("reg%02x: %02x\t", i + offset * 3, value); + mc9s08dz60_read_reg(i + offset * 4, &value); + pr_info("reg%02x: %02x\t", i + offset * 4, value); + mc9s08dz60_read_reg(i + offset * 5, &value); + pr_info("reg%02x: %02x\n", i + offset * 5, value); + } + + return 0; +} + +static ssize_t mc9s08dz60_store(struct device *dev, + struct device_attribute *attr, const char *buf, + size_t count) +{ + int ret; + unsigned long reg, new_value; + u8 value; + char *p; + + strict_strtoul(buf, 16, ®); + + p = NULL; + p = memchr(buf, ' ', count); + + if (p == NULL) { + mc9s08dz60_read_reg(reg, &value); + pr_info("reg%02lu: %06x\n", reg, value); + return count; + } + + p += 1; + + strict_strtoul(p, 16, &new_value); + value = new_value; + + ret = mc9s08dz60_write_reg((u8)reg, value); + if (ret == 0) + pr_info("write reg%02lx: %06x\n", reg, value); + else + pr_info("register update failed\n"); + + return count; +} + +static struct device_attribute mc9s08dz60_dev_attr = { + .attr = { + .name = "mc9s08dz60_ctl", + .mode = S_IRUSR | S_IWUSR, + }, + .show = mc9s08dz60_show, + .store = mc9s08dz60_store, +}; + + +/*! + * mc9s08dz60 I2C attach function + * + * @param adapter struct i2c_adapter * + * @return 0 + */ +static int mc9s08dz60_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + int ret = 0; + struct mc9s08dz60 *mc9s08dz60 = NULL; + struct mc9s08dz60_platform_data *plat_data = client->dev.platform_data; + pr_info("mc9s08dz60 probing .... \n"); + + mc9s08dz60 = kzalloc(sizeof(struct mc9s08dz60), GFP_KERNEL); + if (mc9s08dz60 == NULL) + return -ENOMEM; + + i2c_set_clientdata(client, mc9s08dz60); + mc9s08dz60->dev = &client->dev; + mc9s08dz60->i2c_client = client; + + if (plat_data && plat_data->init) { + ret = plat_data->init(mc9s08dz60); + if (ret != 0) + return -1; + } + + ret = device_create_file(&client->dev, &mc9s08dz60_dev_attr); + if (ret) + dev_err(&client->dev, "create device file failed!\n"); + + + mc9s08dz60_i2c_client = client; + + return 0; +} + +/*! + * mc9s08dz60 I2C detach function + * + * @param client struct i2c_client * + * @return 0 + */ +static int mc9s08dz60_remove(struct i2c_client *client) +{ + return 0; +} + +static const struct i2c_device_id mc9s08dz60_id[] = { + { "mc9s08dz60", 0 }, + {}, +}; +MODULE_DEVICE_TABLE(i2c, mc9s08dz60_id); + +static struct i2c_driver mc9s08dz60_i2c_driver = { + .driver = {.owner = THIS_MODULE, + .name = "mc9s08dz60", + }, + .probe = mc9s08dz60_probe, + .remove = mc9s08dz60_remove, + .id_table = mc9s08dz60_id, +}; + +#define SET_BIT_IN_BYTE(byte, pos) (byte |= (0x01 << pos)) +#define CLEAR_BIT_IN_BYTE(byte, pos) (byte &= ~(0x01 << pos)) + +int mc9s08dz60_init(void) +{ + int err; + err = i2c_add_driver(&mc9s08dz60_i2c_driver); + return err; +} +void mc9s08dz60_exit(void) +{ + i2c_del_driver(&mc9s08dz60_i2c_driver); +} diff --git a/drivers/mxc/mcu_pmic/mc9s08dz60.h b/drivers/mxc/mcu_pmic/mc9s08dz60.h new file mode 100644 index 000000000000..382d905cd3d1 --- /dev/null +++ b/drivers/mxc/mcu_pmic/mc9s08dz60.h @@ -0,0 +1,73 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mc9s08dz60.h + * @brief Driver for mc9s08dz60 + * + * @ingroup pmic + */ +#ifndef _MC9SDZ60_H_ +#define _MC9SDZ60_H_ + +#define MCU_VERSION 0x00 +/*#define Reserved 0x01*/ +#define MCU_SECS 0x02 +#define MCU_MINS 0x03 +#define MCU_HRS 0x04 +#define MCU_DAY 0x05 +#define MCU_DATE 0x06 +#define MCU_MONTH 0x07 +#define MCU_YEAR 0x08 + +#define MCU_ALARM_SECS 0x09 +#define MCU_ALARM_MINS 0x0A +#define MCU_ALARM_HRS 0x0B +/* #define Reserved 0x0C*/ +/* #define Reserved 0x0D*/ +#define MCU_TS_CONTROL 0x0E +#define MCU_X_LOW 0x0F +#define MCU_Y_LOW 0x10 +#define MCU_XY_HIGH 0x11 +#define MCU_X_LEFT_LOW 0x12 +#define MCU_X_LEFT_HIGH 0x13 +#define MCU_X_RIGHT 0x14 +#define MCU_Y_TOP_LOW 0x15 +#define MCU_Y_TOP_HIGH 0x16 +#define MCU_Y_BOTTOM 0x17 +/* #define Reserved 0x18*/ +/* #define Reserved 0x19*/ +#define MCU_RESET_1 0x1A +#define MCU_RESET_2 0x1B +#define MCU_POWER_CTL 0x1C +#define MCU_DELAY_CONFIG 0x1D +/* #define Reserved 0x1E */ +/* #define Reserved 0x1F */ +#define MCU_GPIO_1 0x20 +#define MCU_GPIO_2 0x21 +#define MCU_KPD_1 0x22 +#define MCU_KPD_2 0x23 +#define MCU_KPD_CONTROL 0x24 +#define MCU_INT_ENABLE_1 0x25 +#define MCU_INT_ENABLE_2 0x26 +#define MCU_INT_FLAG_1 0x27 +#define MCU_INT_FLAG_2 0x28 +#define MCU_DES_FLAG 0x29 +int mc9s08dz60_read_reg(u8 reg, u8 *value); +int mc9s08dz60_write_reg(u8 reg, u8 value); +int mc9s08dz60_init(void); +void mc9s08dz60_exit(void); + +extern int reg_mc9s08dz60_probe(void); +extern int reg_mc9s08dz60_remove(void); + +#endif /* _MC9SDZ60_H_ */ diff --git a/drivers/mxc/mcu_pmic/mcu_pmic_core.c b/drivers/mxc/mcu_pmic/mcu_pmic_core.c new file mode 100644 index 000000000000..47c16d1659ca --- /dev/null +++ b/drivers/mxc/mcu_pmic/mcu_pmic_core.c @@ -0,0 +1,226 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mc9s08dz60/mcu_pmic_core.c + * @brief This is the main file of mc9s08dz60 Power Control driver. + * + * @ingroup PMIC_POWER + */ + +/* + * Includes + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "mcu_pmic_core.h" +#include "mc9s08dz60.h" +#include "max8660.h" + +/* bitfield macros for mcu pmic*/ +#define SET_BIT_IN_BYTE(byte, pos) (byte |= (0x01 << pos)) +#define CLEAR_BIT_IN_BYTE(byte, pos) (byte &= ~(0x01 << pos)) + + +/* map reg names (enum pmic_reg in pmic_external.h) to real addr*/ +const static u8 mcu_pmic_reg_addr_table[] = { + MCU_VERSION, + MCU_SECS, + MCU_MINS, + MCU_HRS, + MCU_DAY, + MCU_DATE, + MCU_MONTH, + MCU_YEAR, + MCU_ALARM_SECS, + MCU_ALARM_MINS, + MCU_ALARM_HRS, + MCU_TS_CONTROL, + MCU_X_LOW, + MCU_Y_LOW, + MCU_XY_HIGH, + MCU_X_LEFT_LOW, + MCU_X_LEFT_HIGH, + MCU_X_RIGHT, + MCU_Y_TOP_LOW, + MCU_Y_TOP_HIGH, + MCU_Y_BOTTOM, + MCU_RESET_1, + MCU_RESET_2, + MCU_POWER_CTL, + MCU_DELAY_CONFIG, + MCU_GPIO_1, + MCU_GPIO_2, + MCU_KPD_1, + MCU_KPD_2, + MCU_KPD_CONTROL, + MCU_INT_ENABLE_1, + MCU_INT_ENABLE_2, + MCU_INT_FLAG_1, + MCU_INT_FLAG_2, + MCU_DES_FLAG, + MAX8660_OUTPUT_ENABLE_1, + MAX8660_OUTPUT_ENABLE_2, + MAX8660_VOLT_CHANGE_CONTROL, + MAX8660_V3_TARGET_VOLT_1, + MAX8660_V3_TARGET_VOLT_2, + MAX8660_V4_TARGET_VOLT_1, + MAX8660_V4_TARGET_VOLT_2, + MAX8660_V5_TARGET_VOLT_1, + MAX8660_V5_TARGET_VOLT_2, + MAX8660_V6V7_TARGET_VOLT, + MAX8660_FORCE_PWM +}; + +static int mcu_pmic_read(int reg_num, unsigned int *reg_val) +{ + int ret; + u8 value = 0; + /* mcu ops */ + if (reg_num >= REG_MCU_VERSION && reg_num <= REG_MCU_DES_FLAG) + ret = mc9s08dz60_read_reg(mcu_pmic_reg_addr_table[reg_num], + &value); + else if (reg_num >= REG_MAX8660_OUTPUT_ENABLE_1 + && reg_num <= REG_MAX8660_FORCE_PWM) + ret = max8660_get_buffered_reg_val(reg_num, &value); + else + return -1; + + if (ret < 0) + return -1; + *reg_val = value; + + return 0; +} + +static int mcu_pmic_write(int reg_num, const unsigned int reg_val) +{ + int ret; + u8 value = reg_val; + /* mcu ops */ + if (reg_num >= REG_MCU_VERSION && reg_num <= REG_MCU_DES_FLAG) { + + ret = + mc9s08dz60_write_reg( + mcu_pmic_reg_addr_table[reg_num], value); + if (ret < 0) + return -1; + } else if (reg_num >= REG_MAX8660_OUTPUT_ENABLE_1 + && reg_num <= REG_MAX8660_FORCE_PWM) { + ret = + max8660_write_reg(mcu_pmic_reg_addr_table[reg_num], value); + + if (ret < 0) + return -1; + + ret = max8660_save_buffered_reg_val(reg_num, value); + } else + return -1; + + return 0; +} + +int mcu_pmic_read_reg(int reg, unsigned int *reg_value, + unsigned int reg_mask) +{ + int ret = 0; + unsigned int temp = 0; + + ret = mcu_pmic_read(reg, &temp); + if (ret != 0) + return -1; + *reg_value = (temp & reg_mask); + + pr_debug("Read REG[ %d ] = 0x%x\n", reg, *reg_value); + + return ret; +} + + +int mcu_pmic_write_reg(int reg, unsigned int reg_value, + unsigned int reg_mask) +{ + int ret = 0; + unsigned int temp = 0; + + ret = mcu_pmic_read(reg, &temp); + if (ret != 0) + return -1; + temp = (temp & (~reg_mask)) | reg_value; + + ret = mcu_pmic_write(reg, temp); + if (ret != 0) + return -1; + + pr_debug("Write REG[ %d ] = 0x%x\n", reg, reg_value); + + return ret; +} + +/*! + * make max8660 - mc9s08dz60 enter low-power mode + */ +static void pmic_power_off(void) +{ + mcu_pmic_write_reg(REG_MCU_POWER_CTL, 0x10, 0x10); +} + +static int __init mcu_pmic_init(void) +{ + int err; + + /* init chips */ + err = max8660_init(); + if (err) + goto fail1; + + err = mc9s08dz60_init(); + if (err) + goto fail1; + + if (is_max8660_present()) { + pr_info("max8660 is present \n"); + pm_power_off = pmic_power_off; + } else + pr_debug("max8660 is not present\n"); + pr_info("mcu_pmic_init completed!\n"); + return 0; + +fail1: + pr_err("mcu_pmic_init failed!\n"); + return err; +} + +static void __exit mcu_pmic_exit(void) +{ + reg_max8660_remove(); + mc9s08dz60_exit(); + max8660_exit(); +} + +subsys_initcall_sync(mcu_pmic_init); +module_exit(mcu_pmic_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("mcu pmic driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/mcu_pmic/mcu_pmic_core.h b/drivers/mxc/mcu_pmic/mcu_pmic_core.h new file mode 100644 index 000000000000..969e84ff5df3 --- /dev/null +++ b/drivers/mxc/mcu_pmic/mcu_pmic_core.h @@ -0,0 +1,43 @@ +/* + * Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mcu_pmic_core.h + * @brief Driver for max8660 + * + * @ingroup pmic + */ +#ifndef _MCU_PMIC_CORE_H_ +#define _MCU_PMIC_CORE_H_ + +#include + +#define MAX8660_REG_START (REG_MCU_DES_FLAG + 1) +enum { + + /* reg names for max8660 */ + REG_MAX8660_OUTPUT_ENABLE_1 = MAX8660_REG_START, + REG_MAX8660_OUTPUT_ENABLE_2, + REG_MAX8660_VOLT_CHANGE_CONTROL_1, + REG_MAX8660_V3_TARGET_VOLT_1, + REG_MAX8660_V3_TARGET_VOLT_2, + REG_MAX8660_V4_TARGET_VOLT_1, + REG_MAX8660_V4_TARGET_VOLT_2, + REG_MAX8660_V5_TARGET_VOLT_1, + REG_MAX8660_V5_TARGET_VOLT_2, + REG_MAX8660_V6V7_TARGET_VOLT, + REG_MAX8660_FORCE_PWM +}; + + +#endif /* _MCU_PMIC_CORE_H_ */ diff --git a/drivers/mxc/mcu_pmic/mcu_pmic_gpio.c b/drivers/mxc/mcu_pmic/mcu_pmic_gpio.c new file mode 100644 index 000000000000..417dabe35386 --- /dev/null +++ b/drivers/mxc/mcu_pmic/mcu_pmic_gpio.c @@ -0,0 +1,131 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mc9s08dz60/mcu_pmic_gpio.c + * @brief This is the main file of mc9s08dz60 Power Control driver. + * + * @ingroup PMIC_POWER + */ + +/* + * Includes + */ +#include +#include +#include +#include + +#define SET_BIT_IN_BYTE(byte, pos) (byte |= (0x01 << pos)) +#define CLEAR_BIT_IN_BYTE(byte, pos) (byte &= ~(0x01 << pos)) + +int pmic_gpio_set_bit_val(int reg, unsigned int bit, + unsigned int val) +{ + int reg_name; + u8 reg_mask = 0; + + if (bit > 7) + return -1; + + switch (reg) { + case MCU_GPIO_REG_RESET_1: + reg_name = REG_MCU_RESET_1; + break; + case MCU_GPIO_REG_RESET_2: + reg_name = REG_MCU_RESET_2; + break; + case MCU_GPIO_REG_POWER_CONTROL: + reg_name = REG_MCU_POWER_CTL; + break; + case MCU_GPIO_REG_GPIO_CONTROL_1: + reg_name = REG_MCU_GPIO_1; + break; + case MCU_GPIO_REG_GPIO_CONTROL_2: + reg_name = REG_MCU_GPIO_2; + break; + default: + return -1; + } + + SET_BIT_IN_BYTE(reg_mask, bit); + if (0 == val) + CHECK_ERROR(mcu_pmic_write_reg(reg_name, 0, reg_mask)); + else + CHECK_ERROR(mcu_pmic_write_reg(reg_name, reg_mask, reg_mask)); + + return 0; +} +EXPORT_SYMBOL(pmic_gpio_set_bit_val); + +int pmic_gpio_get_bit_val(int reg, unsigned int bit, + unsigned int *val) +{ + int reg_name; + unsigned int reg_read_val; + u8 reg_mask = 0; + + if (bit > 7) + return -1; + + switch (reg) { + case MCU_GPIO_REG_RESET_1: + reg_name = REG_MCU_RESET_1; + break; + case MCU_GPIO_REG_RESET_2: + reg_name = REG_MCU_RESET_2; + break; + case MCU_GPIO_REG_POWER_CONTROL: + reg_name = REG_MCU_POWER_CTL; + break; + case MCU_GPIO_REG_GPIO_CONTROL_1: + reg_name = REG_MCU_GPIO_1; + break; + case MCU_GPIO_REG_GPIO_CONTROL_2: + reg_name = REG_MCU_GPIO_2; + break; + default: + return -1; + } + + SET_BIT_IN_BYTE(reg_mask, bit); + CHECK_ERROR(mcu_pmic_read_reg(reg_name, ®_read_val, reg_mask)); + if (0 == reg_read_val) + *val = 0; + else + *val = 1; + + return 0; +} +EXPORT_SYMBOL(pmic_gpio_get_bit_val); + +int pmic_gpio_get_designation_bit_val(unsigned int bit, + unsigned int *val) +{ + unsigned int reg_read_val; + u8 reg_mask = 0; + + if (bit > 7) + return -1; + + SET_BIT_IN_BYTE(reg_mask, bit); + CHECK_ERROR( + mcu_pmic_read_reg(REG_MCU_DES_FLAG, ®_read_val, reg_mask)); + if (0 == reg_read_val) + *val = 0; + else + *val = 1; + + return 0; +} +EXPORT_SYMBOL(pmic_gpio_get_designation_bit_val); diff --git a/drivers/mxc/mlb/Kconfig b/drivers/mxc/mlb/Kconfig new file mode 100644 index 000000000000..7e3b16c2ddae --- /dev/null +++ b/drivers/mxc/mlb/Kconfig @@ -0,0 +1,13 @@ +# +# MLB configuration +# + +menu "MXC Media Local Bus Driver" + +config MXC_MLB + tristate "MLB support" + depends on ARCH_MX35 || ARCH_MX53 + ---help--- + Say Y to get the MLB support. + +endmenu diff --git a/drivers/mxc/mlb/Makefile b/drivers/mxc/mlb/Makefile new file mode 100644 index 000000000000..60662eb1c031 --- /dev/null +++ b/drivers/mxc/mlb/Makefile @@ -0,0 +1,5 @@ +# +# Makefile for the kernel MLB driver +# + +obj-$(CONFIG_MXC_MLB) += mxc_mlb.o diff --git a/drivers/mxc/mlb/mxc_mlb.c b/drivers/mxc/mlb/mxc_mlb.c new file mode 100644 index 000000000000..1364f27c6d6d --- /dev/null +++ b/drivers/mxc/mlb/mxc_mlb.c @@ -0,0 +1,1056 @@ +/* + * linux/drivers/mxc/mlb/mxc_mlb.c + * + * Copyright (C) 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/*! + * MLB module memory map registers define + */ +#define MLB_REG_DCCR 0x0 +#define MLB_REG_SSCR 0x4 +#define MLB_REG_SDCR 0x8 +#define MLB_REG_SMCR 0xC +#define MLB_REG_VCCR 0x1C +#define MLB_REG_SBCR 0x20 +#define MLB_REG_ABCR 0x24 +#define MLB_REG_CBCR 0x28 +#define MLB_REG_IBCR 0x2C +#define MLB_REG_CICR 0x30 +#define MLB_REG_CECRn 0x40 +#define MLB_REG_CSCRn 0x44 +#define MLB_REG_CCBCRn 0x48 +#define MLB_REG_CNBCRn 0x4C +#define MLB_REG_LCBCRn 0x280 + +#define MLB_DCCR_FS_OFFSET 28 +#define MLB_DCCR_EN (1 << 31) +#define MLB_DCCR_LBM_OFFSET 30 +#define MLB_DCCR_RESET (1 << 23) +#define MLB_CECR_CE (1 << 31) +#define MLB_CECR_TR (1 << 30) +#define MLB_CECR_CT_OFFSET 28 +#define MLB_CECR_MBS (1 << 19) +#define MLB_CSCR_CBPE (1 << 0) +#define MLB_CSCR_CBDB (1 << 1) +#define MLB_CSCR_CBD (1 << 2) +#define MLB_CSCR_CBS (1 << 3) +#define MLB_CSCR_BE (1 << 4) +#define MLB_CSCR_ABE (1 << 5) +#define MLB_CSCR_LFS (1 << 6) +#define MLB_CSCR_PBPE (1 << 8) +#define MLB_CSCR_PBDB (1 << 9) +#define MLB_CSCR_PBD (1 << 10) +#define MLB_CSCR_PBS (1 << 11) +#define MLB_CSCR_RDY (1 << 16) +#define MLB_CSCR_BM (1 << 31) +#define MLB_CSCR_BF (1 << 30) +#define MLB_SSCR_SDML (1 << 5) + +#define MLB_CONTROL_TX_CHANN (0 << 4) +#define MLB_CONTROL_RX_CHANN (1 << 4) +#define MLB_ASYNC_TX_CHANN (2 << 4) +#define MLB_ASYNC_RX_CHANN (3 << 4) + +#define MLB_MINOR_DEVICES 2 +#define MLB_CONTROL_DEV_NAME "ctrl" +#define MLB_ASYNC_DEV_NAME "async" + +#define TX_CHANNEL 0 +#define RX_CHANNEL 1 +#define TX_CHANNEL_BUF_SIZE 1024 +#define RX_CHANNEL_BUF_SIZE (2*1024) +/* max package data size */ +#define ASYNC_PACKET_SIZE 1024 +#define CTRL_PACKET_SIZE 64 +#define RX_RING_NODES 10 + +#define MLB_IRAM_SIZE (MLB_MINOR_DEVICES * (TX_CHANNEL_BUF_SIZE + RX_CHANNEL_BUF_SIZE)) +#define _get_txchan(dev) mlb_devinfo[dev].channels[TX_CHANNEL] +#define _get_rxchan(dev) mlb_devinfo[dev].channels[RX_CHANNEL] + +enum { + MLB_CTYPE_SYNC, + MLB_CTYPE_ISOC, + MLB_CTYPE_ASYNC, + MLB_CTYPE_CTRL, +}; + +/*! + * Rx ring buffer + */ +struct mlb_rx_ringnode { + int size; + char *data; +}; + +struct mlb_channel_info { + + /* channel offset in memmap */ + const unsigned int reg_offset; + /* channel address */ + int address; + /*! + * channel buffer start address + * for Rx, buf_head pointer to a loop ring buffer + */ + unsigned long buf_head; + /* physical buffer head address */ + unsigned long phy_head; + /* channel buffer size */ + unsigned int buf_size; + /* channel buffer current ptr */ + unsigned long buf_ptr; + /* buffer spin lock */ + rwlock_t buf_lock; +}; + +struct mlb_dev_info { + + /* device node name */ + const char dev_name[20]; + /* channel type */ + const unsigned int channel_type; + /* channel info for tx/rx */ + struct mlb_channel_info channels[2]; + /* rx ring buffer */ + struct mlb_rx_ringnode rx_bufs[RX_RING_NODES]; + /* rx ring buffer read/write ptr */ + unsigned int rdpos, wtpos; + /* exception event */ + unsigned long ex_event; + /* channel started up or not */ + atomic_t on; + /* device open count */ + atomic_t opencnt; + /* wait queue head for channel */ + wait_queue_head_t rd_wq; + wait_queue_head_t wt_wq; + /* spinlock for event access */ + spinlock_t event_lock; +}; + +static struct mlb_dev_info mlb_devinfo[MLB_MINOR_DEVICES] = { + { + .dev_name = MLB_CONTROL_DEV_NAME, + .channel_type = MLB_CTYPE_CTRL, + .channels = { + [0] = { + .reg_offset = MLB_CONTROL_TX_CHANN, + .buf_size = TX_CHANNEL_BUF_SIZE, + .buf_lock = + __RW_LOCK_UNLOCKED(mlb_devinfo[0].channels[0]. + buf_lock), + }, + [1] = { + .reg_offset = MLB_CONTROL_RX_CHANN, + .buf_size = RX_CHANNEL_BUF_SIZE, + .buf_lock = + __RW_LOCK_UNLOCKED(mlb_devinfo[0].channels[1]. + buf_lock), + }, + }, + .on = ATOMIC_INIT(0), + .opencnt = ATOMIC_INIT(0), + .rd_wq = __WAIT_QUEUE_HEAD_INITIALIZER(mlb_devinfo[0].rd_wq), + .wt_wq = __WAIT_QUEUE_HEAD_INITIALIZER(mlb_devinfo[0].wt_wq), + .event_lock = __SPIN_LOCK_UNLOCKED(mlb_devinfo[0].event_lock), + }, + { + .dev_name = MLB_ASYNC_DEV_NAME, + .channel_type = MLB_CTYPE_ASYNC, + .channels = { + [0] = { + .reg_offset = MLB_ASYNC_TX_CHANN, + .buf_size = TX_CHANNEL_BUF_SIZE, + .buf_lock = + __RW_LOCK_UNLOCKED(mlb_devinfo[1].channels[0]. + buf_lock), + }, + [1] = { + .reg_offset = MLB_ASYNC_RX_CHANN, + .buf_size = RX_CHANNEL_BUF_SIZE, + .buf_lock = + __RW_LOCK_UNLOCKED(mlb_devinfo[1].channels[1]. + buf_lock), + }, + }, + .on = ATOMIC_INIT(0), + .opencnt = ATOMIC_INIT(0), + .rd_wq = __WAIT_QUEUE_HEAD_INITIALIZER(mlb_devinfo[1].rd_wq), + .wt_wq = __WAIT_QUEUE_HEAD_INITIALIZER(mlb_devinfo[1].wt_wq), + .event_lock = __SPIN_LOCK_UNLOCKED(mlb_devinfo[1].event_lock), + }, +}; + +static struct regulator *reg_nvcc; /* NVCC_MLB regulator */ +static struct clk *mlb_clk; +static struct cdev mxc_mlb_dev; /* chareset device */ +static dev_t dev; +static struct class *mlb_class; /* device class */ +static struct device *class_dev; +static unsigned long mlb_base; /* mlb module base address */ +static unsigned int irq; +static unsigned long iram_base; +static __iomem void *iram_addr; + +/*! + * Initial the MLB module device + */ +static void mlb_dev_init(void) +{ + unsigned long dccr_val; + unsigned long phyaddr; + + /* reset the MLB module */ + __raw_writel(MLB_DCCR_RESET, mlb_base + MLB_REG_DCCR); + while (__raw_readl(mlb_base + MLB_REG_DCCR) + & MLB_DCCR_RESET) + ; + + /*! + * Enable MLB device, disable loopback mode, + * set default fps to 512, set mlb device address to 0 + */ + dccr_val = MLB_DCCR_EN; + __raw_writel(dccr_val, mlb_base + MLB_REG_DCCR); + + /* disable all the system interrupt */ + __raw_writel(0x5F, mlb_base + MLB_REG_SMCR); + + /* write async, control tx/rx base address */ + phyaddr = _get_txchan(0).phy_head >> 16; + __raw_writel(phyaddr << 16 | phyaddr, mlb_base + MLB_REG_CBCR); + phyaddr = _get_txchan(1).phy_head >> 16; + __raw_writel(phyaddr << 16 | phyaddr, mlb_base + MLB_REG_ABCR); + +} + +static void mlb_dev_exit(void) +{ + __raw_writel(0, mlb_base + MLB_REG_DCCR); +} + +/*! + * MLB receive start function + * + * load phy_head to next buf register to start next rx + * here use single-packet buffer, set start=end + */ +static void mlb_start_rx(int cdev_id) +{ + struct mlb_channel_info *chinfo = &_get_rxchan(cdev_id); + unsigned long next; + + next = chinfo->phy_head & 0xFFFC; + /* load next buf */ + __raw_writel((next << 16) | next, mlb_base + + MLB_REG_CNBCRn + chinfo->reg_offset); + /* set ready bit to start next rx */ + __raw_writel(MLB_CSCR_RDY, mlb_base + MLB_REG_CSCRn + + chinfo->reg_offset); +} + +/*! + * MLB transmit start function + * make sure aquiring the rw buf_lock, when calling this + */ +static void mlb_start_tx(int cdev_id) +{ + struct mlb_channel_info *chinfo = &_get_txchan(cdev_id); + unsigned long begin, end; + + begin = chinfo->phy_head; + end = (chinfo->phy_head + chinfo->buf_ptr - chinfo->buf_head) & 0xFFFC; + /* load next buf */ + __raw_writel((begin << 16) | end, mlb_base + + MLB_REG_CNBCRn + chinfo->reg_offset); + /* set ready bit to start next tx */ + __raw_writel(MLB_CSCR_RDY, mlb_base + MLB_REG_CSCRn + + chinfo->reg_offset); +} + +/*! + * Enable the MLB channel + */ +static void mlb_channel_enable(int chan_dev_id, int on) +{ + unsigned long tx_regval = 0, rx_regval = 0; + /*! + * setup the direction, enable, channel type, + * mode select, channel address and mask buf start + */ + if (on) { + unsigned int ctype = mlb_devinfo[chan_dev_id].channel_type; + tx_regval = MLB_CECR_CE | MLB_CECR_TR | MLB_CECR_MBS | + (ctype << MLB_CECR_CT_OFFSET) | + _get_txchan(chan_dev_id).address; + rx_regval = MLB_CECR_CE | MLB_CECR_MBS | + (ctype << MLB_CECR_CT_OFFSET) | + _get_rxchan(chan_dev_id).address; + + atomic_set(&mlb_devinfo[chan_dev_id].on, 1); + } else { + atomic_set(&mlb_devinfo[chan_dev_id].on, 0); + } + + /* update the rx/tx channel entry config */ + __raw_writel(tx_regval, mlb_base + MLB_REG_CECRn + + _get_txchan(chan_dev_id).reg_offset); + __raw_writel(rx_regval, mlb_base + MLB_REG_CECRn + + _get_rxchan(chan_dev_id).reg_offset); + + if (on) + mlb_start_rx(chan_dev_id); +} + +/*! + * MLB interrupt handler + */ +void mlb_tx_isr(int minor, unsigned int cis) +{ + struct mlb_channel_info *chinfo = &_get_txchan(minor); + + if (cis & MLB_CSCR_CBD) { + /* buffer done, reset the buf_ptr */ + write_lock(&chinfo->buf_lock); + chinfo->buf_ptr = chinfo->buf_head; + write_unlock(&chinfo->buf_lock); + /* wake up the writer */ + wake_up_interruptible(&mlb_devinfo[minor].wt_wq); + } +} + +void mlb_rx_isr(int minor, unsigned int cis) +{ + struct mlb_channel_info *chinfo = &_get_rxchan(minor); + unsigned long end; + unsigned int len; + + if (cis & MLB_CSCR_CBD) { + + int wpos, rpos; + + rpos = mlb_devinfo[minor].rdpos; + wpos = mlb_devinfo[minor].wtpos; + + /* buffer done, get current buffer ptr */ + end = + __raw_readl(mlb_base + MLB_REG_CCBCRn + chinfo->reg_offset); + end >>= 16; /* end here is phy */ + len = end - (chinfo->phy_head & 0xFFFC); + + /*! + * copy packet from IRAM buf to ring buf. + * if the wpos++ == rpos, drop this packet + */ + if (((wpos + 1) % RX_RING_NODES) != rpos) { + +#ifdef DEBUG + if (mlb_devinfo[minor].channel_type == MLB_CTYPE_CTRL) { + if (len > CTRL_PACKET_SIZE) + pr_debug + ("mxc_mlb: ctrl packet" + "overflow\n"); + } else { + if (len > ASYNC_PACKET_SIZE) + pr_debug + ("mxc_mlb: async packet" + "overflow\n"); + } +#endif + memcpy(mlb_devinfo[minor].rx_bufs[wpos].data, + (const void *)chinfo->buf_head, len); + mlb_devinfo[minor].rx_bufs[wpos].size = len; + + /* update the ring wpos */ + mlb_devinfo[minor].wtpos = (wpos + 1) % RX_RING_NODES; + + /* wake up the reader */ + wake_up_interruptible(&mlb_devinfo[minor].rd_wq); + + pr_debug("recv package, len:%d, rdpos: %d, wtpos: %d\n", + len, rpos, mlb_devinfo[minor].wtpos); + } else { + pr_debug + ("drop package, due to no space, (%d,%d)\n", + rpos, mlb_devinfo[minor].wtpos); + } + + /* start next rx */ + mlb_start_rx(minor); + } +} + +static irqreturn_t mlb_isr(int irq, void *dev_id) +{ + unsigned long int_status, sscr, tx_cis, rx_cis; + struct mlb_dev_info *pdev; + int minor; + + sscr = __raw_readl(mlb_base + MLB_REG_SSCR); + pr_debug("mxc_mlb: system interrupt:%lx\n", sscr); + __raw_writel(0x7F, mlb_base + MLB_REG_SSCR); + + int_status = __raw_readl(mlb_base + MLB_REG_CICR) & 0xFFFF; + pr_debug("mxc_mlb: channel interrupt ids: %lx\n", int_status); + + for (minor = 0; minor < MLB_MINOR_DEVICES; minor++) { + + pdev = &mlb_devinfo[minor]; + tx_cis = rx_cis = 0; + + /* get tx channel interrupt status */ + if (int_status & (1 << (_get_txchan(minor).reg_offset >> 4))) + tx_cis = __raw_readl(mlb_base + MLB_REG_CSCRn + + _get_txchan(minor).reg_offset); + /* get rx channel interrupt status */ + if (int_status & (1 << (_get_rxchan(minor).reg_offset >> 4))) + rx_cis = __raw_readl(mlb_base + MLB_REG_CSCRn + + _get_rxchan(minor).reg_offset); + + if (!tx_cis && !rx_cis) + continue; + + pr_debug("tx/rx int status: 0x%08lx/0x%08lx\n", tx_cis, rx_cis); + /* fill exception event */ + spin_lock(&pdev->event_lock); + pdev->ex_event |= tx_cis & 0x303; + pdev->ex_event |= (rx_cis & 0x303) << 16; + spin_unlock(&pdev->event_lock); + + /* clear the interrupt status */ + __raw_writel(tx_cis & 0xFFFF, mlb_base + MLB_REG_CSCRn + + _get_txchan(minor).reg_offset); + __raw_writel(rx_cis & 0xFFFF, mlb_base + MLB_REG_CSCRn + + _get_rxchan(minor).reg_offset); + + /* handel tx channel */ + if (tx_cis) + mlb_tx_isr(minor, tx_cis); + /* handle rx channel */ + if (rx_cis) + mlb_rx_isr(minor, rx_cis); + + } + + return IRQ_HANDLED; +} + +static int mxc_mlb_open(struct inode *inode, struct file *filp) +{ + int minor; + + minor = MINOR(inode->i_rdev); + + if (minor < 0 || minor >= MLB_MINOR_DEVICES) + return -ENODEV; + + /* open for each channel device */ + if (atomic_cmpxchg(&mlb_devinfo[minor].opencnt, 0, 1) != 0) + return -EBUSY; + + /* reset the buffer read/write ptr */ + _get_txchan(minor).buf_ptr = _get_txchan(minor).buf_head; + _get_rxchan(minor).buf_ptr = _get_rxchan(minor).buf_head; + mlb_devinfo[minor].rdpos = mlb_devinfo[minor].wtpos = 0; + mlb_devinfo[minor].ex_event = 0; + + return 0; +} + +static int mxc_mlb_release(struct inode *inode, struct file *filp) +{ + int minor; + + minor = MINOR(inode->i_rdev); + + /* clear channel settings and info */ + mlb_channel_enable(minor, 0); + + /* decrease the open count */ + atomic_set(&mlb_devinfo[minor].opencnt, 0); + + return 0; +} + +static int mxc_mlb_ioctl(struct inode *inode, struct file *filp, + unsigned int cmd, unsigned long arg) +{ + void __user *argp = (void __user *)arg; + unsigned long flags, event; + int minor; + + minor = MINOR(inode->i_rdev); + + switch (cmd) { + + case MLB_CHAN_SETADDR: + { + unsigned int caddr; + /* get channel address from user space */ + if (copy_from_user(&caddr, argp, sizeof(caddr))) { + pr_err("mxc_mlb: copy from user failed\n"); + return -EFAULT; + } + _get_txchan(minor).address = (caddr >> 16) & 0xFFFF; + _get_rxchan(minor).address = caddr & 0xFFFF; + break; + } + + case MLB_CHAN_STARTUP: + if (atomic_read(&mlb_devinfo[minor].on)) { + pr_debug("mxc_mlb: channel areadly startup\n"); + break; + } + mlb_channel_enable(minor, 1); + break; + case MLB_CHAN_SHUTDOWN: + if (atomic_read(&mlb_devinfo[minor].on) == 0) { + pr_debug("mxc_mlb: channel areadly shutdown\n"); + break; + } + mlb_channel_enable(minor, 0); + break; + case MLB_CHAN_GETEVENT: + /* get and clear the ex_event */ + spin_lock_irqsave(&mlb_devinfo[minor].event_lock, flags); + event = mlb_devinfo[minor].ex_event; + mlb_devinfo[minor].ex_event = 0; + spin_unlock_irqrestore(&mlb_devinfo[minor].event_lock, flags); + + if (event) { + if (copy_to_user(argp, &event, sizeof(event))) { + pr_err("mxc_mlb: copy to user failed\n"); + return -EFAULT; + } + } else { + pr_debug("mxc_mlb: no exception event now\n"); + return -EAGAIN; + } + break; + case MLB_SET_FPS: + { + unsigned int fps; + unsigned long dccr_val; + + /* get fps from user space */ + if (copy_from_user(&fps, argp, sizeof(fps))) { + pr_err("mxc_mlb: copy from user failed\n"); + return -EFAULT; + } + + /* check fps value */ + if (fps != 256 && fps != 512 && fps != 1024) { + pr_debug("mxc_mlb: invalid fps argument\n"); + return -EINVAL; + } + + dccr_val = __raw_readl(mlb_base + MLB_REG_DCCR); + dccr_val &= ~(0x3 << MLB_DCCR_FS_OFFSET); + dccr_val |= (fps >> 9) << MLB_DCCR_FS_OFFSET; + __raw_writel(dccr_val, mlb_base + MLB_REG_DCCR); + break; + } + + case MLB_GET_VER: + { + unsigned long version; + + /* get MLB device module version */ + version = __raw_readl(mlb_base + MLB_REG_VCCR); + + if (copy_to_user(argp, &version, sizeof(version))) { + pr_err("mxc_mlb: copy to user failed\n"); + return -EFAULT; + } + break; + } + + case MLB_SET_DEVADDR: + { + unsigned long dccr_val; + unsigned char devaddr; + + /* get MLB device address from user space */ + if (copy_from_user + (&devaddr, argp, sizeof(unsigned char))) { + pr_err("mxc_mlb: copy from user failed\n"); + return -EFAULT; + } + + dccr_val = __raw_readl(mlb_base + MLB_REG_DCCR); + dccr_val &= ~0xFF; + dccr_val |= devaddr; + __raw_writel(dccr_val, mlb_base + MLB_REG_DCCR); + + break; + } + default: + pr_info("mxc_mlb: Invalid ioctl command\n"); + return -EINVAL; + } + + return 0; +} + +/*! + * MLB read routine + * + * Read the current received data from queued buffer, + * and free this buffer for hw to fill ingress data. + */ +static ssize_t mxc_mlb_read(struct file *filp, char __user *buf, + size_t count, loff_t *f_pos) +{ + int minor, ret; + int size, rdpos; + struct mlb_rx_ringnode *rxbuf; + + minor = MINOR(filp->f_dentry->d_inode->i_rdev); + + rdpos = mlb_devinfo[minor].rdpos; + rxbuf = mlb_devinfo[minor].rx_bufs; + + /* check the current rx buffer is available or not */ + if (rdpos == mlb_devinfo[minor].wtpos) { + if (filp->f_flags & O_NONBLOCK) + return -EAGAIN; + /* if !O_NONBLOCK, we wait for recv packet */ + ret = wait_event_interruptible(mlb_devinfo[minor].rd_wq, + (mlb_devinfo[minor].wtpos != + rdpos)); + if (ret < 0) + return ret; + } + + size = rxbuf[rdpos].size; + if (size > count) { + /* the user buffer is too small */ + pr_warning + ("mxc_mlb: received data size is bigger than count\n"); + return -EINVAL; + } + + /* copy rx buffer data to user buffer */ + if (copy_to_user(buf, rxbuf[rdpos].data, size)) { + pr_err("mxc_mlb: copy from user failed\n"); + return -EFAULT; + } + + /* update the read ptr */ + mlb_devinfo[minor].rdpos = (rdpos + 1) % RX_RING_NODES; + + *f_pos = 0; + + return size; +} + +/*! + * MLB write routine + * + * Copy the user data to tx channel buffer, + * and prepare the channel current/next buffer ptr. + */ +static ssize_t mxc_mlb_write(struct file *filp, const char __user *buf, + size_t count, loff_t *f_pos) +{ + int minor; + unsigned long flags; + DEFINE_WAIT(__wait); + int ret; + + minor = MINOR(filp->f_dentry->d_inode->i_rdev); + + if (count > _get_txchan(minor).buf_size) { + /* too many data to write */ + pr_warning("mxc_mlb: overflow write data\n"); + return -EFBIG; + } + + *f_pos = 0; + + /* check the current tx buffer is used or not */ + write_lock_irqsave(&_get_txchan(minor).buf_lock, flags); + if (_get_txchan(minor).buf_ptr != _get_txchan(minor).buf_head) { + write_unlock_irqrestore(&_get_txchan(minor).buf_lock, flags); + + /* there's already some datas being transmit now */ + if (filp->f_flags & O_NONBLOCK) + return -EAGAIN; + + /* if !O_NONBLOCK, we wait for transmit finish */ + for (;;) { + prepare_to_wait(&mlb_devinfo[minor].wt_wq, + &__wait, TASK_INTERRUPTIBLE); + + write_lock_irqsave(&_get_txchan(minor).buf_lock, flags); + if (_get_txchan(minor).buf_ptr == + _get_txchan(minor).buf_head) + break; + + write_unlock_irqrestore(&_get_txchan(minor).buf_lock, + flags); + if (!signal_pending(current)) { + schedule(); + continue; + } + return -ERESTARTSYS; + } + finish_wait(&mlb_devinfo[minor].wt_wq, &__wait); + } + + /* copy user buffer to tx buffer */ + if (copy_from_user((void *)_get_txchan(minor).buf_ptr, buf, count)) { + pr_err("mxc_mlb: copy from user failed\n"); + ret = -EFAULT; + goto out; + } + _get_txchan(minor).buf_ptr += count; + + /* set current/next buffer start/end */ + mlb_start_tx(minor); + + ret = count; + +out: + write_unlock_irqrestore(&_get_txchan(minor).buf_lock, flags); + return ret; +} + +static unsigned int mxc_mlb_poll(struct file *filp, + struct poll_table_struct *wait) +{ + int minor; + unsigned int ret = 0; + unsigned long flags; + + minor = MINOR(filp->f_dentry->d_inode->i_rdev); + + poll_wait(filp, &mlb_devinfo[minor].rd_wq, wait); + poll_wait(filp, &mlb_devinfo[minor].wt_wq, wait); + + /* check the tx buffer is avaiable or not */ + read_lock_irqsave(&_get_txchan(minor).buf_lock, flags); + if (_get_txchan(minor).buf_ptr == _get_txchan(minor).buf_head) + ret |= POLLOUT | POLLWRNORM; + read_unlock_irqrestore(&_get_txchan(minor).buf_lock, flags); + + /* check the rx buffer filled or not */ + if (mlb_devinfo[minor].rdpos != mlb_devinfo[minor].wtpos) + ret |= POLLIN | POLLRDNORM; + + /* check the exception event */ + if (mlb_devinfo[minor].ex_event) + ret |= POLLIN | POLLRDNORM; + + return ret; +} + +/*! + * char dev file operations structure + */ +static struct file_operations mxc_mlb_fops = { + + .owner = THIS_MODULE, + .open = mxc_mlb_open, + .release = mxc_mlb_release, + .ioctl = mxc_mlb_ioctl, + .poll = mxc_mlb_poll, + .read = mxc_mlb_read, + .write = mxc_mlb_write, +}; + +/*! + * This function is called whenever the MLB device is detected. + */ +static int __devinit mxc_mlb_probe(struct platform_device *pdev) +{ + int ret, mlb_major, i, j; + struct mxc_mlb_platform_data *plat_data; + struct resource *res; + void __iomem *base, *bufaddr; + unsigned long phyaddr; + + /* malloc the Rx ring buffer firstly */ + for (i = 0; i < MLB_MINOR_DEVICES; i++) { + char *buf; + int bufsize; + + if (mlb_devinfo[i].channel_type == MLB_CTYPE_ASYNC) + bufsize = ASYNC_PACKET_SIZE; + else + bufsize = CTRL_PACKET_SIZE; + + buf = kmalloc(bufsize * RX_RING_NODES, GFP_KERNEL); + if (buf == NULL) { + ret = -ENOMEM; + dev_err(&pdev->dev, "can not alloc rx buffers\n"); + goto err4; + } + for (j = 0; j < RX_RING_NODES; j++) { + mlb_devinfo[i].rx_bufs[j].data = buf; + buf += bufsize; + } + } + + /** + * Register MLB lld as two character devices + * One for Packet date channel, the other for control data channel + */ + ret = alloc_chrdev_region(&dev, 0, MLB_MINOR_DEVICES, "mxc_mlb"); + mlb_major = MAJOR(dev); + + if (ret < 0) { + dev_err(&pdev->dev, "can't get major %d\n", mlb_major); + goto err3; + } + + cdev_init(&mxc_mlb_dev, &mxc_mlb_fops); + mxc_mlb_dev.owner = THIS_MODULE; + + ret = cdev_add(&mxc_mlb_dev, dev, MLB_MINOR_DEVICES); + if (ret) { + dev_err(&pdev->dev, "can't add cdev\n"); + goto err2; + } + + /* create class and device for udev information */ + mlb_class = class_create(THIS_MODULE, "mlb"); + if (IS_ERR(mlb_class)) { + dev_err(&pdev->dev, "failed to create mlb class\n"); + ret = -ENOMEM; + goto err2; + } + + for (i = 0; i < MLB_MINOR_DEVICES; i++) { + + class_dev = device_create(mlb_class, NULL, MKDEV(mlb_major, i), + NULL, mlb_devinfo[i].dev_name); + if (IS_ERR(class_dev)) { + dev_err(&pdev->dev, "failed to create mlb %s" + " class device\n", mlb_devinfo[i].dev_name); + ret = -ENOMEM; + goto err1; + } + } + + /* get irq line */ + res = platform_get_resource(pdev, IORESOURCE_IRQ, 0); + if (res == NULL) { + dev_err(&pdev->dev, "No mlb irq line provided\n"); + goto err1; + } + + irq = res->start; + /* request irq */ + if (request_irq(irq, mlb_isr, 0, "mlb", NULL)) { + dev_err(&pdev->dev, "failed to request irq\n"); + ret = -EBUSY; + goto err1; + } + + /* ioremap from phy mlb to kernel space */ + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (res == NULL) { + dev_err(&pdev->dev, "No mlb base address provided\n"); + goto err0; + } + + base = ioremap(res->start, res->end - res->start); + dev_dbg(&pdev->dev, "mapped mlb base address: 0x%08x\n", + (unsigned int)base); + + if (base == NULL) { + dev_err(&pdev->dev, "failed to do ioremap with mlb base\n"); + goto err0; + } + mlb_base = (unsigned long)base; + + /*! + * get rx/tx buffer address from platform data + * make sure the buf_address is 4bytes aligned + * + * ------------------- <-- plat_data->buf_address + * | minor 0 tx buf | + * ----------------- + * | minor 0 rx buf | + * ----------------- + * | .... | + * ----------------- + * | minor n tx buf | + * ----------------- + * | minor n rx buf | + * ------------------- + */ + + plat_data = (struct mxc_mlb_platform_data *)pdev->dev.platform_data; + + bufaddr = iram_addr = iram_alloc(MLB_IRAM_SIZE, &iram_base); + phyaddr = iram_base; + + for (i = 0; i < MLB_MINOR_DEVICES; i++) { + /* set the virtual and physical buf head address */ + _get_txchan(i).buf_head = bufaddr; + _get_txchan(i).phy_head = phyaddr; + + bufaddr += TX_CHANNEL_BUF_SIZE; + phyaddr += TX_CHANNEL_BUF_SIZE; + + _get_rxchan(i).buf_head = (unsigned long)bufaddr; + _get_rxchan(i).phy_head = phyaddr; + + bufaddr += RX_CHANNEL_BUF_SIZE; + phyaddr += RX_CHANNEL_BUF_SIZE; + + dev_dbg(&pdev->dev, "phy_head: tx(%lx), rx(%lx)\n", + _get_txchan(i).phy_head, _get_rxchan(i).phy_head); + dev_dbg(&pdev->dev, "buf_head: tx(%lx), rx(%lx)\n", + _get_txchan(i).buf_head, _get_rxchan(i).buf_head); + } + + /* enable GPIO */ + gpio_mlb_active(); + + /* power on MLB */ + reg_nvcc = regulator_get(&pdev->dev, plat_data->reg_nvcc); + /* set MAX LDO6 for NVCC to 2.5V */ + regulator_set_voltage(reg_nvcc, 2500000, 2500000); + regulator_enable(reg_nvcc); + + /* enable clock */ + mlb_clk = clk_get(&pdev->dev, plat_data->mlb_clk); + clk_enable(mlb_clk); + + /* initial MLB module */ + mlb_dev_init(); + + return 0; + +err0: + free_irq(irq, NULL); +err1: + for (--i; i >= 0; i--) + device_destroy(mlb_class, MKDEV(mlb_major, i)); + + class_destroy(mlb_class); +err2: + cdev_del(&mxc_mlb_dev); +err3: + unregister_chrdev_region(dev, MLB_MINOR_DEVICES); +err4: + for (i = 0; i < MLB_MINOR_DEVICES; i++) + kfree(mlb_devinfo[i].rx_bufs[0].data); + + return ret; +} + +static int __devexit mxc_mlb_remove(struct platform_device *pdev) +{ + int i; + + mlb_dev_exit(); + + /* disable mlb clock */ + clk_disable(mlb_clk); + clk_put(mlb_clk); + + /* disable mlb power */ + regulator_disable(reg_nvcc); + regulator_put(reg_nvcc); + + /* inactive GPIO */ + gpio_mlb_inactive(); + + iram_free(iram_base, MLB_IRAM_SIZE); + + /* iounmap */ + iounmap((void *)mlb_base); + + free_irq(irq, NULL); + + /* destroy mlb device class */ + for (i = MLB_MINOR_DEVICES - 1; i >= 0; i--) + device_destroy(mlb_class, MKDEV(MAJOR(dev), i)); + class_destroy(mlb_class); + + /* Unregister the two MLB devices */ + cdev_del(&mxc_mlb_dev); + unregister_chrdev_region(dev, MLB_MINOR_DEVICES); + + for (i = 0; i < MLB_MINOR_DEVICES; i++) + kfree(mlb_devinfo[i].rx_bufs[0].data); + + return 0; +} + +#ifdef CONFIG_PM +static int mxc_mlb_suspend(struct platform_device *pdev, pm_message_t state) +{ + return 0; +} + +static int mxc_mlb_resume(struct platform_device *pdev) +{ + return 0; +} +#else +#define mxc_mlb_suspend NULL +#define mxc_mlb_resume NULL +#endif + +/*! + * platform driver structure for MLB + */ +static struct platform_driver mxc_mlb_driver = { + .driver = { + .name = "mxc_mlb"}, + .probe = mxc_mlb_probe, + .remove = __devexit_p(mxc_mlb_remove), + .suspend = mxc_mlb_suspend, + .resume = mxc_mlb_resume, +}; + +static int __init mxc_mlb_init(void) +{ + return platform_driver_register(&mxc_mlb_driver); +} + +static void __exit mxc_mlb_exit(void) +{ + platform_driver_unregister(&mxc_mlb_driver); +} + +module_init(mxc_mlb_init); +module_exit(mxc_mlb_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MLB low level driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/pmic/Kconfig b/drivers/mxc/pmic/Kconfig new file mode 100644 index 000000000000..4ee91110fc03 --- /dev/null +++ b/drivers/mxc/pmic/Kconfig @@ -0,0 +1,64 @@ +# +# PMIC device driver configuration +# + +menu "MXC PMIC support" + +config MXC_PMIC + boolean + +config MXC_PMIC_MC13783 + tristate "MC13783 PMIC" + depends on ARCH_MXC && SPI + select MXC_PMIC + ---help--- + This is the MXC MC13783(PMIC) support. It include + ADC, Audio, Battery, Connectivity, Light, Power and RTC. + +config MXC_PMIC_MC13892 + tristate "MC13892 PMIC" + depends on ARCH_MXC && (I2C || SPI) + select MXC_PMIC + ---help--- + This is the MXC MC13892(PMIC) support. It include + ADC, Battery, Connectivity, Light, Power and RTC. + +config MXC_PMIC_I2C + bool "Support PMIC I2C Interface" + depends on MXC_PMIC_MC13892 && I2C + +config MXC_PMIC_SPI + bool "Support PMIC SPI Interface" + depends on (MXC_PMIC_MC13892 || MXC_PMIC_MC13783) && SPI + +config MXC_PMIC_MC34704 + tristate "MC34704 PMIC" + depends on ARCH_MXC && I2C + select MXC_PMIC + ---help--- + This is the MXC MC34704 PMIC support. + +config MXC_PMIC_MC9SDZ60 + tristate "MC9sDZ60 PMIC" + depends on ARCH_MXC && I2C + select MXC_PMIC + ---help--- + This is the MXC MC9sDZ60(MCU) PMIC support. + +config MXC_PMIC_CHARDEV + tristate "MXC PMIC device interface" + depends on MXC_PMIC + help + Say Y here to use "pmic" device files, found in the /dev directory + on the system. They make it possible to have user-space programs + use or controll PMIC. Mainly its useful for notifying PMIC events + to user-space programs. + +comment "MXC PMIC Client Drivers" + depends on MXC_PMIC + +source "drivers/mxc/pmic/mc13783/Kconfig" + +source "drivers/mxc/pmic/mc13892/Kconfig" + +endmenu diff --git a/drivers/mxc/pmic/Makefile b/drivers/mxc/pmic/Makefile new file mode 100644 index 000000000000..385c07e8509f --- /dev/null +++ b/drivers/mxc/pmic/Makefile @@ -0,0 +1,7 @@ +# +# Makefile for the MXC PMIC drivers. +# + +obj-y += core/ +obj-$(CONFIG_MXC_PMIC_MC13783) += mc13783/ +obj-$(CONFIG_MXC_PMIC_MC13892) += mc13892/ diff --git a/drivers/mxc/pmic/core/Makefile b/drivers/mxc/pmic/core/Makefile new file mode 100644 index 000000000000..bb42231e3aa8 --- /dev/null +++ b/drivers/mxc/pmic/core/Makefile @@ -0,0 +1,21 @@ +# +# Makefile for the PMIC core drivers. +# +obj-$(CONFIG_MXC_PMIC_MC13783) += pmic_mc13783_mod.o +pmic_mc13783_mod-objs := pmic_external.o pmic_event.o pmic_common.o pmic_core_spi.o mc13783.o + +obj-$(CONFIG_MXC_PMIC_MC13892) += pmic_mc13892_mod.o +pmic_mc13892_mod-objs := pmic_external.o pmic_event.o pmic_common.o mc13892.o + +ifneq ($(CONFIG_MXC_PMIC_SPI),) +pmic_mc13892_mod-objs += pmic_core_spi.o +endif + +ifneq ($(CONFIG_MXC_PMIC_I2C),) +pmic_mc13892_mod-objs += pmic_core_i2c.o +endif + +obj-$(CONFIG_MXC_PMIC_MC34704) += pmic_mc34704_mod.o +pmic_mc34704_mod-objs := pmic_external.o pmic_event.o mc34704.o + +obj-$(CONFIG_MXC_PMIC_CHARDEV) += pmic-dev.o diff --git a/drivers/mxc/pmic/core/mc13783.c b/drivers/mxc/pmic/core/mc13783.c new file mode 100644 index 000000000000..812de6e146aa --- /dev/null +++ b/drivers/mxc/pmic/core/mc13783.c @@ -0,0 +1,380 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file pmic/core/mc13783.c + * @brief This file contains MC13783 specific PMIC code. This implementaion + * may differ for each PMIC chip. + * + * @ingroup PMIC_CORE + */ + +/* + * Includes + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "pmic.h" + +/* + * Defines + */ +#define EVENT_MASK_0 0x697fdf +#define EVENT_MASK_1 0x3efffb +#define MXC_PMIC_FRAME_MASK 0x00FFFFFF +#define MXC_PMIC_MAX_REG_NUM 0x3F +#define MXC_PMIC_REG_NUM_SHIFT 0x19 +#define MXC_PMIC_WRITE_BIT_SHIFT 31 + +static unsigned int events_enabled0; +static unsigned int events_enabled1; +struct mxc_pmic pmic_drv_data; + +/*! + * This function is called to read a register on PMIC. + * + * @param reg_num number of the pmic register to be read + * @param reg_val return value of register + * + * @return Returns 0 on success -1 on failure. + */ +int pmic_read(unsigned int reg_num, unsigned int *reg_val) +{ + unsigned int frame = 0; + int ret = 0; + + if (reg_num > MXC_PMIC_MAX_REG_NUM) + return PMIC_ERROR; + + frame |= reg_num << MXC_PMIC_REG_NUM_SHIFT; + + ret = spi_rw(pmic_drv_data.spi, (u8 *) &frame, 1); + + *reg_val = frame & MXC_PMIC_FRAME_MASK; + + return ret; +} + +/*! + * This function is called to write a value to the register on PMIC. + * + * @param reg_num number of the pmic register to be written + * @param reg_val value to be written + * + * @return Returns 0 on success -1 on failure. + */ +int pmic_write(int reg_num, const unsigned int reg_val) +{ + unsigned int frame = 0; + int ret = 0; + + if (reg_num > MXC_PMIC_MAX_REG_NUM) + return PMIC_ERROR; + + frame |= (1 << MXC_PMIC_WRITE_BIT_SHIFT); + + frame |= reg_num << MXC_PMIC_REG_NUM_SHIFT; + + frame |= reg_val & MXC_PMIC_FRAME_MASK; + + ret = spi_rw(pmic_drv_data.spi, (u8 *) &frame, 1); + + return ret; +} + +void *pmic_alloc_data(struct device *dev) +{ + struct mc13783 *mc13783; + + mc13783 = kzalloc(sizeof(struct mc13783), GFP_KERNEL); + if (mc13783 == NULL) + return NULL; + + mc13783->dev = dev; + + return (void *)mc13783; +} + +/*! + * This function initializes the SPI device parameters for this PMIC. + * + * @param spi the SPI slave device(PMIC) + * + * @return None + */ +int pmic_spi_setup(struct spi_device *spi) +{ + /* Setup the SPI slave i.e.PMIC */ + pmic_drv_data.spi = spi; + + spi->mode = SPI_MODE_2 | SPI_CS_HIGH; + spi->bits_per_word = 32; + + return spi_setup(spi); +} + +/*! + * This function initializes the PMIC registers. + * + * @return None + */ +int pmic_init_registers(void) +{ + CHECK_ERROR(pmic_write(REG_INTERRUPT_MASK_0, MXC_PMIC_FRAME_MASK)); + CHECK_ERROR(pmic_write(REG_INTERRUPT_MASK_1, MXC_PMIC_FRAME_MASK)); + CHECK_ERROR(pmic_write(REG_INTERRUPT_STATUS_0, MXC_PMIC_FRAME_MASK)); + CHECK_ERROR(pmic_write(REG_INTERRUPT_STATUS_1, MXC_PMIC_FRAME_MASK)); + return PMIC_SUCCESS; +} + +/*! + * This function returns the PMIC version in system. + * + * @param ver pointer to the pmic_version_t structure + * + * @return This function returns PMIC version. + */ +void pmic_get_revision(pmic_version_t *ver) +{ + int rev_id = 0; + int rev1 = 0; + int rev2 = 0; + int finid = 0; + int icid = 0; + + ver->id = PMIC_MC13783; + pmic_read(REG_REVISION, &rev_id); + + rev1 = (rev_id & 0x018) >> 3; + rev2 = (rev_id & 0x007); + icid = (rev_id & 0x01C0) >> 6; + finid = (rev_id & 0x01E00) >> 9; + + /* Ver 0.2 is actually 3.2a. Report as 3.2 */ + if ((rev1 == 0) && (rev2 == 2)) { + rev1 = 3; + } + + if (rev1 == 0 || icid != 2) { + ver->revision = -1; + printk(KERN_NOTICE + "mc13783: Not detected.\tAccess failed\t!!!\n"); + } else { + ver->revision = ((rev1 * 10) + rev2); + printk(KERN_INFO "mc13783 Rev %d.%d FinVer %x detected\n", rev1, + rev2, finid); + } + + return; + +} + +/*! + * This function reads the interrupt status registers of PMIC + * and determine the current active events. + * + * @param active_events array pointer to be used to return active + * event numbers. + * + * @return This function returns PMIC version. + */ +unsigned int pmic_get_active_events(unsigned int *active_events) +{ + unsigned int count = 0; + unsigned int status0, status1; + int bit_set; + + pmic_read(REG_INTERRUPT_STATUS_0, &status0); + pmic_read(REG_INTERRUPT_STATUS_1, &status1); + pmic_write(REG_INTERRUPT_STATUS_0, status0); + pmic_write(REG_INTERRUPT_STATUS_1, status1); + status0 &= events_enabled0; + status1 &= events_enabled1; + + while (status0) { + bit_set = ffs(status0) - 1; + *(active_events + count) = bit_set; + count++; + status0 ^= (1 << bit_set); + } + while (status1) { + bit_set = ffs(status1) - 1; + *(active_events + count) = bit_set + 24; + count++; + status1 ^= (1 << bit_set); + } + + return count; +} + +/*! + * This function unsets a bit in mask register of pmic to unmask an event IT. + * + * @param event the event to be unmasked + * + * @return This function returns PMIC_SUCCESS on SUCCESS, error on FAILURE. + */ +int pmic_event_unmask(type_event event) +{ + unsigned int event_mask = 0; + unsigned int mask_reg = 0; + unsigned int event_bit = 0; + int ret; + + if (event < EVENT_E1HZI) { + mask_reg = REG_INTERRUPT_MASK_0; + event_mask = EVENT_MASK_0; + event_bit = (1 << event); + events_enabled0 |= event_bit; + } else { + event -= 24; + mask_reg = REG_INTERRUPT_MASK_1; + event_mask = EVENT_MASK_1; + event_bit = (1 << event); + events_enabled1 |= event_bit; + } + + if ((event_bit & event_mask) == 0) { + pr_debug("Error: unmasking a reserved/unused event\n"); + return PMIC_ERROR; + } + + ret = pmic_write_reg(mask_reg, 0, event_bit); + + pr_debug("Enable Event : %d\n", event); + + return ret; +} + +/*! + * This function sets a bit in mask register of pmic to disable an event IT. + * + * @param event the event to be masked + * + * @return This function returns PMIC_SUCCESS on SUCCESS, error on FAILURE. + */ +int pmic_event_mask(type_event event) +{ + unsigned int event_mask = 0; + unsigned int mask_reg = 0; + unsigned int event_bit = 0; + int ret; + + if (event < EVENT_E1HZI) { + mask_reg = REG_INTERRUPT_MASK_0; + event_mask = EVENT_MASK_0; + event_bit = (1 << event); + events_enabled0 &= ~event_bit; + } else { + event -= 24; + mask_reg = REG_INTERRUPT_MASK_1; + event_mask = EVENT_MASK_1; + event_bit = (1 << event); + events_enabled1 &= ~event_bit; + } + + if ((event_bit & event_mask) == 0) { + pr_debug("Error: masking a reserved/unused event\n"); + return PMIC_ERROR; + } + + ret = pmic_write_reg(mask_reg, event_bit, event_bit); + + pr_debug("Disable Event : %d\n", event); + + return ret; +} + +/*! + * This function is called to read all sensor bits of PMIC. + * + * @param sensor Sensor to be checked. + * + * @return This function returns true if the sensor bit is high; + * or returns false if the sensor bit is low. + */ +bool pmic_check_sensor(t_sensor sensor) +{ + unsigned int reg_val = 0; + + CHECK_ERROR(pmic_read_reg + (REG_INTERRUPT_SENSE_0, ®_val, PMIC_ALL_BITS)); + + if ((1 << sensor) & reg_val) + return true; + else + return false; +} + +/*! + * This function checks one sensor of PMIC. + * + * @param sensor_bits structure of all sensor bits. + * + * @return This function returns PMIC_SUCCESS on SUCCESS, error on FAILURE. + */ + +PMIC_STATUS pmic_get_sensors(t_sensor_bits *sensor_bits) +{ + int sense_0 = 0; + int sense_1 = 0; + + memset(sensor_bits, 0, sizeof(t_sensor_bits)); + + pmic_read_reg(REG_INTERRUPT_SENSE_0, &sense_0, 0xffffff); + pmic_read_reg(REG_INTERRUPT_SENSE_1, &sense_1, 0xffffff); + + sensor_bits->sense_chgdets = (sense_0 & (1 << 6)) ? true : false; + sensor_bits->sense_chgovs = (sense_0 & (1 << 7)) ? true : false; + sensor_bits->sense_chgrevs = (sense_0 & (1 << 8)) ? true : false; + sensor_bits->sense_chgshorts = (sense_0 & (1 << 9)) ? true : false; + sensor_bits->sense_cccvs = (sense_0 & (1 << 10)) ? true : false; + sensor_bits->sense_chgcurrs = (sense_0 & (1 << 11)) ? true : false; + sensor_bits->sense_bpons = (sense_0 & (1 << 12)) ? true : false; + sensor_bits->sense_lobatls = (sense_0 & (1 << 13)) ? true : false; + sensor_bits->sense_lobaths = (sense_0 & (1 << 14)) ? true : false; + sensor_bits->sense_usb4v4s = (sense_0 & (1 << 16)) ? true : false; + sensor_bits->sense_usb2v0s = (sense_0 & (1 << 17)) ? true : false; + sensor_bits->sense_usb0v8s = (sense_0 & (1 << 18)) ? true : false; + sensor_bits->sense_id_floats = (sense_0 & (1 << 19)) ? true : false; + sensor_bits->sense_id_gnds = (sense_0 & (1 << 20)) ? true : false; + sensor_bits->sense_se1s = (sense_0 & (1 << 21)) ? true : false; + sensor_bits->sense_ckdets = (sense_0 & (1 << 22)) ? true : false; + + sensor_bits->sense_onofd1s = (sense_1 & (1 << 3)) ? true : false; + sensor_bits->sense_onofd2s = (sense_1 & (1 << 4)) ? true : false; + sensor_bits->sense_onofd3s = (sense_1 & (1 << 5)) ? true : false; + sensor_bits->sense_pwrrdys = (sense_1 & (1 << 11)) ? true : false; + sensor_bits->sense_thwarnhs = (sense_1 & (1 << 12)) ? true : false; + sensor_bits->sense_thwarnls = (sense_1 & (1 << 13)) ? true : false; + sensor_bits->sense_clks = (sense_1 & (1 << 14)) ? true : false; + sensor_bits->sense_mc2bs = (sense_1 & (1 << 17)) ? true : false; + sensor_bits->sense_hsdets = (sense_1 & (1 << 18)) ? true : false; + sensor_bits->sense_hsls = (sense_1 & (1 << 19)) ? true : false; + sensor_bits->sense_alspths = (sense_1 & (1 << 20)) ? true : false; + sensor_bits->sense_ahsshorts = (sense_1 & (1 << 21)) ? true : false; + return PMIC_SUCCESS; +} + +EXPORT_SYMBOL(pmic_check_sensor); +EXPORT_SYMBOL(pmic_get_sensors); diff --git a/drivers/mxc/pmic/core/mc13892.c b/drivers/mxc/pmic/core/mc13892.c new file mode 100644 index 000000000000..b21039bc666c --- /dev/null +++ b/drivers/mxc/pmic/core/mc13892.c @@ -0,0 +1,335 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file pmic/core/mc13892.c + * @brief This file contains MC13892 specific PMIC code. This implementaion + * may differ for each PMIC chip. + * + * @ingroup PMIC_CORE + */ + +/* + * Includes + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "pmic.h" + +/* + * Defines + */ +#define MC13892_I2C_RETRY_TIMES 10 +#define MXC_PMIC_FRAME_MASK 0x00FFFFFF +#define MXC_PMIC_MAX_REG_NUM 0x3F +#define MXC_PMIC_REG_NUM_SHIFT 0x19 +#define MXC_PMIC_WRITE_BIT_SHIFT 31 + +static unsigned int events_enabled0; +static unsigned int events_enabled1; +static struct mxc_pmic pmic_drv_data; +#ifndef CONFIG_MXC_PMIC_I2C +struct i2c_client *mc13892_client; +#endif + +int pmic_i2c_24bit_read(struct i2c_client *client, unsigned int reg_num, + unsigned int *value) +{ + unsigned char buf[3]; + int ret; + int i; + + memset(buf, 0, 3); + for (i = 0; i < MC13892_I2C_RETRY_TIMES; i++) { + ret = i2c_smbus_read_i2c_block_data(client, reg_num, 3, buf); + if (ret == 3) + break; + msleep(1); + } + + if (ret == 3) { + *value = buf[0] << 16 | buf[1] << 8 | buf[2]; + return ret; + } else { + pr_err("24bit read error, ret = %d\n", ret); + return -1; /* return -1 on failure */ + } +} + +int pmic_i2c_24bit_write(struct i2c_client *client, + unsigned int reg_num, unsigned int reg_val) +{ + char buf[3]; + int ret; + int i; + + buf[0] = (reg_val >> 16) & 0xff; + buf[1] = (reg_val >> 8) & 0xff; + buf[2] = (reg_val) & 0xff; + + for (i = 0; i < MC13892_I2C_RETRY_TIMES; i++) { + ret = i2c_smbus_write_i2c_block_data(client, reg_num, 3, buf); + if (ret == 0) + break; + msleep(1); + } + if (i == MC13892_I2C_RETRY_TIMES) + pr_err("24bit write error, ret = %d\n", ret); + + return ret; +} + +int pmic_read(int reg_num, unsigned int *reg_val) +{ + unsigned int frame = 0; + int ret = 0; + + if (pmic_drv_data.spi != NULL) { + if (reg_num > MXC_PMIC_MAX_REG_NUM) + return PMIC_ERROR; + + frame |= reg_num << MXC_PMIC_REG_NUM_SHIFT; + + ret = spi_rw(pmic_drv_data.spi, (u8 *) &frame, 1); + + *reg_val = frame & MXC_PMIC_FRAME_MASK; + } else { + if (mc13892_client == NULL) + return PMIC_ERROR; + + if (pmic_i2c_24bit_read(mc13892_client, reg_num, reg_val) == -1) + return PMIC_ERROR; + } + + return PMIC_SUCCESS; +} + +int pmic_write(int reg_num, const unsigned int reg_val) +{ + unsigned int frame = 0; + int ret = 0; + + if (pmic_drv_data.spi != NULL) { + if (reg_num > MXC_PMIC_MAX_REG_NUM) + return PMIC_ERROR; + + frame |= (1 << MXC_PMIC_WRITE_BIT_SHIFT); + + frame |= reg_num << MXC_PMIC_REG_NUM_SHIFT; + + frame |= reg_val & MXC_PMIC_FRAME_MASK; + + ret = spi_rw(pmic_drv_data.spi, (u8 *) &frame, 1); + + return ret; + } else { + if (mc13892_client == NULL) + return PMIC_ERROR; + + return pmic_i2c_24bit_write(mc13892_client, reg_num, reg_val); + } +} + +void *pmic_alloc_data(struct device *dev) +{ + struct mc13892 *mc13892; + + mc13892 = kzalloc(sizeof(struct mc13892), GFP_KERNEL); + if (mc13892 == NULL) + return NULL; + + mc13892->dev = dev; + + return (void *)mc13892; +} + +/*! + * This function initializes the SPI device parameters for this PMIC. + * + * @param spi the SPI slave device(PMIC) + * + * @return None + */ +int pmic_spi_setup(struct spi_device *spi) +{ + /* Setup the SPI slave i.e.PMIC */ + pmic_drv_data.spi = spi; + + spi->mode = SPI_MODE_0 | SPI_CS_HIGH; + spi->bits_per_word = 32; + + return spi_setup(spi); +} + +int pmic_init_registers(void) +{ + CHECK_ERROR(pmic_write(REG_INT_MASK0, 0xFFFFFF)); + CHECK_ERROR(pmic_write(REG_INT_MASK0, 0xFFFFFF)); + CHECK_ERROR(pmic_write(REG_INT_STATUS0, 0xFFFFFF)); + CHECK_ERROR(pmic_write(REG_INT_STATUS1, 0xFFFFFF)); + /* disable auto charge */ + if (machine_is_mx51_3ds()) + CHECK_ERROR(pmic_write(REG_CHARGE, 0xB40003)); + + pm_power_off = mc13892_power_off; + + return PMIC_SUCCESS; +} + +unsigned int pmic_get_active_events(unsigned int *active_events) +{ + unsigned int count = 0; + unsigned int status0, status1; + int bit_set; + + pmic_read(REG_INT_STATUS0, &status0); + pmic_read(REG_INT_STATUS1, &status1); + pmic_write(REG_INT_STATUS0, status0); + pmic_write(REG_INT_STATUS1, status1); + status0 &= events_enabled0; + status1 &= events_enabled1; + + while (status0) { + bit_set = ffs(status0) - 1; + *(active_events + count) = bit_set; + count++; + status0 ^= (1 << bit_set); + } + while (status1) { + bit_set = ffs(status1) - 1; + *(active_events + count) = bit_set + 24; + count++; + status1 ^= (1 << bit_set); + } + + return count; +} + +#define EVENT_MASK_0 0x387fff +#define EVENT_MASK_1 0x1177eb + +int pmic_event_unmask(type_event event) +{ + unsigned int event_mask = 0; + unsigned int mask_reg = 0; + unsigned int event_bit = 0; + int ret; + + if (event < EVENT_1HZI) { + mask_reg = REG_INT_MASK0; + event_mask = EVENT_MASK_0; + event_bit = (1 << event); + events_enabled0 |= event_bit; + } else { + event -= 24; + mask_reg = REG_INT_MASK1; + event_mask = EVENT_MASK_1; + event_bit = (1 << event); + events_enabled1 |= event_bit; + } + + if ((event_bit & event_mask) == 0) { + pr_debug("Error: unmasking a reserved/unused event\n"); + return PMIC_ERROR; + } + + ret = pmic_write_reg(mask_reg, 0, event_bit); + + pr_debug("Enable Event : %d\n", event); + + return ret; +} + +int pmic_event_mask(type_event event) +{ + unsigned int event_mask = 0; + unsigned int mask_reg = 0; + unsigned int event_bit = 0; + int ret; + + if (event < EVENT_1HZI) { + mask_reg = REG_INT_MASK0; + event_mask = EVENT_MASK_0; + event_bit = (1 << event); + events_enabled0 &= ~event_bit; + } else { + event -= 24; + mask_reg = REG_INT_MASK1; + event_mask = EVENT_MASK_1; + event_bit = (1 << event); + events_enabled1 &= ~event_bit; + } + + if ((event_bit & event_mask) == 0) { + pr_debug("Error: masking a reserved/unused event\n"); + return PMIC_ERROR; + } + + ret = pmic_write_reg(mask_reg, event_bit, event_bit); + + pr_debug("Disable Event : %d\n", event); + + return ret; +} + +/*! + * This function returns the PMIC version in system. + * + * @param ver pointer to the pmic_version_t structure + * + * @return This function returns PMIC version. + */ +void pmic_get_revision(pmic_version_t *ver) +{ + int rev_id = 0; + int rev1 = 0; + int rev2 = 0; + int finid = 0; + int icid = 0; + + ver->id = PMIC_MC13892; + pmic_read(REG_IDENTIFICATION, &rev_id); + + rev1 = (rev_id & 0x018) >> 3; + rev2 = (rev_id & 0x007); + icid = (rev_id & 0x01C0) >> 6; + finid = (rev_id & 0x01E00) >> 9; + + ver->revision = ((rev1 * 10) + rev2); + printk(KERN_INFO "mc13892 Rev %d.%d FinVer %x detected\n", rev1, + rev2, finid); +} + +void mc13892_power_off(void) +{ + unsigned int value; + + pmic_read_reg(REG_POWER_CTL0, &value, 0xffffff); + + value |= 0x000008; + + pmic_write_reg(REG_POWER_CTL0, value, 0xffffff); +} diff --git a/drivers/mxc/pmic/core/mc34704.c b/drivers/mxc/pmic/core/mc34704.c new file mode 100644 index 000000000000..e70a45134c6a --- /dev/null +++ b/drivers/mxc/pmic/core/mc34704.c @@ -0,0 +1,329 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file pmic/core/mc34704.c + * @brief This file contains MC34704 specific PMIC code. + * + * @ingroup PMIC_CORE + */ + +/* + * Includes + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "pmic.h" + +/* + * Globals + */ +static pmic_version_t mxc_pmic_version = { + .id = PMIC_MC34704, + .revision = 0, +}; +static unsigned int events_enabled; +unsigned int active_events[MAX_ACTIVE_EVENTS]; +struct i2c_client *mc34704_client; +static void pmic_trigger_poll(void); + +#define MAX_MC34704_REG 0x59 +static unsigned int mc34704_reg_readonly[MAX_MC34704_REG / 32 + 1] = { + (1 << 0x03) || (1 << 0x05) || (1 << 0x07) || (1 << 0x09) || + (1 << 0x0B) || (1 << 0x0E) || (1 << 0x11) || (1 << 0x14) || + (1 << 0x17) || (1 << 0x18), + 0, +}; +static unsigned int mc34704_reg_written[MAX_MC34704_REG / 32 + 1]; +static unsigned char mc34704_shadow_regs[MAX_MC34704_REG - 1]; +#define IS_READONLY(r) ((1 << ((r) % 32)) & mc34704_reg_readonly[(r) / 32]) +#define WAS_WRITTEN(r) ((1 << ((r) % 32)) & mc34704_reg_written[(r) / 32]) +#define MARK_WRITTEN(r) do { \ + mc34704_reg_written[(r) / 32] |= (1 << ((r) % 32)); \ +} while (0) + +int pmic_read(int reg_nr, unsigned int *reg_val) +{ + int c; + + /* + * Use the shadow register if we've written to it + */ + if (WAS_WRITTEN(reg_nr)) { + *reg_val = mc34704_shadow_regs[reg_nr]; + return PMIC_SUCCESS; + } + + /* + * Otherwise, actually read the real register. + * Write-only registers will read as zero. + */ + c = i2c_smbus_read_byte_data(mc34704_client, reg_nr); + if (c == -1) { + pr_debug("mc34704: error reading register 0x%02x\n", reg_nr); + return PMIC_ERROR; + } else { + *reg_val = c; + return PMIC_SUCCESS; + } +} + +int pmic_write(int reg_nr, const unsigned int reg_val) +{ + int ret; + + ret = i2c_smbus_write_byte_data(mc34704_client, reg_nr, reg_val); + if (ret == -1) { + return PMIC_ERROR; + } else { + /* + * Update our software copy of the register since you + * can't read what you wrote. + */ + if (!IS_READONLY(reg_nr)) { + mc34704_shadow_regs[reg_nr] = reg_val; + MARK_WRITTEN(reg_nr); + } + return PMIC_SUCCESS; + } +} + +unsigned int pmic_get_active_events(unsigned int *active_events) +{ + unsigned int count = 0; + unsigned int faults; + int bit_set; + + /* Check for any relevant PMIC faults */ + pmic_read(REG_MC34704_FAULTS, &faults); + faults &= events_enabled; + + /* + * Mask all active events, because there is no way to acknowledge + * or dismiss them in the PMIC -- they're sticky. + */ + events_enabled &= ~faults; + + /* Account for all unmasked faults */ + while (faults) { + bit_set = ffs(faults) - 1; + *(active_events + count) = bit_set; + count++; + faults ^= (1 << bit_set); + } + return count; +} + +int pmic_event_unmask(type_event event) +{ + unsigned int event_bit = 0; + unsigned int prior_events = events_enabled; + + event_bit = (1 << event); + events_enabled |= event_bit; + + pr_debug("Enable Event : %d\n", event); + + /* start the polling task as needed */ + if (events_enabled && prior_events == 0) + pmic_trigger_poll(); + + return 0; +} + +int pmic_event_mask(type_event event) +{ + unsigned int event_bit = 0; + + event_bit = (1 << event); + events_enabled &= ~event_bit; + + pr_debug("Disable Event : %d\n", event); + + return 0; +} + +/*! + * PMIC event polling task. This task is called periodically to poll + * for possible MC34704 events (No interrupt supplied by the hardware). + */ +static void pmic_event_task(struct work_struct *work); +DECLARE_DELAYED_WORK(pmic_ws, pmic_event_task); + +static void pmic_trigger_poll(void) +{ + schedule_delayed_work(&pmic_ws, HZ / 10); +} + +static void pmic_event_task(struct work_struct *work) +{ + unsigned int count = 0; + int i; + + count = pmic_get_active_events(active_events); + pr_debug("active events number %d\n", count); + + /* call handlers for all active events */ + for (i = 0; i < count; i++) + pmic_event_callback(active_events[i]); + + /* re-trigger this task, but only if somebody is watching */ + if (events_enabled) + pmic_trigger_poll(); + + return; +} + +pmic_version_t pmic_get_version(void) +{ + return mxc_pmic_version; +} +EXPORT_SYMBOL(pmic_get_version); + +int __devinit pmic_init_registers(void) +{ + /* + * Set some registers to what they should be, + * if for no other reason than to initialize our + * software register copies. + */ + CHECK_ERROR(pmic_write(REG_MC34704_GENERAL2, 0x09)); + CHECK_ERROR(pmic_write(REG_MC34704_VGSET1, 0)); + CHECK_ERROR(pmic_write(REG_MC34704_REG2SET1, 0)); + CHECK_ERROR(pmic_write(REG_MC34704_REG3SET1, 0)); + CHECK_ERROR(pmic_write(REG_MC34704_REG4SET1, 0)); + CHECK_ERROR(pmic_write(REG_MC34704_REG5SET1, 0)); + + return PMIC_SUCCESS; +} + +static int __devinit is_chip_onboard(struct i2c_client *client) +{ + int val; + + /* + * This PMIC has no version or ID register, so just see + * if it ACK's and returns 0 on some write-only register as + * evidence of its presence. + */ + val = i2c_smbus_read_byte_data(client, REG_MC34704_GENERAL2); + if (val != 0) + return -1; + + return 0; +} + +static int __devinit pmic_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + int ret = 0; + struct mc34704 *mc34704; + struct mc34704_platform_data *plat_data = client->dev.platform_data; + + if (!plat_data || !plat_data->init) + return -ENODEV; + + ret = is_chip_onboard(client); + + if (ret == -1) + return -ENODEV; + + mc34704 = kzalloc(sizeof(struct mc34704), GFP_KERNEL); + if (mc34704 == NULL) + return -ENOMEM; + + i2c_set_clientdata(client, mc34704); + mc34704->dev = &client->dev; + mc34704->i2c_client = client; + + mc34704_client = client; + + /* Initialize the PMIC event handling */ + pmic_event_list_init(); + + /* Initialize PMI registers */ + if (pmic_init_registers() != PMIC_SUCCESS) + return PMIC_ERROR; + + ret = plat_data->init(mc34704); + if (ret != 0) + return PMIC_ERROR; + + dev_info(&client->dev, "Loaded\n"); + + return PMIC_SUCCESS; +} + +static int pmic_remove(struct i2c_client *client) +{ + return 0; +} + +static int pmic_suspend(struct i2c_client *client, pm_message_t state) +{ + return 0; +} + +static int pmic_resume(struct i2c_client *client) +{ + return 0; +} + +static const struct i2c_device_id mc34704_id[] = { + {"mc34704", 0}, + {}, +}; + +MODULE_DEVICE_TABLE(i2c, mc34704_id); + +static struct i2c_driver pmic_driver = { + .driver = { + .name = "mc34704", + .bus = NULL, + }, + .probe = pmic_probe, + .remove = pmic_remove, + .suspend = pmic_suspend, + .resume = pmic_resume, + .id_table = mc34704_id, +}; + +static int __init pmic_init(void) +{ + return i2c_add_driver(&pmic_driver); +} + +static void __exit pmic_exit(void) +{ + i2c_del_driver(&pmic_driver); +} + +/* + * Module entry points + */ +subsys_initcall_sync(pmic_init); +module_exit(pmic_exit); + +MODULE_DESCRIPTION("MC34704 PMIC driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/pmic/core/pmic-dev.c b/drivers/mxc/pmic/core/pmic-dev.c new file mode 100644 index 000000000000..9d0765ebb0d1 --- /dev/null +++ b/drivers/mxc/pmic/core/pmic-dev.c @@ -0,0 +1,317 @@ +/* + * Copyright 2005-2010 Freescale Semiconductor, Inc. All rights reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file pmic-dev.c + * @brief This provides /dev interface to the user program. They make it + * possible to have user-space programs use or control PMIC. Mainly its + * useful for notifying PMIC events to user-space programs. + * + * @ingroup PMIC_CORE + */ + +/* + * Includes + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#define PMIC_NAME "pmic" +#define CIRC_BUF_MAX 16 + +static int pmic_major; +static struct class *pmic_class; +static struct fasync_struct *pmic_dev_queue; + +static DECLARE_MUTEX(event_mutex); +static struct circ_buf pmic_events; + +static void callbackfn(void *event) +{ + printk(KERN_INFO "\n\n DETECTED PMIC EVENT : %d\n\n", + (unsigned int)event); +} + +static void user_notify_callback(void *event) +{ + down(&event_mutex); + if (CIRC_SPACE(pmic_events.head, pmic_events.tail, CIRC_BUF_MAX)) { + pmic_events.buf[pmic_events.head] = (char)event; + pmic_events.head = (pmic_events.head + 1) & (CIRC_BUF_MAX - 1); + } else { + pr_info("Failed to notify event to the user\n"); + } + up(&event_mutex); + + kill_fasync(&pmic_dev_queue, SIGIO, POLL_IN); +} + +/*! + * This function implements IOCTL controls on a PMIC device. + * + * @param inode pointer on the node + * @param file pointer on the file + * @param cmd the command + * @param arg the parameter + * @return This function returns 0 if successful. + */ +static int pmic_dev_ioctl(struct inode *inode, struct file *file, + unsigned int cmd, unsigned long arg) +{ + register_info reg_info; + pmic_event_callback_t event_sub; + type_event event; + int ret = 0; + + if (_IOC_TYPE(cmd) != 'P') + return -ENOTTY; + + switch (cmd) { + case PMIC_READ_REG: + if (copy_from_user(®_info, (register_info *) arg, + sizeof(register_info))) { + return -EFAULT; + } + ret = + pmic_read_reg(reg_info.reg, &(reg_info.reg_value), + 0x00ffffff); + pr_debug("read reg %d %x\n", reg_info.reg, reg_info.reg_value); + if (copy_to_user((register_info *) arg, ®_info, + sizeof(register_info))) { + return -EFAULT; + } + break; + + case PMIC_WRITE_REG: + if (copy_from_user(®_info, (register_info *) arg, + sizeof(register_info))) { + return -EFAULT; + } + ret = + pmic_write_reg(reg_info.reg, reg_info.reg_value, + 0x00ffffff); + pr_debug("write reg %d %x\n", reg_info.reg, reg_info.reg_value); + if (copy_to_user((register_info *) arg, ®_info, + sizeof(register_info))) { + return -EFAULT; + } + break; + + case PMIC_SUBSCRIBE: + if (get_user(event, (int __user *)arg)) { + return -EFAULT; + } + event_sub.func = callbackfn; + event_sub.param = (void *)event; + ret = pmic_event_subscribe(event, event_sub); + pr_debug("subscribe done\n"); + break; + + case PMIC_UNSUBSCRIBE: + if (get_user(event, (int __user *)arg)) { + return -EFAULT; + } + event_sub.func = callbackfn; + event_sub.param = (void *)event; + ret = pmic_event_unsubscribe(event, event_sub); + pr_debug("unsubscribe done\n"); + break; + + case PMIC_NOTIFY_USER: + if (get_user(event, (int __user *)arg)) { + return -EFAULT; + } + event_sub.func = user_notify_callback; + event_sub.param = (void *)event; + ret = pmic_event_subscribe(event, event_sub); + break; + + case PMIC_GET_NOTIFY: + down(&event_mutex); + if (CIRC_CNT(pmic_events.head, pmic_events.tail, CIRC_BUF_MAX)) { + event = (int)pmic_events.buf[pmic_events.tail]; + pmic_events.tail = (pmic_events.tail + 1) & (CIRC_BUF_MAX - 1); + } else { + elem = -1; + pr_info("No valid notified event\n"); + } + up(&event_mutex); + + if (put_user(event, (int __user *)arg)) { + return -EFAULT; + } + break; + + default: + printk(KERN_ERR "%d unsupported ioctl command\n", (int)cmd); + return -EINVAL; + } + + return ret; +} + +/*! + * This function implements the open method on a PMIC device. + * + * @param inode pointer on the node + * @param file pointer on the file + * @return This function returns 0. + */ +static int pmic_dev_open(struct inode *inode, struct file *file) +{ + pr_debug("open\n"); + return PMIC_SUCCESS; +} + +/*! + * This function implements the release method on a PMIC device. + * + * @param inode pointer on the node + * @param file pointer on the file + * + * @return This function returns 0. + */ +static int pmic_dev_free(struct inode *inode, struct file *file) +{ + pr_debug("free\n"); + return PMIC_SUCCESS; +} + +static int pmic_dev_fasync(int fd, struct file *filp, int mode) +{ + return fasync_helper(fd, filp, mode, &pmic_dev_queue); +} + +/*! + * This structure defines file operations for a PMIC device. + */ +static struct file_operations pmic_fops = { + /*! + * the owner + */ + .owner = THIS_MODULE, + /*! + * the ioctl operation + */ + .ioctl = pmic_dev_ioctl, + /*! + * the open operation + */ + .open = pmic_dev_open, + /*! + * the release operation + */ + .release = pmic_dev_free, + /*! + * the release operation + */ + .fasync = pmic_dev_fasync, +}; + +/*! + * This function implements the init function of the PMIC char device. + * This function is called when the module is loaded. It registers + * the character device for PMIC to be used by user-space programs. + * + * @return This function returns 0. + */ +static int __init pmic_dev_init(void) +{ + int ret = 0; + struct device *pmic_device; + pmic_version_t pmic_ver; + + pmic_ver = pmic_get_version(); + if (pmic_ver.revision < 0) { + printk(KERN_ERR "No PMIC device found\n"); + return -ENODEV; + } + + pmic_major = register_chrdev(0, PMIC_NAME, &pmic_fops); + if (pmic_major < 0) { + printk(KERN_ERR "unable to get a major for pmic\n"); + return pmic_major; + } + + pmic_class = class_create(THIS_MODULE, PMIC_NAME); + if (IS_ERR(pmic_class)) { + printk(KERN_ERR "Error creating pmic class.\n"); + ret = PMIC_ERROR; + goto err; + } + + pmic_device = device_create(pmic_class, NULL, MKDEV(pmic_major, 0), NULL, + PMIC_NAME); + if (IS_ERR(pmic_device)) { + printk(KERN_ERR "Error creating pmic class device.\n"); + ret = PMIC_ERROR; + goto err1; + } + + pmic_events.buf = kmalloc(CIRC_BUF_MAX * sizeof(char), GFP_KERNEL); + if (NULL == pmic_events.buf) { + ret = -ENOMEM; + goto err2; + } + pmic_events.head = pmic_events.tail = 0; + + printk(KERN_INFO "PMIC Character device: successfully loaded\n"); + return ret; + err2: + device_destroy(pmic_class, MKDEV(pmic_major, 0)); + err1: + class_destroy(pmic_class); + err: + unregister_chrdev(pmic_major, PMIC_NAME); + return ret; + +} + +/*! + * This function implements the exit function of the PMIC character device. + * This function is called when the module is unloaded. It unregisters + * the PMIC character device. + * + */ +static void __exit pmic_dev_exit(void) +{ + device_destroy(pmic_class, MKDEV(pmic_major, 0)); + class_destroy(pmic_class); + + unregister_chrdev(pmic_major, PMIC_NAME); + + printk(KERN_INFO "PMIC Character device: successfully unloaded\n"); +} + +/* + * Module entry points + */ + +module_init(pmic_dev_init); +module_exit(pmic_dev_exit); + +MODULE_DESCRIPTION("PMIC Protocol /dev entries driver"); +MODULE_AUTHOR("FreeScale"); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/pmic/core/pmic.h b/drivers/mxc/pmic/core/pmic.h new file mode 100644 index 000000000000..d4ba34786888 --- /dev/null +++ b/drivers/mxc/pmic/core/pmic.h @@ -0,0 +1,138 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#ifndef __PMIC_H__ +#define __PMIC_H__ + + /*! + * @file pmic.h + * @brief This file contains prototypes of all the functions to be + * defined for each PMIC chip. The implementation of these may differ + * from PMIC chip to PMIC chip. + * + * @ingroup PMIC_CORE + */ + +#include + +#define MAX_ACTIVE_EVENTS 10 + +/*! + * This structure is a way for the PMIC core driver to define their own + * \b spi_device structure. This structure includes the core \b spi_device + * structure that is provided by Linux SPI Framework/driver as an + * element and may contain other elements that are required by core driver. + */ +struct mxc_pmic { + /*! + * Master side proxy for an SPI slave device(PMIC) + */ + struct spi_device *spi; +}; + +/*! + * This function is called to transfer data to PMIC on SPI. + * + * @param spi the SPI slave device(PMIC) + * @param buf the pointer to the data buffer + * @param len the length of the data to be transferred + * + * @return Returns 0 on success -1 on failure. + */ +static inline int spi_rw(struct spi_device *spi, u8 * buf, size_t len) +{ + struct spi_transfer t = { + .tx_buf = (const void *)buf, + .rx_buf = buf, + .len = len, + .cs_change = 0, + .delay_usecs = 0, + }; + struct spi_message m; + + spi_message_init(&m); + spi_message_add_tail(&t, &m); + if (spi_sync(spi, &m) != 0 || m.status != 0) + return PMIC_ERROR; + return len - m.actual_length; +} + +/*! + * This function returns the PMIC version in system. + * + * @param ver pointer to the pmic_version_t structure + * + * @return This function returns PMIC version. + */ +void pmic_get_revision(pmic_version_t *ver); + +/*! + * This function initializes the SPI device parameters for this PMIC. + * + * @param spi the SPI slave device(PMIC) + * + * @return None + */ +int pmic_spi_setup(struct spi_device *spi); + +/*! + * This function initializes the PMIC registers. + * + * @return None + */ +int pmic_init_registers(void); + +/*! + * This function reads the interrupt status registers of PMIC + * and determine the current active events. + * + * @param active_events array pointer to be used to return active + * event numbers. + * + * @return This function returns PMIC version. + */ +unsigned int pmic_get_active_events(unsigned int *active_events); + +/*! + * This function sets a bit in mask register of pmic to disable an event IT. + * + * @param event the event to be masked + * + * @return This function returns PMIC_SUCCESS on SUCCESS, error on FAILURE. + */ +int pmic_event_mask(type_event event); + +/*! + * This function unsets a bit in mask register of pmic to unmask an event IT. + * + * @param event the event to be unmasked + * + * @return This function returns PMIC_SUCCESS on SUCCESS, error on FAILURE. + */ +int pmic_event_unmask(type_event event); + +#ifdef CONFIG_MXC_PMIC_FIXARB +extern PMIC_STATUS pmic_fix_arbitration(struct spi_device *spi); +#else +static inline PMIC_STATUS pmic_fix_arbitration(struct spi_device *spi) +{ + return PMIC_SUCCESS; +} +#endif + +void *pmic_alloc_data(struct device *dev); + +int pmic_start_event_thread(int irq_num); + +void pmic_stop_event_thread(void); + +#endif /* __PMIC_H__ */ diff --git a/drivers/mxc/pmic/core/pmic_common.c b/drivers/mxc/pmic/core/pmic_common.c new file mode 100644 index 000000000000..c15d212da714 --- /dev/null +++ b/drivers/mxc/pmic/core/pmic_common.c @@ -0,0 +1,127 @@ +/* + * Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file pmic_common.c + * @brief This is the common file for the PMIC Core/Protocol driver. + * + * @ingroup PMIC_CORE + */ + +/* + * Includes + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "pmic.h" + +/* + * Global variables + */ +pmic_version_t mxc_pmic_version; +unsigned int active_events[MAX_ACTIVE_EVENTS]; + + +static struct completion event_completion; +static struct task_struct *tstask; + +static int pmic_event_thread_func(void *v) +{ + unsigned int loop; + unsigned int count = 0; + unsigned int irq = (int)v; + + while (1) { + wait_for_completion_interruptible( + &event_completion); + if (kthread_should_stop()) + break; + + count = pmic_get_active_events( + active_events); + pr_debug("active events number %d\n", count); + + for (loop = 0; loop < count; loop++) + pmic_event_callback( + active_events[loop]); + enable_irq(irq); + } + + return 0; +} + +int pmic_start_event_thread(int irq_num) +{ + int ret = 0; + + if (tstask) + return ret; + + init_completion(&event_completion); + + tstask = kthread_run(pmic_event_thread_func, + (void *)irq_num, "pmic-event-thread"); + ret = IS_ERR(tstask) ? -1 : 0; + if (IS_ERR(tstask)) + tstask = NULL; + return ret; +} + +void pmic_stop_event_thread(void) +{ + if (tstask) { + complete(&event_completion); + kthread_stop(tstask); + } +} + +/*! + * This function is called when pmic interrupt occurs on the processor. + * It is the interrupt handler for the pmic module. + * + * @param irq the irq number + * @param dev_id the pointer on the device + * + * @return The function returns IRQ_HANDLED when handled. + */ +irqreturn_t pmic_irq_handler(int irq, void *dev_id) +{ + disable_irq_nosync(irq); + complete(&event_completion); + + return IRQ_HANDLED; +} + +/*! + * This function is used to determine the PMIC type and its revision. + * + * @return Returns the PMIC type and its revision. + */ + +pmic_version_t pmic_get_version(void) +{ + return mxc_pmic_version; +} +EXPORT_SYMBOL(pmic_get_version); diff --git a/drivers/mxc/pmic/core/pmic_core_i2c.c b/drivers/mxc/pmic/core/pmic_core_i2c.c new file mode 100644 index 000000000000..8dfec5ad4976 --- /dev/null +++ b/drivers/mxc/pmic/core/pmic_core_i2c.c @@ -0,0 +1,348 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file pmic_core_i2c.c + * @brief This is the main file for the PMIC Core/Protocol driver. i2c + * should be providing the interface between the PMIC and the MCU. + * + * @ingroup PMIC_CORE + */ + +/* + * Includes + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "pmic.h" + +#define MC13892_GENERATION_ID_LSH 6 +#define MC13892_IC_ID_LSH 13 + +#define MC13892_GENERATION_ID_WID 3 +#define MC13892_IC_ID_WID 6 + +#define MC13892_GEN_ID_VALUE 0x7 +#define MC13892_IC_ID_VALUE 1 + +/* + * Global variables + */ +struct i2c_client *mc13892_client; + +extern pmic_version_t mxc_pmic_version; +extern irqreturn_t pmic_irq_handler(int irq, void *dev_id); +/* + * Platform device structure for PMIC client drivers + */ +static struct platform_device adc_ldm = { + .name = "pmic_adc", + .id = 1, +}; +static struct platform_device battery_ldm = { + .name = "pmic_battery", + .id = 1, +}; +static struct platform_device power_ldm = { + .name = "pmic_power", + .id = 1, +}; +static struct platform_device rtc_ldm = { + .name = "pmic_rtc", + .id = 1, +}; +static struct platform_device light_ldm = { + .name = "pmic_light", + .id = 1, +}; +static struct platform_device rleds_ldm = { + .name = "pmic_leds", + .id = 'r', +}; +static struct platform_device gleds_ldm = { + .name = "pmic_leds", + .id = 'g', +}; +static struct platform_device bleds_ldm = { + .name = "pmic_leds", + .id = 'b', +}; + +static void pmic_pdev_register(struct device *dev) +{ + platform_device_register(&adc_ldm); + + if (!cpu_is_mx53()) + platform_device_register(&battery_ldm); + + platform_device_register(&rtc_ldm); + platform_device_register(&power_ldm); + platform_device_register(&light_ldm); + platform_device_register(&rleds_ldm); + platform_device_register(&gleds_ldm); + platform_device_register(&bleds_ldm); +} + +/*! + * This function unregisters platform device structures for + * PMIC client drivers. + */ +static void pmic_pdev_unregister(void) +{ + platform_device_unregister(&adc_ldm); + platform_device_unregister(&battery_ldm); + platform_device_unregister(&rtc_ldm); + platform_device_unregister(&power_ldm); + platform_device_unregister(&light_ldm); +} + +static int __devinit is_chip_onboard(struct i2c_client *client) +{ + unsigned int ret = 0; + + /*bind the right device to the driver */ + if (pmic_i2c_24bit_read(client, REG_IDENTIFICATION, &ret) == -1) + return -1; + + if (MC13892_GEN_ID_VALUE != BITFEXT(ret, MC13892_GENERATION_ID)) { + /*compare the address value */ + dev_err(&client->dev, + "read generation ID 0x%x is not equal to 0x%x!\n", + BITFEXT(ret, MC13892_GENERATION_ID), + MC13892_GEN_ID_VALUE); + return -1; + } + + return 0; +} + +static ssize_t mc13892_show(struct device *dev, + struct device_attribute *attr, char *buf) +{ + int i, value; + int offset = (REG_TEST4 + 1) / 4; + + for (i = 0; i < offset; i++) { + pmic_read(i, &value); + pr_info("reg%02d: %06x\t\t", i, value); + pmic_read(i + offset, &value); + pr_info("reg%02d: %06x\t\t", i + offset, value); + pmic_read(i + offset * 2, &value); + pr_info("reg%02d: %06x\t\t", i + offset * 2, value); + pmic_read(i + offset * 3, &value); + pr_info("reg%02d: %06x\n", i + offset * 3, value); + } + + return 0; +} + +static ssize_t mc13892_store(struct device *dev, + struct device_attribute *attr, const char *buf, + size_t count) +{ + int reg, value, ret; + char *p; + + reg = simple_strtoul(buf, NULL, 10); + + p = NULL; + p = memchr(buf, ' ', count); + + if (p == NULL) { + pmic_read(reg, &value); + pr_debug("reg%02d: %06x\n", reg, value); + return count; + } + + p += 1; + + value = simple_strtoul(p, NULL, 16); + + ret = pmic_write(reg, value); + if (ret == 0) + pr_debug("write reg%02d: %06x\n", reg, value); + else + pr_debug("register update failed\n"); + + return count; +} + +static struct device_attribute mc13892_dev_attr = { + .attr = { + .name = "mc13892_ctl", + .mode = S_IRUSR | S_IWUSR, + }, + .show = mc13892_show, + .store = mc13892_store, +}; + +static int __devinit pmic_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + int ret = 0; + int pmic_irq; + struct mc13892 *mc13892; + struct mc13892_platform_data *plat_data = client->dev.platform_data; + + ret = is_chip_onboard(client); + if (ret == -1) + return -ENODEV; + + mc13892 = kzalloc(sizeof(struct mc13892), GFP_KERNEL); + if (mc13892 == NULL) + return -ENOMEM; + + i2c_set_clientdata(client, mc13892); + mc13892->dev = &client->dev; + mc13892->i2c_client = client; + + /* so far, we got matched chip on board */ + + mc13892_client = client; + + /* Initialize the PMIC event handling */ + pmic_event_list_init(); + + /* Initialize GPIO for PMIC Interrupt */ + gpio_pmic_active(); + + /* Get the PMIC Version */ + pmic_get_revision(&mxc_pmic_version); + if (mxc_pmic_version.revision < 0) { + dev_err((struct device *)client, + "PMIC not detected!!! Access Failed\n"); + return -ENODEV; + } else { + dev_dbg((struct device *)client, + "Detected pmic core IC version number is %d\n", + mxc_pmic_version.revision); + } + + /* Initialize the PMIC parameters */ + ret = pmic_init_registers(); + if (ret != PMIC_SUCCESS) + return PMIC_ERROR; + + pmic_irq = (int)(client->irq); + if (pmic_irq == 0) + return PMIC_ERROR; + + ret = pmic_start_event_thread(pmic_irq); + if (ret) { + pr_err("mc13892 pmic driver init: \ + fail to start event thread\n"); + return PMIC_ERROR; + } + + /* Set and install PMIC IRQ handler */ + + set_irq_type(pmic_irq, IRQF_TRIGGER_HIGH); + + ret = + request_irq(pmic_irq, pmic_irq_handler, 0, "PMIC_IRQ", + 0); + + if (ret) { + dev_err(&client->dev, "request irq %d error!\n", pmic_irq); + return ret; + } + enable_irq_wake(pmic_irq); + + if (plat_data && plat_data->init) { + ret = plat_data->init(mc13892); + if (ret != 0) + return PMIC_ERROR; + } + + ret = device_create_file(&client->dev, &mc13892_dev_attr); + if (ret) + dev_err(&client->dev, "create device file failed!\n"); + + pmic_pdev_register(&client->dev); + + dev_info(&client->dev, "Loaded\n"); + + return PMIC_SUCCESS; +} + +static int pmic_remove(struct i2c_client *client) +{ + int pmic_irq = (int)(client->irq); + + pmic_stop_event_thread(); + free_irq(pmic_irq, 0); + pmic_pdev_unregister(); + return 0; +} + +static int pmic_suspend(struct i2c_client *client, pm_message_t state) +{ + return 0; +} + +static int pmic_resume(struct i2c_client *client) +{ + return 0; +} + +static const struct i2c_device_id mc13892_id[] = { + {"mc13892", 0}, + {}, +}; + +MODULE_DEVICE_TABLE(i2c, mc13892_id); + +static struct i2c_driver pmic_driver = { + .driver = { + .name = "mc13892", + .bus = NULL, + }, + .probe = pmic_probe, + .remove = pmic_remove, + .suspend = pmic_suspend, + .resume = pmic_resume, + .id_table = mc13892_id, +}; + +static int __init pmic_init(void) +{ + return i2c_add_driver(&pmic_driver); +} + +static void __exit pmic_exit(void) +{ + i2c_del_driver(&pmic_driver); +} + +/* + * Module entry points + */ +subsys_initcall_sync(pmic_init); +module_exit(pmic_exit); + +MODULE_DESCRIPTION("Core/Protocol driver for PMIC"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/pmic/core/pmic_core_spi.c b/drivers/mxc/pmic/core/pmic_core_spi.c new file mode 100644 index 000000000000..5461dbe3f0f0 --- /dev/null +++ b/drivers/mxc/pmic/core/pmic_core_spi.c @@ -0,0 +1,303 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file pmic_core_spi.c + * @brief This is the main file for the PMIC Core/Protocol driver. SPI + * should be providing the interface between the PMIC and the MCU. + * + * @ingroup PMIC_CORE + */ + +/* + * Includes + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "pmic.h" + +/* + * Static functions + */ +static void pmic_pdev_register(void); +static void pmic_pdev_unregister(void); + +/* + * Platform device structure for PMIC client drivers + */ +static struct platform_device adc_ldm = { + .name = "pmic_adc", + .id = 1, +}; +static struct platform_device battery_ldm = { + .name = "pmic_battery", + .id = 1, +}; +static struct platform_device power_ldm = { + .name = "pmic_power", + .id = 1, +}; +static struct platform_device rtc_ldm = { + .name = "pmic_rtc", + .id = 1, +}; +static struct platform_device light_ldm = { + .name = "pmic_light", + .id = 1, +}; +static struct platform_device rleds_ldm = { + .name = "pmic_leds", + .id = 'r', +}; +static struct platform_device gleds_ldm = { + .name = "pmic_leds", + .id = 'g', +}; +static struct platform_device bleds_ldm = { + .name = "pmic_leds", + .id = 'b', +}; + +/* + * External functions + */ +extern void pmic_event_list_init(void); +extern void pmic_event_callback(type_event event); +extern void gpio_pmic_active(void); +extern irqreturn_t pmic_irq_handler(int irq, void *dev_id); +extern pmic_version_t mxc_pmic_version; + +/*! + * This function registers platform device structures for + * PMIC client drivers. + */ +static void pmic_pdev_register(void) +{ + platform_device_register(&adc_ldm); + platform_device_register(&battery_ldm); + platform_device_register(&rtc_ldm); + platform_device_register(&power_ldm); + platform_device_register(&light_ldm); + platform_device_register(&rleds_ldm); + platform_device_register(&gleds_ldm); + platform_device_register(&bleds_ldm); +} + +/*! + * This function unregisters platform device structures for + * PMIC client drivers. + */ +static void pmic_pdev_unregister(void) +{ + platform_device_unregister(&adc_ldm); + platform_device_unregister(&battery_ldm); + platform_device_unregister(&rtc_ldm); + platform_device_unregister(&power_ldm); + platform_device_unregister(&light_ldm); +} + +/*! + * This function puts the SPI slave device in low-power mode/state. + * + * @param spi the SPI slave device + * @param message the power state to enter + * + * @return Returns 0 on SUCCESS and error on FAILURE. + */ +static int pmic_suspend(struct spi_device *spi, pm_message_t message) +{ + return PMIC_SUCCESS; +} + +/*! + * This function brings the SPI slave device back from low-power mode/state. + * + * @param spi the SPI slave device + * + * @return Returns 0 on SUCCESS and error on FAILURE. + */ +static int pmic_resume(struct spi_device *spi) +{ + return PMIC_SUCCESS; +} + +static struct spi_driver pmic_driver; + +/*! + * This function is called whenever the SPI slave device is detected. + * + * @param spi the SPI slave device + * + * @return Returns 0 on SUCCESS and error on FAILURE. + */ +static int __devinit pmic_probe(struct spi_device *spi) +{ + int ret = 0; + struct pmic_platform_data *plat_data = spi->dev.platform_data; + + /* Initialize the PMIC parameters */ + ret = pmic_spi_setup(spi); + if (ret != PMIC_SUCCESS) { + return PMIC_ERROR; + } + + /* Initialize the PMIC event handling */ + pmic_event_list_init(); + + /* Initialize GPIO for PMIC Interrupt */ + gpio_pmic_active(); + + /* Get the PMIC Version */ + pmic_get_revision(&mxc_pmic_version); + if (mxc_pmic_version.revision < 0) { + dev_err((struct device *)spi, + "PMIC not detected!!! Access Failed\n"); + return -ENODEV; + } else { + dev_dbg((struct device *)spi, + "Detected pmic core IC version number is %d\n", + mxc_pmic_version.revision); + } + + spi_set_drvdata(spi, pmic_alloc_data(&(spi->dev))); + + /* Initialize the PMIC parameters */ + ret = pmic_init_registers(); + if (ret != PMIC_SUCCESS) { + kfree(spi_get_drvdata(spi)); + spi_set_drvdata(spi, NULL); + return PMIC_ERROR; + } + + ret = pmic_start_event_thread(spi->irq); + if (ret) { + pr_err("mc13892 pmic driver init: \ + fail to start event thread\n"); + kfree(spi_get_drvdata(spi)); + spi_set_drvdata(spi, NULL); + return PMIC_ERROR; + } + + /* Set and install PMIC IRQ handler */ + set_irq_type(spi->irq, IRQF_TRIGGER_HIGH); + ret = request_irq(spi->irq, pmic_irq_handler, 0, "PMIC_IRQ", 0); + if (ret) { + kfree(spi_get_drvdata(spi)); + spi_set_drvdata(spi, NULL); + dev_err((struct device *)spi, "gpio1: irq%d error.", spi->irq); + return ret; + } + + enable_irq_wake(spi->irq); + + if (plat_data && plat_data->init) { + ret = plat_data->init(spi_get_drvdata(spi)); + if (ret != 0) { + kfree(spi_get_drvdata(spi)); + spi_set_drvdata(spi, NULL); + return PMIC_ERROR; + } + } + + power_ldm.dev.platform_data = spi->dev.platform_data; + + pmic_pdev_register(); + + printk(KERN_INFO "Device %s probed\n", dev_name(&spi->dev)); + + return PMIC_SUCCESS; +} + +/*! + * This function is called whenever the SPI slave device is removed. + * + * @param spi the SPI slave device + * + * @return Returns 0 on SUCCESS and error on FAILURE. + */ +static int __devexit pmic_remove(struct spi_device *spi) +{ + pmic_stop_event_thread(); + free_irq(spi->irq, 0); + + pmic_pdev_unregister(); + + printk(KERN_INFO "Device %s removed\n", dev_name(&spi->dev)); + + return PMIC_SUCCESS; +} + +/*! + * This structure contains pointers to the power management callback functions. + */ +static struct spi_driver pmic_driver = { + .driver = { + .name = "pmic_spi", + .bus = &spi_bus_type, + .owner = THIS_MODULE, + }, + .probe = pmic_probe, + .remove = __devexit_p(pmic_remove), + .suspend = pmic_suspend, + .resume = pmic_resume, +}; + +/* + * Initialization and Exit + */ + +/*! + * This function implements the init function of the PMIC device. + * This function is called when the module is loaded. It registers + * the PMIC Protocol driver. + * + * @return This function returns 0. + */ +static int __init pmic_init(void) +{ + return spi_register_driver(&pmic_driver); +} + +/*! + * This function implements the exit function of the PMIC device. + * This function is called when the module is unloaded. It unregisters + * the PMIC Protocol driver. + * + */ +static void __exit pmic_exit(void) +{ + pr_debug("Unregistering the PMIC Protocol Driver\n"); + spi_unregister_driver(&pmic_driver); +} + +/* + * Module entry points + */ +subsys_initcall_sync(pmic_init); +module_exit(pmic_exit); + +MODULE_DESCRIPTION("Core/Protocol driver for PMIC"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/pmic/core/pmic_event.c b/drivers/mxc/pmic/core/pmic_event.c new file mode 100644 index 000000000000..c8ffc63a4973 --- /dev/null +++ b/drivers/mxc/pmic/core/pmic_event.c @@ -0,0 +1,236 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file pmic_event.c + * @brief This file manage all event of PMIC component. + * + * It contains event subscription, unsubscription and callback + * launch methods implemeted. + * + * @ingroup PMIC_CORE + */ + +/* + * Includes + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "pmic.h" + +/*! + * This structure is used to keep a list of subscribed + * callbacks for an event. + */ +typedef struct { + /*! + * Keeps a list of subscribed clients to an event. + */ + struct list_head list; + + /*! + * Callback function with parameter, called when event occurs + */ + pmic_event_callback_t callback; +} pmic_event_callback_list_t; + +/* Create a mutex to be used to prevent concurrent access to the event list */ +static DEFINE_MUTEX(event_mutex); + +/* This is a pointer to the event handler array. It defines the currently + * active set of events and user-defined callback functions. + */ +static struct list_head pmic_events[PMIC_MAX_EVENTS]; + +/*! + * This function initializes event list for PMIC event handling. + * + */ +void pmic_event_list_init(void) +{ + int i; + + for (i = 0; i < PMIC_MAX_EVENTS; i++) { + INIT_LIST_HEAD(&pmic_events[i]); + } + + mutex_init(&event_mutex); + return; +} + +/*! + * This function is used to subscribe on an event. + * + * @param event the event number to be subscribed + * @param callback the callback funtion to be subscribed + * + * @return This function returns 0 on SUCCESS, error on FAILURE. + */ +PMIC_STATUS pmic_event_subscribe(type_event event, + pmic_event_callback_t callback) +{ + pmic_event_callback_list_t *new = NULL; + + pr_debug("Event:%d Subscribe\n", event); + + /* Check whether the event & callback are valid? */ + if (event >= PMIC_MAX_EVENTS) { + pr_debug("Invalid Event:%d\n", event); + return -EINVAL; + } + if (NULL == callback.func) { + pr_debug("Null or Invalid Callback\n"); + return -EINVAL; + } + + /* Create a new linked list entry */ + new = kmalloc(sizeof(pmic_event_callback_list_t), GFP_KERNEL); + if (NULL == new) { + return -ENOMEM; + } + /* Initialize the list node fields */ + new->callback.func = callback.func; + new->callback.param = callback.param; + INIT_LIST_HEAD(&new->list); + + /* Obtain the lock to access the list */ + if (mutex_lock_interruptible(&event_mutex)) { + kfree(new); + return PMIC_SYSTEM_ERROR_EINTR; + } + + /* Unmask the requested event */ + if (list_empty(&pmic_events[event])) { + if (pmic_event_unmask(event) != PMIC_SUCCESS) { + kfree(new); + mutex_unlock(&event_mutex); + return PMIC_ERROR; + } + } + + /* Add this entry to the event list */ + list_add_tail(&new->list, &pmic_events[event]); + + /* Release the lock */ + mutex_unlock(&event_mutex); + + return PMIC_SUCCESS; +} + +/*! + * This function is used to unsubscribe on an event. + * + * @param event the event number to be unsubscribed + * @param callback the callback funtion to be unsubscribed + * + * @return This function returns 0 on SUCCESS, error on FAILURE. + */ +PMIC_STATUS pmic_event_unsubscribe(type_event event, + pmic_event_callback_t callback) +{ + struct list_head *p; + struct list_head *n; + pmic_event_callback_list_t *temp = NULL; + int ret = PMIC_EVENT_NOT_SUBSCRIBED; + + pr_debug("Event:%d Unsubscribe\n", event); + + /* Check whether the event & callback are valid? */ + if (event >= PMIC_MAX_EVENTS) { + pr_debug("Invalid Event:%d\n", event); + return -EINVAL; + } + + if (NULL == callback.func) { + pr_debug("Null or Invalid Callback\n"); + return -EINVAL; + } + + /* Obtain the lock to access the list */ + if (mutex_lock_interruptible(&event_mutex)) { + return PMIC_SYSTEM_ERROR_EINTR; + } + + /* Find the entry in the list */ + list_for_each_safe(p, n, &pmic_events[event]) { + temp = list_entry(p, pmic_event_callback_list_t, list); + if (temp->callback.func == callback.func + && temp->callback.param == callback.param) { + /* Remove the entry from the list */ + list_del(p); + kfree(temp); + ret = PMIC_SUCCESS; + break; + } + } + + /* Unmask the requested event */ + if (list_empty(&pmic_events[event])) { + if (pmic_event_mask(event) != PMIC_SUCCESS) { + ret = PMIC_UNSUBSCRIBE_ERROR; + } + } + + /* Release the lock */ + mutex_unlock(&event_mutex); + + return ret; +} + +/*! + * This function calls all callback of a specific event. + * + * @param event the active event number + * + * @return None + */ +void pmic_event_callback(type_event event) +{ + struct list_head *p; + pmic_event_callback_list_t *temp = NULL; + + /* Obtain the lock to access the list */ + if (mutex_lock_interruptible(&event_mutex)) { + return; + } + + if (list_empty(&pmic_events[event])) { + pr_debug("PMIC Event:%d detected. No callback subscribed\n", + event); + mutex_unlock(&event_mutex); + return; + } + + list_for_each(p, &pmic_events[event]) { + temp = list_entry(p, pmic_event_callback_list_t, list); + temp->callback.func(temp->callback.param); + } + + /* Release the lock */ + mutex_unlock(&event_mutex); + + return; + +} + +EXPORT_SYMBOL(pmic_event_subscribe); +EXPORT_SYMBOL(pmic_event_unsubscribe); diff --git a/drivers/mxc/pmic/core/pmic_external.c b/drivers/mxc/pmic/core/pmic_external.c new file mode 100644 index 000000000000..02318ed959bb --- /dev/null +++ b/drivers/mxc/pmic/core/pmic_external.c @@ -0,0 +1,100 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file pmic_external.c + * @brief This file contains all external functions of PMIC drivers. + * + * @ingroup PMIC_CORE + */ + +/* + * Includes + */ +#include +#include +#include +#include +#include + +#include +#include + +/* + * External Functions + */ +extern int pmic_read(int reg_num, unsigned int *reg_val); +extern int pmic_write(int reg_num, const unsigned int reg_val); + +/*! + * This function is called by PMIC clients to read a register on PMIC. + * + * @param reg number of register + * @param reg_value return value of register + * @param reg_mask Bitmap mask indicating which bits to modify + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_read_reg(int reg, unsigned int *reg_value, + unsigned int reg_mask) +{ + int ret = 0; + unsigned int temp = 0; + + ret = pmic_read(reg, &temp); + if (ret != PMIC_SUCCESS) { + return PMIC_ERROR; + } + *reg_value = (temp & reg_mask); + + pr_debug("Read REG[ %d ] = 0x%x\n", reg, *reg_value); + + return ret; +} + +/*! + * This function is called by PMIC clients to write a register on PMIC. + * + * @param reg number of register + * @param reg_value New value of register + * @param reg_mask Bitmap mask indicating which bits to modify + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_write_reg(int reg, unsigned int reg_value, + unsigned int reg_mask) +{ + int ret = 0; + unsigned int temp = 0; + + ret = pmic_read(reg, &temp); + if (ret != PMIC_SUCCESS) { + return PMIC_ERROR; + } + temp = (temp & (~reg_mask)) | reg_value; +#ifdef CONFIG_MXC_PMIC_MC13783 + if (reg == REG_POWER_MISCELLANEOUS) + temp &= 0xFFFE7FFF; +#endif + ret = pmic_write(reg, temp); + if (ret != PMIC_SUCCESS) { + return PMIC_ERROR; + } + + pr_debug("Write REG[ %d ] = 0x%x\n", reg, reg_value); + + return ret; +} + +EXPORT_SYMBOL(pmic_read_reg); +EXPORT_SYMBOL(pmic_write_reg); diff --git a/drivers/mxc/pmic/mc13783/Kconfig b/drivers/mxc/pmic/mc13783/Kconfig new file mode 100644 index 000000000000..02496c624e2e --- /dev/null +++ b/drivers/mxc/pmic/mc13783/Kconfig @@ -0,0 +1,55 @@ +# +# PMIC Modules configuration +# + +config MXC_MC13783_ADC + tristate "MC13783 ADC support" + depends on MXC_PMIC_MC13783 + ---help--- + This is the MC13783 ADC module driver. This module provides kernel API + for the ADC system of MC13783. + It controls also the touch screen interface. + If you want MC13783 ADC support, you should say Y here + +config MXC_MC13783_AUDIO + tristate "MC13783 Audio support" + depends on MXC_PMIC_MC13783 + ---help--- + This is the MC13783 audio module driver. This module provides kernel API + for audio part of MC13783. + If you want MC13783 audio support, you should say Y here +config MXC_MC13783_RTC + tristate "MC13783 Real Time Clock (RTC) support" + depends on MXC_PMIC_MC13783 + ---help--- + This is the MC13783 RTC module driver. This module provides kernel API + for RTC part of MC13783. + If you want MC13783 RTC support, you should say Y here +config MXC_MC13783_LIGHT + tristate "MC13783 Light and Backlight support" + depends on MXC_PMIC_MC13783 + ---help--- + This is the MC13783 Light module driver. This module provides kernel API + for led and backlight control part of MC13783. + If you want MC13783 Light support, you should say Y here +config MXC_MC13783_BATTERY + tristate "MC13783 Battery API support" + depends on MXC_PMIC_MC13783 + ---help--- + This is the MC13783 battery module driver. This module provides kernel API + for battery control part of MC13783. + If you want MC13783 battery support, you should say Y here +config MXC_MC13783_CONNECTIVITY + tristate "MC13783 Connectivity API support" + depends on MXC_PMIC_MC13783 + ---help--- + This is the MC13783 connectivity module driver. This module provides kernel API + for USB/RS232 connectivity control part of MC13783. + If you want MC13783 connectivity support, you should say Y here +config MXC_MC13783_POWER + tristate "MC13783 Power API support" + depends on MXC_PMIC_MC13783 + ---help--- + This is the MC13783 power and supplies module driver. This module provides kernel API + for power and regulator control part of MC13783. + If you want MC13783 power support, you should say Y here diff --git a/drivers/mxc/pmic/mc13783/Makefile b/drivers/mxc/pmic/mc13783/Makefile new file mode 100644 index 000000000000..7bbba23f5ab9 --- /dev/null +++ b/drivers/mxc/pmic/mc13783/Makefile @@ -0,0 +1,18 @@ +# +# Makefile for the mc13783 pmic drivers. +# + +obj-$(CONFIG_MXC_MC13783_ADC) += pmic_adc-mod.o +obj-$(CONFIG_MXC_MC13783_AUDIO) += pmic_audio-mod.o +obj-$(CONFIG_MXC_MC13783_RTC) += pmic_rtc-mod.o +obj-$(CONFIG_MXC_MC13783_LIGHT) += pmic_light-mod.o +obj-$(CONFIG_MXC_MC13783_BATTERY) += pmic_battery-mod.o +obj-$(CONFIG_MXC_MC13783_CONNECTIVITY) += pmic_convity-mod.o +obj-$(CONFIG_MXC_MC13783_POWER) += pmic_power-mod.o +pmic_adc-mod-objs := pmic_adc.o +pmic_audio-mod-objs := pmic_audio.o +pmic_rtc-mod-objs := pmic_rtc.o +pmic_light-mod-objs := pmic_light.o +pmic_battery-mod-objs := pmic_battery.o +pmic_convity-mod-objs := pmic_convity.o +pmic_power-mod-objs := pmic_power.o diff --git a/drivers/mxc/pmic/mc13783/pmic_adc.c b/drivers/mxc/pmic/mc13783/pmic_adc.c new file mode 100644 index 000000000000..482d0ee08e39 --- /dev/null +++ b/drivers/mxc/pmic/mc13783/pmic_adc.c @@ -0,0 +1,1541 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mc13783/pmic_adc.c + * @brief This is the main file of PMIC(mc13783) ADC driver. + * + * @ingroup PMIC_ADC + */ + +/* + * Includes + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../core/pmic.h" +#include "pmic_adc_defs.h" + +#define NB_ADC_REG 5 + +static int pmic_adc_major; + +/* internal function */ +static void callback_tsi(void *); +static void callback_adcdone(void *); +static void callback_adcbisdone(void *); +static void callback_adc_comp_high(void *); + +/*! + * Number of users waiting in suspendq + */ +static int swait; + +/*! + * To indicate whether any of the adc devices are suspending + */ +static int suspend_flag; + +/*! + * The suspendq is used by blocking application calls + */ +static wait_queue_head_t suspendq; + +static struct class *pmic_adc_class; + +/* + * ADC mc13783 API + */ +/* EXPORTED FUNCTIONS */ +EXPORT_SYMBOL(pmic_adc_init); +EXPORT_SYMBOL(pmic_adc_deinit); +EXPORT_SYMBOL(pmic_adc_convert); +EXPORT_SYMBOL(pmic_adc_convert_8x); +EXPORT_SYMBOL(pmic_adc_convert_multichnnel); +EXPORT_SYMBOL(pmic_adc_set_touch_mode); +EXPORT_SYMBOL(pmic_adc_get_touch_mode); +EXPORT_SYMBOL(pmic_adc_get_touch_sample); +EXPORT_SYMBOL(pmic_adc_get_battery_current); +EXPORT_SYMBOL(pmic_adc_active_comparator); +EXPORT_SYMBOL(pmic_adc_deactive_comparator); + +static DECLARE_COMPLETION(adcdone_it); +static DECLARE_COMPLETION(adcbisdone_it); +static DECLARE_COMPLETION(adc_tsi); +static pmic_event_callback_t tsi_event; +static pmic_event_callback_t event_adc; +static pmic_event_callback_t event_adc_bis; +static pmic_event_callback_t adc_comp_h; +static bool data_ready_adc_1; +static bool data_ready_adc_2; +static bool adc_ts; +static bool wait_ts; +static bool monitor_en; +static bool monitor_adc; +static t_check_mode wcomp_mode; +static DECLARE_MUTEX(convert_mutex); + +void (*monitoring_cb) (void); /*call back to be called when event is detected. */ + +static DECLARE_WAIT_QUEUE_HEAD(queue_adc_busy); +static t_adc_state adc_dev[2]; + +static unsigned channel_num[] = { + 0, + 1, + 3, + 4, + 2, + 12, + 13, + 14, + 15, + -1, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 7, + 6, + -1, + -1, + -1, + -1, + 5, + 7 +}; + +static bool pmic_adc_ready; + +int is_pmic_adc_ready() +{ + return pmic_adc_ready; +} +EXPORT_SYMBOL(is_pmic_adc_ready); + + +/*! + * This is the suspend of power management for the mc13783 ADC API. + * It supports SAVE and POWER_DOWN state. + * + * @param pdev the device + * @param state the state + * + * @return This function returns 0 if successful. + */ +static int pmic_adc_suspend(struct platform_device *pdev, pm_message_t state) +{ + unsigned int reg_value = 0; + suspend_flag = 1; + CHECK_ERROR(pmic_write_reg(REG_ADC_0, DEF_ADC_0, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(REG_ADC_1, reg_value, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(REG_ADC_2, reg_value, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(REG_ADC_3, DEF_ADC_3, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(REG_ADC_4, reg_value, PMIC_ALL_BITS)); + + return 0; +}; + +/*! + * This is the resume of power management for the mc13783 adc API. + * It supports RESTORE state. + * + * @param pdev the device + * + * @return This function returns 0 if successful. + */ +static int pmic_adc_resume(struct platform_device *pdev) +{ + /* nothing for mc13783 adc */ + unsigned int adc_0_reg, adc_1_reg; + suspend_flag = 0; + + /* let interrupt of TSI again */ + adc_0_reg = ADC_WAIT_TSI_0; + CHECK_ERROR(pmic_write_reg(REG_ADC_0, adc_0_reg, PMIC_ALL_BITS)); + adc_1_reg = ADC_WAIT_TSI_1 | (ADC_BIS * adc_ts); + CHECK_ERROR(pmic_write_reg(REG_ADC_1, adc_1_reg, PMIC_ALL_BITS)); + + while (swait > 0) { + swait--; + wake_up_interruptible(&suspendq); + } + + return 0; +}; + +/* + * Call back functions + */ + +/*! + * This is the callback function called on TSI mc13783 event, used in synchronous call. + */ +static void callback_tsi(void *unused) +{ + pr_debug("*** TSI IT mc13783 PMIC_ADC_GET_TOUCH_SAMPLE ***\n"); + if (wait_ts) { + complete(&adc_tsi); + pmic_event_mask(EVENT_TSI); + } +} + +/*! + * This is the callback function called on ADCDone mc13783 event. + */ +static void callback_adcdone(void *unused) +{ + if (data_ready_adc_1) { + complete(&adcdone_it); + } +} + +/*! + * This is the callback function called on ADCDone mc13783 event. + */ +static void callback_adcbisdone(void *unused) +{ + pr_debug("* adcdone bis it callback *\n"); + if (data_ready_adc_2) { + complete(&adcbisdone_it); + } +} + +/*! + * This is the callback function called on mc13783 event. + */ +static void callback_adc_comp_high(void *unused) +{ + pr_debug("* adc comp it high *\n"); + if (wcomp_mode == CHECK_HIGH || wcomp_mode == CHECK_LOW_OR_HIGH) { + /* launch callback */ + if (monitoring_cb != NULL) { + monitoring_cb(); + } + } +} + +/*! + * This function performs filtering and rejection of excessive noise prone + * samples. + * + * @param ts_curr Touch screen value + * + * @return This function returns 0 on success, -1 otherwise. + */ +static int pmic_adc_filter(t_touch_screen *ts_curr) +{ + unsigned int ydiff1, ydiff2, ydiff3, xdiff1, xdiff2, xdiff3; + unsigned int sample_sumx, sample_sumy; + static unsigned int prev_x[FILTLEN], prev_y[FILTLEN]; + int index = 0; + unsigned int y_curr, x_curr; + static int filt_count; + /* Added a variable filt_type to decide filtering at run-time */ + unsigned int filt_type = 0; + + if (ts_curr->contact_resistance == 0) { + ts_curr->x_position = 0; + ts_curr->y_position = 0; + filt_count = 0; + return 0; + } + + ydiff1 = abs(ts_curr->y_position1 - ts_curr->y_position2); + ydiff2 = abs(ts_curr->y_position2 - ts_curr->y_position3); + ydiff3 = abs(ts_curr->y_position1 - ts_curr->y_position3); + if ((ydiff1 > DELTA_Y_MAX) || + (ydiff2 > DELTA_Y_MAX) || (ydiff3 > DELTA_Y_MAX)) { + pr_debug("pmic_adc_filter: Ret pos 1\n"); + return -1; + } + + xdiff1 = abs(ts_curr->x_position1 - ts_curr->x_position2); + xdiff2 = abs(ts_curr->x_position2 - ts_curr->x_position3); + xdiff3 = abs(ts_curr->x_position1 - ts_curr->x_position3); + + if ((xdiff1 > DELTA_X_MAX) || + (xdiff2 > DELTA_X_MAX) || (xdiff3 > DELTA_X_MAX)) { + pr_debug("mc13783_adc_filter: Ret pos 2\n"); + return -1; + } + /* Compute two closer values among the three available Y readouts */ + + if (ydiff1 < ydiff2) { + if (ydiff1 < ydiff3) { + /* Sample 0 & 1 closest together */ + sample_sumy = ts_curr->y_position1 + + ts_curr->y_position2; + } else { + /* Sample 0 & 2 closest together */ + sample_sumy = ts_curr->y_position1 + + ts_curr->y_position3; + } + } else { + if (ydiff2 < ydiff3) { + /* Sample 1 & 2 closest together */ + sample_sumy = ts_curr->y_position2 + + ts_curr->y_position3; + } else { + /* Sample 0 & 2 closest together */ + sample_sumy = ts_curr->y_position1 + + ts_curr->y_position3; + } + } + + /* + * Compute two closer values among the three available X + * readouts + */ + if (xdiff1 < xdiff2) { + if (xdiff1 < xdiff3) { + /* Sample 0 & 1 closest together */ + sample_sumx = ts_curr->x_position1 + + ts_curr->x_position2; + } else { + /* Sample 0 & 2 closest together */ + sample_sumx = ts_curr->x_position1 + + ts_curr->x_position3; + } + } else { + if (xdiff2 < xdiff3) { + /* Sample 1 & 2 closest together */ + sample_sumx = ts_curr->x_position2 + + ts_curr->x_position3; + } else { + /* Sample 0 & 2 closest together */ + sample_sumx = ts_curr->x_position1 + + ts_curr->x_position3; + } + } + /* + * Wait FILTER_MIN_DELAY number of samples to restart + * filtering + */ + if (filt_count < FILTER_MIN_DELAY) { + /* + * Current output is the average of the two closer + * values and no filtering is used + */ + y_curr = (sample_sumy / 2); + x_curr = (sample_sumx / 2); + ts_curr->y_position = y_curr; + ts_curr->x_position = x_curr; + filt_count++; + } else { + if (abs(sample_sumx - (prev_x[0] + prev_x[1])) > + (DELTA_X_MAX * 16)) { + pr_debug("pmic_adc_filter: : Ret pos 3\n"); + return -1; + } + if (abs(sample_sumy - (prev_y[0] + prev_y[1])) > + (DELTA_Y_MAX * 16)) { + return -1; + } + sample_sumy /= 2; + sample_sumx /= 2; + /* Use hard filtering if the sample difference < 10 */ + if ((abs(sample_sumy - prev_y[0]) > 10) || + (abs(sample_sumx - prev_x[0]) > 10)) { + filt_type = 1; + } + + /* + * Current outputs are the average of three previous + * values and the present readout + */ + y_curr = sample_sumy; + for (index = 0; index < FILTLEN; index++) { + if (filt_type == 0) { + y_curr = y_curr + (prev_y[index]); + } else { + y_curr = y_curr + (prev_y[index] / 3); + } + } + if (filt_type == 0) { + y_curr = y_curr >> 2; + } else { + y_curr = y_curr >> 1; + } + ts_curr->y_position = y_curr; + + x_curr = sample_sumx; + for (index = 0; index < FILTLEN; index++) { + if (filt_type == 0) { + x_curr = x_curr + (prev_x[index]); + } else { + x_curr = x_curr + (prev_x[index] / 3); + } + } + if (filt_type == 0) { + x_curr = x_curr >> 2; + } else { + x_curr = x_curr >> 1; + } + ts_curr->x_position = x_curr; + + } + + /* Update previous X and Y values */ + for (index = (FILTLEN - 1); index > 0; index--) { + prev_x[index] = prev_x[index - 1]; + prev_y[index] = prev_y[index - 1]; + } + + /* + * Current output will be the most recent past for the + * next sample + */ + prev_y[0] = y_curr; + prev_x[0] = x_curr; + + return 0; +} + +/*! + * This function implements the open method on a MC13783 ADC device. + * + * @param inode pointer on the node + * @param file pointer on the file + * @return This function returns 0. + */ +static int pmic_adc_open(struct inode *inode, struct file *file) +{ + while (suspend_flag == 1) { + swait++; + /* Block if the device is suspended */ + if (wait_event_interruptible(suspendq, (suspend_flag == 0))) { + return -ERESTARTSYS; + } + } + pr_debug("mc13783_adc : mc13783_adc_open()\n"); + return 0; +} + +/*! + * This function implements the release method on a MC13783 ADC device. + * + * @param inode pointer on the node + * @param file pointer on the file + * @return This function returns 0. + */ +static int pmic_adc_free(struct inode *inode, struct file *file) +{ + pr_debug("mc13783_adc : mc13783_adc_free()\n"); + return 0; +} + +/*! + * This function initializes all ADC registers with default values. This + * function also registers the interrupt events. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +int pmic_adc_init(void) +{ + unsigned int reg_value = 0, i = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + for (i = 0; i < ADC_NB_AVAILABLE; i++) { + adc_dev[i] = ADC_FREE; + } + CHECK_ERROR(pmic_write_reg(REG_ADC_0, DEF_ADC_0, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(REG_ADC_1, reg_value, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(REG_ADC_2, reg_value, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(REG_ADC_3, DEF_ADC_3, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(REG_ADC_4, reg_value, PMIC_ALL_BITS)); + reg_value = 0x001000; + CHECK_ERROR(pmic_write_reg(REG_ARBITRATION_PERIPHERAL_AUDIO, reg_value, + 0xFFFFFF)); + + data_ready_adc_1 = false; + data_ready_adc_2 = false; + adc_ts = false; + wait_ts = false; + monitor_en = false; + monitor_adc = false; + wcomp_mode = CHECK_LOW; + monitoring_cb = NULL; + /* sub to ADCDone IT */ + event_adc.param = NULL; + event_adc.func = callback_adcdone; + CHECK_ERROR(pmic_event_subscribe(EVENT_ADCDONEI, event_adc)); + + /* sub to ADCDoneBis IT */ + event_adc_bis.param = NULL; + event_adc_bis.func = callback_adcbisdone; + CHECK_ERROR(pmic_event_subscribe(EVENT_ADCBISDONEI, event_adc_bis)); + + /* sub to Touch Screen IT */ + tsi_event.param = NULL; + tsi_event.func = callback_tsi; + CHECK_ERROR(pmic_event_subscribe(EVENT_TSI, tsi_event)); + + /* ADC reading above high limit */ + adc_comp_h.param = NULL; + adc_comp_h.func = callback_adc_comp_high; + CHECK_ERROR(pmic_event_subscribe(EVENT_WHIGHI, adc_comp_h)); + + return PMIC_SUCCESS; +} + +/*! + * This function disables the ADC, de-registers the interrupt events. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_adc_deinit(void) +{ + CHECK_ERROR(pmic_event_unsubscribe(EVENT_ADCDONEI, event_adc)); + CHECK_ERROR(pmic_event_unsubscribe(EVENT_ADCBISDONEI, event_adc_bis)); + CHECK_ERROR(pmic_event_unsubscribe(EVENT_TSI, tsi_event)); + CHECK_ERROR(pmic_event_unsubscribe(EVENT_WHIGHI, adc_comp_h)); + + return PMIC_SUCCESS; +} + +/*! + * This function initializes adc_param structure. + * + * @param adc_param Structure to be initialized. + * + * @return This function returns 0 if successful. + */ +int mc13783_adc_init_param(t_adc_param *adc_param) +{ + int i = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + adc_param->delay = 0; + adc_param->conv_delay = false; + adc_param->single_channel = false; + adc_param->group = false; + adc_param->channel_0 = BATTERY_VOLTAGE; + adc_param->channel_1 = BATTERY_VOLTAGE; + adc_param->read_mode = 0; + adc_param->wait_tsi = 0; + adc_param->chrgraw_devide_5 = true; + adc_param->read_ts = false; + adc_param->ts_value.x_position = 0; + adc_param->ts_value.y_position = 0; + adc_param->ts_value.contact_resistance = 0; + for (i = 0; i <= MAX_CHANNEL; i++) { + adc_param->value[i] = 0; + } + return 0; +} + +/*! + * This function starts the convert. + * + * @param adc_param contains all adc configuration and return value. + * + * @return This function returns 0 if successful. + */ +PMIC_STATUS mc13783_adc_convert(t_adc_param *adc_param) +{ + bool use_bis = false; + unsigned int adc_0_reg = 0, adc_1_reg = 0, reg_1 = 0, result_reg = + 0, i = 0; + unsigned int result = 0, temp = 0; + pmic_version_t mc13783_ver; + pr_debug("mc13783 ADC - mc13783_adc_convert ....\n"); + if (suspend_flag == 1) { + return -EBUSY; + } + + if (adc_param->wait_tsi) { + /* we need to set ADCEN 1 for TSI interrupt on mc13783 1.x */ + /* configure adc to wait tsi interrupt */ + INIT_COMPLETION(adc_tsi); + pr_debug("mc13783 ADC - pmic_write_reg ....\n"); + /*for ts don't use bis */ + adc_0_reg = 0x001c00 | (ADC_BIS * 0); + pmic_event_unmask(EVENT_TSI); + CHECK_ERROR(pmic_write_reg + (REG_ADC_0, adc_0_reg, PMIC_ALL_BITS)); + /*for ts don't use bis */ + adc_1_reg = 0x200001 | (ADC_BIS * 0); + CHECK_ERROR(pmic_write_reg + (REG_ADC_1, adc_1_reg, PMIC_ALL_BITS)); + pr_debug("wait tsi ....\n"); + wait_ts = true; + wait_for_completion_interruptible(&adc_tsi); + wait_ts = false; + } + if (adc_param->read_ts == false) + down(&convert_mutex); + use_bis = mc13783_adc_request(adc_param->read_ts); + if (use_bis < 0) { + pr_debug("process has received a signal and got interrupted\n"); + return -EINTR; + } + + /* CONFIGURE ADC REG 0 */ + adc_0_reg = 0; + adc_1_reg = 0; + if (adc_param->read_ts == false) { + adc_0_reg = adc_param->read_mode & 0x00003F; + /* add auto inc */ + adc_0_reg |= ADC_INC; + if (use_bis) { + /* add adc bis */ + adc_0_reg |= ADC_BIS; + } + mc13783_ver = pmic_get_version(); + if (mc13783_ver.revision >= 20) { + if (adc_param->chrgraw_devide_5) { + adc_0_reg |= ADC_CHRGRAW_D5; + } + } + if (adc_param->single_channel) { + adc_1_reg |= ADC_SGL_CH; + } + + if (adc_param->conv_delay) { + adc_1_reg |= ADC_ATO; + } + + if (adc_param->group) { + adc_1_reg |= ADC_ADSEL; + } + + if (adc_param->single_channel) { + adc_1_reg |= ADC_SGL_CH; + } + + adc_1_reg |= (adc_param->channel_0 << ADC_CH_0_POS) & + ADC_CH_0_MASK; + adc_1_reg |= (adc_param->channel_1 << ADC_CH_1_POS) & + ADC_CH_1_MASK; + } else { + adc_0_reg = 0x003c00 | (ADC_BIS * use_bis) | ADC_INC; + } + pr_debug("Write Reg %i = %x\n", REG_ADC_0, adc_0_reg); + /*Change has been made here */ + CHECK_ERROR(pmic_write_reg(REG_ADC_0, adc_0_reg, + ADC_INC | ADC_BIS | ADC_CHRGRAW_D5 | + 0xfff00ff)); + /* CONFIGURE ADC REG 1 */ + if (adc_param->read_ts == false) { + adc_1_reg |= ADC_NO_ADTRIG; + adc_1_reg |= ADC_EN; + adc_1_reg |= (adc_param->delay << ADC_DELAY_POS) & + ADC_DELAY_MASK; + if (use_bis) { + adc_1_reg |= ADC_BIS; + } + } else { + /* configure and start convert to read x and y position */ + /* configure to read 2 value in channel selection 1 & 2 */ + adc_1_reg = 0x100409 | (ADC_BIS * use_bis) | ADC_NO_ADTRIG; + } + reg_1 = adc_1_reg; + if (use_bis == 0) { + data_ready_adc_1 = false; + adc_1_reg |= ASC_ADC; + data_ready_adc_1 = true; + pr_debug("Write Reg %i = %x\n", REG_ADC_1, adc_1_reg); + INIT_COMPLETION(adcdone_it); + CHECK_ERROR(pmic_write_reg(REG_ADC_1, adc_1_reg, + ADC_SGL_CH | ADC_ATO | ADC_ADSEL + | ADC_CH_0_MASK | ADC_CH_1_MASK | + ADC_NO_ADTRIG | ADC_EN | + ADC_DELAY_MASK | ASC_ADC | ADC_BIS)); + pr_debug("wait adc done \n"); + wait_for_completion_interruptible(&adcdone_it); + data_ready_adc_1 = false; + } else { + data_ready_adc_2 = false; + adc_1_reg |= ASC_ADC; + data_ready_adc_2 = true; + INIT_COMPLETION(adcbisdone_it); + CHECK_ERROR(pmic_write_reg(REG_ADC_1, adc_1_reg, 0xFFFFFF)); + temp = 0x800000; + CHECK_ERROR(pmic_write_reg(REG_ADC_3, temp, 0xFFFFFF)); + temp = 0x001000; + pmic_write_reg(REG_ARBITRATION_PERIPHERAL_AUDIO, temp, + 0xFFFFFF); + pr_debug("wait adc done bis\n"); + wait_for_completion_interruptible(&adcbisdone_it); + data_ready_adc_2 = false; + } + /* read result and store in adc_param */ + result = 0; + if (use_bis == 0) { + result_reg = REG_ADC_2; + } else { + result_reg = REG_ADC_4; + } + CHECK_ERROR(pmic_write_reg(REG_ADC_1, 4 << ADC_CH_1_POS, + ADC_CH_0_MASK | ADC_CH_1_MASK)); + + for (i = 0; i <= 3; i++) { + CHECK_ERROR(pmic_read_reg(result_reg, &result, PMIC_ALL_BITS)); + pr_debug("result %i = %x\n", result_reg, result); + adc_param->value[i] = ((result & ADD1_RESULT_MASK) >> 2); + adc_param->value[i + 4] = ((result & ADD2_RESULT_MASK) >> 14); + } + if (adc_param->read_ts) { + adc_param->ts_value.x_position = adc_param->value[2]; + adc_param->ts_value.x_position1 = adc_param->value[0]; + adc_param->ts_value.x_position2 = adc_param->value[1]; + adc_param->ts_value.x_position3 = adc_param->value[2]; + adc_param->ts_value.y_position1 = adc_param->value[3]; + adc_param->ts_value.y_position2 = adc_param->value[4]; + adc_param->ts_value.y_position3 = adc_param->value[5]; + adc_param->ts_value.y_position = adc_param->value[5]; + adc_param->ts_value.contact_resistance = adc_param->value[6]; + + } + + /*if (adc_param->read_ts) { + adc_param->ts_value.x_position = adc_param->value[2]; + adc_param->ts_value.y_position = adc_param->value[5]; + adc_param->ts_value.contact_resistance = adc_param->value[6]; + } */ + mc13783_adc_release(use_bis); + if (adc_param->read_ts == false) + up(&convert_mutex); + + return PMIC_SUCCESS; +} + +/*! + * This function select the required read_mode for a specific channel. + * + * @param channel The channel to be sampled + * + * @return This function returns the requires read_mode + */ +t_reading_mode mc13783_set_read_mode(t_channel channel) +{ + t_reading_mode read_mode = 0; + + switch (channel) { + case LICELL: + read_mode = M_LITHIUM_CELL; + break; + case CHARGE_CURRENT: + read_mode = M_CHARGE_CURRENT; + break; + case BATTERY_CURRENT: + read_mode = M_BATTERY_CURRENT; + break; + case THERMISTOR: + read_mode = M_THERMISTOR; + break; + case DIE_TEMP: + read_mode = M_DIE_TEMPERATURE; + break; + case USB_ID: + read_mode = M_UID; + break; + default: + read_mode = 0; + } + + return read_mode; +} + +/*! + * This function triggers a conversion and returns one sampling result of one + * channel. + * + * @param channel The channel to be sampled + * @param result The pointer to the conversion result. The memory + * should be allocated by the caller of this function. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_adc_convert(t_channel channel, unsigned short *result) +{ + t_adc_param adc_param; + PMIC_STATUS ret; + + if (suspend_flag == 1) { + return -EBUSY; + } + + channel = channel_num[channel]; + if (channel == -1) { + pr_debug("Wrong channel ID\n"); + return PMIC_PARAMETER_ERROR; + } + mc13783_adc_init_param(&adc_param); + pr_debug("pmic_adc_convert\n"); + adc_param.read_ts = false; + adc_param.read_mode = mc13783_set_read_mode(channel); + + adc_param.single_channel = true; + /* Find the group */ + if ((channel >= 0) && (channel <= 7)) { + adc_param.channel_0 = channel; + adc_param.group = false; + } else if ((channel >= 8) && (channel <= 15)) { + adc_param.channel_0 = channel & 0x07; + adc_param.group = true; + } else { + return PMIC_PARAMETER_ERROR; + } + ret = mc13783_adc_convert(&adc_param); + *result = adc_param.value[0]; + return ret; +} + +/*! + * This function triggers a conversion and returns eight sampling results of + * one channel. + * + * @param channel The channel to be sampled + * @param result The pointer to array to store eight sampling results. + * The memory should be allocated by the caller of this + * function. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_adc_convert_8x(t_channel channel, unsigned short *result) +{ + t_adc_param adc_param; + int i; + PMIC_STATUS ret; + if (suspend_flag == 1) { + return -EBUSY; + } + + channel = channel_num[channel]; + + if (channel == -1) { + pr_debug("Wrong channel ID\n"); + return PMIC_PARAMETER_ERROR; + } + mc13783_adc_init_param(&adc_param); + pr_debug("pmic_adc_convert_8x\n"); + adc_param.read_ts = false; + adc_param.single_channel = true; + adc_param.read_mode = mc13783_set_read_mode(channel); + if ((channel >= 0) && (channel <= 7)) { + adc_param.channel_0 = channel; + adc_param.channel_1 = channel; + adc_param.group = false; + } else if ((channel >= 8) && (channel <= 15)) { + adc_param.channel_0 = channel & 0x07; + adc_param.channel_1 = channel & 0x07; + adc_param.group = true; + } else { + return PMIC_PARAMETER_ERROR; + } + + ret = mc13783_adc_convert(&adc_param); + for (i = 0; i <= 7; i++) { + result[i] = adc_param.value[i]; + } + return ret; +} + +/*! + * This function triggers a conversion and returns sampling results of each + * specified channel. + * + * @param channels This input parameter is bitmap to specify channels + * to be sampled. + * @param result The pointer to array to store sampling results. + * The memory should be allocated by the caller of this + * function. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_adc_convert_multichnnel(t_channel channels, + unsigned short *result) +{ + t_adc_param adc_param; + int i; + PMIC_STATUS ret; + if (suspend_flag == 1) { + return -EBUSY; + } + mc13783_adc_init_param(&adc_param); + pr_debug("pmic_adc_convert_multichnnel\n"); + + channels = channel_num[channels]; + + if (channels == -1) { + pr_debug("Wrong channel ID\n"); + return PMIC_PARAMETER_ERROR; + } + + adc_param.read_ts = false; + adc_param.single_channel = false; + if ((channels >= 0) && (channels <= 7)) { + adc_param.channel_0 = channels; + adc_param.channel_1 = ((channels + 4) % 4) + 4; + adc_param.group = false; + } else if ((channels >= 8) && (channels <= 15)) { + channels = channels & 0x07; + adc_param.channel_0 = channels; + adc_param.channel_1 = ((channels + 4) % 4) + 4; + adc_param.group = true; + } else { + return PMIC_PARAMETER_ERROR; + } + adc_param.read_mode = 0x00003f; + adc_param.read_ts = false; + ret = mc13783_adc_convert(&adc_param); + + for (i = 0; i <= 7; i++) { + result[i] = adc_param.value[i]; + } + return ret; +} + +/*! + * This function sets touch screen operation mode. + * + * @param touch_mode Touch screen operation mode. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_adc_set_touch_mode(t_touch_mode touch_mode) +{ + if (suspend_flag == 1) { + return -EBUSY; + } + CHECK_ERROR(pmic_write_reg(REG_ADC_0, + BITFVAL(MC13783_ADC0_TS_M, touch_mode), + BITFMASK(MC13783_ADC0_TS_M))); + return PMIC_SUCCESS; +} + +/*! + * This function retrieves the current touch screen operation mode. + * + * @param touch_mode Pointer to the retrieved touch screen operation + * mode. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_adc_get_touch_mode(t_touch_mode *touch_mode) +{ + unsigned int value; + if (suspend_flag == 1) { + return -EBUSY; + } + CHECK_ERROR(pmic_read_reg(REG_ADC_0, &value, PMIC_ALL_BITS)); + + *touch_mode = BITFEXT(value, MC13783_ADC0_TS_M); + + return PMIC_SUCCESS; +} + +/*! + * This function retrieves the current touch screen (X,Y) coordinates. + * + * @param touch_sample Pointer to touch sample. + * @param wait indicates whether this call must block or not. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_adc_get_touch_sample(t_touch_screen *touch_sample, int wait) +{ + if (mc13783_adc_read_ts(touch_sample, wait) != 0) + return PMIC_ERROR; + if (0 == pmic_adc_filter(touch_sample)) + return PMIC_SUCCESS; + else + return PMIC_ERROR; +} + +/*! + * This function read the touch screen value. + * + * @param ts_value return value of touch screen + * @param wait_tsi if true, this function is synchronous (wait in TSI event). + * + * @return This function returns 0. + */ +PMIC_STATUS mc13783_adc_read_ts(t_touch_screen *ts_value, int wait_tsi) +{ + t_adc_param param; + pr_debug("mc13783_adc : mc13783_adc_read_ts\n"); + if (suspend_flag == 1) { + return -EBUSY; + } + if (wait_ts) { + pr_debug("mc13783_adc : error TS busy \n"); + return PMIC_ERROR; + } + mc13783_adc_init_param(¶m); + param.wait_tsi = wait_tsi; + param.read_ts = true; + if (mc13783_adc_convert(¶m) != 0) + return PMIC_ERROR; + /* check if x-y is ok */ + if ((param.ts_value.x_position1 < TS_X_MAX) && + (param.ts_value.x_position1 >= TS_X_MIN) && + (param.ts_value.y_position1 < TS_Y_MAX) && + (param.ts_value.y_position1 >= TS_Y_MIN) && + (param.ts_value.x_position2 < TS_X_MAX) && + (param.ts_value.x_position2 >= TS_X_MIN) && + (param.ts_value.y_position2 < TS_Y_MAX) && + (param.ts_value.y_position2 >= TS_Y_MIN) && + (param.ts_value.x_position3 < TS_X_MAX) && + (param.ts_value.x_position3 >= TS_X_MIN) && + (param.ts_value.y_position3 < TS_Y_MAX) && + (param.ts_value.y_position3 >= TS_Y_MIN)) { + ts_value->x_position = param.ts_value.x_position; + ts_value->x_position1 = param.ts_value.x_position1; + ts_value->x_position2 = param.ts_value.x_position2; + ts_value->x_position3 = param.ts_value.x_position3; + ts_value->y_position = param.ts_value.y_position; + ts_value->y_position1 = param.ts_value.y_position1; + ts_value->y_position2 = param.ts_value.y_position2; + ts_value->y_position3 = param.ts_value.y_position3; + ts_value->contact_resistance = + param.ts_value.contact_resistance + 1; + + } else { + ts_value->x_position = 0; + ts_value->y_position = 0; + ts_value->contact_resistance = 0; + + } + return PMIC_SUCCESS; +} + +/*! + * This function starts a Battery Current mode conversion. + * + * @param mode Conversion mode. + * @param result Battery Current measurement result. + * if \a mode = ADC_8CHAN_1X, the result is \n + * result[0] = (BATTP - BATT_I) \n + * if \a mode = ADC_1CHAN_8X, the result is \n + * result[0] = BATTP \n + * result[1] = BATT_I \n + * result[2] = BATTP \n + * result[3] = BATT_I \n + * result[4] = BATTP \n + * result[5] = BATT_I \n + * result[6] = BATTP \n + * result[7] = BATT_I + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_adc_get_battery_current(t_conversion_mode mode, + unsigned short *result) +{ + PMIC_STATUS ret; + t_channel channel; + if (suspend_flag == 1) { + return -EBUSY; + } + channel = BATTERY_CURRENT; + if (mode == ADC_8CHAN_1X) { + ret = pmic_adc_convert(channel, result); + } else { + ret = pmic_adc_convert_8x(channel, result); + } + return ret; +} + +/*! + * This function request a ADC. + * + * @return This function returns index of ADC to be used (0 or 1) if successful. + * return -1 if error. + */ +int mc13783_adc_request(bool read_ts) +{ + int adc_index = -1; + if (read_ts != 0) { + /*for ts we use bis=0 */ + if (adc_dev[0] == ADC_USED) + return -1; + /*no wait here */ + adc_dev[0] = ADC_USED; + adc_index = 0; + } else { + /*for other adc use bis = 1 */ + if (adc_dev[1] == ADC_USED) { + return -1; + /*no wait here */ + } + adc_dev[1] = ADC_USED; + adc_index = 1; + } + pr_debug("mc13783_adc : request ADC %d\n", adc_index); + return adc_index; +} + +/*! + * This function release an ADC. + * + * @param adc_index index of ADC to be released. + * + * @return This function returns 0 if successful. + */ +int mc13783_adc_release(int adc_index) +{ + while (suspend_flag == 1) { + swait++; + /* Block if the device is suspended */ + if (wait_event_interruptible(suspendq, (suspend_flag == 0))) { + return -ERESTARTSYS; + } + } + + pr_debug("mc13783_adc : release ADC %d\n", adc_index); + if ((adc_dev[adc_index] == ADC_MONITORING) || + (adc_dev[adc_index] == ADC_USED)) { + adc_dev[adc_index] = ADC_FREE; + wake_up(&queue_adc_busy); + return 0; + } + return -1; +} + +/*! + * This function initializes monitoring structure. + * + * @param monitor Structure to be initialized. + * + * @return This function returns 0 if successful. + */ +int mc13783_adc_init_monitor_param(t_monitoring_param *monitor) +{ + pr_debug("mc13783_adc : init monitor\n"); + monitor->delay = 0; + monitor->conv_delay = false; + monitor->channel = BATTERY_VOLTAGE; + monitor->read_mode = 0; + monitor->comp_low = 0; + monitor->comp_high = 0; + monitor->group = 0; + monitor->check_mode = CHECK_LOW_OR_HIGH; + monitor->callback = NULL; + return 0; +} + +/*! + * This function actives the comparator. When comparator is active and ADC + * is enabled, the 8th converted value will be digitally compared against the + * window defined by WLOW and WHIGH registers. + * + * @param low Comparison window low threshold (WLOW). + * @param high Comparison window high threshold (WHIGH). + * @param channel The channel to be sampled + * @param callback Callback function to be called when the converted + * value is beyond the comparison window. The callback + * function will pass a parameter of type + * \b t_comp_expection to indicate the reason of + * comparator exception. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_adc_active_comparator(unsigned char low, + unsigned char high, + t_channel channel, + t_comparator_cb callback) +{ + bool use_bis = false; + unsigned int adc_0_reg = 0, adc_1_reg = 0, adc_3_reg = 0; + t_monitoring_param monitoring; + + if (suspend_flag == 1) { + return -EBUSY; + } + if (monitor_en) { + pr_debug("mc13783_adc : monitoring already configured\n"); + return PMIC_ERROR; + } + monitor_en = true; + mc13783_adc_init_monitor_param(&monitoring); + monitoring.comp_low = low; + monitoring.comp_high = high; + monitoring.channel = channel; + monitoring.callback = (void *)callback; + + use_bis = mc13783_adc_request(false); + if (use_bis < 0) { + pr_debug("mc13783_adc : request error\n"); + return PMIC_ERROR; + } + monitor_adc = use_bis; + + adc_0_reg = 0; + + /* TO DO ADOUT CONFIGURE */ + adc_0_reg = monitoring.read_mode & ADC_MODE_MASK; + if (use_bis) { + /* add adc bis */ + adc_0_reg |= ADC_BIS; + } + adc_0_reg |= ADC_WCOMP; + + /* CONFIGURE ADC REG 1 */ + adc_1_reg = 0; + adc_1_reg |= ADC_EN; + if (monitoring.conv_delay) { + adc_1_reg |= ADC_ATO; + } + if (monitoring.group) { + adc_1_reg |= ADC_ADSEL; + } + adc_1_reg |= (monitoring.channel << ADC_CH_0_POS) & ADC_CH_0_MASK; + adc_1_reg |= (monitoring.delay << ADC_DELAY_POS) & ADC_DELAY_MASK; + if (use_bis) { + adc_1_reg |= ADC_BIS; + } + + adc_3_reg |= (monitoring.comp_high << ADC_WCOMP_H_POS) & + ADC_WCOMP_H_MASK; + adc_3_reg |= (monitoring.comp_low << ADC_WCOMP_L_POS) & + ADC_WCOMP_L_MASK; + if (use_bis) { + adc_3_reg |= ADC_BIS; + } + + wcomp_mode = monitoring.check_mode; + /* call back to be called when event is detected. */ + monitoring_cb = monitoring.callback; + + CHECK_ERROR(pmic_write_reg(REG_ADC_0, adc_0_reg, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(REG_ADC_1, adc_1_reg, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(REG_ADC_3, adc_3_reg, PMIC_ALL_BITS)); + return PMIC_SUCCESS; +} + +/*! + * This function deactivates the comparator. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_adc_deactive_comparator(void) +{ + unsigned int reg_value = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + if (!monitor_en) { + pr_debug("mc13783_adc : adc monitoring free\n"); + return PMIC_ERROR; + } + + if (monitor_en) { + reg_value = ADC_BIS; + } + + /* clear all reg value */ + CHECK_ERROR(pmic_write_reg(REG_ADC_0, reg_value, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(REG_ADC_1, reg_value, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(REG_ADC_3, reg_value, PMIC_ALL_BITS)); + + reg_value = 0; + + if (monitor_adc) { + CHECK_ERROR(pmic_write_reg + (REG_ADC_4, reg_value, PMIC_ALL_BITS)); + } else { + CHECK_ERROR(pmic_write_reg + (REG_ADC_2, reg_value, PMIC_ALL_BITS)); + } + + mc13783_adc_release(monitor_adc); + monitor_en = false; + return PMIC_SUCCESS; +} + +/*! + * This function implements IOCTL controls on a MC13783 ADC device. + * + * @param inode pointer on the node + * @param file pointer on the file + * @param cmd the command + * @param arg the parameter + * @return This function returns 0 if successful. + */ +static int pmic_adc_ioctl(struct inode *inode, struct file *file, + unsigned int cmd, unsigned long arg) +{ + t_adc_convert_param *convert_param; + t_touch_mode touch_mode; + t_touch_screen touch_sample; + unsigned short b_current; + t_adc_comp_param *comp_param; + if ((_IOC_TYPE(cmd) != 'p') && (_IOC_TYPE(cmd) != 'D')) + return -ENOTTY; + + while (suspend_flag == 1) { + swait++; + /* Block if the device is suspended */ + if (wait_event_interruptible(suspendq, (suspend_flag == 0))) { + return -ERESTARTSYS; + } + } + + convert_param = kmalloc(sizeof(t_adc_convert_param), GFP_KERNEL); + comp_param = kmalloc(sizeof(t_adc_comp_param), GFP_KERNEL); + switch (cmd) { + case PMIC_ADC_INIT: + pr_debug("init adc\n"); + CHECK_ERROR(pmic_adc_init()); + break; + + case PMIC_ADC_DEINIT: + pr_debug("deinit adc\n"); + CHECK_ERROR(pmic_adc_deinit()); + break; + + case PMIC_ADC_CONVERT: + if (convert_param == NULL) + return -ENOMEM; + + if (copy_from_user(convert_param, (t_adc_convert_param *) arg, + sizeof(t_adc_convert_param))) { + kfree(convert_param); + return -EFAULT; + } + CHECK_ERROR_KFREE(pmic_adc_convert(convert_param->channel, + convert_param->result), + (kfree(convert_param))); + + if (copy_to_user((t_adc_convert_param *) arg, convert_param, + sizeof(t_adc_convert_param))) { + kfree(convert_param); + return -EFAULT; + } + kfree(convert_param); + break; + + case PMIC_ADC_CONVERT_8X: + if (convert_param == NULL) + return -ENOMEM; + + if (copy_from_user(convert_param, (t_adc_convert_param *) arg, + sizeof(t_adc_convert_param))) { + kfree(convert_param); + return -EFAULT; + } + CHECK_ERROR_KFREE(pmic_adc_convert_8x(convert_param->channel, + convert_param->result), + (kfree(convert_param))); + + if (copy_to_user((t_adc_convert_param *) arg, convert_param, + sizeof(t_adc_convert_param))) { + kfree(convert_param); + return -EFAULT; + } + kfree(convert_param); + break; + + case PMIC_ADC_CONVERT_MULTICHANNEL: + if (convert_param == NULL) + return -ENOMEM; + + if (copy_from_user(convert_param, (t_adc_convert_param *) arg, + sizeof(t_adc_convert_param))) { + kfree(convert_param); + return -EFAULT; + } + + CHECK_ERROR_KFREE(pmic_adc_convert_multichnnel + (convert_param->channel, + convert_param->result), + (kfree(convert_param))); + + if (copy_to_user((t_adc_convert_param *) arg, convert_param, + sizeof(t_adc_convert_param))) { + kfree(convert_param); + return -EFAULT; + } + kfree(convert_param); + break; + + case PMIC_ADC_SET_TOUCH_MODE: + CHECK_ERROR(pmic_adc_set_touch_mode((t_touch_mode) arg)); + break; + + case PMIC_ADC_GET_TOUCH_MODE: + CHECK_ERROR(pmic_adc_get_touch_mode(&touch_mode)); + if (copy_to_user((t_touch_mode *) arg, &touch_mode, + sizeof(t_touch_mode))) { + return -EFAULT; + } + break; + + case PMIC_ADC_GET_TOUCH_SAMPLE: + pr_debug("pmic_adc_ioctl: " "PMIC_ADC_GET_TOUCH_SAMPLE\n"); + CHECK_ERROR(pmic_adc_get_touch_sample(&touch_sample, 1)); + if (copy_to_user((t_touch_screen *) arg, &touch_sample, + sizeof(t_touch_screen))) { + return -EFAULT; + } + break; + + case PMIC_ADC_GET_BATTERY_CURRENT: + CHECK_ERROR(pmic_adc_get_battery_current(ADC_8CHAN_1X, + &b_current)); + if (copy_to_user((unsigned short *)arg, &b_current, + sizeof(unsigned short))) { + + return -EFAULT; + } + break; + + case PMIC_ADC_ACTIVATE_COMPARATOR: + if (comp_param == NULL) + return -ENOMEM; + + if (copy_from_user(comp_param, (t_adc_comp_param *) arg, + sizeof(t_adc_comp_param))) { + kfree(comp_param); + return -EFAULT; + } + CHECK_ERROR_KFREE(pmic_adc_active_comparator(comp_param->wlow, + comp_param->whigh, + comp_param-> + channel, + comp_param-> + callback), + (kfree(comp_param))); + break; + + case PMIC_ADC_DEACTIVE_COMPARATOR: + CHECK_ERROR(pmic_adc_deactive_comparator()); + break; + + default: + pr_debug("pmic_adc_ioctl: unsupported ioctl command 0x%x\n", + cmd); + return -EINVAL; + } + return 0; +} + +static struct file_operations mc13783_adc_fops = { + .owner = THIS_MODULE, + .ioctl = pmic_adc_ioctl, + .open = pmic_adc_open, + .release = pmic_adc_free, +}; + +static int pmic_adc_module_probe(struct platform_device *pdev) +{ + int ret = 0; + struct device *temp_class; + + pmic_adc_major = register_chrdev(0, "pmic_adc", &mc13783_adc_fops); + + if (pmic_adc_major < 0) { + pr_debug(KERN_ERR "Unable to get a major for pmic_adc\n"); + return pmic_adc_major; + } + init_waitqueue_head(&suspendq); + + pmic_adc_class = class_create(THIS_MODULE, "pmic_adc"); + if (IS_ERR(pmic_adc_class)) { + pr_debug(KERN_ERR "Error creating pmic_adc class.\n"); + ret = PTR_ERR(pmic_adc_class); + goto err_out1; + } + + temp_class = device_create(pmic_adc_class, NULL, + MKDEV(pmic_adc_major, 0), NULL, "pmic_adc"); + if (IS_ERR(temp_class)) { + pr_debug(KERN_ERR "Error creating pmic_adc class device.\n"); + ret = PTR_ERR(temp_class); + goto err_out2; + } + + ret = pmic_adc_init(); + if (ret != PMIC_SUCCESS) { + pr_debug(KERN_ERR "Error in pmic_adc_init.\n"); + goto err_out4; + } + + pmic_adc_ready = 1; + pr_debug(KERN_INFO "PMIC ADC successfully probed\n"); + return ret; + + err_out4: + device_destroy(pmic_adc_class, MKDEV(pmic_adc_major, 0)); + err_out2: + class_destroy(pmic_adc_class); + err_out1: + unregister_chrdev(pmic_adc_major, "pmic_adc"); + return ret; +} + +static int pmic_adc_module_remove(struct platform_device *pdev) +{ + pmic_adc_ready = 0; + pmic_adc_deinit(); + device_destroy(pmic_adc_class, MKDEV(pmic_adc_major, 0)); + class_destroy(pmic_adc_class); + unregister_chrdev(pmic_adc_major, "pmic_adc"); + pr_debug(KERN_INFO "PMIC ADC successfully removed\n"); + return 0; +} + +static struct platform_driver pmic_adc_driver_ldm = { + .driver = { + .name = "pmic_adc", + }, + .suspend = pmic_adc_suspend, + .resume = pmic_adc_resume, + .probe = pmic_adc_module_probe, + .remove = pmic_adc_module_remove, +}; + +/* + * Initialization and Exit + */ +static int __init pmic_adc_module_init(void) +{ + pr_debug("PMIC ADC driver loading...\n"); + return platform_driver_register(&pmic_adc_driver_ldm); +} + +static void __exit pmic_adc_module_exit(void) +{ + platform_driver_unregister(&pmic_adc_driver_ldm); + pr_debug("PMIC ADC driver successfully unloaded\n"); +} + +/* + * Module entry points + */ + +module_init(pmic_adc_module_init); +module_exit(pmic_adc_module_exit); + +MODULE_DESCRIPTION("PMIC ADC device driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/pmic/mc13783/pmic_adc_defs.h b/drivers/mxc/pmic/mc13783/pmic_adc_defs.h new file mode 100644 index 000000000000..fbde842bad94 --- /dev/null +++ b/drivers/mxc/pmic/mc13783/pmic_adc_defs.h @@ -0,0 +1,321 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mc13783/pmic_adc_defs.h + * @brief This header contains all defines for PMIC(mc13783) ADC driver. + * + * @ingroup PMIC_ADC + */ + +#ifndef __MC13783_ADC__DEFS_H__ +#define __MC13783_ADC__DEFS_H__ + +#define MC13783_ADC_DEVICE "/dev/mc13783_adc" + +#define DEF_ADC_0 0x008000 +#define DEF_ADC_3 0x000080 + +#define ADC_NB_AVAILABLE 2 + +#define MAX_CHANNEL 7 + +/* + * Maximun allowed variation in the three X/Y co-ordinates acquired from + * touch-screen + */ +#define DELTA_Y_MAX 50 +#define DELTA_X_MAX 50 + +/* Upon clearing the filter, this is the delay in restarting the filter */ +#define FILTER_MIN_DELAY 4 + +/* Length of X and Y Touch screen filters */ +#define FILTLEN 3 + +#define TS_X_MAX 1000 +#define TS_Y_MAX 1000 + +#define TS_X_MIN 80 +#define TS_Y_MIN 80 + +#define MC13783_ADC0_TS_M_LSH 14 +#define MC13783_ADC0_TS_M_WID 3 +/* + * ADC 0 + */ +#define ADC_WAIT_TSI_0 0x001C00 + +/* + * ADC 1 + */ + +#define ADC_EN 0x000001 +#define ADC_SGL_CH 0x000002 +#define ADC_ADSEL 0x000008 +#define ADC_CH_0_POS 5 +#define ADC_CH_0_MASK 0x0000E0 +#define ADC_CH_1_POS 8 +#define ADC_CH_1_MASK 0x000700 +#define ADC_DELAY_POS 11 +#define ADC_DELAY_MASK 0x07F800 +#define ADC_ATO 0x080000 +#define ASC_ADC 0x100000 +#define ADC_WAIT_TSI_1 0x300001 +#define ADC_CHRGRAW_D5 0x008000 + +/* + * ADC 2 - 4 + */ +#define ADD1_RESULT_MASK 0x00000FFC +#define ADD2_RESULT_MASK 0x00FFC000 +#define ADC_TS_MASK 0x00FFCFFC + +/* + * ADC 3 + */ +#define ADC_INC 0x030000 +#define ADC_BIS 0x800000 + +/* + * ADC 3 + */ +#define ADC_NO_ADTRIG 0x200000 +#define ADC_WCOMP 0x040000 +#define ADC_WCOMP_H_POS 0 +#define ADC_WCOMP_L_POS 9 +#define ADC_WCOMP_H_MASK 0x00003F +#define ADC_WCOMP_L_MASK 0x007E00 + +#define ADC_MODE_MASK 0x00003F + +/* + * Interrupt Status 0 + */ +#define ADC_INT_BISDONEI 0x02 + +/*! + * Define state mode of ADC. + */ +typedef enum adc_state { + /*! + * Free. + */ + ADC_FREE, + /*! + * Used. + */ + ADC_USED, + /*! + * Monitoring + */ + ADC_MONITORING, +} t_adc_state; + +/*! + * This enumeration, is used to configure the mode of ADC. + */ +typedef enum reading_mode { + /*! + * Enables lithium cell reading + */ + M_LITHIUM_CELL = 0x000001, + /*! + * Enables charge current reading + */ + M_CHARGE_CURRENT = 0x000002, + /*! + * Enables battery current reading + */ + M_BATTERY_CURRENT = 0x000004, + /*! + * Enables thermistor reading + */ + M_THERMISTOR = 0x000008, + /*! + * Enables die temperature reading + */ + M_DIE_TEMPERATURE = 0x000010, + /*! + * Enables UID reading + */ + M_UID = 0x000020, +} t_reading_mode; + +/*! + * This enumeration, is used to configure the monitoring mode. + */ +typedef enum check_mode { + /*! + * Comparator low level + */ + CHECK_LOW, + /*! + * Comparator high level + */ + CHECK_HIGH, + /*! + * Comparator low or high level + */ + CHECK_LOW_OR_HIGH, +} t_check_mode; + +/*! + * This structure is used to configure and report adc value. + */ +typedef struct { + /*! + * Delay before first conversion + */ + unsigned int delay; + /*! + * sets the ATX bit for delay on all conversion + */ + bool conv_delay; + /*! + * Sets the single channel mode + */ + bool single_channel; + /*! + * Selects the set of inputs + */ + bool group; + /*! + * Channel selection 1 + */ + t_channel channel_0; + /*! + * Channel selection 2 + */ + t_channel channel_1; + /*! + * Used to configure ADC mode with t_reading_mode + */ + t_reading_mode read_mode; + /*! + * Sets the Touch screen mode + */ + bool read_ts; + /*! + * Wait TSI event before touch screen reading + */ + bool wait_tsi; + /*! + * Sets CHRGRAW scaling to divide by 5 + * Only supported on 2.0 and higher + */ + bool chrgraw_devide_5; + /*! + * Return ADC values + */ + unsigned int value[8]; + /*! + * Return touch screen values + */ + t_touch_screen ts_value; +} t_adc_param; + +/*! + * This structure is used to configure the monitoring mode of ADC. + */ +typedef struct { + /*! + * Delay before first conversion + */ + unsigned int delay; + /*! + * sets the ATX bit for delay on all conversion + */ + bool conv_delay; + /*! + * Channel selection 1 + */ + t_channel channel; + /*! + * Selects the set of inputs + */ + bool group; + /*! + * Used to configure ADC mode with t_reading_mode + */ + unsigned int read_mode; + /*! + * Comparator low level in WCOMP mode + */ + unsigned int comp_low; + /*! + * Comparator high level in WCOMP mode + */ + unsigned int comp_high; + /*! + * Sets type of monitoring (low, high or both) + */ + t_check_mode check_mode; + /*! + * Callback to be launched when event is detected + */ + void (*callback) (void); +} t_monitoring_param; + +/*! + * This function performs filtering and rejection of excessive noise prone + * samples. + * + * @param ts_curr Touch screen value + * + * @return This function returns 0 on success, -1 otherwise. + */ +static int pmic_adc_filter(t_touch_screen *ts_curr); + +/*! + * This function request a ADC. + * + * @return This function returns index of ADC to be used (0 or 1) if successful. + * return -1 if error. + */ +int mc13783_adc_request(bool read_ts); + +/*! + * This function is used to update buffer of touch screen value in read mode. + */ +void update_buffer(void); + +/*! + * This function release an ADC. + * + * @param adc_index index of ADC to be released. + * + * @return This function returns 0 if successful. + */ +int mc13783_adc_release(int adc_index); + +/*! + * This function select the required read_mode for a specific channel. + * + * @param channel The channel to be sampled + * + * @return This function returns the requires read_mode + */ +t_reading_mode mc13783_set_read_mode(t_channel channel); + +/*! + * This function read the touch screen value. + * + * @param touch_sample return value of touch screen + * @param wait_tsi if true, this function is synchronous (wait in TSI event). + * + * @return This function returns 0. + */ +PMIC_STATUS mc13783_adc_read_ts(t_touch_screen *touch_sample, int wait_tsi); + +#endif /* __MC13783_ADC__DEFS_H__ */ diff --git a/drivers/mxc/pmic/mc13783/pmic_audio.c b/drivers/mxc/pmic/mc13783/pmic_audio.c new file mode 100644 index 000000000000..acdde44b738f --- /dev/null +++ b/drivers/mxc/pmic/mc13783/pmic_audio.c @@ -0,0 +1,5873 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mc13783/pmic_audio.c + * @brief Implementation of the PMIC(mc13783) Audio driver APIs. + * + * The PMIC Audio driver and this API were developed to support the + * audio playback, recording, and mixing capabilities of the power + * management ICs that are available from Freescale Semiconductor, Inc. + * + * The following operating modes are supported: + * + * @verbatim + Operating Mode mc13783 + ---------------------------- ------- + Stereo DAC Playback Yes + Stereo DAC Input Mixing Yes + Voice CODEC Playback Yes + Voice CODEC Input Mixing Yes + Voice CODEC Mono Recording Yes + Voice CODEC Stereo Recording Yes + Microphone Bias Control Yes + Output Amplifier Control Yes + Output Mixing Control Yes + Input Amplifier Control Yes + Master/Slave Mode Select Yes + Anti Pop Bias Circuit Control Yes + @endverbatim + * + * Note that the Voice CODEC may also be referred to as the Telephone + * CODEC in the PMIC DTS documentation. Also note that, while the power + * management ICs do provide similar audio capabilities, each PMIC may + * support additional configuration settings and features. Therefore, it + * is highly recommended that the appropriate power management IC DTS + * documents be used in conjunction with this API interface. + * + * @ingroup PMIC_AUDIO + */ + +#include +#include /* For tasklet interface. */ +#include /* For kernel module interface. */ +#include +#include /* For spinlock interface. */ +#include /* For PMIC ADC driver interface. */ +#include +#include /* For PMIC Audio driver interface. */ + +/* + * mc13783 PMIC Audio API + */ + +/* EXPORTED FUNCTIONS */ +EXPORT_SYMBOL(MIN_STDAC_SAMPLING_RATE_HZ); +EXPORT_SYMBOL(MAX_STDAC_SAMPLING_RATE_HZ); +EXPORT_SYMBOL(pmic_audio_open); +EXPORT_SYMBOL(pmic_audio_close); +EXPORT_SYMBOL(pmic_audio_set_protocol); +EXPORT_SYMBOL(pmic_audio_get_protocol); +EXPORT_SYMBOL(pmic_audio_enable); +EXPORT_SYMBOL(pmic_audio_disable); +EXPORT_SYMBOL(pmic_audio_reset); +EXPORT_SYMBOL(pmic_audio_reset_all); +EXPORT_SYMBOL(pmic_audio_set_callback); +EXPORT_SYMBOL(pmic_audio_clear_callback); +EXPORT_SYMBOL(pmic_audio_get_callback); +EXPORT_SYMBOL(pmic_audio_antipop_enable); +EXPORT_SYMBOL(pmic_audio_antipop_disable); +EXPORT_SYMBOL(pmic_audio_digital_filter_reset); +EXPORT_SYMBOL(pmic_audio_vcodec_set_clock); +EXPORT_SYMBOL(pmic_audio_vcodec_get_clock); +EXPORT_SYMBOL(pmic_audio_vcodec_set_rxtx_timeslot); +EXPORT_SYMBOL(pmic_audio_vcodec_get_rxtx_timeslot); +EXPORT_SYMBOL(pmic_audio_vcodec_set_secondary_txslot); +EXPORT_SYMBOL(pmic_audio_vcodec_get_secondary_txslot); +EXPORT_SYMBOL(pmic_audio_vcodec_set_config); +EXPORT_SYMBOL(pmic_audio_vcodec_clear_config); +EXPORT_SYMBOL(pmic_audio_vcodec_get_config); +EXPORT_SYMBOL(pmic_audio_vcodec_enable_bypass); +EXPORT_SYMBOL(pmic_audio_vcodec_disable_bypass); +EXPORT_SYMBOL(pmic_audio_stdac_set_clock); +EXPORT_SYMBOL(pmic_audio_stdac_get_clock); +EXPORT_SYMBOL(pmic_audio_stdac_set_rxtx_timeslot); +EXPORT_SYMBOL(pmic_audio_stdac_get_rxtx_timeslot); +EXPORT_SYMBOL(pmic_audio_stdac_set_config); +EXPORT_SYMBOL(pmic_audio_stdac_clear_config); +EXPORT_SYMBOL(pmic_audio_stdac_get_config); +EXPORT_SYMBOL(pmic_audio_input_set_config); +EXPORT_SYMBOL(pmic_audio_input_clear_config); +EXPORT_SYMBOL(pmic_audio_input_get_config); +EXPORT_SYMBOL(pmic_audio_vcodec_set_mic); +EXPORT_SYMBOL(pmic_audio_vcodec_get_mic); +EXPORT_SYMBOL(pmic_audio_vcodec_set_mic_on_off); +EXPORT_SYMBOL(pmic_audio_vcodec_get_mic_on_off); +EXPORT_SYMBOL(pmic_audio_vcodec_set_record_gain); +EXPORT_SYMBOL(pmic_audio_vcodec_get_record_gain); +EXPORT_SYMBOL(pmic_audio_vcodec_enable_micbias); +EXPORT_SYMBOL(pmic_audio_vcodec_disable_micbias); +EXPORT_SYMBOL(pmic_audio_vcodec_enable_mixer); +EXPORT_SYMBOL(pmic_audio_vcodec_disable_mixer); +EXPORT_SYMBOL(pmic_audio_stdac_enable_mixer); +EXPORT_SYMBOL(pmic_audio_stdac_disable_mixer); +EXPORT_SYMBOL(pmic_audio_output_set_port); +EXPORT_SYMBOL(pmic_audio_output_get_port); +EXPORT_SYMBOL(pmic_audio_output_clear_port); +EXPORT_SYMBOL(pmic_audio_output_set_stereo_in_gain); +EXPORT_SYMBOL(pmic_audio_output_get_stereo_in_gain); +EXPORT_SYMBOL(pmic_audio_output_set_pgaGain); +EXPORT_SYMBOL(pmic_audio_output_get_pgaGain); +EXPORT_SYMBOL(pmic_audio_output_enable_mixer); +EXPORT_SYMBOL(pmic_audio_output_disable_mixer); +EXPORT_SYMBOL(pmic_audio_output_set_balance); +EXPORT_SYMBOL(pmic_audio_output_get_balance); +EXPORT_SYMBOL(pmic_audio_output_enable_mono_adder); +EXPORT_SYMBOL(pmic_audio_output_disable_mono_adder); +EXPORT_SYMBOL(pmic_audio_output_set_mono_adder_gain); +EXPORT_SYMBOL(pmic_audio_output_get_mono_adder_gain); +EXPORT_SYMBOL(pmic_audio_output_set_config); +EXPORT_SYMBOL(pmic_audio_output_clear_config); +EXPORT_SYMBOL(pmic_audio_output_get_config); +EXPORT_SYMBOL(pmic_audio_output_enable_phantom_ground); +EXPORT_SYMBOL(pmic_audio_output_disable_phantom_ground); +EXPORT_SYMBOL(pmic_audio_set_autodetect); +#ifdef DEBUG_AUDIO +EXPORT_SYMBOL(pmic_audio_dump_registers); +#endif /* DEBUG_AUDIO */ +/*! + * Define the minimum sampling rate (in Hz) that is supported by the + * Stereo DAC. + */ +const unsigned MIN_STDAC_SAMPLING_RATE_HZ = 8000; + +/*! + * Define the maximum sampling rate (in Hz) that is supported by the + * Stereo DAC. + */ +const unsigned MAX_STDAC_SAMPLING_RATE_HZ = 96000; + +/*! @def SET_BITS + * Set a register field to a given value. + */ +#define SET_BITS(reg, field, value) (((value) << reg.field.offset) & \ + reg.field.mask) +/*! @def GET_BITS + * Get the current value of a given register field. + */ +#define GET_BITS(reg, field, value) (((value) & reg.field.mask) >> \ + reg.field.offset) + +/*! + * @brief Define the possible states for a device handle. + * + * This enumeration is used to track the current state of each device handle. + */ +typedef enum { + HANDLE_FREE, /*!< Handle is available for use. */ + HANDLE_IN_USE /*!< Handle is currently in use. */ +} HANDLE_STATE; + +/*! + * @brief Identifies the hardware interrupt source. + * + * This enumeration identifies which of the possible hardware interrupt + * sources actually caused the current interrupt handler to be called. + */ +typedef enum { + CORE_EVENT_MC2BI, /*!< Microphone Bias 2 detect. */ + CORE_EVENT_HSDETI, /*!< Detect Headset attach */ + CORE_EVENT_HSLI, /*!< Detect Stereo Headset */ + CORE_EVENT_ALSPTHI, /*!< Detect Thermal shutdown of ALSP */ + CORE_EVENT_AHSSHORTI /*!< Detect Short circuit on AHS outputs */ +} PMIC_CORE_EVENT; + +/*! + * @brief This structure is used to track the state of a microphone input. + */ +typedef struct { + PMIC_AUDIO_INPUT_PORT mic; /*!< Microphone input port. */ + PMIC_AUDIO_INPUT_MIC_STATE micOnOff; /*!< Microphone On/Off state. */ + PMIC_AUDIO_MIC_AMP_MODE ampMode; /*!< Input amplifier mode. */ + PMIC_AUDIO_MIC_GAIN gain; /*!< Input amplifier gain level. */ +} PMIC_MICROPHONE_STATE; + +/*! + * @brief Tracks whether a headset is currently attached or not. + */ +typedef enum { + NO_HEADSET, /*!< No headset currently attached. */ + HEADSET_ON /*!< Headset has been attached. */ +} HEADSET_STATUS; + +/*! + * @brief mc13783 only enum that indicates the path to output taken + * by the voice codec output + */ +typedef enum { + VCODEC_DIRECT_OUT, /*!< Vcodec signal out direct */ + VCODEC_MIXER_OUT /*!< Output via the mixer */ +} PMIC_AUDIO_VCODEC_OUTPUT_PATH; + +/*! + * @brief This structure is used to define a specific hardware register field. + * + * All hardware register fields are defined using an offset to the LSB + * and a mask. The offset is used to right shift a register value before + * applying the mask to actually obtain the value of the field. + */ +typedef struct { + const unsigned char offset; /*!< Offset of LSB of register field. */ + const unsigned int mask; /*!< Mask value used to isolate register field. */ +} REGFIELD; + +/*! + * @brief This structure lists all fields of the AUD_CODEC hardware register. + */ +typedef struct { + REGFIELD CDCSSISEL; /*!< codec SSI bus select */ + REGFIELD CDCCLKSEL; /*!< Codec clock input select */ + REGFIELD CDCSM; /*!< Codec slave / master select */ + REGFIELD CDCBCLINV; /*!< Codec bitclock inversion */ + REGFIELD CDCFSINV; /*!< Codec framesync inversion */ + REGFIELD CDCFS; /*!< Bus protocol selection - 2 bits */ + REGFIELD CDCCLK; /*!< Codec clock setting - 3 bits */ + REGFIELD CDCFS8K16K; /*!< Codec framesync select */ + REGFIELD CDCEN; /*!< Codec enable */ + REGFIELD CDCCLKEN; /*!< Codec clocking enable */ + REGFIELD CDCTS; /*!< Codec SSI tristate */ + REGFIELD CDCDITH; /*!< Codec dithering */ + REGFIELD CDCRESET; /*!< Codec filter reset */ + REGFIELD CDCBYP; /*!< Codec bypass */ + REGFIELD CDCALM; /*!< Codec analog loopback */ + REGFIELD CDCDLM; /*!< Codec digital loopback */ + REGFIELD AUDIHPF; /*!< Transmit high pass filter enable */ + REGFIELD AUDOHPF; /*!< Receive high pass filter enable */ +} REGISTER_AUD_CODEC; + +/*! + * @brief This variable is used to access the AUD_CODEC hardware register. + * + * This variable defines how to access all of the fields within the + * AUD_CODEC hardware register. The initial values consist of the offset + * and mask values needed to access each of the register fields. + */ +static const REGISTER_AUD_CODEC regAUD_CODEC = { + {0, 0x000001}, /* CDCSSISEL */ + {1, 0x000002}, /* CDCCLKSEL */ + {2, 0x000004}, /* CDCSM */ + {3, 0x000008}, /* CDCBCLINV */ + {4, 0x000010}, /* CDCFSINV */ + {5, 0x000060}, /* CDCFS */ + {7, 0x000380}, /* CDCCLK */ + {10, 0x000400}, /* CDCFS8K16K */ + {11, 0x000800}, /* CDCEN */ + {12, 0x001000}, /* CDCCLKEN */ + {13, 0x002000}, /* CDCTS */ + {14, 0x004000}, /* CDCDITH */ + {15, 0x008000}, /* CDCRESET */ + {16, 0x010000}, /* CDCBYP */ + {17, 0x020000}, /* CDCALM */ + {18, 0x040000}, /* CDCDLM */ + {19, 0x080000}, /* AUDIHPF */ + {20, 0x100000} /* AUDOHPF */ + /* Unused */ + /* Unused */ + /* Unused */ + +}; + +/*! + * @brief This structure lists all fields of the ST_DAC hardware register. + */ + /* VVV */ +typedef struct { + REGFIELD STDCSSISEL; /*!< Stereo DAC SSI bus select */ + REGFIELD STDCCLKSEL; /*!< Stereo DAC clock input select */ + REGFIELD STDCSM; /*!< Stereo DAC slave / master select */ + REGFIELD STDCBCLINV; /*!< Stereo DAC bitclock inversion */ + REGFIELD STDCFSINV; /*!< Stereo DAC framesync inversion */ + REGFIELD STDCFS; /*!< Bus protocol selection - 2 bits */ + REGFIELD STDCCLK; /*!< Stereo DAC clock setting - 3 bits */ + REGFIELD STDCFSDLYB; /*!< Stereo DAC framesync delay bar */ + REGFIELD STDCEN; /*!< Stereo DAC enable */ + REGFIELD STDCCLKEN; /*!< Stereo DAC clocking enable */ + REGFIELD STDCRESET; /*!< Stereo DAC filter reset */ + REGFIELD SPDIF; /*!< Stereo DAC SSI SPDIF mode. Mode no longer available. */ + REGFIELD SR; /*!< Stereo DAC sample rate - 4 bits */ +} REGISTER_ST_DAC; + +/*! + * @brief This variable is used to access the ST_DAC hardware register. + * + * This variable defines how to access all of the fields within the + * ST_DAC hardware register. The initial values consist of the offset + * and mask values needed to access each of the register fields. + */ +static const REGISTER_ST_DAC regST_DAC = { + {0, 0x000001}, /* STDCSSISEL */ + {1, 0x000002}, /* STDCCLKSEL */ + {2, 0x000004}, /* STDCSM */ + {3, 0x000008}, /* STDCBCLINV */ + {4, 0x000010}, /* STDCFSINV */ + {5, 0x000060}, /* STDCFS */ + {7, 0x000380}, /* STDCCLK */ + {10, 0x000400}, /* STDCFSDLYB */ + {11, 0x000800}, /* STDCEN */ + {12, 0x001000}, /* STDCCLKEN */ + {15, 0x008000}, /* STDCRESET */ + {16, 0x010000}, /* SPDIF */ + {17, 0x1E0000} /* SR */ +}; + +/*! + * @brief This structure lists all of the fields in the SSI_NETWORK hardware register. + */ +typedef struct { + REGFIELD CDCTXRXSLOT; /*!< Codec timeslot assignment - 2 bits */ + REGFIELD CDCTXSECSLOT; /*!< Codec secondary transmit timeslot - 2 bits */ + REGFIELD CDCRXSECSLOT; /*!< Codec secondary receive timeslot - 2 bits */ + REGFIELD CDCRXSECGAIN; /*!< Codec secondary receive channel gain setting - 2 bits */ + REGFIELD CDCSUMGAIN; /*!< Codec summed receive signal gain setting */ + REGFIELD CDCFSDLY; /*!< Codec framesync delay */ + REGFIELD STDCSLOTS; /*!< Stereo DAC number of timeslots select - 2 bits */ + REGFIELD STDCRXSLOT; /*!< Stereo DAC timeslot assignment - 2 bits */ + REGFIELD STDCRXSECSLOT; /*!< Stereo DAC secondary receive timeslot - 2 bits */ + REGFIELD STDCRXSECGAIN; /*!< Stereo DAC secondary receive channel gain setting - 2 bits */ + REGFIELD STDCSUMGAIN; /*!< Stereo DAC summed receive signal gain setting */ +} REGISTER_SSI_NETWORK; + +/*! + * @brief This variable is used to access the SSI_NETWORK hardware register. + * + * This variable defines how to access all of the fields within the + * SSI_NETWORK hardware register. The initial values consist of the offset + * and mask values needed to access each of the register fields. + */ +static const REGISTER_SSI_NETWORK regSSI_NETWORK = { + {2, 0x00000c}, /* CDCTXRXSLOT */ + {4, 0x000030}, /* CDCTXSECSLOT */ + {6, 0x0000c0}, /* CDCRXSECSLOT */ + {8, 0x000300}, /* CDCRXSECGAIN */ + {10, 0x000400}, /* CDCSUMGAIN */ + {11, 0x000800}, /* CDCFSDLY */ + {12, 0x003000}, /* STDCSLOTS */ + {14, 0x00c000}, /* STDCRXSLOT */ + {16, 0x030000}, /* STDCRXSECSLOT */ + {18, 0x0c0000}, /* STDCRXSECGAIN */ + {20, 0x100000} /* STDCSUMGAIN */ +}; + +/*! + * @brief This structure lists all fields of the AUDIO_TX hardware register. + * + * + */ +typedef struct { + REGFIELD MC1BEN; /*!< Microphone bias 1 enable */ + REGFIELD MC2BEN; /*!< Microphone bias 2 enable */ + REGFIELD MC2BDETDBNC; /*!< Microphone bias detect debounce setting */ + REGFIELD MC2BDETEN; /*!< Microphone bias 2 detect enable */ + REGFIELD AMC1REN; /*!< Amplifier Amc1R enable */ + REGFIELD AMC1RITOV; /*!< Amplifier Amc1R current to voltage mode enable */ + REGFIELD AMC1LEN; /*!< Amplifier Amc1L enable */ + REGFIELD AMC1LITOV; /*!< Amplifier Amc1L current to voltage mode enable */ + REGFIELD AMC2EN; /*!< Amplifier Amc2 enable */ + REGFIELD AMC2ITOV; /*!< Amplifier Amc2 current to voltage mode enable */ + REGFIELD ATXINEN; /*!< Amplifier Atxin enable */ + REGFIELD ATXOUTEN; /*!< Reserved for output TXOUT enable, currently not used */ + REGFIELD RXINREC; /*!< RXINR/RXINL to voice CODEC ADC routing enable */ + REGFIELD PGATXR; /*!< Transmit gain setting right - 5 bits */ + REGFIELD PGATXL; /*!< Transmit gain setting left - 5 bits */ +} REGISTER_AUDIO_TX; + +/*! + * @brief This variable is used to access the AUDIO_TX hardware register. + * + * This variable defines how to access all of the fields within the + * AUDIO_TX hardware register. The initial values consist of the offset + * and mask values needed to access each of the register fields. + */ +static const REGISTER_AUDIO_TX regAUDIO_TX = { + {0, 0x000001}, /* MC1BEN */ + {1, 0x000002}, /* MC2BEN */ + {2, 0x000004}, /* MC2BDETDBNC */ + {3, 0x000008}, /* MC2BDETEN */ + {5, 0x000020}, /* AMC1REN */ + {6, 0x000040}, /* AMC1RITOV */ + {7, 0x000080}, /* AMC1LEN */ + {8, 0x000100}, /* AMC1LITOV */ + {9, 0x000200}, /* AMC2EN */ + {10, 0x000400}, /* AMC2ITOV */ + {11, 0x000800}, /* ATXINEN */ + {12, 0x001000}, /* ATXOUTEN */ + {13, 0x002000}, /* RXINREC */ + {14, 0x07c000}, /* PGATXR */ + {19, 0xf80000} /* PGATXL */ +}; + +/*! + * @brief This structure lists all fields of the AUDIO_RX_0 hardware register. + */ +typedef struct { + REGFIELD VAUDIOON; /*!< Forces VAUDIO in active on mode */ + REGFIELD BIASEN; /*!< Audio bias enable */ + REGFIELD BIASSPEED; /*!< Turn on ramp speed of the audio bias */ + REGFIELD ASPEN; /*!< Amplifier Asp enable */ + REGFIELD ASPSEL; /*!< Asp input selector */ + REGFIELD ALSPEN; /*!< Amplifier Alsp enable */ + REGFIELD ALSPREF; /*!< Bias Alsp at common audio reference */ + REGFIELD ALSPSEL; /*!< Alsp input selector */ + REGFIELD LSPLEN; /*!< Output LSPL enable */ + REGFIELD AHSREN; /*!< Amplifier AhsR enable */ + REGFIELD AHSLEN; /*!< Amplifier AhsL enable */ + REGFIELD AHSSEL; /*!< Ahsr and Ahsl input selector */ + REGFIELD HSPGDIS; /*!< Phantom ground disable */ + REGFIELD HSDETEN; /*!< Headset detect enable */ + REGFIELD HSDETAUTOB; /*!< Amplifier state determined by headset detect */ + REGFIELD ARXOUTREN; /*!< Output RXOUTR enable */ + REGFIELD ARXOUTLEN; /*!< Output RXOUTL enable */ + REGFIELD ARXOUTSEL; /*!< Arxout input selector */ + REGFIELD CDCOUTEN; /*!< Output CDCOUT enable */ + REGFIELD HSLDETEN; /*!< Headset left channel detect enable */ + REGFIELD ADDCDC; /*!< Adder channel codec selection */ + REGFIELD ADDSTDC; /*!< Adder channel stereo DAC selection */ + REGFIELD ADDRXIN; /*!< Adder channel line in selection */ +} REGISTER_AUDIO_RX_0; + +/*! + * @brief This variable is used to access the AUDIO_RX_0 hardware register. + * + * This variable defines how to access all of the fields within the + * AUDIO_RX_0 hardware register. The initial values consist of the offset + * and mask values needed to access each of the register fields. + */ +static const REGISTER_AUDIO_RX_0 regAUDIO_RX_0 = { + {0, 0x000001}, /* VAUDIOON */ + {1, 0x000002}, /* BIASEN */ + {2, 0x000004}, /* BIASSPEED */ + {3, 0x000008}, /* ASPEN */ + {4, 0x000010}, /* ASPSEL */ + {5, 0x000020}, /* ALSPEN */ + {6, 0x000040}, /* ALSPREF */ + {7, 0x000080}, /* ALSPSEL */ + {8, 0x000100}, /* LSPLEN */ + {9, 0x000200}, /* AHSREN */ + {10, 0x000400}, /* AHSLEN */ + {11, 0x000800}, /* AHSSEL */ + {12, 0x001000}, /* HSPGDIS */ + {13, 0x002000}, /* HSDETEN */ + {14, 0x004000}, /* HSDETAUTOB */ + {15, 0x008000}, /* ARXOUTREN */ + {16, 0x010000}, /* ARXOUTLEN */ + {17, 0x020000}, /* ARXOUTSEL */ + {18, 0x040000}, /* CDCOUTEN */ + {19, 0x080000}, /* HSLDETEN */ + {21, 0x200000}, /* ADDCDC */ + {22, 0x400000}, /* ADDSTDC */ + {23, 0x800000} /* ADDRXIN */ +}; + +/*! + * @brief This structure lists all fields of the AUDIO_RX_1 hardware register. + */ +typedef struct { + REGFIELD PGARXEN; /*!< Codec receive PGA enable */ + REGFIELD PGARX; /*!< Codec receive gain setting - 4 bits */ + REGFIELD PGASTEN; /*!< Stereo DAC PGA enable */ + REGFIELD PGAST; /*!< Stereo DAC gain setting - 4 bits */ + REGFIELD ARXINEN; /*!< Amplifier Arx enable */ + REGFIELD ARXIN; /*!< Amplifier Arx additional gain setting */ + REGFIELD PGARXIN; /*!< PGArxin gain setting - 4 bits */ + REGFIELD MONO; /*!< Mono adder setting - 2 bits */ + REGFIELD BAL; /*!< Balance control - 3 bits */ + REGFIELD BALLR; /*!< Left / right balance */ +} REGISTER_AUDIO_RX_1; + +/*! + * @brief This variable is used to access the AUDIO_RX_1 hardware register. + * + * This variable defines how to access all of the fields within the + * AUDIO_RX_1 hardware register. The initial values consist of the offset + * and mask values needed to access each of the register fields. + */ +static const REGISTER_AUDIO_RX_1 regAUDIO_RX_1 = { + {0, 0x000001}, /* PGARXEN */ + {1, 0x00001e}, /* PGARX */ + {5, 0x000020}, /* PGASTEN */ + {6, 0x0003c0}, /* PGAST */ + {10, 0x000400}, /* ARXINEN */ + {11, 0x000800}, /* ARXIN */ + {12, 0x00f000}, /* PGARXIN */ + {16, 0x030000}, /* MONO */ + {18, 0x1c0000}, /* BAL */ + {21, 0x200000} /* BALLR */ +}; + +/*! Define a mask to access the entire hardware register. */ +static const unsigned int REG_FULLMASK = 0xffffff; + +/*! Reset value for the AUD_CODEC register. */ +static const unsigned int RESET_AUD_CODEC = 0x180027; + +/*! Reset value for the ST_DAC register. + * + * Note that we avoid resetting any of the arbitration bits. + */ +static const unsigned int RESET_ST_DAC = 0x0E0004; + +/*! Reset value for the SSI_NETWORK register. */ +static const unsigned int RESET_SSI_NETWORK = 0x013060; + +/*! Reset value for the AUDIO_TX register. + * + * Note that we avoid resetting any of the arbitration bits. + */ +static const unsigned int RESET_AUDIO_TX = 0x420000; + +/*! Reset value for the AUDIO_RX_0 register. */ +static const unsigned int RESET_AUDIO_RX_0 = 0x001000; + +/*! Reset value for the AUDIO_RX_1 register. */ +static const unsigned int RESET_AUDIO_RX_1 = 0x00D35A; + +/*! Reset mask for the SSI network Vcodec part. first 12 bits + * 0 - 11 */ +static const unsigned int REG_SSI_VCODEC_MASK = 0x000fff; + +/*! Reset mask for the SSI network STDAC part. last 12 bits + * 12 - 24 */ +static const unsigned int REG_SSI_STDAC_MASK = 0xfff000; + +/*! Constant NULL value for initializing/reseting the audio handles. */ +static const PMIC_AUDIO_HANDLE AUDIO_HANDLE_NULL = (PMIC_AUDIO_HANDLE) NULL; + +/*! + * @brief This structure maintains the current state of the Stereo DAC. + */ +typedef struct { + PMIC_AUDIO_HANDLE handle; /*!< Handle used to access + the Stereo DAC. */ + HANDLE_STATE handleState; /*!< Current handle state. */ + PMIC_AUDIO_DATA_BUS busID; /*!< Data bus used to access + the Stereo DAC. */ + bool protocol_set; + PMIC_AUDIO_BUS_PROTOCOL protocol; /*!< Data bus protocol. */ + PMIC_AUDIO_BUS_MODE masterSlave; /*!< Master/Slave mode + select. */ + PMIC_AUDIO_NUMSLOTS numSlots; /*!< Number of timeslots + used. */ + PMIC_AUDIO_CALLBACK callback; /*!< Event notification + callback function + pointer. */ + PMIC_AUDIO_EVENTS eventMask; /*!< Event notification mask. */ + PMIC_AUDIO_CLOCK_IN_SOURCE clockIn; /*!< Stereo DAC clock input + source select. */ + PMIC_AUDIO_STDAC_SAMPLING_RATE samplingRate; /*!< Stereo DAC sampling rate + select. */ + PMIC_AUDIO_STDAC_CLOCK_IN_FREQ clockFreq; /*!< Stereo DAC clock input + frequency. */ + PMIC_AUDIO_CLOCK_INVERT invert; /*!< Stereo DAC clock signal + invert select. */ + PMIC_AUDIO_STDAC_TIMESLOTS timeslot; /*!< Stereo DAC data + timeslots select. */ + PMIC_AUDIO_STDAC_CONFIG config; /*!< Stereo DAC configuration + options. */ +} PMIC_AUDIO_STDAC_STATE; + +/*! + * @brief This variable maintains the current state of the Stereo DAC. + * + * This variable tracks the current state of the Stereo DAC audio hardware + * along with any information that is required by the device driver to + * manage the hardware (e.g., callback functions and event notification + * masks). + * + * The initial values represent the reset/power on state of the Stereo DAC. + */ +static PMIC_AUDIO_STDAC_STATE stDAC = { + (PMIC_AUDIO_HANDLE) NULL, /* handle */ + HANDLE_FREE, /* handleState */ + AUDIO_DATA_BUS_1, /* busID */ + false, + NORMAL_MSB_JUSTIFIED_MODE, /* protocol */ + BUS_MASTER_MODE, /* masterSlave */ + USE_2_TIMESLOTS, /* numSlots */ + (PMIC_AUDIO_CALLBACK) NULL, /* callback */ + (PMIC_AUDIO_EVENTS) NULL, /* eventMask */ + CLOCK_IN_CLIA, /* clockIn */ + STDAC_RATE_44_1_KHZ, /* samplingRate */ + STDAC_CLI_13MHZ, /* clockFreq */ + NO_INVERT, /* invert */ + USE_TS0_TS1, /* timeslot */ + (PMIC_AUDIO_STDAC_CONFIG) 0 /* config */ +}; + +/*! + * @brief This structure maintains the current state of the Voice CODEC. + */ +typedef struct { + PMIC_AUDIO_HANDLE handle; /*!< Handle used to access + the Voice CODEC. */ + HANDLE_STATE handleState; /*!< Current handle state. */ + PMIC_AUDIO_DATA_BUS busID; /*!< Data bus used to access + the Voice CODEC. */ + bool protocol_set; + PMIC_AUDIO_BUS_PROTOCOL protocol; /*!< Data bus protocol. */ + PMIC_AUDIO_BUS_MODE masterSlave; /*!< Master/Slave mode + select. */ + PMIC_AUDIO_NUMSLOTS numSlots; /*!< Number of timeslots + used. */ + PMIC_AUDIO_CALLBACK callback; /*!< Event notification + callback function + pointer. */ + PMIC_AUDIO_EVENTS eventMask; /*!< Event notification + mask. */ + PMIC_AUDIO_CLOCK_IN_SOURCE clockIn; /*!< Voice CODEC clock input + source select. */ + PMIC_AUDIO_VCODEC_SAMPLING_RATE samplingRate; /*!< Voice CODEC sampling + rate select. */ + PMIC_AUDIO_VCODEC_CLOCK_IN_FREQ clockFreq; /*!< Voice CODEC clock input + frequency. */ + PMIC_AUDIO_CLOCK_INVERT invert; /*!< Voice CODEC clock + signal invert select. */ + PMIC_AUDIO_VCODEC_TIMESLOT timeslot; /*!< Voice CODEC data + timeslot select. */ + PMIC_AUDIO_VCODEC_TIMESLOT secondaryTXtimeslot; + + PMIC_AUDIO_VCODEC_CONFIG config; /*!< Voice CODEC + configuration + options. */ + PMIC_MICROPHONE_STATE leftChannelMic; /*!< Left channel + microphone + configuration. */ + PMIC_MICROPHONE_STATE rightChannelMic; /*!< Right channel + microphone + configuration. */ +} PMIC_AUDIO_VCODEC_STATE; + +/*! + * @brief This variable maintains the current state of the Voice CODEC. + * + * This variable tracks the current state of the Voice CODEC audio hardware + * along with any information that is required by the device driver to + * manage the hardware (e.g., callback functions and event notification + * masks). + * + * The initial values represent the reset/power on state of the Voice CODEC. + */ +static PMIC_AUDIO_VCODEC_STATE vCodec = { + (PMIC_AUDIO_HANDLE) NULL, /* handle */ + HANDLE_FREE, /* handleState */ + AUDIO_DATA_BUS_2, /* busID */ + false, + NETWORK_MODE, /* protocol */ + BUS_SLAVE_MODE, /* masterSlave */ + USE_4_TIMESLOTS, /* numSlots */ + (PMIC_AUDIO_CALLBACK) NULL, /* callback */ + (PMIC_AUDIO_EVENTS) NULL, /* eventMask */ + CLOCK_IN_CLIB, /* clockIn */ + VCODEC_RATE_8_KHZ, /* samplingRate */ + VCODEC_CLI_13MHZ, /* clockFreq */ + NO_INVERT, /* invert */ + USE_TS0, /* timeslot pri */ + USE_TS2, /* timeslot sec TX */ + INPUT_HIGHPASS_FILTER | OUTPUT_HIGHPASS_FILTER, /* config */ + /* leftChannelMic */ + {NO_MIC, /* mic */ + MICROPHONE_OFF, /* micOnOff */ + AMP_OFF, /* ampMode */ + MIC_GAIN_0DB /* gain */ + }, + /* rightChannelMic */ + {NO_MIC, /* mic */ + MICROPHONE_OFF, /* micOnOff */ + AMP_OFF, /* ampMode */ + MIC_GAIN_0DB /* gain */ + } +}; + +/*! + * @brief This maintains the current state of the External Stereo Input. + */ +typedef struct { + PMIC_AUDIO_HANDLE handle; /*!< Handle used to access the + External Stereo Inputs. */ + HANDLE_STATE handleState; /*!< Current handle state. */ + PMIC_AUDIO_CALLBACK callback; /*!< Event notification callback + function pointer. */ + PMIC_AUDIO_EVENTS eventMask; /*!< Event notification mask. */ + PMIC_AUDIO_STEREO_IN_GAIN inputGain; /*!< External Stereo Input + amplifier gain level. */ +} PMIC_AUDIO_EXT_STEREO_IN_STATE; + +/*! + * @brief This maintains the current state of the External Stereo Input. + * + * This variable tracks the current state of the External Stereo Input audio + * hardware along with any information that is required by the device driver + * to manage the hardware (e.g., callback functions and event notification + * masks). + * + * The initial values represent the reset/power on state of the External + * Stereo Input. + */ +static PMIC_AUDIO_EXT_STEREO_IN_STATE extStereoIn = { + (PMIC_AUDIO_HANDLE) NULL, /* handle */ + HANDLE_FREE, /* handleState */ + (PMIC_AUDIO_CALLBACK) NULL, /* callback */ + (PMIC_AUDIO_EVENTS) NULL, /* eventMask */ + STEREO_IN_GAIN_0DB /* inputGain */ +}; + +/*! + * @brief This maintains the current state of the callback & Eventmask. + */ +typedef struct { + PMIC_AUDIO_CALLBACK callback; /*!< Event notification callback + function pointer. */ + PMIC_AUDIO_EVENTS eventMask; /*!< Event notification mask. */ +} PMIC_AUDIO_EVENT_STATE; + +static PMIC_AUDIO_EVENT_STATE event_state = { + (PMIC_AUDIO_CALLBACK) NULL, /*Callback */ + (PMIC_AUDIO_EVENTS) NULL, /* EventMask */ + +}; + +/*! + * @brief This maintains the current state of the Audio Output Section. + */ +typedef struct { + PMIC_AUDIO_OUTPUT_PORT outputPort; /*!< Current audio + output port. */ + PMIC_AUDIO_OUTPUT_PGA_GAIN vCodecoutputPGAGain; /*!< Output PGA gain + level codec */ + PMIC_AUDIO_OUTPUT_PGA_GAIN stDacoutputPGAGain; /*!< Output PGA gain + level stDAC */ + PMIC_AUDIO_OUTPUT_PGA_GAIN extStereooutputPGAGain; /*!< Output PGA gain + level stereo ext */ + PMIC_AUDIO_OUTPUT_BALANCE_GAIN balanceLeftGain; /*!< Left channel + balance gain + level. */ + PMIC_AUDIO_OUTPUT_BALANCE_GAIN balanceRightGain; /*!< Right channel + balance gain + level. */ + PMIC_AUDIO_MONO_ADDER_OUTPUT_GAIN monoAdderGain; /*!< Mono adder gain + level. */ + PMIC_AUDIO_OUTPUT_CONFIG config; /*!< Audio output + section config + options. */ + PMIC_AUDIO_VCODEC_OUTPUT_PATH vCodecOut; + +} PMIC_AUDIO_AUDIO_OUTPUT_STATE; + +/*! + * @brief This variable maintains the current state of the Audio Output Section. + * + * This variable tracks the current state of the Audio Output Section. + * + * The initial values represent the reset/power on state of the Audio + * Output Section. + */ +static PMIC_AUDIO_AUDIO_OUTPUT_STATE audioOutput = { + (PMIC_AUDIO_OUTPUT_PORT) NULL, /* outputPort */ + OUTPGA_GAIN_0DB, /* outputPGAGain */ + OUTPGA_GAIN_0DB, /* outputPGAGain */ + OUTPGA_GAIN_0DB, /* outputPGAGain */ + BAL_GAIN_0DB, /* balanceLeftGain */ + BAL_GAIN_0DB, /* balanceRightGain */ + MONOADD_GAIN_0DB, /* monoAdderGain */ + (PMIC_AUDIO_OUTPUT_CONFIG) 0, /* config */ + VCODEC_DIRECT_OUT +}; + +/*! The current headset status. */ +static HEADSET_STATUS headsetState = NO_HEADSET; + +/* Removed PTT variable */ +/*! Define a 1 ms wait interval that is needed to ensure that certain + * hardware operations are successfully completed. + */ +static const unsigned long delay_1ms = (HZ / 1000); + +/*! + * @brief This spinlock is used to provide mutual exclusion. + * + * Create a spinlock that can be used to provide mutually exclusive + * read/write access to the globally accessible data structures + * that were defined above. Mutually exclusive access is required to + * ensure that the audio data structures are consistent at all times + * when possibly accessed by multiple threads of execution (for example, + * while simultaneously handling a user request and an interrupt event). + * + * We need to use a spinlock whenever we do need to provide mutual + * exclusion while possibly executing in a hardware interrupt context. + * Spinlocks should be held for the minimum time that is necessary + * because hardware interrupts are disabled while a spinlock is held. + * + */ +static DEFINE_SPINLOCK(lock); + +/*! + * @brief This mutex is used to provide mutual exclusion. + * + * Create a mutex that can be used to provide mutually exclusive + * read/write access to the globally accessible data structures + * that were defined above. Mutually exclusive access is required to + * ensure that the audio data structures are consistent at all times + * when possibly accessed by multiple threads of execution. + * + * Note that we use a mutex instead of the spinlock whenever disabling + * interrupts while in the critical section is not required. This helps + * to minimize kernel interrupt handling latency. + */ +static DECLARE_MUTEX(mutex); + +/*! + * @brief Global variable to track currently active interrupt events. + * + * This global variable is used to keep track of all of the currently + * active interrupt events for the audio driver. Note that access to this + * variable may occur while within an interrupt context and, therefore, + * must be guarded by using a spinlock. + */ +/* static PMIC_CORE_EVENT eventID = 0; */ + +/* Prototypes for all static audio driver functions. */ +/* +static PMIC_STATUS pmic_audio_mic_boost_enable(void); +static PMIC_STATUS pmic_audio_mic_boost_disable(void);*/ +static PMIC_STATUS pmic_audio_close_handle(const PMIC_AUDIO_HANDLE handle); +static PMIC_STATUS pmic_audio_reset_device(const PMIC_AUDIO_HANDLE handle); + +static PMIC_STATUS pmic_audio_deregister(void *callback, + PMIC_AUDIO_EVENTS * const eventMask); + +/************************************************************************* + * Audio device access APIs. + ************************************************************************* + */ + +/*! + * @name General Setup and Configuration APIs + * Functions for general setup and configuration of the PMIC Audio + * hardware. + */ +/*@{*/ + +PMIC_STATUS pmic_audio_set_autodetect(int val) +{ + PMIC_STATUS status; + unsigned int reg_mask = 0, reg_write = 0; + reg_mask = SET_BITS(regAUDIO_RX_0, VAUDIOON, 1); + status = pmic_write_reg(REG_AUDIO_RX_0, reg_mask, reg_mask); + if (status != PMIC_SUCCESS) + return status; + reg_mask = 0; + if (val == 1) { + reg_write = SET_BITS(regAUDIO_RX_0, HSDETEN, 1) | + SET_BITS(regAUDIO_RX_0, HSDETAUTOB, 1); + } else { + reg_write = 0; + } + reg_mask = + SET_BITS(regAUDIO_RX_0, HSDETEN, 1) | SET_BITS(regAUDIO_RX_0, + HSDETAUTOB, 1); + status = pmic_write_reg(REG_AUDIO_RX_0, reg_write, reg_mask); + + return status; +} + +/*! + * @brief Request exclusive access to the PMIC Audio hardware. + * + * Attempt to open and gain exclusive access to a key PMIC audio hardware + * component (e.g., the Stereo DAC or the Voice CODEC). Depending upon the + * type of audio operation that is desired and the nature of the audio data + * stream, the Stereo DAC and/or the Voice CODEC will be a required hardware + * component and needs to be acquired by calling this function. + * + * If the open request is successful, then a numeric handle is returned + * and this handle must be used in all subsequent function calls to complete + * the configuration of either the Stereo DAC or the Voice CODEC and along + * with any other associated audio hardware components that will be needed. + * + * The same handle must also be used in the close call when use of the PMIC + * audio hardware is no longer required. + * + * The open request will fail if the requested audio hardware component has + * already been acquired by a previous open call but not yet closed. + * + * @param handle Device handle to be used for subsequent PMIC + * audio API calls. + * @param device The required PMIC audio hardware component. + * + * @retval PMIC_SUCCESS If the open request was successful + * @retval PMIC_PARAMETER_ERROR If the handle argument is NULL. + * @retval PMIC_ERROR If the audio hardware component is + * unavailable. + */ +PMIC_STATUS pmic_audio_open(PMIC_AUDIO_HANDLE * const handle, + const PMIC_AUDIO_SOURCE device) +{ + PMIC_STATUS rc = PMIC_ERROR; + + if (handle == (PMIC_AUDIO_HANDLE *) NULL) { + /* Do not dereference a NULL pointer. */ + return PMIC_PARAMETER_ERROR; + } + + /* We only need to acquire a mutex here because the interrupt handler + * never modifies the device handle or device handle state. Therefore, + * we don't need to worry about conflicts with the interrupt handler + * or the need to execute in an interrupt context. + * + * But we do need a critical section here to avoid problems in case + * multiple calls to pmic_audio_open() are made since we can only allow + * one of them to succeed. + */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + /* Check the current device handle state and acquire the handle if + * it is available. + */ + + if ((device == STEREO_DAC) && (stDAC.handleState == HANDLE_FREE)) { + stDAC.handle = (PMIC_AUDIO_HANDLE) (&stDAC); + stDAC.handleState = HANDLE_IN_USE; + *handle = stDAC.handle; + rc = PMIC_SUCCESS; + } else if ((device == VOICE_CODEC) + && (vCodec.handleState == HANDLE_FREE)) { + vCodec.handle = (PMIC_AUDIO_HANDLE) (&vCodec); + vCodec.handleState = HANDLE_IN_USE; + *handle = vCodec.handle; + rc = PMIC_SUCCESS; + } else if ((device == EXTERNAL_STEREO_IN) && + (extStereoIn.handleState == HANDLE_FREE)) { + extStereoIn.handle = (PMIC_AUDIO_HANDLE) (&extStereoIn); + extStereoIn.handleState = HANDLE_IN_USE; + *handle = extStereoIn.handle; + rc = PMIC_SUCCESS; + } else { + *handle = AUDIO_HANDLE_NULL; + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Terminate further access to the PMIC audio hardware. + * + * Terminate further access to the PMIC audio hardware that was previously + * acquired by calling pmic_audio_open(). This now allows another thread to + * successfully call pmic_audio_open() to gain access. + * + * Note that we will shutdown/reset the Voice CODEC or Stereo DAC as well as + * any associated audio input/output components that are no longer required. + * + * @param handle Device handle from pmic_audio_open() call. + * + * @retval PMIC_SUCCESS If the close request was successful. + * @retval PMIC_PARAMETER_ERROR If the handle is invalid. + */ +PMIC_STATUS pmic_audio_close(const PMIC_AUDIO_HANDLE handle) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + + /* We need a critical section here to maintain a consistent state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + /* We can now call pmic_audio_close_handle() to actually do the work. */ + rc = pmic_audio_close_handle(handle); + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Configure the data bus protocol to be used. + * + * Provide the parameters needed to properly configure the audio data bus + * protocol so that data can be read/written to either the Stereo DAC or + * the Voice CODEC. + * + * @param handle Device handle from pmic_audio_open() call. + * @param busID Select data bus to be used. + * @param protocol Select the data bus protocol. + * @param masterSlave Select the data bus timing mode. + * @param numSlots Define the number of timeslots (only if in + * master mode). + * + * @retval PMIC_SUCCESS If the protocol was successful configured. + * @retval PMIC_PARAMETER_ERROR If the handle or the protocol parameters + * are invalid. + */ +PMIC_STATUS pmic_audio_set_protocol(const PMIC_AUDIO_HANDLE handle, + const PMIC_AUDIO_DATA_BUS busID, + const PMIC_AUDIO_BUS_PROTOCOL protocol, + const PMIC_AUDIO_BUS_MODE masterSlave, + const PMIC_AUDIO_NUMSLOTS numSlots) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + const unsigned int ST_DAC_MASK = SET_BITS(regST_DAC, STDCSSISEL, 1) | + SET_BITS(regST_DAC, STDCFS, 3) | SET_BITS(regST_DAC, STDCSM, 1); + + unsigned int reg_mask; + /*unsigned int VCODEC_MASK = SET_BITS(regAUD_CODEC, CDCSSISEL, 1) | + SET_BITS(regAUD_CODEC, CDCFS, 3) | SET_BITS(regAUD_CODEC, CDCSM, 1); */ + + unsigned int SSI_NW_MASK = SET_BITS(regSSI_NETWORK, STDCSLOTS, 1); + unsigned int reg_value = 0; + unsigned int ssi_nw_value = 0; + + /* Enter a critical section so that we can ensure only one + * state change request is completed at a time. + */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if (handle == (PMIC_AUDIO_HANDLE) NULL) { + rc = PMIC_PARAMETER_ERROR; + } else { + if ((handle == vCodec.handle) && + (vCodec.handleState == HANDLE_IN_USE)) { + if ((stDAC.handleState == HANDLE_IN_USE) && + (stDAC.busID == busID) && (stDAC.protocol_set)) { + pr_debug("The requested bus already in USE\n"); + rc = PMIC_PARAMETER_ERROR; + } else if ((masterSlave == BUS_MASTER_MODE) + && (numSlots != USE_4_TIMESLOTS)) { + pr_debug + ("mc13783 supports only 4 slots in Master mode\n"); + rc = PMIC_NOT_SUPPORTED; + } else if ((masterSlave == BUS_SLAVE_MODE) + && (numSlots != USE_4_TIMESLOTS)) { + pr_debug + ("Driver currently supports only 4 slots in Slave mode\n"); + rc = PMIC_NOT_SUPPORTED; + } else if (!((protocol == NETWORK_MODE) || + (protocol == I2S_MODE))) { + pr_debug + ("mc13783 Voice codec works only in Network and I2S modes\n"); + rc = PMIC_NOT_SUPPORTED; + } else { + pr_debug + ("Proceeding to configure Voice Codec\n"); + if (busID == AUDIO_DATA_BUS_1) { + reg_value = + SET_BITS(regAUD_CODEC, CDCSSISEL, + 0); + } else { + reg_value = + SET_BITS(regAUD_CODEC, CDCSSISEL, + 1); + } + reg_mask = SET_BITS(regAUD_CODEC, CDCSSISEL, 1); + if (PMIC_SUCCESS != + pmic_write_reg(REG_AUDIO_CODEC, + reg_value, reg_mask)) + return PMIC_ERROR; + + if (masterSlave == BUS_MASTER_MODE) { + reg_value = + SET_BITS(regAUD_CODEC, CDCSM, 0); + } else { + reg_value = + SET_BITS(regAUD_CODEC, CDCSM, 1); + } + reg_mask = SET_BITS(regAUD_CODEC, CDCSM, 1); + if (PMIC_SUCCESS != + pmic_write_reg(REG_AUDIO_CODEC, + reg_value, reg_mask)) + return PMIC_ERROR; + + if (protocol == NETWORK_MODE) { + reg_value = + SET_BITS(regAUD_CODEC, CDCFS, 1); + } else { /* protocol == I2S, other options have been already eliminated */ + reg_value = + SET_BITS(regAUD_CODEC, CDCFS, 2); + } + reg_mask = SET_BITS(regAUD_CODEC, CDCFS, 3); + if (PMIC_SUCCESS != + pmic_write_reg(REG_AUDIO_CODEC, + reg_value, reg_mask)) + return PMIC_ERROR; + + ssi_nw_value = + SET_BITS(regSSI_NETWORK, CDCFSDLY, 1); + /*if (pmic_write_reg + (REG_AUDIO_CODEC, reg_value, + VCODEC_MASK) != PMIC_SUCCESS) { + rc = PMIC_ERROR; + } else { */ + vCodec.busID = busID; + vCodec.protocol = protocol; + vCodec.masterSlave = masterSlave; + vCodec.numSlots = numSlots; + vCodec.protocol_set = true; + + pr_debug + ("mc13783 Voice codec successfully configured\n"); + rc = PMIC_SUCCESS; + } + + } else if ((handle == stDAC.handle) && + (stDAC.handleState == HANDLE_IN_USE)) { + if ((vCodec.handleState == HANDLE_IN_USE) && + (vCodec.busID == busID) && (vCodec.protocol_set)) { + pr_debug("The requested bus already in USE\n"); + rc = PMIC_PARAMETER_ERROR; + } else if (((protocol == NORMAL_MSB_JUSTIFIED_MODE) || + (protocol == I2S_MODE)) + && (numSlots != USE_2_TIMESLOTS)) { + pr_debug + ("STDAC uses only 2 slots in Normal and I2S modes\n"); + rc = PMIC_PARAMETER_ERROR; + } else if ((protocol == NETWORK_MODE) && + !((numSlots == USE_2_TIMESLOTS) || + (numSlots == USE_4_TIMESLOTS) || + (numSlots == USE_8_TIMESLOTS))) { + pr_debug + ("STDAC uses only 2,4 or 8 slots in Network mode\n"); + rc = PMIC_PARAMETER_ERROR; + } else if (protocol == SPD_IF_MODE) { + pr_debug + ("STDAC driver currently does not support SPD IF mode\n"); + rc = PMIC_NOT_SUPPORTED; + } else { + pr_debug + ("Proceeding to configure Stereo DAC\n"); + if (busID == AUDIO_DATA_BUS_1) { + reg_value = + SET_BITS(regST_DAC, STDCSSISEL, 0); + } else { + reg_value = + SET_BITS(regST_DAC, STDCSSISEL, 1); + } + if (masterSlave == BUS_MASTER_MODE) { + reg_value |= + SET_BITS(regST_DAC, STDCSM, 0); + } else { + reg_value |= + SET_BITS(regST_DAC, STDCSM, 1); + } + if (protocol == NETWORK_MODE) { + reg_value |= + SET_BITS(regST_DAC, STDCFS, 1); + } else if (protocol == + NORMAL_MSB_JUSTIFIED_MODE) { + reg_value |= + SET_BITS(regST_DAC, STDCFS, 0); + } else { /* I2S mode as the other option has already been eliminated */ + reg_value |= + SET_BITS(regST_DAC, STDCFS, 2); + } + + if (pmic_write_reg + (REG_AUDIO_STEREO_DAC, + reg_value, ST_DAC_MASK) != PMIC_SUCCESS) { + rc = PMIC_ERROR; + } else { + if (numSlots == USE_2_TIMESLOTS) { + reg_value = + SET_BITS(regSSI_NETWORK, + STDCSLOTS, 3); + } else if (numSlots == USE_4_TIMESLOTS) { + reg_value = + SET_BITS(regSSI_NETWORK, + STDCSLOTS, 2); + } else { /* Use 8 timeslots - L , R and 6 other */ + reg_value = + SET_BITS(regSSI_NETWORK, + STDCSLOTS, 1); + } + if (pmic_write_reg + (REG_AUDIO_SSI_NETWORK, + reg_value, + SSI_NW_MASK) != PMIC_SUCCESS) { + rc = PMIC_ERROR; + } else { + stDAC.busID = busID; + stDAC.protocol = protocol; + stDAC.protocol_set = true; + stDAC.masterSlave = masterSlave; + stDAC.numSlots = numSlots; + pr_debug + ("mc13783 Stereo DAC successfully configured\n"); + rc = PMIC_SUCCESS; + } + } + + } + } else { + rc = PMIC_PARAMETER_ERROR; + /* Handle can only be Voice Codec or Stereo DAC */ + pr_debug("Handles only STDAC and VCODEC\n"); + } + + } + /* Exit critical section. */ + up(&mutex); + return rc; +} + +/*! + * @brief Retrieve the current data bus protocol configuration. + * + * Retrieve the parameters that define the current audio data bus protocol. + * + * @param handle Device handle from pmic_audio_open() call. + * @param busID The data bus being used. + * @param protocol The data bus protocol being used. + * @param masterSlave The data bus timing mode being used. + * @param numSlots The number of timeslots being used (if in + * master mode). + * + * @retval PMIC_SUCCESS If the protocol was successful retrieved. + * @retval PMIC_PARAMETER_ERROR If the handle is invalid. + */ +PMIC_STATUS pmic_audio_get_protocol(const PMIC_AUDIO_HANDLE handle, + PMIC_AUDIO_DATA_BUS * const busID, + PMIC_AUDIO_BUS_PROTOCOL * const protocol, + PMIC_AUDIO_BUS_MODE * const masterSlave, + PMIC_AUDIO_NUMSLOTS * const numSlots) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + + if ((busID != (PMIC_AUDIO_DATA_BUS *) NULL) && + (protocol != (PMIC_AUDIO_BUS_PROTOCOL *) NULL) && + (masterSlave != (PMIC_AUDIO_BUS_MODE *) NULL) && + (numSlots != (PMIC_AUDIO_NUMSLOTS *) NULL)) { + /* Enter a critical section so that we return a consistent state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == stDAC.handle) && + (stDAC.handleState == HANDLE_IN_USE)) { + *busID = stDAC.busID; + *protocol = stDAC.protocol; + *masterSlave = stDAC.masterSlave; + *numSlots = stDAC.numSlots; + rc = PMIC_SUCCESS; + } else if ((handle == vCodec.handle) && + (vCodec.handleState == HANDLE_IN_USE)) { + *busID = vCodec.busID; + *protocol = vCodec.protocol; + *masterSlave = vCodec.masterSlave; + *numSlots = vCodec.numSlots; + rc = PMIC_SUCCESS; + } + + /* Exit critical section. */ + up(&mutex); + } + + return rc; +} + +/*! + * @brief Enable the Stereo DAC or the Voice CODEC. + * + * Explicitly enable the Stereo DAC or the Voice CODEC to begin audio + * playback or recording as required. This should only be done after + * successfully configuring all of the associated audio components (e.g., + * microphones, amplifiers, etc.). + * + * Note that the timed delays used in this function are necessary to + * ensure reliable operation of the Voice CODEC and Stereo DAC. The + * Stereo DAC seems to be particularly sensitive and it has been observed + * to fail to generate the required master mode clock signals if it is + * not allowed enough time to initialize properly. + * + * @param handle Device handle from pmic_audio_open() call. + * + * @retval PMIC_SUCCESS If the device was successful enabled. + * @retval PMIC_PARAMETER_ERROR If the handle is invalid. + * @retval PMIC_ERROR If the device could not be enabled. + */ +PMIC_STATUS pmic_audio_enable(const PMIC_AUDIO_HANDLE handle) +{ + const unsigned int AUDIO_BIAS_ENABLE = SET_BITS(regAUDIO_RX_0, + VAUDIOON, 1); + const unsigned int STDAC_ENABLE = SET_BITS(regST_DAC, STDCEN, 1); + const unsigned int VCODEC_ENABLE = SET_BITS(regAUD_CODEC, CDCEN, 1); + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_write = 0; + unsigned int reg_mask = 0; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == stDAC.handle) && (stDAC.handleState == HANDLE_IN_USE)) { + pmic_write_reg(REG_AUDIO_RX_0, AUDIO_BIAS_ENABLE, + AUDIO_BIAS_ENABLE); + reg_mask = + SET_BITS(regAUDIO_RX_0, HSDETEN, + 1) | SET_BITS(regAUDIO_RX_0, HSDETAUTOB, 1); + reg_write = + SET_BITS(regAUDIO_RX_0, HSDETEN, + 1) | SET_BITS(regAUDIO_RX_0, HSDETAUTOB, 1); + rc = pmic_write_reg(REG_AUDIO_RX_0, reg_write, reg_mask); + if (rc == PMIC_SUCCESS) + pr_debug("pmic_audio_enable\n"); + /* We can enable the Stereo DAC. */ + rc = pmic_write_reg(REG_AUDIO_STEREO_DAC, + STDAC_ENABLE, STDAC_ENABLE); + /*pmic_read_reg(REG_AUDIO_STEREO_DAC, ®_value); */ + if (rc != PMIC_SUCCESS) { + pr_debug("Failed to enable the Stereo DAC\n"); + rc = PMIC_ERROR; + } + } else if ((handle == vCodec.handle) + && (vCodec.handleState == HANDLE_IN_USE)) { + /* Must first set the audio bias bit to power up the audio circuits. */ + pmic_write_reg(REG_AUDIO_RX_0, AUDIO_BIAS_ENABLE, + AUDIO_BIAS_ENABLE); + reg_mask = SET_BITS(regAUDIO_RX_0, HSDETEN, 1) | + SET_BITS(regAUDIO_RX_0, HSDETAUTOB, 1); + reg_write = SET_BITS(regAUDIO_RX_0, HSDETEN, 1) | + SET_BITS(regAUDIO_RX_0, HSDETAUTOB, 1); + rc = pmic_write_reg(REG_AUDIO_RX_0, reg_write, reg_mask); + + /* Then we can enable the Voice CODEC. */ + rc = pmic_write_reg(REG_AUDIO_CODEC, VCODEC_ENABLE, + VCODEC_ENABLE); + + /* pmic_read_reg(REG_AUDIO_CODEC, ®_value); */ + if (rc != PMIC_SUCCESS) { + pr_debug("Failed to enable the Voice codec\n"); + rc = PMIC_ERROR; + } + } + /* Exit critical section. */ + up(&mutex); + return rc; +} + +/*! + * @brief Disable the Stereo DAC or the Voice CODEC. + * + * Explicitly disable the Stereo DAC or the Voice CODEC to end audio + * playback or recording as required. + * + * @param handle Device handle from pmic_audio_open() call. + * + * @retval PMIC_SUCCESS If the device was successful disabled. + * @retval PMIC_PARAMETER_ERROR If the handle is invalid. + * @retval PMIC_ERROR If the device could not be disabled. + */ +PMIC_STATUS pmic_audio_disable(const PMIC_AUDIO_HANDLE handle) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + const unsigned int STDAC_DISABLE = SET_BITS(regST_DAC, STDCEN, 1); + const unsigned int VCODEC_DISABLE = SET_BITS(regAUD_CODEC, CDCEN, 1); + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + if ((handle == stDAC.handle) && (stDAC.handleState == HANDLE_IN_USE)) { + rc = pmic_write_reg(REG_AUDIO_STEREO_DAC, 0, STDAC_DISABLE); + } else if ((handle == vCodec.handle) + && (vCodec.handleState == HANDLE_IN_USE)) { + rc = pmic_write_reg(REG_AUDIO_CODEC, 0, VCODEC_DISABLE); + } + if (rc == PMIC_SUCCESS) { + pr_debug("Disabled successfully\n"); + } + /* Exit critical section. */ + up(&mutex); + return rc; +} + +/*! + * @brief Reset the selected audio hardware control registers to their + * power on state. + * + * This resets all of the audio hardware control registers currently + * associated with the device handle back to their power on states. For + * example, if the handle is associated with the Stereo DAC and a + * specific output port and output amplifiers, then this function will + * reset all of those components to their initial power on state. + * + * @param handle Device handle from pmic_audio_open() call. + * + * @retval PMIC_SUCCESS If the reset operation was successful. + * @retval PMIC_PARAMETER_ERROR If the handle is invalid. + * @retval PMIC_ERROR If the reset was unsuccessful. + */ +PMIC_STATUS pmic_audio_reset(const PMIC_AUDIO_HANDLE handle) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + rc = pmic_audio_reset_device(handle); + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Reset all audio hardware control registers to their power on state. + * + * This resets all of the audio hardware control registers back to their + * power on states. Use this function with care since it also invalidates + * (i.e., automatically closes) all currently opened device handles. + * + * @retval PMIC_SUCCESS If the reset operation was successful. + * @retval PMIC_ERROR If the reset was unsuccessful. + */ +PMIC_STATUS pmic_audio_reset_all(void) +{ + PMIC_STATUS rc = PMIC_SUCCESS; + unsigned int audio_ssi_reset = 0; + unsigned int audio_rx1_reset = 0; + /* We need a critical section here to maintain a consistent state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + /* First close all opened device handles, also deregisters callbacks. */ + pmic_audio_close_handle(stDAC.handle); + pmic_audio_close_handle(vCodec.handle); + pmic_audio_close_handle(extStereoIn.handle); + + if (pmic_write_reg(REG_AUDIO_RX_1, RESET_AUDIO_RX_1, + PMIC_ALL_BITS) != PMIC_SUCCESS) { + rc = PMIC_ERROR; + } else { + audio_rx1_reset = 1; + } + if (pmic_write_reg(REG_AUDIO_SSI_NETWORK, RESET_SSI_NETWORK, + PMIC_ALL_BITS) != PMIC_SUCCESS) { + rc = PMIC_ERROR; + } else { + audio_ssi_reset = 1; + } + if (pmic_write_reg + (REG_AUDIO_STEREO_DAC, RESET_ST_DAC, + PMIC_ALL_BITS) != PMIC_SUCCESS) { + rc = PMIC_ERROR; + } else { + /* Also reset the driver state information to match. Note that we + * keep the device handle and event callback settings unchanged + * since these don't affect the actual hardware and we rely on + * the user to explicitly close the handle or deregister callbacks + */ + if (audio_ssi_reset) { + /* better to check if SSI is also reset as some fields are represennted in SSI reg */ + stDAC.busID = AUDIO_DATA_BUS_1; + stDAC.protocol = NORMAL_MSB_JUSTIFIED_MODE; + stDAC.masterSlave = BUS_MASTER_MODE; + stDAC.protocol_set = false; + stDAC.numSlots = USE_2_TIMESLOTS; + stDAC.clockIn = CLOCK_IN_CLIA; + stDAC.samplingRate = STDAC_RATE_44_1_KHZ; + stDAC.clockFreq = STDAC_CLI_13MHZ; + stDAC.invert = NO_INVERT; + stDAC.timeslot = USE_TS0_TS1; + stDAC.config = (PMIC_AUDIO_STDAC_CONFIG) 0; + } + } + + if (pmic_write_reg(REG_AUDIO_CODEC, RESET_AUD_CODEC, + PMIC_ALL_BITS) != PMIC_SUCCESS) { + rc = PMIC_ERROR; + } else { + /* Also reset the driver state information to match. Note that we + * keep the device handle and event callback settings unchanged + * since these don't affect the actual hardware and we rely on + * the user to explicitly close the handle or deregister callbacks + */ + if (audio_ssi_reset) { + vCodec.busID = AUDIO_DATA_BUS_2; + vCodec.protocol = NETWORK_MODE; + vCodec.masterSlave = BUS_SLAVE_MODE; + vCodec.protocol_set = false; + vCodec.numSlots = USE_4_TIMESLOTS; + vCodec.clockIn = CLOCK_IN_CLIB; + vCodec.samplingRate = VCODEC_RATE_8_KHZ; + vCodec.clockFreq = VCODEC_CLI_13MHZ; + vCodec.invert = NO_INVERT; + vCodec.timeslot = USE_TS0; + vCodec.config = + INPUT_HIGHPASS_FILTER | OUTPUT_HIGHPASS_FILTER; + } + } + + if (pmic_write_reg(REG_AUDIO_RX_0, RESET_AUDIO_RX_0, + PMIC_ALL_BITS) != PMIC_SUCCESS) { + rc = PMIC_ERROR; + } else { + /* Also reset the driver state information to match. */ + audioOutput.outputPort = (PMIC_AUDIO_OUTPUT_PORT) NULL; + audioOutput.vCodecoutputPGAGain = OUTPGA_GAIN_0DB; + audioOutput.stDacoutputPGAGain = OUTPGA_GAIN_0DB; + audioOutput.extStereooutputPGAGain = OUTPGA_GAIN_0DB; + audioOutput.balanceLeftGain = BAL_GAIN_0DB; + audioOutput.balanceRightGain = BAL_GAIN_0DB; + audioOutput.monoAdderGain = MONOADD_GAIN_0DB; + audioOutput.config = (PMIC_AUDIO_OUTPUT_CONFIG) 0; + audioOutput.vCodecOut = VCODEC_DIRECT_OUT; + } + + if (pmic_write_reg(REG_AUDIO_TX, RESET_AUDIO_TX, + PMIC_ALL_BITS) != PMIC_SUCCESS) { + rc = PMIC_ERROR; + } else { + /* Also reset the driver state information to match. Note that we + * reset the vCodec fields since all of the input/recording + * devices are only connected to the Voice CODEC and are managed + * as part of the Voice CODEC state. + */ + if (audio_rx1_reset) { + vCodec.leftChannelMic.mic = NO_MIC; + vCodec.leftChannelMic.micOnOff = MICROPHONE_OFF; + vCodec.leftChannelMic.ampMode = CURRENT_TO_VOLTAGE; + vCodec.leftChannelMic.gain = MIC_GAIN_0DB; + vCodec.rightChannelMic.mic = NO_MIC; + vCodec.rightChannelMic.micOnOff = MICROPHONE_OFF; + vCodec.rightChannelMic.ampMode = AMP_OFF; + vCodec.rightChannelMic.gain = MIC_GAIN_0DB; + } + } + /* Finally, also reset any global state variables. */ + headsetState = NO_HEADSET; + /* Exit the critical section. */ + up(&mutex); + return rc; +} + +/*! + * @brief Set the Audio callback function. + * + * Register a callback function that will be used to signal PMIC audio + * events. For example, the OSS audio driver should register a callback + * function in order to be notified of headset connect/disconnect events. + * + * @param func A pointer to the callback function. + * @param eventMask A mask selecting events to be notified. + * @param hs_state To know the headset state. + * + * + * + * @retval PMIC_SUCCESS If the callback was successfully + * registered. + * @retval PMIC_PARAMETER_ERROR If the handle or the eventMask is invalid. + */ +PMIC_STATUS pmic_audio_set_callback(void *func, + const PMIC_AUDIO_EVENTS eventMask, + PMIC_HS_STATE *hs_state) +{ + unsigned long flags; + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + pmic_event_callback_t eventNotify; + + /* We need to start a critical section here to ensure a consistent state + * in case simultaneous calls to pmic_audio_set_callback() are made. In + * that case, we must serialize the calls to ensure that the "callback" + * and "eventMask" state variables are always consistent. + * + * Note that we don't actually need to acquire the spinlock until later + * when we are finally ready to update the "callback" and "eventMask" + * state variables which are shared with the interrupt handler. + */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + rc = PMIC_ERROR; + /* Register for PMIC events from the core protocol driver. */ + if (eventMask & MICROPHONE_DETECTED) { + /* We need to register for the A1 amplifier interrupt. */ + eventNotify.func = func; + eventNotify.param = (void *)(CORE_EVENT_MC2BI); + rc = pmic_event_subscribe(EVENT_MC2BI, eventNotify); + + if (rc != PMIC_SUCCESS) { + pr_debug + ("%s: pmic_event_subscribe() for EVENT_HSDETI " + "failed\n", __FILE__); + goto End; + } + } + + if (eventMask & HEADSET_DETECTED) { + /* We need to register for the A1 amplifier interrupt. */ + eventNotify.func = func; + eventNotify.param = (void *)(CORE_EVENT_HSDETI); + rc = pmic_event_subscribe(EVENT_HSDETI, eventNotify); + + if (rc != PMIC_SUCCESS) { + pr_debug + ("%s: pmic_event_subscribe() for EVENT_HSDETI " + "failed\n", __FILE__); + goto Cleanup_HDT; + } + + } + if (eventMask & HEADSET_STEREO) { + /* We need to register for the A1 amplifier interrupt. */ + eventNotify.func = func; + eventNotify.param = (void *)(CORE_EVENT_HSLI); + rc = pmic_event_subscribe(EVENT_HSLI, eventNotify); + + if (rc != PMIC_SUCCESS) { + pr_debug + ("%s: pmic_event_subscribe() for EVENT_HSLI " + "failed\n", __FILE__); + goto Cleanup_HST; + } + } + if (eventMask & HEADSET_THERMAL_SHUTDOWN) { + /* We need to register for the A1 amplifier interrupt. */ + eventNotify.func = func; + eventNotify.param = (void *)(CORE_EVENT_ALSPTHI); + rc = pmic_event_subscribe(EVENT_ALSPTHI, eventNotify); + + if (rc != PMIC_SUCCESS) { + pr_debug + ("%s: pmic_event_subscribe() for EVENT_ALSPTHI " + "failed\n", __FILE__); + goto Cleanup_TSD; + } + pr_debug("Registered for EVENT_ALSPTHI\n"); + } + if (eventMask & HEADSET_SHORT_CIRCUIT) { + /* We need to register for the A1 amplifier interrupt. */ + eventNotify.func = func; + eventNotify.param = (void *)(CORE_EVENT_AHSSHORTI); + rc = pmic_event_subscribe(EVENT_AHSSHORTI, eventNotify); + + if (rc != PMIC_SUCCESS) { + pr_debug + ("%s: pmic_event_subscribe() for EVENT_AHSSHORTI " + "failed\n", __FILE__); + goto Cleanup_HShort; + } + pr_debug("Registered for EVENT_AHSSHORTI\n"); + } + + /* We also need the spinlock here to avoid possible problems + * with the interrupt handler when we update the + * "callback" and "eventMask" state variables. + */ + spin_lock_irqsave(&lock, flags); + + /* Successfully registered for all events. */ + event_state.callback = func; + event_state.eventMask = eventMask; + + /* The spinlock is no longer needed now that we've finished + * updating the "callback" and "eventMask" state variables. + */ + spin_unlock_irqrestore(&lock, flags); + + goto End; + + /* This section unregisters any already registered events if we should + * encounter an error partway through the registration process. Note + * that we don't check the return status here since it is already set + * to PMIC_ERROR before we get here. + */ + Cleanup_HShort: + + if (eventMask & HEADSET_SHORT_CIRCUIT) { + eventNotify.func = func; + eventNotify.param = (void *)(CORE_EVENT_AHSSHORTI); + pmic_event_unsubscribe(EVENT_AHSSHORTI, eventNotify); + } + + Cleanup_TSD: + + if (eventMask & HEADSET_THERMAL_SHUTDOWN) { + eventNotify.func = func; + eventNotify.param = (void *)(CORE_EVENT_ALSPTHI); + pmic_event_unsubscribe(EVENT_ALSPTHI, eventNotify); + } + + Cleanup_HST: + + if (eventMask & HEADSET_STEREO) { + eventNotify.func = func; + eventNotify.param = (void *)(CORE_EVENT_HSLI); + pmic_event_unsubscribe(EVENT_HSLI, eventNotify); + } + + Cleanup_HDT: + + if (eventMask & HEADSET_DETECTED) { + eventNotify.func = func; + eventNotify.param = (void *)(CORE_EVENT_HSDETI); + pmic_event_unsubscribe(EVENT_HSDETI, eventNotify); + } + + End: + /* Exit the critical section. */ + up(&mutex); + return rc; +} + +/*! + * @brief Deregisters the existing audio callback function. + * + * Deregister the callback function that was previously registered by calling + * pmic_audio_set_callback(). + * + * + * @retval PMIC_SUCCESS If the callback was successfully + * deregistered. + * @retval PMIC_PARAMETER_ERROR If the handle is invalid. + */ +PMIC_STATUS pmic_audio_clear_callback(void) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + + /* We need a critical section to maintain a consistent state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if (event_state.callback != (PMIC_AUDIO_CALLBACK) NULL) { + rc = pmic_audio_deregister(&(event_state.callback), + &(event_state.eventMask)); + } + + /* Exit the critical section. */ + up(&mutex); + return rc; +} + +/*! + * @brief Get the current audio callback function settings. + * + * Get the current callback function and event mask. + * + * @param func The current callback function. + * @param eventMask The current event selection mask. + * + * @retval PMIC_SUCCESS If the callback information was + * successfully retrieved. + * @retval PMIC_PARAMETER_ERROR If the handle is invalid. + */ +PMIC_STATUS pmic_audio_get_callback(PMIC_AUDIO_CALLBACK * const func, + PMIC_AUDIO_EVENTS * const eventMask) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + + /* We only need to acquire the mutex here because we will not be updating + * anything that may affect the interrupt handler. We just need to ensure + * that the callback fields are not changed while we are in the critical + * section by calling either pmic_audio_set_callback() or + * pmic_audio_clear_callback(). + */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((func != (PMIC_AUDIO_CALLBACK *) NULL) && + (eventMask != (PMIC_AUDIO_EVENTS *) NULL)) { + + *func = event_state.callback; + *eventMask = event_state.eventMask; + + rc = PMIC_SUCCESS; + } + + /* Exit the critical section. */ + up(&mutex); + return rc; +} + +/*! + * @brief Enable the anti-pop circuitry to avoid extra noise when inserting + * or removing a external device (e.g., a headset). + * + * Enable the use of the built-in anti-pop circuitry to prevent noise from + * being generated when an external audio device is inserted or removed + * from an audio plug. A slow ramp speed may be needed to avoid extra noise. + * + * @param rampSpeed The desired anti-pop circuitry ramp speed. + * + * @retval PMIC_SUCCESS If the anti-pop circuitry was successfully + * enabled. + * @retval PMIC_ERROR If the anti-pop circuitry could not be + * enabled. + */ +PMIC_STATUS pmic_audio_antipop_enable(const PMIC_AUDIO_ANTI_POP_RAMP_SPEED + rampSpeed) +{ + PMIC_STATUS rc = PMIC_ERROR; + unsigned int reg_value = 0; + const unsigned int reg_mask = SET_BITS(regAUDIO_RX_0, BIASEN, 1) | + SET_BITS(regAUDIO_RX_0, BIASSPEED, 1); + + /* No critical section required here since we are not updating any + * global data. + */ + + /* + * Antipop is enabled by enabling the BIAS (BIASEN) and setting the + * BIASSPEED . + * BIASEN is just to make sure that BIAS is enabled + */ + reg_value = SET_BITS(regAUDIO_RX_0, BIASEN, 1) + | SET_BITS(regAUDIO_RX_0, BIASSPEED, 0) | SET_BITS(regAUDIO_RX_0, + HSLDETEN, 1); + rc = pmic_write_reg(REG_AUDIO_RX_0, reg_value, reg_mask); + return rc; +} + +/*! + * @brief Disable the anti-pop circuitry. + * + * Disable the use of the built-in anti-pop circuitry to prevent noise from + * being generated when an external audio device is inserted or removed + * from an audio plug. + * + * @retval PMIC_SUCCESS If the anti-pop circuitry was successfully + * disabled. + * @retval PMIC_ERROR If the anti-pop circuitry could not be + * disabled. + */ +PMIC_STATUS pmic_audio_antipop_disable(void) +{ + PMIC_STATUS rc = PMIC_ERROR; + const unsigned int reg_mask = SET_BITS(regAUDIO_RX_0, BIASSPEED, 1) | + SET_BITS(regAUDIO_RX_0, BIASEN, 1); + const unsigned int reg_write = SET_BITS(regAUDIO_RX_0, BIASSPEED, 1) | + SET_BITS(regAUDIO_RX_0, BIASEN, 0); + + /* No critical section required here since we are not updating any + * global data. + */ + + /* + * Antipop is disabled by setting BIASSPEED = 0. BIASEN bit remains set + * as only antipop needs to be disabled + */ + rc = pmic_write_reg(REG_AUDIO_RX_0, reg_write, reg_mask); + + return rc; +} + +/*! + * @brief Performs a reset of the Voice CODEC/Stereo DAC digital filter. + * + * The digital filter should be reset whenever the clock or sampling rate + * configuration has been changed. + * + * @param handle Device handle from pmic_audio_open() call. + * + * @retval PMIC_SUCCESS If the digital filter was successfully + * reset. + * @retval PMIC_ERROR If the digital filter could not be reset. + */ +PMIC_STATUS pmic_audio_digital_filter_reset(const PMIC_AUDIO_HANDLE handle) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_mask = 0; + + /* No critical section required here since we are not updating any + * global data. + */ + + if ((handle == stDAC.handle) && (stDAC.handleState == HANDLE_IN_USE)) { + reg_mask = SET_BITS(regST_DAC, STDCRESET, 1); + if (pmic_write_reg(REG_AUDIO_STEREO_DAC, reg_mask, + reg_mask) != PMIC_SUCCESS) { + rc = PMIC_ERROR; + } else { + pr_debug("STDAC filter reset\n"); + } + + } else if ((handle == vCodec.handle) && + (vCodec.handleState == HANDLE_IN_USE)) { + reg_mask = SET_BITS(regAUD_CODEC, CDCRESET, 1); + if (pmic_write_reg(REG_AUDIO_CODEC, reg_mask, + reg_mask) != PMIC_SUCCESS) { + rc = PMIC_ERROR; + } else { + pr_debug("CODEC filter reset\n"); + } + } + return rc; +} + +/*! + * @brief Get the most recent PTT button voltage reading. + * + * This feature is not supported by mc13783 + * @param level PTT button level. + * + * @retval PMIC_SUCCESS If the most recent PTT button voltage was + * returned. + * @retval PMIC_PARAMETER_ERROR If a NULL pointer argument was given. + */ +PMIC_STATUS pmic_audio_get_ptt_button_level(unsigned int *const level) +{ + PMIC_STATUS rc = PMIC_NOT_SUPPORTED; + return rc; +} + +#ifdef DEBUG_AUDIO + +/*! + * @brief Provide a hexadecimal dump of all PMIC audio registers (DEBUG only) + * + * This function is intended strictly for debugging purposes only and will + * print the current values of the following PMIC registers: + * + * - AUD_CODEC + * - ST_DAC + * - AUDIO_RX_0 + * - AUDIO_RX_1 + * - AUDIO_TX + * - AUDIO_SSI_NW + * + * The register fields will not be decoded. + * + * Note that we don't dump any of the arbitration bits because we cannot + * access the true arbitration bit settings when reading the registers + * from the secondary SPI bus. + * + * Also note that we must not call this function with interrupts disabled, + * for example, while holding a spinlock, because calls to pmic_read_reg() + * eventually end up in the SPI driver which will want to perform a + * schedule() operation. If schedule() is called with interrupts disabled, + * then you will see messages like the following: + * + * BUG: scheduling while atomic: ... + * + */ +void pmic_audio_dump_registers(void) +{ + unsigned int reg_value = 0; + + /* Dump the AUD_CODEC (Voice CODEC) register. */ + if (pmic_read_reg(REG_AUDIO_CODEC, ®_value, REG_FULLMASK) + == PMIC_SUCCESS) { + pr_debug("Audio Codec = 0x%x\n", reg_value); + } else { + pr_debug("Failed to read audio codec\n"); + } + + /* Dump the ST DAC (Stereo DAC) register. */ + if (pmic_read_reg + (REG_AUDIO_STEREO_DAC, ®_value, REG_FULLMASK) == PMIC_SUCCESS) { + pr_debug("Stereo DAC = 0x%x\n", reg_value); + } else { + pr_debug("Failed to read Stereo DAC\n"); + } + + /* Dump the SSI NW register. */ + if (pmic_read_reg + (REG_AUDIO_SSI_NETWORK, ®_value, REG_FULLMASK) == PMIC_SUCCESS) { + pr_debug("SSI Network = 0x%x\n", reg_value); + } else { + pr_debug("Failed to read SSI network\n"); + } + + /* Dump the Audio RX 0 register. */ + if (pmic_read_reg(REG_AUDIO_RX_0, ®_value, REG_FULLMASK) + == PMIC_SUCCESS) { + pr_debug("Audio RX 0 = 0x%x\n", reg_value); + } else { + pr_debug("Failed to read audio RX 0\n"); + } + + /* Dump the Audio RX 1 register. */ + if (pmic_read_reg(REG_AUDIO_RX_1, ®_value, REG_FULLMASK) + == PMIC_SUCCESS) { + pr_debug("Audio RX 1 = 0x%x\n", reg_value); + } else { + pr_debug("Failed to read audio RX 1\n"); + } + /* Dump the Audio TX register. */ + if (pmic_read_reg(REG_AUDIO_TX, ®_value, REG_FULLMASK) == + PMIC_SUCCESS) { + pr_debug("Audio Tx = 0x%x\n", reg_value); + } else { + pr_debug("Failed to read audio TX\n"); + } + +} + +#endif /* DEBUG_AUDIO */ + +/*@}*/ + +/************************************************************************* + * General Voice CODEC configuration. + ************************************************************************* + */ + +/*! + * @name General Voice CODEC Setup and Configuration APIs + * Functions for general setup and configuration of the PMIC Voice + * CODEC hardware. + */ +/*@{*/ + +/*! + * @brief Set the Voice CODEC clock source and operating characteristics. + * + * Define the Voice CODEC clock source and operating characteristics. This + * must be done before the Voice CODEC is enabled. + * + * + * + * @param handle Device handle from pmic_audio_open() call. + * @param clockIn Select the clock signal source. + * @param clockFreq Select the clock signal frequency. + * @param samplingRate Select the audio data sampling rate. + * @param invert Enable inversion of the frame sync and/or + * bit clock inputs. + * + * @retval PMIC_SUCCESS If the Voice CODEC clock settings were + * successfully configured. + * @retval PMIC_PARAMETER_ERROR If the handle or clock configuration was + * invalid. + * @retval PMIC_ERROR If the Voice CODEC clock configuration + * could not be set. + */ +PMIC_STATUS pmic_audio_vcodec_set_clock(const PMIC_AUDIO_HANDLE handle, + const PMIC_AUDIO_CLOCK_IN_SOURCE + clockIn, + const PMIC_AUDIO_VCODEC_CLOCK_IN_FREQ + clockFreq, + const PMIC_AUDIO_VCODEC_SAMPLING_RATE + samplingRate, + const PMIC_AUDIO_CLOCK_INVERT invert) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_value = 0; + unsigned int reg_mask = 0; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + /* Validate all of the calling parameters. */ + if (handle == (PMIC_AUDIO_HANDLE) NULL) { + rc = PMIC_PARAMETER_ERROR; + } else if ((handle == vCodec.handle) && + (vCodec.handleState == HANDLE_IN_USE)) { + if ((clockIn != CLOCK_IN_CLIA) && (clockIn != CLOCK_IN_CLIB)) { + rc = PMIC_PARAMETER_ERROR; + } else if (!((clockFreq >= VCODEC_CLI_13MHZ) + && (clockFreq <= VCODEC_CLI_33_6MHZ))) { + rc = PMIC_PARAMETER_ERROR; + } else if ((samplingRate != VCODEC_RATE_8_KHZ) + && (samplingRate != VCODEC_RATE_16_KHZ)) { + rc = PMIC_PARAMETER_ERROR; + } else if (!((invert >= NO_INVERT) + && (invert <= INVERT_FRAMESYNC))) { + rc = PMIC_PARAMETER_ERROR; + } else { + /*reg_mask = SET_BITS(regAUD_CODEC, CDCCLK, 7) | + SET_BITS(regAUD_CODEC, CDCCLKSEL, 1) | + SET_BITS(regAUD_CODEC, CDCFS8K16K, 1) | + SET_BITS(regAUD_CODEC, CDCBCLINV, 1) | + SET_BITS(regAUD_CODEC, CDCFSINV, 1); */ + if (clockIn == CLOCK_IN_CLIA) { + reg_value = + SET_BITS(regAUD_CODEC, CDCCLKSEL, 0); + } else { + reg_value = + SET_BITS(regAUD_CODEC, CDCCLKSEL, 1); + } + reg_mask = SET_BITS(regAUD_CODEC, CDCCLKSEL, 1); + if (PMIC_SUCCESS != + pmic_write_reg(REG_AUDIO_CODEC, + reg_value, reg_mask)) + return PMIC_ERROR; + + reg_value = 0; + if (clockFreq == VCODEC_CLI_13MHZ) { + reg_value |= SET_BITS(regAUD_CODEC, CDCCLK, 0); + } else if (clockFreq == VCODEC_CLI_15_36MHZ) { + reg_value |= SET_BITS(regAUD_CODEC, CDCCLK, 1); + } else if (clockFreq == VCODEC_CLI_16_8MHZ) { + reg_value |= SET_BITS(regAUD_CODEC, CDCCLK, 2); + } else if (clockFreq == VCODEC_CLI_26MHZ) { + reg_value |= SET_BITS(regAUD_CODEC, CDCCLK, 4); + } else { + reg_value |= SET_BITS(regAUD_CODEC, CDCCLK, 7); + } + reg_mask = SET_BITS(regAUD_CODEC, CDCCLK, 7); + if (PMIC_SUCCESS != + pmic_write_reg(REG_AUDIO_CODEC, + reg_value, reg_mask)) + return PMIC_ERROR; + + reg_value = 0; + reg_mask = 0; + + if (samplingRate == VCODEC_RATE_8_KHZ) { + reg_value |= + SET_BITS(regAUD_CODEC, CDCFS8K16K, 0); + } else { + reg_value |= + SET_BITS(regAUD_CODEC, CDCFS8K16K, 1); + } + reg_mask = SET_BITS(regAUD_CODEC, CDCFS8K16K, 1); + if (PMIC_SUCCESS != + pmic_write_reg(REG_AUDIO_CODEC, + reg_value, reg_mask)) + return PMIC_ERROR; + reg_value = 0; + reg_mask = + SET_BITS(regAUD_CODEC, CDCBCLINV, + 1) | SET_BITS(regAUD_CODEC, CDCFSINV, 1); + + if (invert & INVERT_BITCLOCK) { + reg_value |= + SET_BITS(regAUD_CODEC, CDCBCLINV, 1); + } + if (invert & INVERT_FRAMESYNC) { + reg_value |= + SET_BITS(regAUD_CODEC, CDCFSINV, 1); + } + if (invert & NO_INVERT) { + reg_value |= + SET_BITS(regAUD_CODEC, CDCBCLINV, 0); + reg_value |= + SET_BITS(regAUD_CODEC, CDCFSINV, 0); + } + if (pmic_write_reg + (REG_AUDIO_CODEC, reg_value, + reg_mask) != PMIC_SUCCESS) { + rc = PMIC_ERROR; + } else { + pr_debug("CODEC clock set\n"); + vCodec.clockIn = clockIn; + vCodec.clockFreq = clockFreq; + vCodec.samplingRate = samplingRate; + vCodec.invert = invert; + } + + } + + } else { + rc = PMIC_PARAMETER_ERROR; + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Get the Voice CODEC clock source and operating characteristics. + * + * Get the current Voice CODEC clock source and operating characteristics. + * + * @param handle Device handle from pmic_audio_open() call. + * @param clockIn The clock signal source. + * @param clockFreq The clock signal frequency. + * @param samplingRate The audio data sampling rate. + * @param invert Inversion of the frame sync and/or + * bit clock inputs is enabled/disabled. + * + * @retval PMIC_SUCCESS If the Voice CODEC clock settings were + * successfully retrieved. + * @retval PMIC_PARAMETER_ERROR If the handle invalid. + * @retval PMIC_ERROR If the Voice CODEC clock configuration + * could not be retrieved. + */ +PMIC_STATUS pmic_audio_vcodec_get_clock(const PMIC_AUDIO_HANDLE handle, + PMIC_AUDIO_CLOCK_IN_SOURCE * + const clockIn, + PMIC_AUDIO_VCODEC_CLOCK_IN_FREQ * + const clockFreq, + PMIC_AUDIO_VCODEC_SAMPLING_RATE * + const samplingRate, + PMIC_AUDIO_CLOCK_INVERT * const invert) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + + /* Use a critical section to ensure that we return a consistent state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == vCodec.handle) && + (vCodec.handleState == HANDLE_IN_USE) && + (clockIn != (PMIC_AUDIO_CLOCK_IN_SOURCE *) NULL) && + (clockFreq != (PMIC_AUDIO_VCODEC_CLOCK_IN_FREQ *) NULL) && + (samplingRate != (PMIC_AUDIO_VCODEC_SAMPLING_RATE *) NULL) && + (invert != (PMIC_AUDIO_CLOCK_INVERT *) NULL)) { + *clockIn = vCodec.clockIn; + *clockFreq = vCodec.clockFreq; + *samplingRate = vCodec.samplingRate; + *invert = vCodec.invert; + + rc = PMIC_SUCCESS; + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Set the Voice CODEC primary audio channel timeslot. + * + * Set the Voice CODEC primary audio channel timeslot. This function must be + * used if the default timeslot for the primary audio channel is to be changed. + * + * @param handle Device handle from pmic_audio_open() call. + * @param timeslot Select the primary audio channel timeslot. + * + * @retval PMIC_SUCCESS If the Voice CODEC primary audio channel + * timeslot was successfully configured. + * @retval PMIC_PARAMETER_ERROR If the handle or audio channel timeslot + * was invalid. + * @retval PMIC_ERROR If the Voice CODEC primary audio channel + * timeslot could not be set. + */ +PMIC_STATUS pmic_audio_vcodec_set_rxtx_timeslot(const PMIC_AUDIO_HANDLE handle, + const PMIC_AUDIO_VCODEC_TIMESLOT + timeslot) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_write = 0; + const unsigned int reg_mask = SET_BITS(regSSI_NETWORK, CDCTXRXSLOT, 3); + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == vCodec.handle) && + (vCodec.handleState == HANDLE_IN_USE) && + ((timeslot == USE_TS0) || (timeslot == USE_TS1) || + (timeslot == USE_TS2) || (timeslot == USE_TS3))) { + reg_write = SET_BITS(regSSI_NETWORK, CDCTXRXSLOT, timeslot); + + rc = pmic_write_reg(REG_AUDIO_SSI_NETWORK, reg_write, reg_mask); + + if (rc == PMIC_SUCCESS) { + vCodec.timeslot = timeslot; + } + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Get the current Voice CODEC primary audio channel timeslot. + * + * Get the current Voice CODEC primary audio channel timeslot. + * + * @param handle Device handle from pmic_audio_open() call. + * @param timeslot The primary audio channel timeslot. + * + * @retval PMIC_SUCCESS If the Voice CODEC primary audio channel + * timeslot was successfully retrieved. + * @retval PMIC_PARAMETER_ERROR If the handle was invalid. + * @retval PMIC_ERROR If the Voice CODEC primary audio channel + * timeslot could not be retrieved. + */ +PMIC_STATUS pmic_audio_vcodec_get_rxtx_timeslot(const PMIC_AUDIO_HANDLE handle, + PMIC_AUDIO_VCODEC_TIMESLOT * + const timeslot) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == vCodec.handle) && + (vCodec.handleState == HANDLE_IN_USE) && + (timeslot != (PMIC_AUDIO_VCODEC_TIMESLOT *) NULL)) { + *timeslot = vCodec.timeslot; + + rc = PMIC_SUCCESS; + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Set the Voice CODEC secondary recording audio channel timeslot. + * + * Set the Voice CODEC secondary audio channel timeslot. This function must be + * used if the default timeslot for the secondary audio channel is to be + * changed. The secondary audio channel timeslot is used to transmit the audio + * data that was recorded by the Voice CODEC from the secondary audio input + * channel. + * + * @param handle Device handle from pmic_audio_open() call. + * @param timeslot Select the secondary audio channel timeslot. + * + * @retval PMIC_SUCCESS If the Voice CODEC secondary audio channel + * timeslot was successfully configured. + * @retval PMIC_PARAMETER_ERROR If the handle or audio channel timeslot + * was invalid. + * @retval PMIC_ERROR If the Voice CODEC secondary audio channel + * timeslot could not be set. + */ +PMIC_STATUS pmic_audio_vcodec_set_secondary_txslot(const PMIC_AUDIO_HANDLE + handle, + const + PMIC_AUDIO_VCODEC_TIMESLOT + timeslot) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_mask = SET_BITS(regSSI_NETWORK, CDCTXSECSLOT, 3); + unsigned int reg_write = 0; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == vCodec.handle) && (vCodec.handleState == HANDLE_IN_USE)) { + /* How to handle primary slot and secondary slot being the same */ + if ((timeslot >= USE_TS0) && (timeslot <= USE_TS3) + && (timeslot != vCodec.timeslot)) { + reg_write = + SET_BITS(regSSI_NETWORK, CDCTXSECSLOT, timeslot); + + rc = pmic_write_reg(REG_AUDIO_SSI_NETWORK, + reg_write, reg_mask); + + if (rc == PMIC_SUCCESS) { + vCodec.secondaryTXtimeslot = timeslot; + } + } + + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Get the Voice CODEC secondary recording audio channel timeslot. + * + * Get the Voice CODEC secondary audio channel timeslot. + * + * @param handle Device handle from pmic_audio_open() call. + * @param timeslot The secondary audio channel timeslot. + * + * @retval PMIC_SUCCESS If the Voice CODEC secondary audio channel + * timeslot was successfully retrieved. + * @retval PMIC_PARAMETER_ERROR If the handle was invalid. + * @retval PMIC_ERROR If the Voice CODEC secondary audio channel + * timeslot could not be retrieved. + */ +PMIC_STATUS pmic_audio_vcodec_get_secondary_txslot(const PMIC_AUDIO_HANDLE + handle, + PMIC_AUDIO_VCODEC_TIMESLOT * + const timeslot) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == vCodec.handle) && + (vCodec.handleState == HANDLE_IN_USE) && + (timeslot != (PMIC_AUDIO_VCODEC_TIMESLOT *) NULL)) { + rc = PMIC_SUCCESS; + *timeslot = vCodec.secondaryTXtimeslot; + } + + /* Exit the critical section. */ + up(&mutex); + return rc; +} + +/*! + * @brief Set/Enable the Voice CODEC options. + * + * Set or enable various Voice CODEC options. The available options include + * the use of dithering, highpass digital filters, and loopback modes. + * + * @param handle Device handle from pmic_audio_open() call. + * @param config The Voice CODEC options to enable. + * + * @retval PMIC_SUCCESS If the Voice CODEC options were + * successfully configured. + * @retval PMIC_PARAMETER_ERROR If the handle or Voice CODEC options + * were invalid. + * @retval PMIC_ERROR If the Voice CODEC options could not be + * successfully set/enabled. + */ +PMIC_STATUS pmic_audio_vcodec_set_config(const PMIC_AUDIO_HANDLE handle, + const PMIC_AUDIO_VCODEC_CONFIG config) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_write = 0; + unsigned int reg_mask = 0; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == vCodec.handle) && (vCodec.handleState == HANDLE_IN_USE)) { + if (config & DITHERING) { + reg_write = SET_BITS(regAUD_CODEC, CDCDITH, 0); + reg_mask = SET_BITS(regAUD_CODEC, CDCDITH, 1); + } + + if (config & INPUT_HIGHPASS_FILTER) { + reg_write |= SET_BITS(regAUD_CODEC, AUDIHPF, 1); + reg_mask |= SET_BITS(regAUD_CODEC, AUDIHPF, 1); + } + + if (config & OUTPUT_HIGHPASS_FILTER) { + reg_write |= SET_BITS(regAUD_CODEC, AUDOHPF, 1); + reg_mask |= SET_BITS(regAUD_CODEC, AUDOHPF, 1); + } + + if (config & DIGITAL_LOOPBACK) { + reg_write |= SET_BITS(regAUD_CODEC, CDCDLM, 1); + reg_mask |= SET_BITS(regAUD_CODEC, CDCDLM, 1); + } + + if (config & ANALOG_LOOPBACK) { + reg_write |= SET_BITS(regAUD_CODEC, CDCALM, 1); + reg_mask |= SET_BITS(regAUD_CODEC, CDCALM, 1); + } + + if (config & VCODEC_MASTER_CLOCK_OUTPUTS) { + reg_write |= SET_BITS(regAUD_CODEC, CDCCLKEN, 1) | + SET_BITS(regAUD_CODEC, CDCTS, 0); + reg_mask |= SET_BITS(regAUD_CODEC, CDCCLKEN, 1) | + SET_BITS(regAUD_CODEC, CDCTS, 1); + + } + + if (config & TRISTATE_TS) { + reg_write |= SET_BITS(regAUD_CODEC, CDCTS, 1); + reg_mask |= SET_BITS(regAUD_CODEC, CDCTS, 1); + } + + if (reg_mask == 0) { + /* We should not reach this point without having to configure + * anything so we flag it as an error. + */ + rc = PMIC_ERROR; + } else { + rc = pmic_write_reg(REG_AUDIO_CODEC, + reg_write, reg_mask); + } + + if (rc == PMIC_SUCCESS) { + vCodec.config |= config; + } + } + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Clear/Disable the Voice CODEC options. + * + * Clear or disable various Voice CODEC options. + * + * @param handle Device handle from pmic_audio_open() call. + * @param config The Voice CODEC options to be cleared/disabled. + * + * @retval PMIC_SUCCESS If the Voice CODEC options were + * successfully cleared/disabled. + * @retval PMIC_PARAMETER_ERROR If the handle or the Voice CODEC options + * were invalid. + * @retval PMIC_ERROR If the Voice CODEC options could not be + * cleared/disabled. + */ +PMIC_STATUS pmic_audio_vcodec_clear_config(const PMIC_AUDIO_HANDLE handle, + const PMIC_AUDIO_VCODEC_CONFIG + config) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_write = 0; + unsigned int reg_mask = 0; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == vCodec.handle) && (vCodec.handleState == HANDLE_IN_USE)) { + if (config & DITHERING) { + reg_mask = SET_BITS(regAUD_CODEC, CDCDITH, 1); + reg_write = SET_BITS(regAUD_CODEC, CDCDITH, 1); + } + + if (config & INPUT_HIGHPASS_FILTER) { + reg_mask |= SET_BITS(regAUD_CODEC, AUDIHPF, 1); + } + + if (config & OUTPUT_HIGHPASS_FILTER) { + reg_mask |= SET_BITS(regAUD_CODEC, AUDOHPF, 1); + } + + if (config & DIGITAL_LOOPBACK) { + reg_mask |= SET_BITS(regAUD_CODEC, CDCDLM, 1); + } + + if (config & ANALOG_LOOPBACK) { + reg_mask |= SET_BITS(regAUD_CODEC, CDCALM, 1); + } + + if (config & VCODEC_MASTER_CLOCK_OUTPUTS) { + reg_mask |= SET_BITS(regAUD_CODEC, CDCCLKEN, 1); + } + + if (config & TRISTATE_TS) { + reg_mask |= SET_BITS(regAUD_CODEC, CDCTS, 1); + } + + if (reg_mask == 0) { + /* We should not reach this point without having to configure + * anything so we flag it as an error. + */ + rc = PMIC_ERROR; + } else { + rc = pmic_write_reg(REG_AUDIO_CODEC, + reg_write, reg_mask); + } + + if (rc == PMIC_SUCCESS) { + vCodec.config |= config; + } + + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Get the current Voice CODEC options. + * + * Get the current Voice CODEC options. + * + * @param handle Device handle from pmic_audio_open() call. + * @param config The current set of Voice CODEC options. + * + * @retval PMIC_SUCCESS If the Voice CODEC options were + * successfully retrieved. + * @retval PMIC_PARAMETER_ERROR If the handle was invalid. + * @retval PMIC_ERROR If the Voice CODEC options could not be + * retrieved. + */ +PMIC_STATUS pmic_audio_vcodec_get_config(const PMIC_AUDIO_HANDLE handle, + PMIC_AUDIO_VCODEC_CONFIG * + const config) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == vCodec.handle) && + (vCodec.handleState == HANDLE_IN_USE) && + (config != (PMIC_AUDIO_VCODEC_CONFIG *) NULL)) { + *config = vCodec.config; + + rc = PMIC_SUCCESS; + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Enable the Voice CODEC bypass audio pathway. + * + * Enables the Voice CODEC bypass pathway for audio data. This allows direct + * output of the voltages on the TX data bus line to the output amplifiers + * (bypassing the digital-to-analog converters within the Voice CODEC). + * + * @param handle Device handle from pmic_audio_open() call. + * + * @retval PMIC_SUCCESS If the Voice CODEC bypass was successfully + * enabled. + * @retval PMIC_PARAMETER_ERROR If the handle was invalid. + * @retval PMIC_ERROR If the Voice CODEC bypass could not be + * enabled. + */ +PMIC_STATUS pmic_audio_vcodec_enable_bypass(const PMIC_AUDIO_HANDLE handle) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + const unsigned int reg_write = SET_BITS(regAUD_CODEC, CDCBYP, 1); + const unsigned int reg_mask = SET_BITS(regAUD_CODEC, CDCBYP, 1); + + /* No critical section required here since we are not updating any + * global data. + */ + + if ((handle == vCodec.handle) && (vCodec.handleState == HANDLE_IN_USE)) { + rc = pmic_write_reg(REG_AUDIO_CODEC, reg_write, reg_mask); + } + + return rc; +} + +/*! + * @brief Disable the Voice CODEC bypass audio pathway. + * + * Disables the Voice CODEC bypass pathway for audio data. This means that + * the TX data bus line will deliver digital data to the digital-to-analog + * converters within the Voice CODEC. + * + * @param handle Device handle from pmic_audio_open() call. + * + * @retval PMIC_SUCCESS If the Voice CODEC bypass was successfully + * disabled. + * @retval PMIC_PARAMETER_ERROR If the handle was invalid. + * @retval PMIC_ERROR If the Voice CODEC bypass could not be + * disabled. + */ +PMIC_STATUS pmic_audio_vcodec_disable_bypass(const PMIC_AUDIO_HANDLE handle) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + const unsigned int reg_write = 0; + const unsigned int reg_mask = SET_BITS(regAUD_CODEC, CDCBYP, 1); + + /* No critical section required here since we are not updating any + * global data. + */ + + if ((handle == vCodec.handle) && (vCodec.handleState == HANDLE_IN_USE)) { + rc = pmic_write_reg(REG_AUDIO_CODEC, reg_write, reg_mask); + } + + return rc; +} + +/*@}*/ + +/************************************************************************* + * General Stereo DAC configuration. + ************************************************************************* + */ + +/*! + * @name General Stereo DAC Setup and Configuration APIs + * Functions for general setup and configuration of the PMIC Stereo + * DAC hardware. + */ +/*@{*/ + +/*! + * @brief Set the Stereo DAC clock source and operating characteristics. + * + * Define the Stereo DAC clock source and operating characteristics. This + * must be done before the Stereo DAC is enabled. + * + * + * @param handle Device handle from pmic_audio_open() call. + * @param clockIn Select the clock signal source. + * @param clockFreq Select the clock signal frequency. + * @param samplingRate Select the audio data sampling rate. + * @param invert Enable inversion of the frame sync and/or + * bit clock inputs. + * + * @retval PMIC_SUCCESS If the Stereo DAC clock settings were + * successfully configured. + * @retval PMIC_PARAMETER_ERROR If the handle or clock configuration was + * invalid. + * @retval PMIC_ERROR If the Stereo DAC clock configuration + * could not be set. + */ +PMIC_STATUS pmic_audio_stdac_set_clock(const PMIC_AUDIO_HANDLE handle, + const PMIC_AUDIO_CLOCK_IN_SOURCE clockIn, + const PMIC_AUDIO_STDAC_CLOCK_IN_FREQ + clockFreq, + const PMIC_AUDIO_STDAC_SAMPLING_RATE + samplingRate, + const PMIC_AUDIO_CLOCK_INVERT invert) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_value = 0; + unsigned int reg_mask = 0; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + /* Validate all of the calling parameters. */ + if (handle == (PMIC_AUDIO_HANDLE) NULL) { + rc = PMIC_PARAMETER_ERROR; + } else if ((handle == stDAC.handle) && + (stDAC.handleState == HANDLE_IN_USE)) { + if ((clockIn != CLOCK_IN_CLIA) && (clockIn != CLOCK_IN_CLIB)) { + rc = PMIC_PARAMETER_ERROR; + } else if ((stDAC.masterSlave == BUS_MASTER_MODE) + && !((clockFreq >= STDAC_CLI_3_36864MHZ) + && (clockFreq <= STDAC_CLI_33_6MHZ))) { + rc = PMIC_PARAMETER_ERROR; + } else if ((stDAC.masterSlave == BUS_SLAVE_MODE) + && !((clockFreq >= STDAC_MCLK_PLL_DISABLED) + && (clockFreq <= STDAC_BCLK_IN_PLL))) { + rc = PMIC_PARAMETER_ERROR; + } else if (!((samplingRate >= STDAC_RATE_8_KHZ) + && (samplingRate <= STDAC_RATE_96_KHZ))) { + rc = PMIC_PARAMETER_ERROR; + } + /* + else if(!((invert >= NO_INVERT) && (invert <= INVERT_FRAMESYNC))) + { + rc = PMIC_PARAMETER_ERROR; + } */ + else { + reg_mask = SET_BITS(regST_DAC, STDCCLK, 7) | + SET_BITS(regST_DAC, STDCCLKSEL, 1) | + SET_BITS(regST_DAC, SR, 15) | + SET_BITS(regST_DAC, STDCBCLINV, 1) | + SET_BITS(regST_DAC, STDCFSINV, 1); + if (clockIn == CLOCK_IN_CLIA) { + reg_value = SET_BITS(regST_DAC, STDCCLKSEL, 0); + } else { + reg_value = SET_BITS(regST_DAC, STDCCLKSEL, 1); + } + /* How to take care of sample rates in SLAVE mode */ + if ((clockFreq == STDAC_CLI_3_36864MHZ) + || ((clockFreq == STDAC_FSYNC_IN_PLL))) { + reg_value |= SET_BITS(regST_DAC, STDCCLK, 6); + } else if ((clockFreq == STDAC_CLI_12MHZ) + || (clockFreq == STDAC_MCLK_PLL_DISABLED)) { + reg_value |= SET_BITS(regST_DAC, STDCCLK, 5); + } else if (clockFreq == STDAC_CLI_13MHZ) { + reg_value |= SET_BITS(regST_DAC, STDCCLK, 0); + } else if (clockFreq == STDAC_CLI_15_36MHZ) { + reg_value |= SET_BITS(regST_DAC, STDCCLK, 1); + } else if (clockFreq == STDAC_CLI_16_8MHZ) { + reg_value |= SET_BITS(regST_DAC, STDCCLK, 2); + } else if (clockFreq == STDAC_CLI_26MHZ) { + reg_value |= SET_BITS(regST_DAC, STDCCLK, 4); + } else if ((clockFreq == STDAC_CLI_33_6MHZ) + || (clockFreq == STDAC_BCLK_IN_PLL)) { + reg_value |= SET_BITS(regST_DAC, STDCCLK, 7); + } + + reg_value |= SET_BITS(regST_DAC, SR, samplingRate); + + if (invert & INVERT_BITCLOCK) { + reg_value |= SET_BITS(regST_DAC, STDCBCLINV, 1); + } + if (invert & INVERT_FRAMESYNC) { + reg_value |= SET_BITS(regST_DAC, STDCFSINV, 1); + } + if (invert & NO_INVERT) { + reg_value |= SET_BITS(regST_DAC, STDCBCLINV, 0); + reg_value |= SET_BITS(regST_DAC, STDCFSINV, 0); + } + if (pmic_write_reg + (REG_AUDIO_STEREO_DAC, reg_value, + reg_mask) != PMIC_SUCCESS) { + rc = PMIC_ERROR; + } else { + pr_debug("STDAC clock set\n"); + rc = PMIC_SUCCESS; + stDAC.clockIn = clockIn; + stDAC.clockFreq = clockFreq; + stDAC.samplingRate = samplingRate; + stDAC.invert = invert; + } + + } + + } else { + rc = PMIC_PARAMETER_ERROR; + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Get the Stereo DAC clock source and operating characteristics. + * + * Get the current Stereo DAC clock source and operating characteristics. + * + * @param handle Device handle from pmic_audio_open() call. + * @param clockIn The clock signal source. + * @param clockFreq The clock signal frequency. + * @param samplingRate The audio data sampling rate. + * @param invert Inversion of the frame sync and/or + * bit clock inputs is enabled/disabled. + * + * @retval PMIC_SUCCESS If the Stereo DAC clock settings were + * successfully retrieved. + * @retval PMIC_PARAMETER_ERROR If the handle invalid. + * @retval PMIC_ERROR If the Stereo DAC clock configuration + * could not be retrieved. + */ +PMIC_STATUS pmic_audio_stdac_get_clock(const PMIC_AUDIO_HANDLE handle, + PMIC_AUDIO_CLOCK_IN_SOURCE * + const clockIn, + PMIC_AUDIO_STDAC_SAMPLING_RATE * + const samplingRate, + PMIC_AUDIO_STDAC_CLOCK_IN_FREQ * + const clockFreq, + PMIC_AUDIO_CLOCK_INVERT * const invert) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == stDAC.handle) && + (stDAC.handleState == HANDLE_IN_USE) && + (clockIn != (PMIC_AUDIO_CLOCK_IN_SOURCE *) NULL) && + (samplingRate != (PMIC_AUDIO_STDAC_SAMPLING_RATE *) NULL) && + (clockFreq != (PMIC_AUDIO_STDAC_CLOCK_IN_FREQ *) NULL) && + (invert != (PMIC_AUDIO_CLOCK_INVERT *) NULL)) { + *clockIn = stDAC.clockIn; + *samplingRate = stDAC.samplingRate; + *clockFreq = stDAC.clockFreq; + *invert = stDAC.invert; + rc = PMIC_SUCCESS; + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Set the Stereo DAC primary audio channel timeslot. + * + * Set the Stereo DAC primary audio channel timeslot. This function must be + * used if the default timeslot for the primary audio channel is to be changed. + * + * @param handle Device handle from pmic_audio_open() call. + * @param timeslot Select the primary audio channel timeslot. + * + * @retval PMIC_SUCCESS If the Stereo DAC primary audio channel + * timeslot was successfully configured. + * @retval PMIC_PARAMETER_ERROR If the handle or audio channel timeslot + * was invalid. + * @retval PMIC_ERROR If the Stereo DAC primary audio channel + * timeslot could not be set. + */ +PMIC_STATUS pmic_audio_stdac_set_rxtx_timeslot(const PMIC_AUDIO_HANDLE handle, + const PMIC_AUDIO_STDAC_TIMESLOTS + timeslot) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_mask = SET_BITS(regSSI_NETWORK, STDCRXSLOT, 3); + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == stDAC.handle) && (stDAC.handleState == HANDLE_IN_USE)) { + if ((timeslot == USE_TS0_TS1) || (timeslot == USE_TS2_TS3) + || (timeslot == USE_TS4_TS5) || (timeslot == USE_TS6_TS7)) { + if (pmic_write_reg + (REG_AUDIO_SSI_NETWORK, timeslot, + reg_mask) != PMIC_SUCCESS) { + rc = PMIC_ERROR; + } else { + pr_debug("STDAC primary timeslot set\n"); + stDAC.timeslot = timeslot; + rc = PMIC_SUCCESS; + } + + } else { + rc = PMIC_PARAMETER_ERROR; + } + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Get the current Stereo DAC primary audio channel timeslot. + * + * Get the current Stereo DAC primary audio channel timeslot. + * + * @param handle Device handle from pmic_audio_open() call. + * @param timeslot The primary audio channel timeslot. + * + * @retval PMIC_SUCCESS If the Stereo DAC primary audio channel + * timeslot was successfully retrieved. + * @retval PMIC_PARAMETER_ERROR If the handle was invalid. + * @retval PMIC_ERROR If the Stereo DAC primary audio channel + * timeslot could not be retrieved. + */ +PMIC_STATUS pmic_audio_stdac_get_rxtx_timeslot(const PMIC_AUDIO_HANDLE handle, + PMIC_AUDIO_STDAC_TIMESLOTS * + const timeslot) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == stDAC.handle) && + (stDAC.handleState == HANDLE_IN_USE) && + (timeslot != (PMIC_AUDIO_STDAC_TIMESLOTS *) NULL)) { + *timeslot = stDAC.timeslot; + + rc = PMIC_SUCCESS; + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Set/Enable the Stereo DAC options. + * + * Set or enable various Stereo DAC options. The available options include + * resetting the digital filter and enabling the bus master clock outputs. + * + * @param handle Device handle from pmic_audio_open() call. + * @param config The Stereo DAC options to enable. + * + * @retval PMIC_SUCCESS If the Stereo DAC options were + * successfully configured. + * @retval PMIC_PARAMETER_ERROR If the handle or Stereo DAC options + * were invalid. + * @retval PMIC_ERROR If the Stereo DAC options could not be + * successfully set/enabled. + */ +PMIC_STATUS pmic_audio_stdac_set_config(const PMIC_AUDIO_HANDLE handle, + const PMIC_AUDIO_STDAC_CONFIG config) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_write = 0; + unsigned int reg_mask = 0; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == stDAC.handle) && (stDAC.handleState == HANDLE_IN_USE)) { + if (config & STDAC_MASTER_CLOCK_OUTPUTS) { + reg_write |= SET_BITS(regST_DAC, STDCCLKEN, 1); + reg_mask |= SET_BITS(regST_DAC, STDCCLKEN, 1); + } + + rc = pmic_write_reg(REG_AUDIO_STEREO_DAC, reg_write, reg_mask); + + if (rc == PMIC_SUCCESS) { + stDAC.config |= config; + pr_debug("STDAC config set\n"); + + } + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Clear/Disable the Stereo DAC options. + * + * Clear or disable various Stereo DAC options. + * + * @param handle Device handle from pmic_audio_open() call. + * @param config The Stereo DAC options to be cleared/disabled. + * + * @retval PMIC_SUCCESS If the Stereo DAC options were + * successfully cleared/disabled. + * @retval PMIC_PARAMETER_ERROR If the handle or the Stereo DAC options + * were invalid. + * @retval PMIC_ERROR If the Stereo DAC options could not be + * cleared/disabled. + */ +PMIC_STATUS pmic_audio_stdac_clear_config(const PMIC_AUDIO_HANDLE handle, + const PMIC_AUDIO_STDAC_CONFIG config) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + + unsigned int reg_write = 0; + unsigned int reg_mask = 0; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == stDAC.handle) && (stDAC.handleState == HANDLE_IN_USE)) { + + if (config & STDAC_MASTER_CLOCK_OUTPUTS) { + reg_mask |= SET_BITS(regST_DAC, STDCCLKEN, 1); + } + + if (reg_mask != 0) { + rc = pmic_write_reg(REG_AUDIO_STEREO_DAC, + reg_write, reg_mask); + + if (rc == PMIC_SUCCESS) { + stDAC.config &= ~config; + } + } + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Get the current Stereo DAC options. + * + * Get the current Stereo DAC options. + * + * @param handle Device handle from pmic_audio_open() call. + * @param config The current set of Stereo DAC options. + * + * @retval PMIC_SUCCESS If the Stereo DAC options were + * successfully retrieved. + * @retval PMIC_PARAMETER_ERROR If the handle was invalid. + * @retval PMIC_ERROR If the Stereo DAC options could not be + * retrieved. + */ +PMIC_STATUS pmic_audio_stdac_get_config(const PMIC_AUDIO_HANDLE handle, + PMIC_AUDIO_STDAC_CONFIG * const config) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == stDAC.handle) && + (stDAC.handleState == HANDLE_IN_USE) && + (config != (PMIC_AUDIO_STDAC_CONFIG *) NULL)) { + *config = stDAC.config; + + rc = PMIC_SUCCESS; + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*@}*/ + +/************************************************************************* + * Audio input section configuration. + ************************************************************************* + */ + +/*! + * @name Audio Input Setup and Configuration APIs + * Functions for general setup and configuration of the PMIC audio + * input hardware. + */ +/*@{*/ + +/*! + * @brief Set/Enable the audio input section options. + * + * Set or enable various audio input section options. The only available + * option right now is to enable the automatic disabling of the microphone + * input amplifiers when a microphone/headset is inserted or removed. + * NOT SUPPORTED BY MC13783 + * + * @param handle Device handle from pmic_audio_open() call. + * @param config The audio input section options to enable. + * + * @retval PMIC_SUCCESS If the audio input section options were + * successfully configured. + * @retval PMIC_PARAMETER_ERROR If the handle or audio input section + * options were invalid. + * @retval PMIC_ERROR If the audio input section options could + * not be successfully set/enabled. + */ +PMIC_STATUS pmic_audio_input_set_config(const PMIC_AUDIO_HANDLE handle, + const PMIC_AUDIO_INPUT_CONFIG config) +{ + PMIC_STATUS rc = PMIC_NOT_SUPPORTED; + return rc; +} + +/*! + * @brief Clear/Disable the audio input section options. + * + * Clear or disable various audio input section options. + * + * @param handle Device handle from pmic_audio_open() call. + * @param config The audio input section options to be + * cleared/disabled. + * NOT SUPPORTED BY MC13783 + * + * @retval PMIC_SUCCESS If the audio input section options were + * successfully cleared/disabled. + * @retval PMIC_PARAMETER_ERROR If the handle or the audio input section + * options were invalid. + * @retval PMIC_ERROR If the audio input section options could + * not be cleared/disabled. + */ +PMIC_STATUS pmic_audio_input_clear_config(const PMIC_AUDIO_HANDLE handle, + const PMIC_AUDIO_INPUT_CONFIG config) +{ + PMIC_STATUS rc = PMIC_NOT_SUPPORTED; + return rc; + +} + +/*! + * @brief Get the current audio input section options. + * + * Get the current audio input section options. + * + * @param[in] handle Device handle from pmic_audio_open() call. + * @param[out] config The current set of audio input section options. + * NOT SUPPORTED BY MC13783 + * + * @retval PMIC_SUCCESS If the audio input section options were + * successfully retrieved. + * @retval PMIC_PARAMETER_ERROR If the handle was invalid. + * @retval PMIC_ERROR If the audio input section options could + * not be retrieved. + */ +PMIC_STATUS pmic_audio_input_get_config(const PMIC_AUDIO_HANDLE handle, + PMIC_AUDIO_INPUT_CONFIG * const config) +{ + PMIC_STATUS rc = PMIC_NOT_SUPPORTED; + return rc; +} + +/*@}*/ + +/************************************************************************* + * Audio recording using the Voice CODEC. + ************************************************************************* + */ + +/*! + * @name Audio Recording Using the Voice CODEC Setup and Configuration APIs + * Functions for general setup and configuration of the PMIC Voice CODEC + * to perform audio recording. + */ +/*@{*/ + +/*! + * @brief Select the microphone inputs to be used for Voice CODEC recording. + * + * Select left (mc13783-only) and right microphone inputs for Voice CODEC + * recording. It is possible to disable or not use a particular microphone + * input channel by specifying NO_MIC as a parameter. + * + * @param handle Device handle from pmic_audio_open() call. + * @param leftChannel Select the left microphone input channel. + * @param rightChannel Select the right microphone input channel. + * + * @retval PMIC_SUCCESS If the microphone input channels were + * successfully enabled. + * @retval PMIC_PARAMETER_ERROR If the handle or microphone input ports + * were invalid. + * @retval PMIC_ERROR If the microphone input channels could + * not be successfully enabled. + */ +PMIC_STATUS pmic_audio_vcodec_set_mic(const PMIC_AUDIO_HANDLE handle, + const PMIC_AUDIO_INPUT_PORT leftChannel, + const PMIC_AUDIO_INPUT_PORT rightChannel) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_write = 0; + unsigned int reg_mask = 0; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == vCodec.handle) && (vCodec.handleState == HANDLE_IN_USE)) { + if (!((leftChannel == NO_MIC) || (leftChannel == MIC1_LEFT))) { + rc = PMIC_PARAMETER_ERROR; + } else if (!((rightChannel == NO_MIC) + || (rightChannel == MIC1_RIGHT_MIC_MONO) + || (rightChannel == TXIN_EXT) + || (rightChannel == MIC2_AUX))) { + rc = PMIC_PARAMETER_ERROR; + } else { + if (leftChannel == NO_MIC) { + } else { /* Left channel MIC enable */ + reg_mask = SET_BITS(regAUDIO_TX, AMC1LEN, 1) | + SET_BITS(regAUDIO_TX, RXINREC, 1); + reg_write = SET_BITS(regAUDIO_TX, AMC1LEN, 1) | + SET_BITS(regAUDIO_TX, RXINREC, 0); + } + /*For right channel enable one and clear the other two as well as RXINREC */ + if (rightChannel == NO_MIC) { + } else if (rightChannel == MIC1_RIGHT_MIC_MONO) { + reg_mask |= SET_BITS(regAUDIO_TX, AMC1REN, 1) | + SET_BITS(regAUDIO_TX, RXINREC, 1) | + SET_BITS(regAUDIO_TX, AMC2EN, 1) | + SET_BITS(regAUDIO_TX, ATXINEN, 1); + reg_write |= SET_BITS(regAUDIO_TX, AMC1REN, 1) | + SET_BITS(regAUDIO_TX, RXINREC, 0) | + SET_BITS(regAUDIO_TX, AMC2EN, 0) | + SET_BITS(regAUDIO_TX, ATXINEN, 0); + } else if (rightChannel == MIC2_AUX) { + reg_mask |= SET_BITS(regAUDIO_TX, AMC1REN, 1) | + SET_BITS(regAUDIO_TX, RXINREC, 1) | + SET_BITS(regAUDIO_TX, AMC2EN, 1) | + SET_BITS(regAUDIO_TX, ATXINEN, 1); + reg_write |= SET_BITS(regAUDIO_TX, AMC1REN, 0) | + SET_BITS(regAUDIO_TX, RXINREC, 0) | + SET_BITS(regAUDIO_TX, AMC2EN, 1) | + SET_BITS(regAUDIO_TX, ATXINEN, 0); + } else { /* TX line in */ + reg_mask |= SET_BITS(regAUDIO_TX, AMC1REN, 1) | + SET_BITS(regAUDIO_TX, RXINREC, 1) | + SET_BITS(regAUDIO_TX, AMC2EN, 1) | + SET_BITS(regAUDIO_TX, ATXINEN, 1); + reg_write |= SET_BITS(regAUDIO_TX, AMC1REN, 0) | + SET_BITS(regAUDIO_TX, RXINREC, 0) | + SET_BITS(regAUDIO_TX, AMC2EN, 0) | + SET_BITS(regAUDIO_TX, ATXINEN, 1); + } + + if (reg_mask == 0) { + rc = PMIC_PARAMETER_ERROR; + } else { + rc = pmic_write_reg(REG_AUDIO_TX, + reg_write, reg_mask); + + if (rc == PMIC_SUCCESS) { + pr_debug + ("MIC inputs configured successfully\n"); + vCodec.leftChannelMic.mic = leftChannel; + vCodec.rightChannelMic.mic = + rightChannel; + + } + } + } + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Get the current microphone inputs being used for Voice CODEC + * recording. + * + * Get the left (mc13783-only) and right microphone inputs currently being + * used for Voice CODEC recording. + * + * @param handle Device handle from pmic_audio_open() call. + * @param leftChannel The left microphone input channel. + * @param rightChannel The right microphone input channel. + * + * @retval PMIC_SUCCESS If the microphone input channels were + * successfully retrieved. + * @retval PMIC_PARAMETER_ERROR If the handle was invalid. + * @retval PMIC_ERROR If the microphone input channels could + * not be retrieved. + */ +PMIC_STATUS pmic_audio_vcodec_get_mic(const PMIC_AUDIO_HANDLE handle, + PMIC_AUDIO_INPUT_PORT * const leftChannel, + PMIC_AUDIO_INPUT_PORT * + const rightChannel) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == vCodec.handle) && + (vCodec.handleState == HANDLE_IN_USE) && + (leftChannel != (PMIC_AUDIO_INPUT_PORT *) NULL) && + (rightChannel != (PMIC_AUDIO_INPUT_PORT *) NULL)) { + *leftChannel = vCodec.leftChannelMic.mic; + *rightChannel = vCodec.rightChannelMic.mic; + rc = PMIC_SUCCESS; + } + + /* Exit the critical section. */ + up(&mutex); + return rc; +} + +/*! + * @brief Enable/disable the microphone input. + * + * This function enables/disables the current microphone input channel. The + * input amplifier is automatically turned off when the microphone input is + * disabled. + * + * @param handle Device handle from pmic_audio_open() call. + * @param leftChannel The left microphone input channel state. + * @param rightChannel the right microphone input channel state. + * + * @retval PMIC_SUCCESS If the microphone input channels were + * successfully reconfigured. + * @retval PMIC_PARAMETER_ERROR If the handle or microphone input states + * were invalid. + * @retval PMIC_ERROR If the microphone input channels could + * not be reconfigured. + */ +PMIC_STATUS pmic_audio_vcodec_set_mic_on_off(const PMIC_AUDIO_HANDLE handle, + const PMIC_AUDIO_INPUT_MIC_STATE + leftChannel, + const PMIC_AUDIO_INPUT_MIC_STATE + rightChannel) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_write = 0; + unsigned int reg_mask = 0; + unsigned int curr_left = 0; + unsigned int curr_right = 0; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == vCodec.handle) && (vCodec.handleState == HANDLE_IN_USE)) { + curr_left = vCodec.leftChannelMic.mic; + curr_right = vCodec.rightChannelMic.mic; + if ((curr_left == NO_MIC) && (curr_right == NO_MIC)) { + rc = PMIC_PARAMETER_ERROR; + } else { + if (curr_left == MIC1_LEFT) { + if ((leftChannel == MICROPHONE_ON) && + (vCodec.leftChannelMic.micOnOff == + MICROPHONE_OFF)) { + /* Enable the microphone */ + reg_mask |= + SET_BITS(regAUDIO_TX, AMC1LEN, + 1) | SET_BITS(regAUDIO_TX, + RXINREC, 1); + reg_write |= + SET_BITS(regAUDIO_TX, AMC1LEN, + 1) | SET_BITS(regAUDIO_TX, + RXINREC, 0); + + } else if ((leftChannel == MICROPHONE_OFF) && + (vCodec.leftChannelMic.micOnOff == + MICROPHONE_ON)) { + /* Disable the microphone */ + reg_mask |= + SET_BITS(regAUDIO_TX, AMC1LEN, + 1) | SET_BITS(regAUDIO_TX, + RXINREC, 1); + reg_write |= + SET_BITS(regAUDIO_TX, AMC1LEN, + 0) | SET_BITS(regAUDIO_TX, + RXINREC, 0); + + } else { + /* Both are in same state . Nothing to be done */ + } + + } + if (curr_right == MIC1_RIGHT_MIC_MONO) { + if ((rightChannel == MICROPHONE_ON) && + (vCodec.leftChannelMic.micOnOff == + MICROPHONE_OFF)) { + /* Enable the microphone */ + reg_mask |= + SET_BITS(regAUDIO_TX, AMC1REN, + 1) | SET_BITS(regAUDIO_TX, + RXINREC, + 1) | + SET_BITS(regAUDIO_TX, AMC2EN, + 1) | SET_BITS(regAUDIO_TX, + ATXINEN, 1); + reg_write |= + SET_BITS(regAUDIO_TX, AMC1REN, + 1) | SET_BITS(regAUDIO_TX, + RXINREC, + 0) | + SET_BITS(regAUDIO_TX, AMC2EN, + 0) | SET_BITS(regAUDIO_TX, + ATXINEN, 0); + } else if ((rightChannel == MICROPHONE_OFF) + && (vCodec.leftChannelMic.micOnOff == + MICROPHONE_ON)) { + /* Disable the microphone */ + reg_mask |= + SET_BITS(regAUDIO_TX, AMC1REN, + 1) | SET_BITS(regAUDIO_TX, + RXINREC, + 1) | + SET_BITS(regAUDIO_TX, AMC2EN, + 1) | SET_BITS(regAUDIO_TX, + ATXINEN, 1); + reg_write |= + SET_BITS(regAUDIO_TX, AMC1REN, + 0) | SET_BITS(regAUDIO_TX, + RXINREC, + 0) | + SET_BITS(regAUDIO_TX, AMC2EN, + 0) | SET_BITS(regAUDIO_TX, + ATXINEN, 0); + } else { + /* Both are in same state . Nothing to be done */ + } + } else if (curr_right == MIC2_AUX) { + if ((rightChannel == MICROPHONE_ON) + && (vCodec.leftChannelMic.micOnOff == + MICROPHONE_OFF)) { + /* Enable the microphone */ + reg_mask |= + SET_BITS(regAUDIO_TX, AMC1REN, + 1) | SET_BITS(regAUDIO_TX, + RXINREC, + 1) | + SET_BITS(regAUDIO_TX, AMC2EN, + 1) | SET_BITS(regAUDIO_TX, + ATXINEN, 1); + reg_write |= + SET_BITS(regAUDIO_TX, AMC1REN, + 0) | SET_BITS(regAUDIO_TX, + RXINREC, + 0) | + SET_BITS(regAUDIO_TX, AMC2EN, + 1) | SET_BITS(regAUDIO_TX, + ATXINEN, 0); + } else if ((rightChannel == MICROPHONE_OFF) + && (vCodec.leftChannelMic.micOnOff == + MICROPHONE_ON)) { + /* Disable the microphone */ + reg_mask |= + SET_BITS(regAUDIO_TX, AMC1REN, + 1) | SET_BITS(regAUDIO_TX, + RXINREC, + 1) | + SET_BITS(regAUDIO_TX, AMC2EN, + 1) | SET_BITS(regAUDIO_TX, + ATXINEN, 1); + reg_write |= + SET_BITS(regAUDIO_TX, AMC1REN, + 0) | SET_BITS(regAUDIO_TX, + RXINREC, + 0) | + SET_BITS(regAUDIO_TX, AMC2EN, + 0) | SET_BITS(regAUDIO_TX, + ATXINEN, 0); + } else { + /* Both are in same state . Nothing to be done */ + } + } else if (curr_right == TXIN_EXT) { + if ((rightChannel == MICROPHONE_ON) + && (vCodec.leftChannelMic.micOnOff == + MICROPHONE_OFF)) { + /* Enable the microphone */ + reg_mask |= + SET_BITS(regAUDIO_TX, AMC1REN, + 1) | SET_BITS(regAUDIO_TX, + RXINREC, + 1) | + SET_BITS(regAUDIO_TX, AMC2EN, + 1) | SET_BITS(regAUDIO_TX, + ATXINEN, 1); + reg_write |= + SET_BITS(regAUDIO_TX, AMC1REN, + 0) | SET_BITS(regAUDIO_TX, + RXINREC, + 0) | + SET_BITS(regAUDIO_TX, AMC2EN, + 0) | SET_BITS(regAUDIO_TX, + ATXINEN, 1); + } else if ((rightChannel == MICROPHONE_OFF) + && (vCodec.leftChannelMic.micOnOff == + MICROPHONE_ON)) { + /* Disable the microphone */ + reg_mask |= + SET_BITS(regAUDIO_TX, AMC1REN, + 1) | SET_BITS(regAUDIO_TX, + RXINREC, + 1) | + SET_BITS(regAUDIO_TX, AMC2EN, + 1) | SET_BITS(regAUDIO_TX, + ATXINEN, 1); + reg_write |= + SET_BITS(regAUDIO_TX, AMC1REN, + 0) | SET_BITS(regAUDIO_TX, + RXINREC, + 0) | + SET_BITS(regAUDIO_TX, AMC2EN, + 0) | SET_BITS(regAUDIO_TX, + ATXINEN, 0); + } else { + /* Both are in same state . Nothing to be done */ + } + } + if (reg_mask == 0) { + } else { + rc = pmic_write_reg(REG_AUDIO_TX, + reg_write, reg_mask); + + if (rc == PMIC_SUCCESS) { + pr_debug + ("MIC states configured successfully\n"); + vCodec.leftChannelMic.micOnOff = + leftChannel; + vCodec.rightChannelMic.micOnOff = + rightChannel; + } + } + } + + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Return the current state of the microphone inputs. + * + * This function returns the current state (on/off) of the microphone + * input channels. + * + * @param handle Device handle from pmic_audio_open() call. + * @param leftChannel The current left microphone input channel + * state. + * @param rightChannel the current right microphone input channel + * state. + * + * @retval PMIC_SUCCESS If the microphone input channel states + * were successfully retrieved. + * @retval PMIC_PARAMETER_ERROR If the handle was invalid. + * @retval PMIC_ERROR If the microphone input channel states + * could not be retrieved. + */ +PMIC_STATUS pmic_audio_vcodec_get_mic_on_off(const PMIC_AUDIO_HANDLE handle, + PMIC_AUDIO_INPUT_MIC_STATE * + const leftChannel, + PMIC_AUDIO_INPUT_MIC_STATE * + const rightChannel) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == vCodec.handle) && + (vCodec.handleState == HANDLE_IN_USE) && + (leftChannel != (PMIC_AUDIO_INPUT_MIC_STATE *) NULL) && + (rightChannel != (PMIC_AUDIO_INPUT_MIC_STATE *) NULL)) { + *leftChannel = vCodec.leftChannelMic.micOnOff; + *rightChannel = vCodec.rightChannelMic.micOnOff; + + rc = PMIC_SUCCESS; + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Set the microphone input amplifier mode and gain level. + * + * This function sets the current microphone input amplifier operating mode + * and gain level. + * + * @param handle Device handle from pmic_audio_open() call. + * @param leftChannelMode The left microphone input amplifier mode. + * @param leftChannelGain The left microphone input amplifier gain level. + * @param rightChannelMode The right microphone input amplifier mode. + * @param rightChannelGain The right microphone input amplifier gain + * level. + * + * @retval PMIC_SUCCESS If the microphone input amplifiers were + * successfully reconfigured. + * @retval PMIC_PARAMETER_ERROR If the handle or microphone input amplifier + * modes or gain levels were invalid. + * @retval PMIC_ERROR If the microphone input amplifiers could + * not be reconfigured. + */ +PMIC_STATUS pmic_audio_vcodec_set_record_gain(const PMIC_AUDIO_HANDLE handle, + const PMIC_AUDIO_MIC_AMP_MODE + leftChannelMode, + const PMIC_AUDIO_MIC_GAIN + leftChannelGain, + const PMIC_AUDIO_MIC_AMP_MODE + rightChannelMode, + const PMIC_AUDIO_MIC_GAIN + rightChannelGain) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_write = 0; + unsigned int reg_mask = 0; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == vCodec.handle) && (vCodec.handleState == HANDLE_IN_USE)) { + if (!(((leftChannelGain >= MIC_GAIN_MINUS_8DB) + && (leftChannelGain <= MIC_GAIN_PLUS_23DB)) + && ((rightChannelGain >= MIC_GAIN_MINUS_8DB) + && (rightChannelGain <= MIC_GAIN_PLUS_23DB)))) { + rc = PMIC_PARAMETER_ERROR; + pr_debug("VCODEC set record gain - wrong gain value\n"); + } else if (((leftChannelMode != AMP_OFF) + && (leftChannelMode != VOLTAGE_TO_VOLTAGE) + && (leftChannelMode != CURRENT_TO_VOLTAGE)) + || ((rightChannelMode != VOLTAGE_TO_VOLTAGE) + && (rightChannelMode != CURRENT_TO_VOLTAGE) + && (rightChannelMode != AMP_OFF))) { + rc = PMIC_PARAMETER_ERROR; + pr_debug("VCODEC set record gain - wrong amp mode\n"); + } else { + if (vCodec.leftChannelMic.mic == MIC1_LEFT) { + reg_mask = SET_BITS(regAUDIO_TX, AMC1LITOV, 1) | + SET_BITS(regAUDIO_TX, PGATXL, 31); + if (leftChannelMode == VOLTAGE_TO_VOLTAGE) { + reg_write = + SET_BITS(regAUDIO_TX, AMC1LITOV, 0); + } else { + reg_write = + SET_BITS(regAUDIO_TX, AMC1LITOV, 1); + } + reg_write |= + SET_BITS(regAUDIO_TX, PGATXL, + leftChannelGain); + } + if (vCodec.rightChannelMic.mic == MIC1_RIGHT_MIC_MONO) { + reg_mask |= + SET_BITS(regAUDIO_TX, AMC1RITOV, + 1) | SET_BITS(regAUDIO_TX, PGATXR, + 31); + if (rightChannelMode == VOLTAGE_TO_VOLTAGE) { + reg_write |= + SET_BITS(regAUDIO_TX, AMC1RITOV, 0); + } else { + reg_write |= + SET_BITS(regAUDIO_TX, AMC1RITOV, 1); + } + reg_write |= + SET_BITS(regAUDIO_TX, PGATXR, + rightChannelGain); + } else if (vCodec.rightChannelMic.mic == MIC2_AUX) { + reg_mask |= SET_BITS(regAUDIO_TX, AMC2ITOV, 1); + reg_mask |= SET_BITS(regAUDIO_TX, PGATXR, 31); + if (rightChannelMode == VOLTAGE_TO_VOLTAGE) { + reg_write |= + SET_BITS(regAUDIO_TX, AMC2ITOV, 0); + } else { + reg_write |= + SET_BITS(regAUDIO_TX, AMC2ITOV, 1); + } + reg_write |= + SET_BITS(regAUDIO_TX, PGATXR, + rightChannelGain); + } else if (vCodec.rightChannelMic.mic == TXIN_EXT) { + reg_mask |= SET_BITS(regAUDIO_TX, PGATXR, 31); + /* No current to voltage option for TX IN amplifier */ + reg_write |= + SET_BITS(regAUDIO_TX, PGATXR, + rightChannelGain); + } + + if (reg_mask == 0) { + } else { + rc = pmic_write_reg(REG_AUDIO_TX, + reg_write, reg_mask); + reg_write = + SET_BITS(regAUDIO_TX, PGATXL, + leftChannelGain); + reg_mask = SET_BITS(regAUDIO_TX, PGATXL, 31); + rc = pmic_write_reg(REG_AUDIO_TX, + reg_write, reg_mask); + + if (rc == PMIC_SUCCESS) { + pr_debug("MIC amp mode and gain set\n"); + vCodec.leftChannelMic.ampMode = + leftChannelMode; + vCodec.leftChannelMic.gain = + leftChannelGain; + vCodec.rightChannelMic.ampMode = + rightChannelMode; + vCodec.rightChannelMic.gain = + rightChannelGain; + + } + } + } + } + + /* Exit critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Get the current microphone input amplifier mode and gain level. + * + * This function gets the current microphone input amplifier operating mode + * and gain level. + * + * @param handle Device handle from pmic_audio_open() call. + * @param leftChannelMode The left microphone input amplifier mode. + * @param leftChannelGain The left microphone input amplifier gain level. + * @param rightChannelMode The right microphone input amplifier mode. + * @param rightChannelGain The right microphone input amplifier gain + * level. + * + * @retval PMIC_SUCCESS If the microphone input amplifier modes + * and gain levels were successfully + * retrieved. + * @retval PMIC_PARAMETER_ERROR If the handle was invalid. + * @retval PMIC_ERROR If the microphone input amplifier modes + * and gain levels could not be retrieved. + */ +PMIC_STATUS pmic_audio_vcodec_get_record_gain(const PMIC_AUDIO_HANDLE handle, + PMIC_AUDIO_MIC_AMP_MODE * + const leftChannelMode, + PMIC_AUDIO_MIC_GAIN * + const leftChannelGain, + PMIC_AUDIO_MIC_AMP_MODE * + const rightChannelMode, + PMIC_AUDIO_MIC_GAIN * + const rightChannelGain) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == vCodec.handle) && + (vCodec.handleState == HANDLE_IN_USE) && + (leftChannelMode != (PMIC_AUDIO_MIC_AMP_MODE *) NULL) && + (leftChannelGain != (PMIC_AUDIO_MIC_GAIN *) NULL) && + (rightChannelMode != (PMIC_AUDIO_MIC_AMP_MODE *) NULL) && + (rightChannelGain != (PMIC_AUDIO_MIC_GAIN *) NULL)) { + *leftChannelMode = vCodec.leftChannelMic.ampMode; + *leftChannelGain = vCodec.leftChannelMic.gain; + *rightChannelMode = vCodec.rightChannelMic.ampMode; + *rightChannelGain = vCodec.rightChannelMic.gain; + + rc = PMIC_SUCCESS; + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Enable a microphone bias circuit. + * + * This function enables one of the available microphone bias circuits. + * + * @param handle Device handle from pmic_audio_open() call. + * @param biasCircuit The microphone bias circuit to be enabled. + * + * @retval PMIC_SUCCESS If the microphone bias circuit was + * successfully enabled. + * @retval PMIC_PARAMETER_ERROR If the handle or selected microphone bias + * circuit was invalid. + * @retval PMIC_ERROR If the microphone bias circuit could not + * be enabled. + */ +PMIC_STATUS pmic_audio_vcodec_enable_micbias(const PMIC_AUDIO_HANDLE handle, + const PMIC_AUDIO_MIC_BIAS + biasCircuit) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_write = 0; + unsigned int reg_mask = 0; + + /* No critical section required here since we are not updating any + * global data. + */ + + if ((handle == vCodec.handle) && (vCodec.handleState == HANDLE_IN_USE)) { + if (biasCircuit & MIC_BIAS1) { + reg_write = SET_BITS(regAUDIO_TX, MC1BEN, 1); + reg_mask = SET_BITS(regAUDIO_TX, MC1BEN, 1); + } + if (biasCircuit & MIC_BIAS2) { + reg_write |= SET_BITS(regAUDIO_TX, MC2BEN, 1); + reg_mask |= SET_BITS(regAUDIO_TX, MC2BEN, 1); + } + if (reg_mask != 0) { + rc = pmic_write_reg(REG_AUDIO_TX, reg_write, reg_mask); + } + } + + return rc; +} + +/*! + * @brief Disable a microphone bias circuit. + * + * This function disables one of the available microphone bias circuits. + * + * @param handle Device handle from pmic_audio_open() call. + * @param biasCircuit The microphone bias circuit to be disabled. + * + * @retval PMIC_SUCCESS If the microphone bias circuit was + * successfully disabled. + * @retval PMIC_PARAMETER_ERROR If the handle or selected microphone bias + * circuit was invalid. + * @retval PMIC_ERROR If the microphone bias circuit could not + * be disabled. + */ +PMIC_STATUS pmic_audio_vcodec_disable_micbias(const PMIC_AUDIO_HANDLE handle, + const PMIC_AUDIO_MIC_BIAS + biasCircuit) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_write = 0; + unsigned int reg_mask = 0; + + /* No critical section required here since we are not updating any + * global data. + */ + + if ((handle == vCodec.handle) && (vCodec.handleState == HANDLE_IN_USE)) { + if (biasCircuit & MIC_BIAS1) { + reg_mask = SET_BITS(regAUDIO_TX, MC1BEN, 1); + } + + if (biasCircuit & MIC_BIAS2) { + reg_mask |= SET_BITS(regAUDIO_TX, MC2BEN, 1); + } + + if (reg_mask != 0) { + rc = pmic_write_reg(REG_AUDIO_TX, reg_write, reg_mask); + } + } + + return rc; +} + +/*@}*/ + +/************************************************************************* + * Audio Playback Using the Voice CODEC. + ************************************************************************* + */ + +/*! + * @name Audio Playback Using the Voice CODEC Setup and Configuration APIs + * Functions for general setup and configuration of the PMIC Voice CODEC + * to perform audio playback. + */ +/*@{*/ + +/*! + * @brief Configure and enable the Voice CODEC mixer. + * + * This function configures and enables the Voice CODEC mixer. + * + * @param handle Device handle from pmic_audio_open() call. + * @param rxSecondaryTimeslot The timeslot used for the secondary audio + * channel. + * @param gainIn The secondary audio channel gain level. + * @param gainOut The mixer output gain level. + * + * @retval PMIC_SUCCESS If the Voice CODEC mixer was successfully + * configured and enabled. + * @retval PMIC_PARAMETER_ERROR If the handle or mixer configuration + * was invalid. + * @retval PMIC_ERROR If the Voice CODEC mixer could not be + * reconfigured or enabled. + */ +PMIC_STATUS pmic_audio_vcodec_enable_mixer(const PMIC_AUDIO_HANDLE handle, + const PMIC_AUDIO_VCODEC_TIMESLOT + rxSecondaryTimeslot, + const PMIC_AUDIO_VCODEC_MIX_IN_GAIN + gainIn, + const PMIC_AUDIO_VCODEC_MIX_OUT_GAIN + gainOut) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_write = 0; + unsigned int reg_mask = 0; + + /* No critical section required here since we are not updating any + * global data. + */ + + if ((handle == vCodec.handle) && (vCodec.handleState == HANDLE_IN_USE)) { + if (!((rxSecondaryTimeslot >= USE_TS0) + && (rxSecondaryTimeslot <= USE_TS3))) { + pr_debug + ("VCODEC enable mixer - wrong sec rx timeslot\n"); + } else if (!((gainIn >= VCODEC_NO_MIX) + && (gainIn <= VCODEC_MIX_IN_MINUS_12DB))) { + pr_debug("VCODEC enable mixer - wrong mix in gain\n"); + + } else if (!((gainOut >= VCODEC_MIX_OUT_0DB) + && (gainOut <= VCODEC_MIX_OUT_MINUS_6DB))) { + pr_debug("VCODEC enable mixer - wrong mix out gain\n"); + } else { + + reg_mask = SET_BITS(regSSI_NETWORK, CDCRXSECSLOT, 3) | + SET_BITS(regSSI_NETWORK, CDCRXSECGAIN, 3) | + SET_BITS(regSSI_NETWORK, CDCSUMGAIN, 1); + reg_write = + SET_BITS(regSSI_NETWORK, CDCRXSECSLOT, + rxSecondaryTimeslot) | + SET_BITS(regSSI_NETWORK, CDCRXSECGAIN, + gainIn) | SET_BITS(regSSI_NETWORK, + CDCSUMGAIN, gainOut); + rc = pmic_write_reg(REG_AUDIO_SSI_NETWORK, + reg_write, reg_mask); + if (rc == PMIC_SUCCESS) { + pr_debug("Vcodec mixer enabled\n"); + } + } + } + + return rc; +} + +/*! + * @brief Disable the Voice CODEC mixer. + * + * This function disables the Voice CODEC mixer. + * + * @param handle Device handle from pmic_audio_open() call. + * + * @retval PMIC_SUCCESS If the Voice CODEC mixer was successfully + * disabled. + * @retval PMIC_PARAMETER_ERROR If the handle was invalid. + * @retval PMIC_ERROR If the Voice CODEC mixer could not be + * disabled. + */ +PMIC_STATUS pmic_audio_vcodec_disable_mixer(const PMIC_AUDIO_HANDLE handle) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_mask; + + if ((handle == vCodec.handle) && (vCodec.handleState == HANDLE_IN_USE)) { + reg_mask = SET_BITS(regSSI_NETWORK, CDCRXSECGAIN, 1); + rc = pmic_write_reg(REG_AUDIO_SSI_NETWORK, + VCODEC_NO_MIX, reg_mask); + + if (rc == PMIC_SUCCESS) { + pr_debug("Vcodec mixer disabled\n"); + } + + } + + return rc; +} + +/*@}*/ + +/************************************************************************* + * Audio Playback Using the Stereo DAC. + ************************************************************************* + */ + +/*! + * @name Audio Playback Using the Stereo DAC Setup and Configuration APIs + * Functions for general setup and configuration of the PMIC Stereo DAC + * to perform audio playback. + */ +/*@{*/ + +/*! + * @brief Configure and enable the Stereo DAC mixer. + * + * This function configures and enables the Stereo DAC mixer. + * + * @param handle Device handle from pmic_audio_open() call. + * @param rxSecondaryTimeslot The timeslot used for the secondary audio + * channel. + * @param gainIn The secondary audio channel gain level. + * @param gainOut The mixer output gain level. + * + * @retval PMIC_SUCCESS If the Stereo DAC mixer was successfully + * configured and enabled. + * @retval PMIC_PARAMETER_ERROR If the handle or mixer configuration + * was invalid. + * @retval PMIC_ERROR If the Stereo DAC mixer could not be + * reconfigured or enabled. + */ +PMIC_STATUS pmic_audio_stdac_enable_mixer(const PMIC_AUDIO_HANDLE handle, + const PMIC_AUDIO_STDAC_TIMESLOTS + rxSecondaryTimeslot, + const PMIC_AUDIO_STDAC_MIX_IN_GAIN + gainIn, + const PMIC_AUDIO_STDAC_MIX_OUT_GAIN + gainOut) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_write = 0; + unsigned int reg_mask = 0; + + /* No critical section required here since we are not updating any + * global data. + */ + + if ((handle == stDAC.handle) && (stDAC.handleState == HANDLE_IN_USE)) { + if (!((rxSecondaryTimeslot >= USE_TS0_TS1) + && (rxSecondaryTimeslot <= USE_TS6_TS7))) { + rc = PMIC_PARAMETER_ERROR; + pr_debug("STDAC enable mixer - wrong sec timeslot\n"); + } else if (!((gainIn >= STDAC_NO_MIX) + && (gainIn <= STDAC_MIX_IN_MINUS_12DB))) { + rc = PMIC_PARAMETER_ERROR; + pr_debug("STDAC enable mixer - wrong mix in gain\n"); + } else if (!((gainOut >= STDAC_MIX_OUT_0DB) + && (gainOut <= STDAC_MIX_OUT_MINUS_6DB))) { + rc = PMIC_PARAMETER_ERROR; + pr_debug("STDAC enable mixer - wrong mix out gain\n"); + } else { + + reg_mask = SET_BITS(regSSI_NETWORK, STDCRXSECSLOT, 3) | + SET_BITS(regSSI_NETWORK, STDCRXSECGAIN, 3) | + SET_BITS(regSSI_NETWORK, STDCSUMGAIN, 1); + reg_write = + SET_BITS(regSSI_NETWORK, STDCRXSECSLOT, + rxSecondaryTimeslot) | + SET_BITS(regSSI_NETWORK, STDCRXSECGAIN, + gainIn) | SET_BITS(regSSI_NETWORK, + STDCSUMGAIN, gainOut); + rc = pmic_write_reg(REG_AUDIO_SSI_NETWORK, + reg_write, reg_mask); + if (rc == PMIC_SUCCESS) { + pr_debug("STDAC mixer enabled\n"); + } + } + + } + + return rc; +} + +/*! + * @brief Disable the Stereo DAC mixer. + * + * This function disables the Stereo DAC mixer. + * + * @param handle Device handle from pmic_audio_open() call. + * + * @retval PMIC_SUCCESS If the Stereo DAC mixer was successfully + * disabled. + * @retval PMIC_PARAMETER_ERROR If the handle was invalid. + * @retval PMIC_ERROR If the Stereo DAC mixer could not be + * disabled. + */ +PMIC_STATUS pmic_audio_stdac_disable_mixer(const PMIC_AUDIO_HANDLE handle) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + const unsigned int reg_write = 0; + const unsigned int reg_mask = + SET_BITS(regSSI_NETWORK, STDCRXSECGAIN, 1); + + /* No critical section required here since we are not updating any + * global data. + */ + + if ((handle == stDAC.handle) && (stDAC.handleState == HANDLE_IN_USE)) { + rc = pmic_write_reg(REG_AUDIO_SSI_NETWORK, reg_write, reg_mask); + } + + return rc; +} + +/*@}*/ + +/************************************************************************* + * Audio Output Control + ************************************************************************* + */ + +/*! + * @name Audio Output Section Setup and Configuration APIs + * Functions for general setup and configuration of the PMIC audio output + * section to support playback. + */ +/*@{*/ + +/*! + * @brief Select the audio output ports. + * + * This function selects the audio output ports to be used. This also enables + * the appropriate output amplifiers. + * + * @param handle Device handle from pmic_audio_open() call. + * @param port The audio output ports to be used. + * + * @retval PMIC_SUCCESS If the audio output ports were successfully + * acquired. + * @retval PMIC_PARAMETER_ERROR If the handle or output ports were + * invalid. + * @retval PMIC_ERROR If the audio output ports could not be + * acquired. + */ +PMIC_STATUS pmic_audio_output_set_port(const PMIC_AUDIO_HANDLE handle, + const PMIC_AUDIO_OUTPUT_PORT port) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_write = 0; + unsigned int reg_mask = 0; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((port == MONO_ALERT) || (port == MONO_EXTOUT)) { + rc = PMIC_NOT_SUPPORTED; + } else { + if (((handle == stDAC.handle) + && (stDAC.handleState == HANDLE_IN_USE)) + || ((handle == extStereoIn.handle) + && (extStereoIn.handleState == HANDLE_IN_USE)) + || ((handle == vCodec.handle) + && (vCodec.handleState == HANDLE_IN_USE) + && (audioOutput.vCodecOut == VCODEC_MIXER_OUT))) { + /* Stereo signal and MIXER source needs to be routed to the port + / Avoid Codec direct out */ + + if (port & MONO_SPEAKER) { + reg_mask = SET_BITS(regAUDIO_RX_0, ASPEN, 1) | + SET_BITS(regAUDIO_RX_0, ASPSEL, 1); + reg_write = SET_BITS(regAUDIO_RX_0, ASPEN, 1) | + SET_BITS(regAUDIO_RX_0, ASPSEL, 1); + } + if (port & MONO_LOUDSPEAKER) { + reg_mask |= SET_BITS(regAUDIO_RX_0, ALSPEN, 1) | + SET_BITS(regAUDIO_RX_0, ALSPREF, 1) | + SET_BITS(regAUDIO_RX_0, ALSPSEL, 1); + reg_write |= + SET_BITS(regAUDIO_RX_0, ALSPEN, + 1) | SET_BITS(regAUDIO_RX_0, + ALSPREF, + 1) | + SET_BITS(regAUDIO_RX_0, ALSPSEL, 1); + } + if (port & STEREO_HEADSET_LEFT) { + reg_mask |= SET_BITS(regAUDIO_RX_0, AHSLEN, 1) | + SET_BITS(regAUDIO_RX_0, AHSSEL, 1); + reg_write |= + SET_BITS(regAUDIO_RX_0, AHSLEN, + 1) | SET_BITS(regAUDIO_RX_0, + AHSSEL, 1); + } + if (port & STEREO_HEADSET_RIGHT) { + reg_mask |= SET_BITS(regAUDIO_RX_0, AHSREN, 1) | + SET_BITS(regAUDIO_RX_0, AHSSEL, 1); + reg_write |= + SET_BITS(regAUDIO_RX_0, AHSREN, + 1) | SET_BITS(regAUDIO_RX_0, + AHSSEL, 1); + } + if (port & STEREO_OUT_LEFT) { + reg_mask |= + SET_BITS(regAUDIO_RX_0, ARXOUTLEN, + 1) | SET_BITS(regAUDIO_RX_0, + ARXOUTSEL, 1); + reg_write |= + SET_BITS(regAUDIO_RX_0, ARXOUTLEN, + 1) | SET_BITS(regAUDIO_RX_0, + ARXOUTSEL, 1); + } + if (port & STEREO_OUT_RIGHT) { + reg_mask |= + SET_BITS(regAUDIO_RX_0, ARXOUTREN, + 1) | SET_BITS(regAUDIO_RX_0, + ARXOUTSEL, 1); + reg_write |= + SET_BITS(regAUDIO_RX_0, ARXOUTREN, + 1) | SET_BITS(regAUDIO_RX_0, + ARXOUTSEL, 1); + } + if (port & STEREO_LEFT_LOW_POWER) { + reg_mask |= SET_BITS(regAUDIO_RX_0, LSPLEN, 1); + + reg_write |= SET_BITS(regAUDIO_RX_0, LSPLEN, 1); + } + } else if ((handle == vCodec.handle) + && (vCodec.handleState == HANDLE_IN_USE) + && (audioOutput.vCodecOut == VCODEC_DIRECT_OUT)) { + if (port & MONO_SPEAKER) { + reg_mask = SET_BITS(regAUDIO_RX_0, ASPEN, 1) | + SET_BITS(regAUDIO_RX_0, ASPSEL, 1); + reg_write = SET_BITS(regAUDIO_RX_0, ASPEN, 1) | + SET_BITS(regAUDIO_RX_0, ASPSEL, 0); + } + if (port & MONO_LOUDSPEAKER) { + reg_mask |= SET_BITS(regAUDIO_RX_0, ALSPEN, 1) | + SET_BITS(regAUDIO_RX_0, ALSPREF, 1) | + SET_BITS(regAUDIO_RX_0, ALSPSEL, 1); + reg_write |= + SET_BITS(regAUDIO_RX_0, ALSPEN, + 1) | SET_BITS(regAUDIO_RX_0, + ALSPREF, + 1) | + SET_BITS(regAUDIO_RX_0, ALSPSEL, 0); + } + + if (port & STEREO_HEADSET_LEFT) { + reg_mask |= SET_BITS(regAUDIO_RX_0, AHSLEN, 1) | + SET_BITS(regAUDIO_RX_0, AHSSEL, 1); + reg_write |= + SET_BITS(regAUDIO_RX_0, AHSLEN, + 1) | SET_BITS(regAUDIO_RX_0, + AHSSEL, 0); + } + if (port & STEREO_HEADSET_RIGHT) { + reg_mask |= SET_BITS(regAUDIO_RX_0, AHSREN, 1) | + SET_BITS(regAUDIO_RX_0, AHSSEL, 1); + reg_write |= + SET_BITS(regAUDIO_RX_0, AHSREN, + 1) | SET_BITS(regAUDIO_RX_0, + AHSSEL, 0); + } + if (port & STEREO_OUT_LEFT) { + reg_mask |= + SET_BITS(regAUDIO_RX_0, ARXOUTLEN, + 1) | SET_BITS(regAUDIO_RX_0, + ARXOUTSEL, 1); + reg_write |= + SET_BITS(regAUDIO_RX_0, ARXOUTLEN, + 1) | SET_BITS(regAUDIO_RX_0, + ARXOUTSEL, 0); + } + if (port & STEREO_OUT_RIGHT) { + reg_mask |= + SET_BITS(regAUDIO_RX_0, ARXOUTREN, + 1) | SET_BITS(regAUDIO_RX_0, + ARXOUTSEL, 1); + reg_write |= + SET_BITS(regAUDIO_RX_0, ARXOUTREN, + 1) | SET_BITS(regAUDIO_RX_0, + ARXOUTSEL, 0); + } + if (port & MONO_CDCOUT) { + reg_mask |= + SET_BITS(regAUDIO_RX_0, CDCOUTEN, 1); + + reg_write |= + SET_BITS(regAUDIO_RX_0, CDCOUTEN, 1); + } + } + + if (reg_mask == 0) { + + } else { + rc = pmic_write_reg(REG_AUDIO_RX_0, + reg_write, reg_mask); + + if (rc == PMIC_SUCCESS) { + pr_debug("output ports enabled\n"); + audioOutput.outputPort = port; + + } + } + } + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Deselect/disable the audio output ports. + * + * This function disables the audio output ports that were previously enabled + * by calling pmic_audio_output_set_port(). + * + * @param handle Device handle from pmic_audio_open() call. + * @param port The audio output ports to be disabled. + * + * @retval PMIC_SUCCESS If the audio output ports were successfully + * disabled. + * @retval PMIC_PARAMETER_ERROR If the handle or output ports were + * invalid. + * @retval PMIC_ERROR If the audio output ports could not be + * disabled. + */ +PMIC_STATUS pmic_audio_output_clear_port(const PMIC_AUDIO_HANDLE handle, + const PMIC_AUDIO_OUTPUT_PORT port) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_write = 0; + unsigned int reg_mask = 0; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((port == MONO_ALERT) || (port == MONO_EXTOUT)) { + rc = PMIC_NOT_SUPPORTED; + } else { + if (((handle == stDAC.handle) + && (stDAC.handleState == HANDLE_IN_USE)) + || ((handle == extStereoIn.handle) + && (extStereoIn.handleState == HANDLE_IN_USE)) + || ((handle == vCodec.handle) + && (vCodec.handleState == HANDLE_IN_USE) + && (audioOutput.vCodecOut == VCODEC_MIXER_OUT))) { + /* Stereo signal and MIXER source needs to be routed to the port / + Avoid Codec direct out */ + if (port & MONO_SPEAKER) { + reg_mask = SET_BITS(regAUDIO_RX_0, ASPEN, 1); + reg_write = SET_BITS(regAUDIO_RX_0, ASPEN, 0); + } + if (port & MONO_LOUDSPEAKER) { + reg_mask |= SET_BITS(regAUDIO_RX_0, ALSPEN, 1) | + SET_BITS(regAUDIO_RX_0, ALSPREF, 1); + + reg_write |= + SET_BITS(regAUDIO_RX_0, ALSPEN, + 0) | SET_BITS(regAUDIO_RX_0, + ALSPREF, 0); + + } + if (port & STEREO_HEADSET_LEFT) { + reg_mask |= SET_BITS(regAUDIO_RX_0, AHSLEN, 1); + reg_write |= SET_BITS(regAUDIO_RX_0, AHSLEN, 0); + } + if (port & STEREO_HEADSET_RIGHT) { + reg_mask |= SET_BITS(regAUDIO_RX_0, AHSREN, 1); + reg_write |= SET_BITS(regAUDIO_RX_0, AHSREN, 0); + } + if (port & STEREO_OUT_LEFT) { + reg_mask |= + SET_BITS(regAUDIO_RX_0, ARXOUTLEN, 1); + reg_write |= + SET_BITS(regAUDIO_RX_0, ARXOUTLEN, 0); + } + if (port & STEREO_OUT_RIGHT) { + reg_mask |= + SET_BITS(regAUDIO_RX_0, ARXOUTREN, 1); + reg_write |= + SET_BITS(regAUDIO_RX_0, ARXOUTREN, 0); + } + if (port & STEREO_LEFT_LOW_POWER) { + reg_mask |= SET_BITS(regAUDIO_RX_0, LSPLEN, 1); + reg_write |= SET_BITS(regAUDIO_RX_0, LSPLEN, 0); + } + } else if ((handle == vCodec.handle) + && (vCodec.handleState == HANDLE_IN_USE) + && (audioOutput.vCodecOut == VCODEC_DIRECT_OUT)) { + if (port & MONO_SPEAKER) { + reg_mask = SET_BITS(regAUDIO_RX_0, ASPEN, 1); + reg_write = SET_BITS(regAUDIO_RX_0, ASPEN, 0); + } + if (port & MONO_LOUDSPEAKER) { + reg_mask |= SET_BITS(regAUDIO_RX_0, ALSPEN, 1) | + SET_BITS(regAUDIO_RX_0, ALSPREF, 1); + reg_write |= + SET_BITS(regAUDIO_RX_0, ALSPEN, + 0) | SET_BITS(regAUDIO_RX_0, + ALSPREF, 0); + } + if (port & STEREO_HEADSET_LEFT) { + reg_mask |= SET_BITS(regAUDIO_RX_0, AHSLEN, 1); + reg_write |= SET_BITS(regAUDIO_RX_0, AHSLEN, 0); + } + if (port & STEREO_HEADSET_RIGHT) { + reg_mask |= SET_BITS(regAUDIO_RX_0, AHSREN, 1); + reg_write |= SET_BITS(regAUDIO_RX_0, AHSREN, 0); + } + if (port & STEREO_OUT_LEFT) { + reg_mask |= + SET_BITS(regAUDIO_RX_0, ARXOUTLEN, 1); + reg_write |= + SET_BITS(regAUDIO_RX_0, ARXOUTLEN, 0); + } + if (port & STEREO_OUT_RIGHT) { + reg_mask |= + SET_BITS(regAUDIO_RX_0, ARXOUTREN, 1); + reg_write |= + SET_BITS(regAUDIO_RX_0, ARXOUTREN, 0); + } + if (port & MONO_CDCOUT) { + reg_mask |= + SET_BITS(regAUDIO_RX_0, CDCOUTEN, 1); + reg_write |= + SET_BITS(regAUDIO_RX_0, CDCOUTEN, 0); + } + } +#ifdef CONFIG_HEADSET_DETECT_ENABLE + + if (port & STEREO_HEADSET_LEFT) { + reg_mask |= SET_BITS(regAUDIO_RX_0, AHSLEN, 1); + reg_write |= SET_BITS(regAUDIO_RX_0, AHSLEN, 0); + } + if (port & STEREO_HEADSET_RIGHT) { + reg_mask |= SET_BITS(regAUDIO_RX_0, AHSREN, 1); + reg_write |= SET_BITS(regAUDIO_RX_0, AHSREN, 0); + } +#endif + + if (reg_mask == 0) { + + } else { + rc = pmic_write_reg(REG_AUDIO_RX_0, + reg_write, reg_mask); + if (rc == PMIC_SUCCESS) { + pr_debug("output ports disabled\n"); + audioOutput.outputPort &= ~port; + } + } + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Get the current audio output ports. + * + * This function retrieves the audio output ports that are currently being + * used. + * + * @param handle Device handle from pmic_audio_open() call. + * @param port The audio output ports currently being used. + * + * @retval PMIC_SUCCESS If the audio output ports were successfully + * retrieved. + * @retval PMIC_PARAMETER_ERROR If the handle was invalid. + * @retval PMIC_ERROR If the audio output ports could not be + * retrieved. + */ +PMIC_STATUS pmic_audio_output_get_port(const PMIC_AUDIO_HANDLE handle, + PMIC_AUDIO_OUTPUT_PORT * const port) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((((handle == stDAC.handle) && + (stDAC.handleState == HANDLE_IN_USE)) || + ((handle == vCodec.handle) && + (vCodec.handleState == HANDLE_IN_USE)) || + ((handle == extStereoIn.handle) && + (extStereoIn.handleState == HANDLE_IN_USE))) && + (port != (PMIC_AUDIO_OUTPUT_PORT *) NULL)) { + *port = audioOutput.outputPort; + + rc = PMIC_SUCCESS; + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Set the gain level for the external stereo inputs. + * + * This function sets the gain levels for the external stereo inputs. + * + * @param handle Device handle from pmic_audio_open() call. + * @param gain The external stereo input gain level. + * + * @retval PMIC_SUCCESS If the gain level was successfully set. + * @retval PMIC_PARAMETER_ERROR If the handle or gain level was invalid. + * @retval PMIC_ERROR If the gain level could not be set. + */ +PMIC_STATUS pmic_audio_output_set_stereo_in_gain(const PMIC_AUDIO_HANDLE handle, + const PMIC_AUDIO_STEREO_IN_GAIN + gain) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_mask = SET_BITS(regAUDIO_RX_1, ARXINEN, 1) | + SET_BITS(regAUDIO_RX_1, ARXIN, 1); + unsigned int reg_write = SET_BITS(regAUDIO_RX_1, ARXINEN, 1); + + /* No critical section required here since we are not updating any + * global data. + */ + + /* The ARX amplifier for stereo is also enabled over here */ + + if ((gain == STEREO_IN_GAIN_0DB) || (gain == STEREO_IN_GAIN_PLUS_18DB)) { + if ((handle == extStereoIn.handle) && + (extStereoIn.handleState == HANDLE_IN_USE)) { + + if (gain == STEREO_IN_GAIN_0DB) { + reg_write |= SET_BITS(regAUDIO_RX_1, ARXIN, 1); + } else { + reg_write |= SET_BITS(regAUDIO_RX_1, ARXIN, 0); + } + + rc = pmic_write_reg(REG_AUDIO_RX_1, + reg_write, reg_mask); + + if (rc == PMIC_SUCCESS) { + pr_debug("Ext stereo gain set\n"); + extStereoIn.inputGain = gain; + + } + + } else { + rc = PMIC_PARAMETER_ERROR; + } + } + + return rc; +} + +/*! + * @brief Get the current gain level for the external stereo inputs. + * + * This function retrieves the current gain levels for the external stereo + * inputs. + * + * @param handle Device handle from pmic_audio_open() call. + * @param gain The current external stereo input gain + * level. + * + * @retval PMIC_SUCCESS If the gain level was successfully + * retrieved. + * @retval PMIC_PARAMETER_ERROR If the handle was invalid. + * @retval PMIC_ERROR If the gain level could not be retrieved. + */ +PMIC_STATUS pmic_audio_output_get_stereo_in_gain(const PMIC_AUDIO_HANDLE handle, + PMIC_AUDIO_STEREO_IN_GAIN * + const gain) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == extStereoIn.handle) && + (extStereoIn.handleState == HANDLE_IN_USE) && + (gain != (PMIC_AUDIO_STEREO_IN_GAIN *) NULL)) { + *gain = extStereoIn.inputGain; + rc = PMIC_SUCCESS; + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Set the output PGA gain level. + * + * This function sets the audio output PGA gain level. + * + * @param handle Device handle from pmic_audio_open() call. + * @param gain The output PGA gain level. + * + * @retval PMIC_SUCCESS If the gain level was successfully set. + * @retval PMIC_PARAMETER_ERROR If the handle or gain level was invalid. + * @retval PMIC_ERROR If the gain level could not be set. + */ +PMIC_STATUS pmic_audio_output_set_pgaGain(const PMIC_AUDIO_HANDLE handle, + const PMIC_AUDIO_OUTPUT_PGA_GAIN gain) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_write = 0; + unsigned int reg_mask = 0; + unsigned int reg_gain; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if (!((gain >= OUTPGA_GAIN_MINUS_33DB) + && (gain <= OUTPGA_GAIN_PLUS_6DB))) { + rc = PMIC_NOT_SUPPORTED; + pr_debug("output set PGA gain - wrong gain value\n"); + } else { + reg_gain = gain + 2; + if ((handle == extStereoIn.handle) && + (extStereoIn.handleState == HANDLE_IN_USE)) { + reg_mask = SET_BITS(regAUDIO_RX_1, ARXIN, 15) | + SET_BITS(regAUDIO_RX_1, ARXINEN, 1); + reg_write = SET_BITS(regAUDIO_RX_1, ARXIN, reg_gain) | + SET_BITS(regAUDIO_RX_1, ARXINEN, 1); + } else if ((handle == vCodec.handle) && + (vCodec.handleState == HANDLE_IN_USE)) { + reg_mask = SET_BITS(regAUDIO_RX_1, PGARX, 15); + reg_write = SET_BITS(regAUDIO_RX_1, PGARX, reg_gain); + } else if ((handle == stDAC.handle) && + (stDAC.handleState == HANDLE_IN_USE)) { + reg_mask = SET_BITS(regAUDIO_RX_1, PGAST, 15); + reg_write = SET_BITS(regAUDIO_RX_1, PGAST, reg_gain); + } + + if (reg_mask == 0) { + + } else { + rc = pmic_write_reg(REG_AUDIO_RX_1, + reg_write, reg_mask); + + if (rc == PMIC_SUCCESS) { + pr_debug("Output PGA gains set\n"); + + if (handle == stDAC.handle) { + audioOutput.stDacoutputPGAGain = gain; + } else if (handle == vCodec.handle) { + audioOutput.vCodecoutputPGAGain = gain; + } else { + audioOutput.extStereooutputPGAGain = + gain; + } + } else { + pr_debug + ("Error writing PGA gains to register\n"); + } + } + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Get the output PGA gain level. + * + * This function retrieves the current audio output PGA gain level. + * + * @param handle Device handle from pmic_audio_open() call. + * @param gain The current output PGA gain level. + * + * @retval PMIC_SUCCESS If the gain level was successfully + * retrieved. + * @retval PMIC_PARAMETER_ERROR If the handle was invalid. + * @retval PMIC_ERROR If the gain level could not be retrieved. + */ +PMIC_STATUS pmic_audio_output_get_pgaGain(const PMIC_AUDIO_HANDLE handle, + PMIC_AUDIO_OUTPUT_PGA_GAIN * + const gain) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if (gain != (PMIC_AUDIO_OUTPUT_PGA_GAIN *) NULL) { + if ((handle == extStereoIn.handle) && + (extStereoIn.handleState == HANDLE_IN_USE)) { + *gain = audioOutput.extStereooutputPGAGain; + rc = PMIC_SUCCESS; + } else if ((handle == vCodec.handle) && + (vCodec.handleState == HANDLE_IN_USE)) { + *gain = audioOutput.vCodecoutputPGAGain; + rc = PMIC_SUCCESS; + } else if ((handle == stDAC.handle) && + (stDAC.handleState == HANDLE_IN_USE)) { + *gain = audioOutput.stDacoutputPGAGain; + rc = PMIC_SUCCESS; + } else { + rc = PMIC_PARAMETER_ERROR; + } + } else { + rc = PMIC_PARAMETER_ERROR; + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Enable the output mixer. + * + * This function enables the output mixer for the audio stream that + * corresponds to the current handle (i.e., the Voice CODEC, Stereo DAC, or + * the external stereo inputs). + * + * @param handle Device handle from pmic_audio_open() call. + * + * @retval PMIC_SUCCESS If the mixer was successfully enabled. + * @retval PMIC_PARAMETER_ERROR If the handle was invalid. + * @retval PMIC_ERROR If the mixer could not be enabled. + */ +PMIC_STATUS pmic_audio_output_enable_mixer(const PMIC_AUDIO_HANDLE handle) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_mask = 0; + unsigned int reg_write = 0; + unsigned int reg_mask_mix = 0; + unsigned int reg_write_mix = 0; + + /* No critical section required here since we are not updating any + * global data. + */ + + if (((handle == stDAC.handle) && (stDAC.handleState == HANDLE_IN_USE))) { + reg_mask = SET_BITS(regAUDIO_RX_1, PGASTEN, 1); + reg_write = SET_BITS(regAUDIO_RX_1, PGASTEN, 1); + reg_mask_mix = SET_BITS(regAUDIO_RX_0, ADDSTDC, 1); + reg_write_mix = SET_BITS(regAUDIO_RX_0, ADDSTDC, 1); + } else if ((handle == vCodec.handle) && + (vCodec.handleState == HANDLE_IN_USE)) { + reg_mask = SET_BITS(regAUDIO_RX_1, PGARXEN, 1); + reg_write = SET_BITS(regAUDIO_RX_1, PGARXEN, 1); + audioOutput.vCodecOut = VCODEC_MIXER_OUT; + + reg_mask_mix = SET_BITS(regAUDIO_RX_0, ADDCDC, 1); + reg_write_mix = SET_BITS(regAUDIO_RX_0, ADDCDC, 1); + } else if ((handle == extStereoIn.handle) && + (extStereoIn.handleState == HANDLE_IN_USE)) { + reg_mask = SET_BITS(regAUDIO_RX_1, ARXINEN, 1); + reg_write = SET_BITS(regAUDIO_RX_1, ARXINEN, 1); + reg_mask_mix = SET_BITS(regAUDIO_RX_0, ADDRXIN, 1); + reg_write_mix = SET_BITS(regAUDIO_RX_0, ADDRXIN, 1); + } + + if (reg_mask == 0) { + + } else { + rc = pmic_write_reg(REG_AUDIO_RX_1, reg_write, reg_mask); + + if (rc == PMIC_SUCCESS) { + + rc = pmic_write_reg(REG_AUDIO_RX_0, + reg_write_mix, reg_mask_mix); + if (rc == PMIC_SUCCESS) { + pr_debug("Output PGA mixers enabled\n"); + rc = PMIC_SUCCESS; + } + + } else { + pr_debug("Error writing mixer enable to register\n"); + } + + } + + return rc; +} + +/*! + * @brief Disable the output mixer. + * + * This function disables the output mixer for the audio stream that + * corresponds to the current handle (i.e., the Voice CODEC, Stereo DAC, or + * the external stereo inputs). + * + * @param handle Device handle from pmic_audio_open() call. + * + * @retval PMIC_SUCCESS If the mixer was successfully disabled. + * @retval PMIC_PARAMETER_ERROR If the handle was invalid. + * @retval PMIC_ERROR If the mixer could not be disabled. + */ +PMIC_STATUS pmic_audio_output_disable_mixer(const PMIC_AUDIO_HANDLE handle) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_mask = 0; + unsigned int reg_write = 0; + + unsigned int reg_mask_mix = 0; + unsigned int reg_write_mix = 0; + + /* No critical section required here since we are not updating any + * global data. + */ + if (((handle == stDAC.handle) && (stDAC.handleState == HANDLE_IN_USE))) { + /*reg_mask = SET_BITS(regAUDIO_RX_1, PGASTEN, 1); + reg_write = SET_BITS(regAUDIO_RX_1, PGASTEN, 0); */ + + reg_mask_mix = SET_BITS(regAUDIO_RX_0, ADDSTDC, 1); + reg_write_mix = SET_BITS(regAUDIO_RX_0, ADDSTDC, 0); + } else if ((handle == vCodec.handle) && + (vCodec.handleState == HANDLE_IN_USE)) { + reg_mask = SET_BITS(regAUDIO_RX_1, PGARXEN, 1); + reg_write = SET_BITS(regAUDIO_RX_1, PGARXEN, 0); + audioOutput.vCodecOut = VCODEC_DIRECT_OUT; + + reg_mask_mix = SET_BITS(regAUDIO_RX_0, ADDCDC, 1); + reg_write_mix = SET_BITS(regAUDIO_RX_0, ADDCDC, 0); + } else if ((handle == extStereoIn.handle) && + (extStereoIn.handleState == HANDLE_IN_USE)) { + /*reg_mask = SET_BITS(regAUDIO_RX_1, ARXINEN, 1); + reg_write = SET_BITS(regAUDIO_RX_1, ARXINEN, 0); */ + + reg_mask_mix = SET_BITS(regAUDIO_RX_0, ADDRXIN, 1); + reg_write_mix = SET_BITS(regAUDIO_RX_0, ADDRXIN, 1); + } + + if (reg_mask == 0) { + + } else { + rc = pmic_write_reg(REG_AUDIO_RX_1, reg_write, reg_mask); + + if (rc == PMIC_SUCCESS) { + + rc = pmic_write_reg(REG_AUDIO_RX_0, + reg_write_mix, reg_mask_mix); + if (rc == PMIC_SUCCESS) { + pr_debug("Output PGA mixers disabled\n"); + } + } + } + return rc; +} + +/*! + * @brief Configure and enable the output balance amplifiers. + * + * This function configures and enables the output balance amplifiers. + * + * @param handle Device handle from pmic_audio_open() call. + * @param leftGain The desired left channel gain level. + * @param rightGain The desired right channel gain level. + * + * @retval PMIC_SUCCESS If the output balance amplifiers were + * successfully configured and enabled. + * @retval PMIC_PARAMETER_ERROR If the handle or gain levels were invalid. + * @retval PMIC_ERROR If the output balance amplifiers could not + * be reconfigured or enabled. + */ +PMIC_STATUS pmic_audio_output_set_balance(const PMIC_AUDIO_HANDLE handle, + const PMIC_AUDIO_OUTPUT_BALANCE_GAIN + leftGain, + const PMIC_AUDIO_OUTPUT_BALANCE_GAIN + rightGain) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_mask = 0; + unsigned int reg_write = 0; + unsigned int reg_mask_ch = 0; + unsigned int reg_write_ch = 0; + + /* No critical section required here since we are not updating any + * global data. + */ + + if (!((leftGain >= BAL_GAIN_MINUS_21DB) && (leftGain <= BAL_GAIN_0DB))) { + rc = PMIC_PARAMETER_ERROR; + } else if (!((rightGain >= BAL_GAIN_MINUS_21DB) + && (rightGain <= BAL_GAIN_0DB))) { + rc = PMIC_PARAMETER_ERROR; + } else { + if (((handle == stDAC.handle) && + (stDAC.handleState == HANDLE_IN_USE)) || + ((handle == vCodec.handle) && + (vCodec.handleState == HANDLE_IN_USE)) || + ((handle == extStereoIn.handle) && + (extStereoIn.handleState == HANDLE_IN_USE))) { + /* In mc13783 only one channel can be attenuated wrt the other. + * It is not possible to specify attenuation for both + * This function will return an error if both channels + * are required to be attenuated + * The BALLR bit is set/reset depending on whether leftGain + * or rightGain is specified*/ + if ((rightGain == BAL_GAIN_0DB) + && (leftGain == BAL_GAIN_0DB)) { + /* Nothing to be done */ + } else if ((rightGain != BAL_GAIN_0DB) + && (leftGain == BAL_GAIN_0DB)) { + /* Attenuate right channel */ + reg_mask = SET_BITS(regAUDIO_RX_1, BAL, 7); + reg_mask_ch = SET_BITS(regAUDIO_RX_1, BALLR, 1); + reg_write = + SET_BITS(regAUDIO_RX_1, BAL, + (BAL_GAIN_0DB - rightGain)); + /* The enum and the register values are reversed in order .. */ + reg_write_ch = + SET_BITS(regAUDIO_RX_1, BALLR, 0); + /* BALLR = 0 selects right channel for atten */ + } else if ((rightGain == BAL_GAIN_0DB) + && (leftGain != BAL_GAIN_0DB)) { + /* Attenuate left channel */ + + reg_mask = SET_BITS(regAUDIO_RX_1, BAL, 7); + reg_mask_ch = SET_BITS(regAUDIO_RX_1, BALLR, 1); + reg_write = + SET_BITS(regAUDIO_RX_1, BAL, + (BAL_GAIN_0DB - leftGain)); + reg_write_ch = + SET_BITS(regAUDIO_RX_1, BALLR, 1); + /* BALLR = 1 selects left channel for atten */ + } else { + rc = PMIC_PARAMETER_ERROR; + } + + if ((reg_mask == 0) || (reg_mask_ch == 0)) { + + } else { + rc = pmic_write_reg(REG_AUDIO_RX_1, + reg_write_ch, reg_mask_ch); + + if (rc == PMIC_SUCCESS) { + rc = pmic_write_reg(REG_AUDIO_RX_1, + reg_write, + reg_mask); + + if (rc == PMIC_SUCCESS) { + pr_debug + ("Output balance attenuation set\n"); + audioOutput.balanceLeftGain = + leftGain; + audioOutput.balanceRightGain = + rightGain; + } + } + } + } + } + return rc; +} + +/*! + * @brief Get the current output balance amplifier gain levels. + * + * This function retrieves the current output balance amplifier gain levels. + * + * @param handle Device handle from pmic_audio_open() call. + * @param leftGain The current left channel gain level. + * @param rightGain The current right channel gain level. + * + * @retval PMIC_SUCCESS If the output balance amplifier gain levels + * were successfully retrieved. + * @retval PMIC_PARAMETER_ERROR If the handle was invalid. + * @retval PMIC_ERROR If the output balance amplifier gain levels + * could be retrieved. + */ +PMIC_STATUS pmic_audio_output_get_balance(const PMIC_AUDIO_HANDLE handle, + PMIC_AUDIO_OUTPUT_BALANCE_GAIN * + const leftGain, + PMIC_AUDIO_OUTPUT_BALANCE_GAIN * + const rightGain) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((((handle == stDAC.handle) && + (stDAC.handleState == HANDLE_IN_USE)) || + ((handle == vCodec.handle) && + (vCodec.handleState == HANDLE_IN_USE)) || + ((handle == extStereoIn.handle) && + (extStereoIn.handleState == HANDLE_IN_USE))) && + ((leftGain != (PMIC_AUDIO_OUTPUT_BALANCE_GAIN *) NULL) && + (rightGain != (PMIC_AUDIO_OUTPUT_BALANCE_GAIN *) NULL))) { + *leftGain = audioOutput.balanceLeftGain; + *rightGain = audioOutput.balanceRightGain; + + rc = PMIC_SUCCESS; + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Configure and enable the output mono adder. + * + * This function configures and enables the output mono adder. + * + * @param handle Device handle from pmic_audio_open() call. + * @param mode The desired mono adder operating mode. + * + * @retval PMIC_SUCCESS If the mono adder was successfully + * configured and enabled. + * @retval PMIC_PARAMETER_ERROR If the handle or mono adder mode was + * invalid. + * @retval PMIC_ERROR If the mono adder could not be reconfigured + * or enabled. + */ +PMIC_STATUS pmic_audio_output_enable_mono_adder(const PMIC_AUDIO_HANDLE handle, + const PMIC_AUDIO_MONO_ADDER_MODE + mode) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_write = 0; + unsigned int reg_mask = SET_BITS(regAUDIO_RX_1, MONO, 3); + + /* No critical section required here since we are not updating any + * global data. + */ + + if ((mode >= MONO_ADDER_OFF) && (mode <= STEREO_OPPOSITE_PHASE)) { + if (((handle == stDAC.handle) && + (stDAC.handleState == HANDLE_IN_USE)) || + ((handle == vCodec.handle) && + (vCodec.handleState == HANDLE_IN_USE)) || + ((handle == extStereoIn.handle) && + (extStereoIn.handleState == HANDLE_IN_USE))) { + if (mode == MONO_ADDER_OFF) { + reg_write = SET_BITS(regAUDIO_RX_1, MONO, 0); + } else if (mode == MONO_ADD_LEFT_RIGHT) { + reg_write = SET_BITS(regAUDIO_RX_1, MONO, 2); + } else if (mode == MONO_ADD_OPPOSITE_PHASE) { + reg_write = SET_BITS(regAUDIO_RX_1, MONO, 3); + } else { /* stereo opposite */ + + reg_write = SET_BITS(regAUDIO_RX_1, MONO, 1); + } + + rc = pmic_write_reg(REG_AUDIO_RX_1, + reg_write, reg_mask); + + if (rc == PMIC_SUCCESS) { + pr_debug("Output mono adder mode set\n"); + + } + + } else { + rc = PMIC_PARAMETER_ERROR; + } + } else { + rc = PMIC_PARAMETER_ERROR; + } + return rc; +} + +/*! + * @brief Disable the output mono adder. + * + * This function disables the output mono adder. + * + * @param handle Device handle from pmic_audio_open() call. + * + * @retval PMIC_SUCCESS If the mono adder was successfully + * disabled. + * @retval PMIC_PARAMETER_ERROR If the handle was invalid. + * @retval PMIC_ERROR If the mono adder could not be disabled. + */ +PMIC_STATUS pmic_audio_output_disable_mono_adder(const PMIC_AUDIO_HANDLE handle) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + const unsigned int reg_write = 0; + const unsigned int reg_mask = SET_BITS(regAUDIO_RX_1, MONO, 3); + + /* No critical section required here since we are not updating any + * global data. + */ + + if (((handle == stDAC.handle) && + (stDAC.handleState == HANDLE_IN_USE)) || + ((handle == vCodec.handle) && + (vCodec.handleState == HANDLE_IN_USE)) || + ((handle == extStereoIn.handle) && + (extStereoIn.handleState == HANDLE_IN_USE))) { + rc = pmic_write_reg(REG_AUDIO_RX_1, reg_write, reg_mask); + } + + return rc; +} + +/*! + * @brief Configure the mono adder output gain level. + * + * This function configures the mono adder output amplifier gain level. + * + * @param handle Device handle from pmic_audio_open() call. + * @param gain The desired output gain level. + * + * @retval PMIC_SUCCESS If the mono adder output amplifier gain + * level was successfully set. + * @retval PMIC_PARAMETER_ERROR If the handle or gain level was invalid. + * @retval PMIC_ERROR If the mono adder output amplifier gain + * level could not be reconfigured. + */ +PMIC_STATUS pmic_audio_output_set_mono_adder_gain(const PMIC_AUDIO_HANDLE + handle, + const + PMIC_AUDIO_MONO_ADDER_OUTPUT_GAIN + gain) +{ + PMIC_STATUS rc = PMIC_NOT_SUPPORTED; + return rc; +} + +/*! + * @brief Get the current mono adder output gain level. + * + * This function retrieves the current mono adder output amplifier gain level. + * + * @param handle Device handle from pmic_audio_open() call. + * @param gain The current output gain level. + * + * @retval PMIC_SUCCESS If the mono adder output amplifier gain + * level was successfully retrieved. + * @retval PMIC_PARAMETER_ERROR If the handle was invalid. + * @retval PMIC_ERROR If the mono adder output amplifier gain + * level could not be retrieved. + */ +PMIC_STATUS pmic_audio_output_get_mono_adder_gain(const PMIC_AUDIO_HANDLE + handle, + PMIC_AUDIO_MONO_ADDER_OUTPUT_GAIN + * const gain) +{ + PMIC_STATUS rc = PMIC_NOT_SUPPORTED; + return rc; +} + +/*! + * @brief Set various audio output section options. + * + * This function sets one or more audio output section configuration + * options. The currently supported options include whether to disable + * the non-inverting mono speaker output, enabling the loudspeaker common + * bias circuit, enabling detection of headset insertion/removal, and + * whether to automatically disable the headset amplifiers when a headset + * insertion/removal has been detected. + * + * @param handle Device handle from pmic_audio_open() call. + * @param config The desired audio output section + * configuration options to be set. + * + * @retval PMIC_SUCCESS If the desired configuration options were + * all successfully set. + * @retval PMIC_PARAMETER_ERROR If the handle or configuration options + * were invalid. + * @retval PMIC_ERROR If the desired configuration options + * could not be set. + */ +PMIC_STATUS pmic_audio_output_set_config(const PMIC_AUDIO_HANDLE handle, + const PMIC_AUDIO_OUTPUT_CONFIG config) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_mask = 0; + unsigned int reg_write = 0; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if (((handle == stDAC.handle) && + (stDAC.handleState == HANDLE_IN_USE)) || + ((handle == vCodec.handle) && + (vCodec.handleState == HANDLE_IN_USE)) || + ((handle == extStereoIn.handle) && + (extStereoIn.handleState == HANDLE_IN_USE))) { + if (config & MONO_SPEAKER_INVERT_OUT_ONLY) { + /* If this is one of the parameters */ + rc = PMIC_NOT_SUPPORTED; + } else { + if (config & MONO_LOUDSPEAKER_COMMON_BIAS) { + reg_mask = SET_BITS(regAUDIO_RX_0, ALSPREF, 1); + reg_write = SET_BITS(regAUDIO_RX_0, ALSPREF, 1); + } + if (config & HEADSET_DETECT_ENABLE) { + reg_mask |= SET_BITS(regAUDIO_RX_0, HSDETEN, 1); + reg_write |= + SET_BITS(regAUDIO_RX_0, HSDETEN, 1); + } + if (config & STEREO_HEADSET_AMP_AUTO_DISABLE) { + reg_mask |= + SET_BITS(regAUDIO_RX_0, HSDETAUTOB, 1); + reg_write |= + SET_BITS(regAUDIO_RX_0, HSDETAUTOB, 1); + } + + if (reg_mask == 0) { + rc = PMIC_PARAMETER_ERROR; + } else { + rc = pmic_write_reg(REG_AUDIO_RX_0, + reg_write, reg_mask); + + if (rc == PMIC_SUCCESS) { + pr_debug("Output config set\n"); + audioOutput.config |= config; + + } + } + } + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Clear various audio output section options. + * + * This function clears one or more audio output section configuration + * options. + * + * @param handle Device handle from pmic_audio_open() call. + * @param config The desired audio output section + * configuration options to be cleared. + * + * @retval PMIC_SUCCESS If the desired configuration options were + * all successfully cleared. + * @retval PMIC_PARAMETER_ERROR If the handle or configuration options + * were invalid. + * @retval PMIC_ERROR If the desired configuration options + * could not be cleared. + */ +PMIC_STATUS pmic_audio_output_clear_config(const PMIC_AUDIO_HANDLE handle, + const PMIC_AUDIO_OUTPUT_CONFIG + config) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + /*unsigned int reg_write_RX = 0; + unsigned int reg_mask_RX = 0; + unsigned int reg_write_TX = 0; + unsigned int reg_mask_TX = 0; */ + unsigned int reg_mask = 0; + unsigned int reg_write = 0; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if (((handle == stDAC.handle) && + (stDAC.handleState == HANDLE_IN_USE)) || + ((handle == vCodec.handle) && + (vCodec.handleState == HANDLE_IN_USE)) || + ((handle == extStereoIn.handle) && + (extStereoIn.handleState == HANDLE_IN_USE))) { + if (config & MONO_SPEAKER_INVERT_OUT_ONLY) { + /* If this is one of the parameters */ + rc = PMIC_NOT_SUPPORTED; + } else { + if (config & MONO_LOUDSPEAKER_COMMON_BIAS) { + reg_mask = SET_BITS(regAUDIO_RX_0, ALSPREF, 1); + reg_write = SET_BITS(regAUDIO_RX_0, ALSPREF, 0); + } + + if (config & HEADSET_DETECT_ENABLE) { + reg_mask |= SET_BITS(regAUDIO_RX_0, HSDETEN, 1); + reg_write |= + SET_BITS(regAUDIO_RX_0, HSDETEN, 0); + } + + if (config & STEREO_HEADSET_AMP_AUTO_DISABLE) { + reg_mask |= + SET_BITS(regAUDIO_RX_0, HSDETAUTOB, 1); + reg_write |= + SET_BITS(regAUDIO_RX_0, HSDETAUTOB, 0); + } + + if (reg_mask == 0) { + rc = PMIC_PARAMETER_ERROR; + } else { + rc = pmic_write_reg(REG_AUDIO_RX_0, + reg_write, reg_mask); + + if (rc == PMIC_SUCCESS) { + pr_debug("Output config cleared\n"); + audioOutput.config &= ~config; + + } + } + } + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Get the current audio output section options. + * + * This function retrieves the current audio output section configuration + * option settings. + * + * @param handle Device handle from pmic_audio_open() call. + * @param config The current audio output section + * configuration option settings. + * + * @retval PMIC_SUCCESS If the current configuration options were + * successfully retrieved. + * @retval PMIC_PARAMETER_ERROR If the handle was invalid. + * @retval PMIC_ERROR If the current configuration options + * could not be retrieved. + */ +PMIC_STATUS pmic_audio_output_get_config(const PMIC_AUDIO_HANDLE handle, + PMIC_AUDIO_OUTPUT_CONFIG * + const config) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + + /* Use a critical section to ensure a consistent hardware state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((((handle == stDAC.handle) && + (stDAC.handleState == HANDLE_IN_USE)) || + ((handle == vCodec.handle) && + (vCodec.handleState == HANDLE_IN_USE)) || + ((handle == extStereoIn.handle) && + (extStereoIn.handleState == HANDLE_IN_USE))) && + (config != (PMIC_AUDIO_OUTPUT_CONFIG *) NULL)) { + *config = audioOutput.config; + + rc = PMIC_SUCCESS; + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * @brief Enable the phantom ground circuit that is used to help identify + * the type of headset that has been inserted. + * + * This function enables the phantom ground circuit that is used to help + * identify the type of headset (e.g., stereo or mono) that has been inserted. + * + * @param handle Device handle from pmic_audio_open() call. + * + * @retval PMIC_SUCCESS If the phantom ground circuit was + * successfully enabled. + * @retval PMIC_PARAMETER_ERROR If the handle was invalid. + * @retval PMIC_ERROR If the phantom ground circuit could not + * be enabled. + */ +PMIC_STATUS pmic_audio_output_enable_phantom_ground() +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + const unsigned int reg_mask = SET_BITS(regAUDIO_RX_0, HSPGDIS, 1); + + /* No critical section required here since we are not updating any + * global data. + */ + + rc = pmic_write_reg(REG_AUDIO_RX_0, 0, reg_mask); + if (rc == PMIC_SUCCESS) { + pr_debug("Phantom ground enabled\n"); + + } + return rc; +} + +/*! + * @brief Disable the phantom ground circuit that is used to help identify + * the type of headset that has been inserted. + * + * This function disables the phantom ground circuit that is used to help + * identify the type of headset (e.g., stereo or mono) that has been inserted. + * + * @param handle Device handle from pmic_audio_open() call. + * + * @retval PMIC_SUCCESS If the phantom ground circuit was + * successfully disabled. + * @retval PMIC_PARAMETER_ERROR If the handle was invalid. + * @retval PMIC_ERROR If the phantom ground circuit could not + * be disabled. + */ +PMIC_STATUS pmic_audio_output_disable_phantom_ground() +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + const unsigned int reg_mask = SET_BITS(regAUDIO_RX_0, HSPGDIS, 1); + + /* No critical section required here since we are not updating any + * global data. + */ + + rc = pmic_write_reg(REG_AUDIO_RX_0, 1, reg_mask); + if (rc == PMIC_SUCCESS) { + pr_debug("Phantom ground disabled\n"); + + } + return rc; +} + +/*@}*/ + +/************************************************************************** + * Static functions. + ************************************************************************** + */ + +/*! + * @name Audio Driver Internal Support Functions + * These non-exported internal functions are used to support the functionality + * of the exported audio APIs. + */ +/*@{*/ + +/*! + * @brief Enables the 5.6V boost for the microphone bias 2 circuit. + * + * This function enables the switching regulator SW3 and configures it to + * provide the 5.6V boost that is required for driving the microphone bias 2 + * circuit when using a 5-pole jack configuration (which is the case for the + * Sphinx board). + * + * @retval PMIC_SUCCESS The 5.6V boost was successfully enabled. + * @retval PMIC_ERROR Failed to enable the 5.6V boost. + */ +/* +static PMIC_STATUS pmic_audio_mic_boost_enable(void) +{ + PMIC_STATUS rc = PMIC_NOT_SUPPORTED; + + return rc; +} +*/ +/*! + * @brief Disables the 5.6V boost for the microphone bias 2 circuit. + * + * This function disables the switching regulator SW3 to turn off the 5.6V + * boost for the microphone bias 2 circuit. + * + * @retval PMIC_SUCCESS The 5.6V boost was successfully disabled. + * @retval PMIC_ERROR Failed to disable the 5.6V boost. + */ +/* +static PMIC_STATUS pmic_audio_mic_boost_disable(void) +{ + PMIC_STATUS rc = PMIC_NOT_SUPPORTED; + + return rc; +} +*/ + +/*! + * @brief Free a device handle previously acquired by calling pmic_audio_open(). + * + * Terminate further access to the PMIC audio hardware that was previously + * acquired by calling pmic_audio_open(). This now allows another thread to + * successfully call pmic_audio_open() to gain access. + * + * Note that we will shutdown/reset the Voice CODEC or Stereo DAC as well as + * any associated audio input/output components that are no longer required. + * + * Also note that this function should only be called with the mutex already + * acquired. + * + * @param handle Device handle from pmic_audio_open() call. + * + * @retval PMIC_SUCCESS If the close request was successful. + * @retval PMIC_PARAMETER_ERROR If the handle is invalid. + */ +static PMIC_STATUS pmic_audio_close_handle(const PMIC_AUDIO_HANDLE handle) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + + /* Match up the handle to the audio device and then close it. */ + if ((handle == stDAC.handle) && (stDAC.handleState == HANDLE_IN_USE)) { + /* Also shutdown the Stereo DAC hardware. The simplest way to + * do this is to simply call pmic_audio_reset_device() which will + * restore the ST_DAC register to it's initial power-on state. + * + * This will also shutdown the audio output section if no one + * else is still using it. + */ + rc = pmic_audio_reset_device(stDAC.handle); + + if (rc == PMIC_SUCCESS) { + stDAC.handle = AUDIO_HANDLE_NULL; + stDAC.handleState = HANDLE_FREE; + } + } else if ((handle == vCodec.handle) && + (vCodec.handleState == HANDLE_IN_USE)) { + /* Also shutdown the Voice CODEC and audio input hardware. The + * simplest way to do this is to simply call pmic_audio_reset_device() + * which will restore the AUD_CODEC register to it's initial + * power-on state. + * + * This will also shutdown the audio output section if no one + * else is still using it. + */ + rc = pmic_audio_reset_device(vCodec.handle); + if (rc == PMIC_SUCCESS) { + vCodec.handle = AUDIO_HANDLE_NULL; + vCodec.handleState = HANDLE_FREE; + } + } else if ((handle == extStereoIn.handle) && + (extStereoIn.handleState == HANDLE_IN_USE)) { + + /* Call pmic_audio_reset_device() here to shutdown the audio output + * section if no one else is still using it. + */ + rc = pmic_audio_reset_device(extStereoIn.handle); + + if (rc == PMIC_SUCCESS) { + extStereoIn.handle = AUDIO_HANDLE_NULL; + extStereoIn.handleState = HANDLE_FREE; + } + } + + return rc; +} + +/*! + * @brief Reset the selected audio hardware control registers to their + * power on state. + * + * This resets all of the audio hardware control registers currently + * associated with the device handle back to their power on states. For + * example, if the handle is associated with the Stereo DAC and a + * specific output port and output amplifiers, then this function will + * reset all of those components to their initial power on state. + * + * This function can only be called if the mutex has already been acquired. + * + * @param handle Device handle from pmic_audio_open() call. + * + * @retval PMIC_SUCCESS If the reset operation was successful. + * @retval PMIC_PARAMETER_ERROR If the handle is invalid. + * @retval PMIC_ERROR If the reset was unsuccessful. + */ +static PMIC_STATUS pmic_audio_reset_device(const PMIC_AUDIO_HANDLE handle) +{ + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + unsigned int reg_mask = 0; + + if ((handle == stDAC.handle) && (stDAC.handleState == HANDLE_IN_USE)) { + /* Also shutdown the audio output section if nobody else is using it. + if ((vCodec.handleState == HANDLE_FREE) && + (extStereoIn.handleState == HANDLE_FREE)) + { + pmic_write_reg(REG_RX_AUD_AMPS, RESET_RX_AUD_AMPS, + REG_FULLMASK); + } */ + + rc = pmic_write_reg(REG_AUDIO_STEREO_DAC, + RESET_ST_DAC, REG_FULLMASK); + + if (rc == PMIC_SUCCESS) { + rc = pmic_write_reg(REG_AUDIO_SSI_NETWORK, + RESET_SSI_NETWORK, + REG_SSI_STDAC_MASK); + if (rc == PMIC_SUCCESS) { + /* Also reset the driver state information to match. Note that we + * keep the device handle and event callback settings unchanged + * since these don't affect the actual hardware and we rely on + * the user to explicitly close the handle or deregister callbacks + */ + stDAC.busID = AUDIO_DATA_BUS_1; + stDAC.protocol = NORMAL_MSB_JUSTIFIED_MODE; + stDAC.protocol_set = false; + stDAC.masterSlave = BUS_MASTER_MODE; + stDAC.numSlots = USE_2_TIMESLOTS; + stDAC.clockIn = CLOCK_IN_CLIA; + stDAC.samplingRate = STDAC_RATE_44_1_KHZ; + stDAC.clockFreq = STDAC_CLI_13MHZ; + stDAC.invert = NO_INVERT; + stDAC.timeslot = USE_TS0_TS1; + stDAC.config = (PMIC_AUDIO_STDAC_CONFIG) 0; + + } + } + } else if ((handle == vCodec.handle) + && (vCodec.handleState == HANDLE_IN_USE)) { + /* Disable the audio input section when disabling the Voice CODEC. */ + pmic_write_reg(REG_AUDIO_TX, RESET_AUDIO_TX, REG_FULLMASK); + + rc = pmic_write_reg(REG_AUDIO_CODEC, + RESET_AUD_CODEC, REG_FULLMASK); + + if (rc == PMIC_SUCCESS) { + rc = pmic_write_reg(REG_AUDIO_SSI_NETWORK, + RESET_SSI_NETWORK, + REG_SSI_VCODEC_MASK); + if (rc == PMIC_SUCCESS) { + + /* Also reset the driver state information to match. Note that we + * keep the device handle and event callback settings unchanged + * since these don't affect the actual hardware and we rely on + * the user to explicitly close the handle or deregister callbacks + */ + vCodec.busID = AUDIO_DATA_BUS_2; + vCodec.protocol = NETWORK_MODE; + vCodec.protocol_set = false; + vCodec.masterSlave = BUS_SLAVE_MODE; + vCodec.numSlots = USE_4_TIMESLOTS; + vCodec.clockIn = CLOCK_IN_CLIB; + vCodec.samplingRate = VCODEC_RATE_8_KHZ; + vCodec.clockFreq = VCODEC_CLI_13MHZ; + vCodec.invert = NO_INVERT; + vCodec.timeslot = USE_TS0; + vCodec.config = + INPUT_HIGHPASS_FILTER | + OUTPUT_HIGHPASS_FILTER; + + } + } + + } else if ((handle == extStereoIn.handle) && + (extStereoIn.handleState == HANDLE_IN_USE)) { + /* Disable the Ext stereo Amplifier and disable it as analog mixer input */ + reg_mask = SET_BITS(regAUDIO_RX_1, ARXINEN, 1); + pmic_write_reg(REG_AUDIO_RX_1, 0, reg_mask); + + reg_mask = SET_BITS(regAUDIO_RX_0, ADDRXIN, 1); + pmic_write_reg(REG_AUDIO_RX_0, 0, reg_mask); + + /* We don't need to reset any other registers for this case. */ + rc = PMIC_SUCCESS; + } + + return rc; +} + +/*! + * @brief Deregister the callback function and event mask currently associated + * with an audio device handle. + * + * This function deregisters any existing callback function and event mask for + * the given audio device handle. This is done by either calling the + * pmic_audio_clear_callback() API or by closing the device handle. + * + * Note that this function should only be called with the mutex already + * acquired. We will also acquire the spinlock here to prevent possible + * race conditions with the interrupt handler. + * + * @param[in] callback The current event callback function pointer. + * @param[in] eventMask The current audio event mask. + * + * @retval PMIC_SUCCESS If the callback function and event mask + * were both successfully deregistered. + * @retval PMIC_ERROR If either the callback function or the + * event mask was not successfully + * deregistered. + */ + +static PMIC_STATUS pmic_audio_deregister(void *callback, + PMIC_AUDIO_EVENTS * const eventMask) +{ + unsigned long flags; + pmic_event_callback_t eventNotify; + PMIC_STATUS rc = PMIC_SUCCESS; + + /* Deregister each of the PMIC events that we had previously + * registered for by calling pmic_event_subscribe(). + */ + if (*eventMask & (HEADSET_DETECTED)) { + /* We need to deregister for the A1 amplifier interrupt. */ + eventNotify.func = callback; + eventNotify.param = (void *)(CORE_EVENT_HSDETI); + if (pmic_event_unsubscribe(EVENT_HSDETI, eventNotify) == + PMIC_SUCCESS) { + *eventMask &= ~(HEADSET_DETECTED); + pr_debug("Deregistered for EVENT_HSDETI\n"); + } else { + rc = PMIC_ERROR; + } + } + + if (*eventMask & (HEADSET_STEREO)) { + /* We need to deregister for the A1 amplifier interrupt. */ + eventNotify.func = callback; + eventNotify.param = (void *)(CORE_EVENT_HSLI); + if (pmic_event_unsubscribe(EVENT_HSLI, eventNotify) == + PMIC_SUCCESS) { + *eventMask &= ~(HEADSET_STEREO); + pr_debug("Deregistered for EVENT_HSLI\n"); + } else { + rc = PMIC_ERROR; + } + } + if (*eventMask & (HEADSET_THERMAL_SHUTDOWN)) { + /* We need to deregister for the A1 amplifier interrupt. */ + eventNotify.func = callback; + eventNotify.param = (void *)(CORE_EVENT_ALSPTHI); + if (pmic_event_unsubscribe(EVENT_ALSPTHI, eventNotify) == + PMIC_SUCCESS) { + *eventMask &= ~(HEADSET_THERMAL_SHUTDOWN); + pr_debug("Deregistered for EVENT_ALSPTHI\n"); + } else { + rc = PMIC_ERROR; + } + } + if (*eventMask & (HEADSET_SHORT_CIRCUIT)) { + /* We need to deregister for the A1 amplifier interrupt. */ + eventNotify.func = callback; + eventNotify.param = (void *)(CORE_EVENT_AHSSHORTI); + if (pmic_event_unsubscribe(EVENT_AHSSHORTI, eventNotify) == + PMIC_SUCCESS) { + *eventMask &= ~(HEADSET_SHORT_CIRCUIT); + pr_debug("Deregistered for EVENT_AHSSHORTI\n"); + } else { + rc = PMIC_ERROR; + } + } + + if (rc == PMIC_SUCCESS) { + /* We need to grab the spinlock here to create a critical section to + * avoid any possible race conditions with the interrupt handler + */ + spin_lock_irqsave(&lock, flags); + + /* Restore the initial reset values for the callback function + * and event mask parameters. This should be NULL and zero, + * respectively. + */ + callback = NULL; + *eventMask = 0; + + /* Exit the critical section. */ + spin_unlock_irqrestore(&lock, flags); + } + + return rc; +} + +/*! + * @brief enable/disable fm output. + * + * @param[in] enable true to enable false to disable + */ +PMIC_STATUS pmic_audio_fm_output_enable(bool enable) +{ + unsigned int reg_mask = 0; + unsigned int reg_write = 0; + PMIC_STATUS rc = PMIC_PARAMETER_ERROR; + if (enable) { + pmic_audio_antipop_enable(ANTI_POP_RAMP_FAST); + reg_mask |= SET_BITS(regAUDIO_RX_0, AHSLEN, 1); + reg_write |= SET_BITS(regAUDIO_RX_0, AHSLEN, 1); + reg_mask |= SET_BITS(regAUDIO_RX_0, AHSREN, 1); + reg_write |= SET_BITS(regAUDIO_RX_0, AHSREN, 1); + + reg_mask |= SET_BITS(regAUDIO_RX_0, AHSSEL, 1); + reg_write |= SET_BITS(regAUDIO_RX_0, AHSSEL, 1); + + reg_mask |= SET_BITS(regAUDIO_RX_0, ADDRXIN, 1); + reg_write |= SET_BITS(regAUDIO_RX_0, ADDRXIN, 1); + + reg_mask |= SET_BITS(regAUDIO_RX_0, HSPGDIS, 1); + reg_write |= SET_BITS(regAUDIO_RX_0, HSPGDIS, 0); + } else { + reg_mask |= SET_BITS(regAUDIO_RX_0, ADDRXIN, 1); + reg_write |= SET_BITS(regAUDIO_RX_0, ADDRXIN, 0); + } + rc = pmic_write_reg(REG_AUDIO_RX_0, reg_write, reg_mask); + if (rc != PMIC_SUCCESS) + return rc; + if (enable) { + reg_mask = SET_BITS(regAUDIO_RX_1, ARXINEN, 1); + reg_write = SET_BITS(regAUDIO_RX_1, ARXINEN, 1); + } else { + reg_mask = SET_BITS(regAUDIO_RX_1, ARXINEN, 1); + reg_write = SET_BITS(regAUDIO_RX_1, ARXINEN, 0); + } + rc = pmic_write_reg(REG_AUDIO_RX_1, reg_write, reg_mask); + return rc; +} + +/*@}*/ + +/************************************************************************** + * Module initialization and termination functions. + * + * Note that if this code is compiled into the kernel, then the + * module_init() function will be called within the device_initcall() + * group. + ************************************************************************** + */ + +/*! + * @name Audio Driver Loading/Unloading Functions + * These non-exported internal functions are used to support the audio + * device driver initialization and de-initialization operations. + */ +/*@{*/ + +/*! + * @brief This is the audio device driver initialization function. + * + * This function is called by the kernel when this device driver is first + * loaded. + */ +static int __init mc13783_pmic_audio_init(void) +{ + printk(KERN_INFO "PMIC Audio driver loading...\n"); + + return 0; +} + +/*! + * @brief This is the audio device driver de-initialization function. + * + * This function is called by the kernel when this device driver is about + * to be unloaded. + */ +static void __exit mc13783_pmic_audio_exit(void) +{ + printk(KERN_INFO "PMIC Audio driver unloading...\n"); + + /* Close all device handles that are still open. This will also + * deregister any callbacks that may still be active. + */ + if (stDAC.handleState == HANDLE_IN_USE) { + pmic_audio_close(stDAC.handle); + } + if (vCodec.handleState == HANDLE_IN_USE) { + pmic_audio_close(vCodec.handle); + } + if (extStereoIn.handleState == HANDLE_IN_USE) { + pmic_audio_close(extStereoIn.handle); + } + + /* Explicitly reset all of the audio registers so that there is no + * possibility of leaving the audio hardware in a state + * where it can cause problems if there is no device driver loaded. + */ + pmic_write_reg(REG_AUDIO_STEREO_DAC, RESET_ST_DAC, REG_FULLMASK); + pmic_write_reg(REG_AUDIO_CODEC, RESET_AUD_CODEC, REG_FULLMASK); + pmic_write_reg(REG_AUDIO_TX, RESET_AUDIO_TX, REG_FULLMASK); + pmic_write_reg(REG_AUDIO_SSI_NETWORK, RESET_SSI_NETWORK, REG_FULLMASK); + pmic_write_reg(REG_AUDIO_RX_0, RESET_AUDIO_RX_0, REG_FULLMASK); + pmic_write_reg(REG_AUDIO_RX_1, RESET_AUDIO_RX_1, REG_FULLMASK); +} + +/*@}*/ + +/* + * Module entry points and description information. + */ + +module_init(mc13783_pmic_audio_init); +module_exit(mc13783_pmic_audio_exit); + +MODULE_DESCRIPTION("PMIC - mc13783 ADC driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/pmic/mc13783/pmic_battery.c b/drivers/mxc/pmic/mc13783/pmic_battery.c new file mode 100644 index 000000000000..f721218e8fb1 --- /dev/null +++ b/drivers/mxc/pmic/mc13783/pmic_battery.c @@ -0,0 +1,1220 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mc13783/pmic_battery.c + * @brief This is the main file of PMIC(mc13783) Battery driver. + * + * @ingroup PMIC_BATTERY + */ + +/* + * Includes + */ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "pmic_battery_defs.h" + +#include +#ifdef CONFIG_MXC_HWEVENT +#include +#endif + +static int pmic_battery_major; + +/*! + * Number of users waiting in suspendq + */ +static int swait; + +/*! + * To indicate whether any of the battery devices are suspending + */ +static int suspend_flag; + +/*! + * The suspendq is used to block application calls + */ +static wait_queue_head_t suspendq; + +static struct class *pmic_battery_class; + +/* EXPORTED FUNCTIONS */ +EXPORT_SYMBOL(pmic_batt_enable_charger); +EXPORT_SYMBOL(pmic_batt_disable_charger); +EXPORT_SYMBOL(pmic_batt_set_charger); +EXPORT_SYMBOL(pmic_batt_get_charger_setting); +EXPORT_SYMBOL(pmic_batt_get_charge_current); +EXPORT_SYMBOL(pmic_batt_enable_eol); +EXPORT_SYMBOL(pmic_batt_bp_enable_eol); +EXPORT_SYMBOL(pmic_batt_disable_eol); +EXPORT_SYMBOL(pmic_batt_set_out_control); +EXPORT_SYMBOL(pmic_batt_set_threshold); +EXPORT_SYMBOL(pmic_batt_led_control); +EXPORT_SYMBOL(pmic_batt_set_reverse_supply); +EXPORT_SYMBOL(pmic_batt_set_unregulated); +EXPORT_SYMBOL(pmic_batt_set_5k_pull); +EXPORT_SYMBOL(pmic_batt_event_subscribe); +EXPORT_SYMBOL(pmic_batt_event_unsubscribe); + +static DECLARE_MUTEX(count_mutex); /* open count mutex */ +static int open_count; /* open count for device file */ + +/*! + * Callback function for events, we want on MGN board + */ +static void callback_chg_detect(void) +{ +#ifdef CONFIG_MXC_HWEVENT + t_sensor_bits sensor; + struct mxc_hw_event event = { HWE_BAT_CHARGER_PLUG, 0 }; + + pr_debug("In callback_chg_detect\n"); + + /* get sensor values */ + pmic_get_sensors(&sensor); + + pr_debug("Callback, charger detect:%d\n", sensor.sense_chgdets); + + if (sensor.sense_chgdets) + event.args = 1; + else + event.args = 0; + /* send hardware event */ + hw_event_send(HWE_DEF_PRIORITY, &event); +#endif +} + +static void callback_low_battery(void) +{ +#ifdef CONFIG_MXC_HWEVENT + struct mxc_hw_event event = { HWE_BAT_BATTERY_LOW, 0 }; + + pr_debug("In callback_low_battery\n"); + /* send hardware event */ + hw_event_send(HWE_DEF_PRIORITY, &event); +#endif +} + +static void callback_power_fail(void) +{ +#ifdef CONFIG_MXC_HWEVENT + struct mxc_hw_event event = { HWE_BAT_POWER_FAILED, 0 }; + + pr_debug("In callback_power_fail\n"); + /* send hardware event */ + hw_event_send(HWE_DEF_PRIORITY, &event); +#endif +} + +static void callback_chg_overvoltage(void) +{ +#ifdef CONFIG_MXC_HWEVENT + struct mxc_hw_event event = { HWE_BAT_CHARGER_OVERVOLTAGE, 0 }; + + pr_debug("In callback_chg_overvoltage\n"); + /* send hardware event */ + hw_event_send(HWE_DEF_PRIORITY, &event); +#endif +} + +static void callback_chg_full(void) +{ +#ifdef CONFIG_MXC_HWEVENT + t_sensor_bits sensor; + struct mxc_hw_event event = { HWE_BAT_CHARGER_FULL, 0 }; + + pr_debug("In callback_chg_full\n"); + + /* disable charge function */ + pmic_batt_disable_charger(BATT_MAIN_CHGR); + + /* get charger sensor */ + pmic_get_sensors(&sensor); + + /* if did not detect the charger */ + if (sensor.sense_chgdets) + return; + /* send hardware event */ + hw_event_send(HWE_DEF_PRIORITY, &event); +#endif +} + +/*! + * This is the suspend of power management for the pmic battery API. + * It suports SAVE and POWER_DOWN state. + * + * @param pdev the device + * @param state the state + * + * @return This function returns 0 if successful. + */ +static int pmic_battery_suspend(struct platform_device *pdev, + pm_message_t state) +{ + unsigned int reg_value = 0; + + suspend_flag = 1; + CHECK_ERROR(pmic_write_reg(REG_CHARGER, reg_value, PMIC_ALL_BITS)); + + return 0; +}; + +/*! + * This is the resume of power management for the pmic battery API. + * It suports RESTORE state. + * + * @param pdev the device + * + * @return This function returns 0 if successful. + */ +static int pmic_battery_resume(struct platform_device *pdev) +{ + suspend_flag = 0; + while (swait > 0) { + swait--; + wake_up_interruptible(&suspendq); + } + + return 0; +}; + +/*! + * This function is used to start charging a battery. For different charger, + * different voltage and current range are supported. \n + * + * + * @param chgr Charger as defined in \b t_batt_charger. + * @param c_voltage Charging voltage. + * @param c_current Charging current. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_batt_enable_charger(t_batt_charger chgr, + unsigned char c_voltage, + unsigned char c_current) +{ + unsigned int val, mask, reg; + + val = 0; + mask = 0; + reg = 0; + + if (suspend_flag == 1) + return PMIC_ERROR; + + switch (chgr) { + case BATT_MAIN_CHGR: + val = BITFVAL(MC13783_BATT_DAC_DAC, c_current) | + BITFVAL(MC13783_BATT_DAC_V_DAC, c_voltage); + mask = BITFMASK(MC13783_BATT_DAC_DAC) | + BITFMASK(MC13783_BATT_DAC_V_DAC); + reg = REG_CHARGER; + break; + + case BATT_CELL_CHGR: + val = BITFVAL(MC13783_BATT_DAC_V_COIN, c_voltage) | + BITFVAL(MC13783_BATT_DAC_COIN_CH_EN, + MC13783_BATT_DAC_COIN_CH_EN_ENABLED); + mask = BITFMASK(MC13783_BATT_DAC_V_COIN) | + BITFMASK(MC13783_BATT_DAC_COIN_CH_EN); + reg = REG_POWER_CONTROL_0; + break; + + case BATT_TRCKLE_CHGR: + val = BITFVAL(MC13783_BATT_DAC_TRCKLE, c_current); + mask = BITFMASK(MC13783_BATT_DAC_TRCKLE); + reg = REG_CHARGER; + break; + + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(reg, val, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function turns off a charger. + * + * @param chgr Charger as defined in \b t_batt_charger. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_batt_disable_charger(t_batt_charger chgr) +{ + unsigned int val, mask, reg; + + val = 0; + mask = 0; + reg = 0; + + if (suspend_flag == 1) + return PMIC_ERROR; + switch (chgr) { + case BATT_MAIN_CHGR: + val = BITFVAL(MC13783_BATT_DAC_DAC, 0) | + BITFVAL(MC13783_BATT_DAC_V_DAC, 0); + mask = BITFMASK(MC13783_BATT_DAC_DAC) | + BITFMASK(MC13783_BATT_DAC_V_DAC); + reg = REG_CHARGER; + break; + + case BATT_CELL_CHGR: + val = BITFVAL(MC13783_BATT_DAC_COIN_CH_EN, + MC13783_BATT_DAC_COIN_CH_EN_DISABLED); + mask = BITFMASK(MC13783_BATT_DAC_COIN_CH_EN); + reg = REG_POWER_CONTROL_0; + break; + + case BATT_TRCKLE_CHGR: + val = BITFVAL(MC13783_BATT_DAC_TRCKLE, 0); + mask = BITFMASK(MC13783_BATT_DAC_TRCKLE); + reg = REG_CHARGER; + break; + + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(reg, val, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function is used to change the charger setting. + * + * @param chgr Charger as defined in \b t_batt_charger. + * @param c_voltage Charging voltage. + * @param c_current Charging current. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_batt_set_charger(t_batt_charger chgr, + unsigned char c_voltage, + unsigned char c_current) +{ + unsigned int val, mask, reg; + + val = 0; + mask = 0; + reg = 0; + + if (suspend_flag == 1) + return PMIC_ERROR; + + switch (chgr) { + case BATT_MAIN_CHGR: + val = BITFVAL(MC13783_BATT_DAC_DAC, c_current) | + BITFVAL(MC13783_BATT_DAC_V_DAC, c_voltage); + mask = BITFMASK(MC13783_BATT_DAC_DAC) | + BITFMASK(MC13783_BATT_DAC_V_DAC); + reg = REG_CHARGER; + break; + + case BATT_CELL_CHGR: + val = BITFVAL(MC13783_BATT_DAC_V_COIN, c_voltage); + mask = BITFMASK(MC13783_BATT_DAC_V_COIN); + reg = REG_POWER_CONTROL_0; + break; + + case BATT_TRCKLE_CHGR: + val = BITFVAL(MC13783_BATT_DAC_TRCKLE, c_current); + mask = BITFMASK(MC13783_BATT_DAC_TRCKLE); + reg = REG_CHARGER; + break; + + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(reg, val, mask)); + return PMIC_SUCCESS; +} + +/*! + * This function is used to retrive the charger setting. + * + * @param chgr Charger as defined in \b t_batt_charger. + * @param c_voltage Output parameter for charging voltage setting. + * @param c_current Output parameter for charging current setting. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_batt_get_charger_setting(t_batt_charger chgr, + unsigned char *c_voltage, + unsigned char *c_current) +{ + unsigned int val, reg; + + reg = 0; + + if (suspend_flag == 1) + return PMIC_ERROR; + + switch (chgr) { + case BATT_MAIN_CHGR: + case BATT_TRCKLE_CHGR: + reg = REG_CHARGER; + break; + case BATT_CELL_CHGR: + reg = REG_POWER_CONTROL_0; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_read_reg(reg, &val, PMIC_ALL_BITS)); + + switch (chgr) { + case BATT_MAIN_CHGR: + *c_voltage = BITFEXT(val, MC13783_BATT_DAC_V_DAC);; + *c_current = BITFEXT(val, MC13783_BATT_DAC_DAC); + break; + + case BATT_CELL_CHGR: + *c_voltage = BITFEXT(val, MC13783_BATT_DAC_V_COIN); + *c_current = 0; + break; + + case BATT_TRCKLE_CHGR: + *c_voltage = 0; + *c_current = BITFEXT(val, MC13783_BATT_DAC_TRCKLE); + break; + + default: + return PMIC_PARAMETER_ERROR; + } + + return PMIC_SUCCESS; +} + +/*! + * This function is retrives the main battery voltage. + * + * @param b_voltage Output parameter for voltage setting. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_batt_get_batt_voltage(unsigned short *b_voltage) +{ + t_channel channel; + unsigned short result[8]; + + if (suspend_flag == 1) + return PMIC_ERROR; + channel = BATTERY_VOLTAGE; + CHECK_ERROR(pmic_adc_convert(channel, result)); + *b_voltage = result[0]; + + return PMIC_SUCCESS; +} + +/*! + * This function is retrives the main battery current. + * + * @param b_current Output parameter for current setting. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_batt_get_batt_current(unsigned short *b_current) +{ + t_channel channel; + unsigned short result[8]; + + if (suspend_flag == 1) + return PMIC_ERROR; + + channel = BATTERY_CURRENT; + CHECK_ERROR(pmic_adc_convert(channel, result)); + *b_current = result[0]; + + return PMIC_SUCCESS; +} + +/*! + * This function is retrives the main battery temperature. + * + * @param b_temper Output parameter for temperature setting. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_batt_get_batt_temperature(unsigned short *b_temper) +{ + t_channel channel; + unsigned short result[8]; + + if (suspend_flag == 1) + return PMIC_ERROR; + + channel = GEN_PURPOSE_AD5; + CHECK_ERROR(pmic_adc_convert(channel, result)); + *b_temper = result[0]; + + return PMIC_SUCCESS; +} + +/*! + * This function is retrives the main battery charging voltage. + * + * @param c_voltage Output parameter for charging voltage setting. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_batt_get_charge_voltage(unsigned short *c_voltage) +{ + t_channel channel; + unsigned short result[8]; + + if (suspend_flag == 1) + return PMIC_ERROR; + + channel = CHARGE_VOLTAGE; + CHECK_ERROR(pmic_adc_convert(channel, result)); + *c_voltage = result[0]; + + return PMIC_SUCCESS; +} + +/*! + * This function is retrives the main battery charging current. + * + * @param c_current Output parameter for charging current setting. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_batt_get_charge_current(unsigned short *c_current) +{ + t_channel channel; + unsigned short result[8]; + + if (suspend_flag == 1) + return PMIC_ERROR; + + channel = CHARGE_CURRENT; + CHECK_ERROR(pmic_adc_convert(channel, result)); + *c_current = result[0]; + + return PMIC_SUCCESS; +} + +/*! + * This function enables End-of-Life comparator. Not supported on + * mc13783. Use pmic_batt_bp_enable_eol function. + * + * @param threshold End-of-Life threshold. + * + * @return This function returns PMIC_UNSUPPORTED + */ +PMIC_STATUS pmic_batt_enable_eol(unsigned char threshold) +{ + return PMIC_NOT_SUPPORTED; +} + +/*! + * This function enables End-of-Life comparator. + * + * @param typical Falling Edge Threshold threshold. + * @verbatim + BPDET UVDET LOBATL + ____ _____ ___________ + 0 2.6 UVDET + 0.2 + 1 2.6 UVDET + 0.3 + 2 2.6 UVDET + 0.4 + 3 2.6 UVDET + 0.5 + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_batt_bp_enable_eol(t_bp_threshold typical) +{ + unsigned int val, mask; + + if (suspend_flag == 1) + return PMIC_ERROR; + + val = BITFVAL(MC13783_BATT_DAC_EOL_CMP_EN, + MC13783_BATT_DAC_EOL_CMP_EN_ENABLE) | + BITFVAL(MC13783_BATT_DAC_EOL_SEL, typical); + mask = BITFMASK(MC13783_BATT_DAC_EOL_CMP_EN) | + BITFMASK(MC13783_BATT_DAC_EOL_SEL); + + CHECK_ERROR(pmic_write_reg(REG_POWER_CONTROL_0, val, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function disables End-of-Life comparator. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_batt_disable_eol(void) +{ + unsigned int val, mask; + + if (suspend_flag == 1) + return PMIC_ERROR; + + val = BITFVAL(MC13783_BATT_DAC_EOL_CMP_EN, + MC13783_BATT_DAC_EOL_CMP_EN_DISABLE); + mask = BITFMASK(MC13783_BATT_DAC_EOL_CMP_EN); + + CHECK_ERROR(pmic_write_reg(REG_POWER_CONTROL_0, val, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function sets the output controls. + * It sets the FETOVRD and FETCTRL bits of mc13783 + * + * @param control type of control. + * + * @return This function returns 0 if successful. + */ +PMIC_STATUS pmic_batt_set_out_control(t_control control) +{ + unsigned int val, mask; + if (suspend_flag == 1) + return PMIC_ERROR; + + switch (control) { + case CONTROL_HARDWARE: + val = BITFVAL(MC13783_BATT_DAC_FETOVRD_EN, 0) | + BITFVAL(MC13783_BATT_DAC_FETCTRL_EN, 0); + mask = BITFMASK(MC13783_BATT_DAC_FETOVRD_EN) | + BITFMASK(MC13783_BATT_DAC_FETCTRL_EN); + break; + case CONTROL_BPFET_LOW: + val = BITFVAL(MC13783_BATT_DAC_FETOVRD_EN, 1) | + BITFVAL(MC13783_BATT_DAC_FETCTRL_EN, 0); + mask = BITFMASK(MC13783_BATT_DAC_FETOVRD_EN) | + BITFMASK(MC13783_BATT_DAC_FETCTRL_EN); + break; + case CONTROL_BPFET_HIGH: + val = BITFVAL(MC13783_BATT_DAC_FETOVRD_EN, 1) | + BITFVAL(MC13783_BATT_DAC_FETCTRL_EN, 1); + mask = BITFMASK(MC13783_BATT_DAC_FETOVRD_EN) | + BITFMASK(MC13783_BATT_DAC_FETCTRL_EN); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(REG_CHARGER, val, mask)); + return PMIC_SUCCESS; +} + +/*! + * This function sets over voltage threshold. + * + * @param threshold value of over voltage threshold. + * + * @return This function returns 0 if successful. + */ +PMIC_STATUS pmic_batt_set_threshold(int threshold) +{ + unsigned int val, mask; + + if (suspend_flag == 1) + return PMIC_ERROR; + + if (threshold > BAT_THRESHOLD_MAX) + return PMIC_PARAMETER_ERROR; + + val = BITFVAL(MC13783_BATT_DAC_OVCTRL, threshold); + mask = BITFMASK(MC13783_BATT_DAC_OVCTRL); + CHECK_ERROR(pmic_write_reg(REG_CHARGER, val, mask)); + return PMIC_SUCCESS; +} + +/*! + * This function controls charge LED. + * + * @param on If on is ture, LED will be turned on, + * or otherwise, LED will be turned off. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_batt_led_control(bool on) +{ + unsigned val, mask; + + if (suspend_flag == 1) + return PMIC_ERROR; + + val = BITFVAL(MC13783_BATT_DAC_LED_EN, on); + mask = BITFMASK(MC13783_BATT_DAC_LED_EN); + + CHECK_ERROR(pmic_write_reg(REG_CHARGER, val, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function sets reverse supply mode. + * + * @param enable If enable is ture, reverse supply mode is enable, + * or otherwise, reverse supply mode is disabled. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_batt_set_reverse_supply(bool enable) +{ + unsigned val, mask; + + if (suspend_flag == 1) + return PMIC_ERROR; + + val = BITFVAL(MC13783_BATT_DAC_REVERSE_SUPPLY, enable); + mask = BITFMASK(MC13783_BATT_DAC_REVERSE_SUPPLY); + + CHECK_ERROR(pmic_write_reg(REG_CHARGER, val, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function sets unregulatored charging mode on main battery. + * + * @param enable If enable is ture, unregulated charging mode is + * enable, or otherwise, disabled. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_batt_set_unregulated(bool enable) +{ + unsigned val, mask; + + if (suspend_flag == 1) + return PMIC_ERROR; + + val = BITFVAL(MC13783_BATT_DAC_UNREGULATED, enable); + mask = BITFMASK(MC13783_BATT_DAC_UNREGULATED); + + CHECK_ERROR(pmic_write_reg(REG_CHARGER, val, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function sets a 5K pull down at CHRGRAW. + * To be used in the dual path charging configuration. + * + * @param enable If enable is true, 5k pull down is + * enable, or otherwise, disabled. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_batt_set_5k_pull(bool enable) +{ + unsigned val, mask; + + if (suspend_flag == 1) + return PMIC_ERROR; + + val = BITFVAL(MC13783_BATT_DAC_5K, enable); + mask = BITFMASK(MC13783_BATT_DAC_5K); + + CHECK_ERROR(pmic_write_reg(REG_CHARGER, val, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function is used to un/subscribe on battery event IT. + * + * @param event type of event. + * @param callback event callback function. + * @param sub define if Un/subscribe event. + * + * @return This function returns 0 if successful. + */ +PMIC_STATUS mc13783_battery_event(t_batt_event event, void *callback, bool sub) +{ + pmic_event_callback_t bat_callback; + type_event bat_event; + + bat_callback.func = callback; + bat_callback.param = NULL; + switch (event) { + case BAT_IT_CHG_DET: + bat_event = EVENT_CHGDETI; + break; + case BAT_IT_CHG_OVERVOLT: + bat_event = EVENT_CHGOVI; + break; + case BAT_IT_CHG_REVERSE: + bat_event = EVENT_CHGREVI; + break; + case BAT_IT_CHG_SHORT_CIRCUIT: + bat_event = EVENT_CHGSHORTI; + break; + case BAT_IT_CCCV: + bat_event = EVENT_CCCVI; + break; + case BAT_IT_BELOW_THRESHOLD: + bat_event = EVENT_CHRGCURRI; + break; + default: + return PMIC_PARAMETER_ERROR; + } + if (sub == true) { + CHECK_ERROR(pmic_event_subscribe(bat_event, bat_callback)); + } else { + CHECK_ERROR(pmic_event_unsubscribe(bat_event, bat_callback)); + } + return 0; +} + +/*! + * This function is used to subscribe on battery event IT. + * + * @param event type of event. + * @param callback event callback function. + * + * @return This function returns 0 if successful. + */ +PMIC_STATUS pmic_batt_event_subscribe(t_batt_event event, void *callback) +{ + if (suspend_flag == 1) + return PMIC_ERROR; + + return mc13783_battery_event(event, callback, true); +} + +/*! + * This function is used to un subscribe on battery event IT. + * + * @param event type of event. + * @param callback event callback function. + * + * @return This function returns 0 if successful. + */ +PMIC_STATUS pmic_batt_event_unsubscribe(t_batt_event event, void *callback) +{ + if (suspend_flag == 1) + return PMIC_ERROR; + + return mc13783_battery_event(event, callback, false); +} + +/*! + * This function implements IOCTL controls on a PMIC Battery device. + * + * @param inode pointer on the node + * @param file pointer on the file + * @param cmd the command + * @param arg the parameter + * @return This function returns 0 if successful. + */ +static int pmic_battery_ioctl(struct inode *inode, struct file *file, + unsigned int cmd, unsigned long arg) +{ + t_charger_setting *chgr_setting = NULL; + unsigned short c_current; + unsigned int bc_info; + t_eol_setting *eol_setting; + + if (_IOC_TYPE(cmd) != 'p') + return -ENOTTY; + + chgr_setting = kmalloc(sizeof(t_charger_setting), GFP_KERNEL); + eol_setting = kmalloc(sizeof(t_eol_setting), GFP_KERNEL); + switch (cmd) { + case PMIC_BATT_CHARGER_CONTROL: + if (chgr_setting == NULL) + return -ENOMEM; + + if (copy_from_user(chgr_setting, (t_charger_setting *) arg, + sizeof(t_charger_setting))) { + kfree(chgr_setting); + return -EFAULT; + } + + if (chgr_setting->on != false) { + CHECK_ERROR_KFREE(pmic_batt_enable_charger + (chgr_setting->chgr, + chgr_setting->c_voltage, + chgr_setting->c_current), + (kfree(chgr_setting))); + } else { + CHECK_ERROR(pmic_batt_disable_charger + (chgr_setting->chgr)); + } + + kfree(chgr_setting); + break; + + case PMIC_BATT_SET_CHARGER: + if (chgr_setting == NULL) + return -ENOMEM; + + if (copy_from_user(chgr_setting, (t_charger_setting *) arg, + sizeof(t_charger_setting))) { + kfree(chgr_setting); + return -EFAULT; + } + + CHECK_ERROR_KFREE(pmic_batt_set_charger(chgr_setting->chgr, + chgr_setting->c_voltage, + chgr_setting-> + c_current), + (kfree(chgr_setting))); + + kfree(chgr_setting); + break; + + case PMIC_BATT_GET_CHARGER: + if (chgr_setting == NULL) + return -ENOMEM; + + if (copy_from_user(chgr_setting, (t_charger_setting *) arg, + sizeof(t_charger_setting))) { + kfree(chgr_setting); + return -EFAULT; + } + + CHECK_ERROR_KFREE(pmic_batt_get_charger_setting + (chgr_setting->chgr, &chgr_setting->c_voltage, + &chgr_setting->c_current), + (kfree(chgr_setting))); + if (copy_to_user + ((t_charger_setting *) arg, chgr_setting, + sizeof(t_charger_setting))) { + return -EFAULT; + } + + kfree(chgr_setting); + break; + + case PMIC_BATT_GET_CHARGER_SENSOR: + { + t_sensor_bits sensor; + pmic_get_sensors(&sensor); + if (copy_to_user + ((unsigned int *)arg, &sensor.sense_chgdets, + sizeof(unsigned int))) + return -EFAULT; + + break; + } + case PMIC_BATT_GET_BATTERY_VOLTAGE: + CHECK_ERROR(pmic_batt_get_batt_voltage(&c_current)); + bc_info = (unsigned int)c_current * 2300 / 1023 + 2400; + if (copy_to_user((unsigned int *)arg, &bc_info, + sizeof(unsigned int))) + return -EFAULT; + + break; + + case PMIC_BATT_GET_BATTERY_CURRENT: + CHECK_ERROR(pmic_batt_get_batt_current(&c_current)); + bc_info = (unsigned int)c_current * 5750 / 1023; + if (copy_to_user((unsigned int *)arg, &bc_info, + sizeof(unsigned int))) + return -EFAULT; + break; + + case PMIC_BATT_GET_BATTERY_TEMPERATURE: + CHECK_ERROR(pmic_batt_get_batt_temperature(&c_current)); + bc_info = (unsigned int)c_current; + if (copy_to_user((unsigned int *)arg, &bc_info, + sizeof(unsigned int))) + return -EFAULT; + + break; + + case PMIC_BATT_GET_CHARGER_VOLTAGE: + CHECK_ERROR(pmic_batt_get_charge_voltage(&c_current)); + bc_info = (unsigned int)c_current * 23000 / 1023; + if (copy_to_user((unsigned int *)arg, &bc_info, + sizeof(unsigned int))) + return -EFAULT; + + break; + + case PMIC_BATT_GET_CHARGER_CURRENT: + CHECK_ERROR(pmic_batt_get_charge_current(&c_current)); + bc_info = (unsigned int)c_current * 5750 / 1023; + if (copy_to_user((unsigned int *)arg, &bc_info, + sizeof(unsigned int))) + return -EFAULT; + + break; + + case PMIC_BATT_EOL_CONTROL: + if (eol_setting == NULL) + return -ENOMEM; + + if (copy_from_user(eol_setting, (t_eol_setting *) arg, + sizeof(t_eol_setting))) { + kfree(eol_setting); + return -EFAULT; + } + + if (eol_setting->enable != false) { + CHECK_ERROR_KFREE(pmic_batt_bp_enable_eol + (eol_setting->typical), + (kfree(chgr_setting))); + } else { + CHECK_ERROR_KFREE(pmic_batt_disable_eol(), + (kfree(chgr_setting))); + } + + kfree(eol_setting); + break; + + case PMIC_BATT_SET_OUT_CONTROL: + CHECK_ERROR(pmic_batt_set_out_control((t_control) arg)); + break; + + case PMIC_BATT_SET_THRESHOLD: + CHECK_ERROR(pmic_batt_set_threshold((int)arg)); + break; + + case PMIC_BATT_LED_CONTROL: + CHECK_ERROR(pmic_batt_led_control((bool) arg)); + break; + + case PMIC_BATT_REV_SUPP_CONTROL: + CHECK_ERROR(pmic_batt_set_reverse_supply((bool) arg)); + break; + + case PMIC_BATT_UNREG_CONTROL: + CHECK_ERROR(pmic_batt_set_unregulated((bool) arg)); + break; + + default: + return -EINVAL; + } + return 0; +} + +/*! + * This function implements the open method on a Pmic battery device. + * + * @param inode pointer on the node + * @param file pointer on the file + * @return This function returns 0. + */ +static int pmic_battery_open(struct inode *inode, struct file *file) +{ + while (suspend_flag == 1) { + swait++; + /* Block if the device is suspended */ + if (wait_event_interruptible(suspendq, (suspend_flag == 0))) { + return -ERESTARTSYS; + } + } + + /* check open count, if open firstly, register callbacks */ + down(&count_mutex); + if (open_count++ > 0) { + up(&count_mutex); + return 0; + } + + pr_debug("Subscribe the callbacks\n"); + /* register battery event callback */ + if (pmic_batt_event_subscribe(BAT_IT_CHG_DET, callback_chg_detect)) { + pr_debug("Failed to subscribe the charger detect callback\n"); + goto event_err1; + } + if (pmic_power_event_sub(PWR_IT_LOBATLI, callback_power_fail)) { + pr_debug("Failed to subscribe the power failed callback\n"); + goto event_err2; + } + if (pmic_power_event_sub(PWR_IT_LOBATHI, callback_low_battery)) { + pr_debug("Failed to subscribe the low battery callback\n"); + goto event_err3; + } + if (pmic_batt_event_subscribe + (BAT_IT_CHG_OVERVOLT, callback_chg_overvoltage)) { + pr_debug("Failed to subscribe the low battery callback\n"); + goto event_err4; + } + if (pmic_batt_event_subscribe + (BAT_IT_BELOW_THRESHOLD, callback_chg_full)) { + pr_debug("Failed to subscribe the charge full callback\n"); + goto event_err5; + } + + up(&count_mutex); + + return 0; + + /* un-subscribe the event callbacks */ +event_err5: + pmic_batt_event_unsubscribe(BAT_IT_CHG_OVERVOLT, + callback_chg_overvoltage); +event_err4: + pmic_power_event_unsub(PWR_IT_LOBATHI, callback_low_battery); +event_err3: + pmic_power_event_unsub(PWR_IT_LOBATLI, callback_power_fail); +event_err2: + pmic_batt_event_unsubscribe(BAT_IT_CHG_DET, callback_chg_detect); +event_err1: + + open_count--; + up(&count_mutex); + + return -EFAULT; + +} + +/*! + * This function implements the release method on a Pmic battery device. + * + * @param inode pointer on the node + * @param file pointer on the file + * @return This function returns 0. + */ +static int pmic_battery_release(struct inode *inode, struct file *file) +{ + while (suspend_flag == 1) { + swait++; + /* Block if the device is suspended */ + if (wait_event_interruptible(suspendq, (suspend_flag == 0))) { + return -ERESTARTSYS; + } + } + + /* check open count, if open firstly, register callbacks */ + down(&count_mutex); + if (--open_count == 0) { + /* unregister these event callback */ + pr_debug("Unsubscribe the callbacks\n"); + pmic_batt_event_unsubscribe(BAT_IT_BELOW_THRESHOLD, + callback_chg_full); + pmic_batt_event_unsubscribe(BAT_IT_CHG_OVERVOLT, + callback_chg_overvoltage); + pmic_power_event_unsub(PWR_IT_LOBATHI, callback_low_battery); + pmic_power_event_unsub(PWR_IT_LOBATLI, callback_power_fail); + pmic_batt_event_unsubscribe(BAT_IT_CHG_DET, + callback_chg_detect); + } + up(&count_mutex); + + return 0; +} + +static struct file_operations pmic_battery_fops = { + .owner = THIS_MODULE, + .ioctl = pmic_battery_ioctl, + .open = pmic_battery_open, + .release = pmic_battery_release, +}; + +static int pmic_battery_remove(struct platform_device *pdev) +{ + device_destroy(pmic_battery_class, MKDEV(pmic_battery_major, 0)); + class_destroy(pmic_battery_class); + unregister_chrdev(pmic_battery_major, PMIC_BATTERY_STRING); + return 0; +} + +static int pmic_battery_probe(struct platform_device *pdev) +{ + int ret = 0; + struct device *temp_class; + + pmic_battery_major = register_chrdev(0, PMIC_BATTERY_STRING, + &pmic_battery_fops); + + if (pmic_battery_major < 0) { + printk(KERN_ERR "Unable to get a major for pmic_battery\n"); + return pmic_battery_major; + } + init_waitqueue_head(&suspendq); + + pmic_battery_class = class_create(THIS_MODULE, PMIC_BATTERY_STRING); + if (IS_ERR(pmic_battery_class)) { + printk(KERN_ERR "Error creating PMIC battery class.\n"); + ret = PTR_ERR(pmic_battery_class); + goto err_out1; + } + + temp_class = device_create(pmic_battery_class, NULL, + MKDEV(pmic_battery_major, 0), NULL, + PMIC_BATTERY_STRING); + if (IS_ERR(temp_class)) { + printk(KERN_ERR "Error creating PMIC battery class device.\n"); + ret = PTR_ERR(temp_class); + goto err_out2; + } + + pmic_batt_led_control(true); + pmic_batt_set_5k_pull(true); + + printk(KERN_INFO "PMIC Battery successfully probed\n"); + + return ret; + + err_out2: + class_destroy(pmic_battery_class); + err_out1: + unregister_chrdev(pmic_battery_major, PMIC_BATTERY_STRING); + return ret; +} + +static struct platform_driver pmic_battery_driver_ldm = { + .driver = { + .name = "pmic_battery", + .bus = &platform_bus_type, + }, + .suspend = pmic_battery_suspend, + .resume = pmic_battery_resume, + .probe = pmic_battery_probe, + .remove = pmic_battery_remove, +}; + +/* + * Init and Exit + */ + +static int __init pmic_battery_init(void) +{ + pr_debug("PMIC Battery driver loading...\n"); + return platform_driver_register(&pmic_battery_driver_ldm); +} + +static void __exit pmic_battery_exit(void) +{ + platform_driver_unregister(&pmic_battery_driver_ldm); + pr_debug("PMIC Battery driver successfully unloaded\n"); +} + +/* + * Module entry points + */ + +module_init(pmic_battery_init); +module_exit(pmic_battery_exit); + +MODULE_DESCRIPTION("pmic_battery driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/pmic/mc13783/pmic_battery_defs.h b/drivers/mxc/pmic/mc13783/pmic_battery_defs.h new file mode 100644 index 000000000000..29704de301d1 --- /dev/null +++ b/drivers/mxc/pmic/mc13783/pmic_battery_defs.h @@ -0,0 +1,81 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mc13783/pmic_battery_defs.h + * @brief This is the internal header for PMIC(mc13783) Battery driver. + * + * @ingroup PMIC_BATTERY + */ + +#ifndef __PMIC_BATTERY_DEFS_H__ +#define __PMIC_BATTERY_DEFS_H__ + +#define PMIC_BATTERY_STRING "pmic_battery" + +/* REG_CHARGE */ +#define MC13783_BATT_DAC_V_DAC_LSH 0 +#define MC13783_BATT_DAC_V_DAC_WID 3 +#define MC13783_BATT_DAC_DAC_LSH 3 +#define MC13783_BATT_DAC_DAC_WID 4 +#define MC13783_BATT_DAC_TRCKLE_LSH 7 +#define MC13783_BATT_DAC_TRCKLE_WID 3 +#define MC13783_BATT_DAC_FETOVRD_EN_LSH 10 +#define MC13783_BATT_DAC_FETOVRD_EN_WID 1 +#define MC13783_BATT_DAC_FETCTRL_EN_LSH 11 +#define MC13783_BATT_DAC_FETCTRL_EN_WID 1 +#define MC13783_BATT_DAC_REVERSE_SUPPLY_LSH 13 +#define MC13783_BATT_DAC_REVERSE_SUPPLY_WID 1 +#define MC13783_BATT_DAC_OVCTRL_LSH 15 +#define MC13783_BATT_DAC_OVCTRL_WID 2 +#define MC13783_BATT_DAC_UNREGULATED_LSH 17 +#define MC13783_BATT_DAC_UNREGULATED_WID 1 +#define MC13783_BATT_DAC_LED_EN_LSH 18 +#define MC13783_BATT_DAC_LED_EN_WID 1 +#define MC13783_BATT_DAC_5K_LSH 19 +#define MC13783_BATT_DAC_5K_WID 1 + +#define BITS_OUT_VOLTAGE 0 +#define LONG_OUT_VOLTAGE 3 +#define BITS_CURRENT_MAIN 3 +#define LONG_CURRENT_MAIN 4 +#define BITS_CURRENT_TRICKLE 7 +#define LONG_CURRENT_TRICKLE 3 +#define BIT_FETOVRD 10 +#define BIT_FETCTRL 11 +#define BIT_RVRSMODE 13 +#define BITS_OVERVOLTAGE 15 +#define LONG_OVERVOLTAGE 2 +#define BIT_UNREGULATED 17 +#define BIT_CHRG_LED 18 +#define BIT_CHRGRAWPDEN 19 + +/* REG_POWXER_CONTROL_0 */ +#define MC13783_BATT_DAC_V_COIN_LSH 20 +#define MC13783_BATT_DAC_V_COIN_WID 3 +#define MC13783_BATT_DAC_COIN_CH_EN_LSH 23 +#define MC13783_BATT_DAC_COIN_CH_EN_WID 1 +#define MC13783_BATT_DAC_COIN_CH_EN_ENABLED 1 +#define MC13783_BATT_DAC_COIN_CH_EN_DISABLED 0 +#define MC13783_BATT_DAC_EOL_CMP_EN_LSH 18 +#define MC13783_BATT_DAC_EOL_CMP_EN_WID 1 +#define MC13783_BATT_DAC_EOL_CMP_EN_ENABLE 1 +#define MC13783_BATT_DAC_EOL_CMP_EN_DISABLE 0 +#define MC13783_BATT_DAC_EOL_SEL_LSH 16 +#define MC13783_BATT_DAC_EOL_SEL_WID 2 + +#define DEF_VALUE 0 + +#define BAT_THRESHOLD_MAX 3 + +#endif /* __PMIC_BATTERY_DEFS_H__ */ diff --git a/drivers/mxc/pmic/mc13783/pmic_convity.c b/drivers/mxc/pmic/mc13783/pmic_convity.c new file mode 100644 index 000000000000..9d89f493a8f2 --- /dev/null +++ b/drivers/mxc/pmic/mc13783/pmic_convity.c @@ -0,0 +1,2468 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mc13783/pmic_convity.c + * @brief Implementation of the PMIC Connectivity driver APIs. + * + * The PMIC connectivity device driver and this API were developed to support + * the external connectivity capabilities of several power management ICs that + * are available from Freescale Semiconductor, Inc. + * + * The following operating modes, in terms of external connectivity, are + * supported: + * + * @verbatim + Operating Mode mc13783 + --------------- ------- + USB (incl. OTG) Yes + RS-232 Yes + CEA-936 Yes + + @endverbatim + * + * @ingroup PMIC_CONNECTIVITY + */ + +#include /* For tasklet interface. */ +#include /* For kernel module interface. */ +#include /* For spinlock interface. */ +#include /* For PMIC ADC driver interface. */ +#include +#include /* For PMIC Connectivity driver interface. */ + +/* + * mc13783 Connectivity API + */ +/* EXPORTED FUNCTIONS */ +EXPORT_SYMBOL(pmic_convity_open); +EXPORT_SYMBOL(pmic_convity_close); +EXPORT_SYMBOL(pmic_convity_set_mode); +EXPORT_SYMBOL(pmic_convity_get_mode); +EXPORT_SYMBOL(pmic_convity_reset); +EXPORT_SYMBOL(pmic_convity_set_callback); +EXPORT_SYMBOL(pmic_convity_clear_callback); +EXPORT_SYMBOL(pmic_convity_get_callback); +EXPORT_SYMBOL(pmic_convity_usb_set_speed); +EXPORT_SYMBOL(pmic_convity_usb_get_speed); +EXPORT_SYMBOL(pmic_convity_usb_set_power_source); +EXPORT_SYMBOL(pmic_convity_usb_get_power_source); +EXPORT_SYMBOL(pmic_convity_usb_set_xcvr); +EXPORT_SYMBOL(pmic_convity_usb_get_xcvr); +EXPORT_SYMBOL(pmic_convity_usb_otg_set_dlp_duration); +EXPORT_SYMBOL(pmic_convity_usb_otg_get_dlp_duration); +EXPORT_SYMBOL(pmic_convity_usb_otg_set_config); +EXPORT_SYMBOL(pmic_convity_usb_otg_clear_config); +EXPORT_SYMBOL(pmic_convity_usb_otg_get_config); +EXPORT_SYMBOL(pmic_convity_set_output); +EXPORT_SYMBOL(pmic_convity_rs232_set_config); +EXPORT_SYMBOL(pmic_convity_rs232_get_config); +EXPORT_SYMBOL(pmic_convity_cea936_exit_signal); + +/*! @def SET_BITS + * Set a register field to a given value. + */ + +#define SET_BITS(reg, field, value) (((value) << reg.field.offset) & \ + reg.field.mask) + +/*! @def GET_BITS + * Get the current value of a given register field. + */ +#define GET_BITS(reg, value) (((value) & reg.mask) >> \ + reg.offset) + +/*! + * @brief Define the possible states for a device handle. + * + * This enumeration is used to track the current state of each device handle. + */ +typedef enum { + HANDLE_FREE, /*!< Handle is available for use. */ + HANDLE_IN_USE /*!< Handle is currently in use. */ +} HANDLE_STATE; + +/* + * This structure is used to define a specific hardware register field. + * + * All hardware register fields are defined using an offset to the LSB + * and a mask. The offset is used to right shift a register value before + * applying the mask to actually obtain the value of the field. + */ +typedef struct { + const unsigned char offset; /* Offset of LSB of register field. */ + const unsigned int mask; /* Mask value used to isolate register field. */ +} REGFIELD; + +/*! + * @brief This structure is used to identify the fields in the USBCNTRL_REG_0 hardware register. + * + * This structure lists all of the fields within the USBCNTRL_REG_0 hardware + * register. + */ +typedef struct { + REGFIELD FSENB; /*!< USB Full Speed Enable */ + REGFIELD USB_SUSPEND; /*!< USB Suspend Mode Enable */ + REGFIELD USB_PU; /*!< USB Pullup Enable */ + REGFIELD UDP_PD; /*!< USB Data Plus Pulldown Enable */ + REGFIELD UDM_PD; /*!< USB 150K UDP Pullup Enable */ + REGFIELD DP150K_PU; /*!< USB Pullup/Pulldown Override Enable */ + REGFIELD VBUSPDENB; /*!< USB VBUS Pulldown NMOS Switch Enable */ + REGFIELD CURRENT_LIMIT; /*!< USB Regulator Current Limit Setting-3 bits */ + REGFIELD DLP_SRP; /*!< USB Data Line Pulsing Timer Enable */ + REGFIELD SE0_CONN; /*!< USB Pullup Connect When SE0 Detected */ + REGFIELD USBXCVREN; /*!< USB Transceiver Enabled When INTERFACE_MODE[2:0]=000 and RESETB=high */ + REGFIELD PULLOVR; /*!< 1K5 Pullup and UDP/UDM Pulldown Disable When UTXENB=Low */ + REGFIELD INTERFACE_MODE; /*!< Connectivity Interface Mode Select-3 Bits */ + REGFIELD DATSE0; /*!< USB Single or Differential Mode Select */ + REGFIELD BIDIR; /*!< USB Unidirectional/Bidirectional Transmission */ + REGFIELD USBCNTRL; /*!< USB Mode of Operation controlled By USBEN/SPI Pin */ + REGFIELD IDPD; /*!< USB UID Pulldown Enable */ + REGFIELD IDPULSE; /*!< USB Pulse to Gnd on UID Line Generated */ + REGFIELD IDPUCNTRL; /*!< USB UID Pin pulled high By 5ua Curr Source */ + REGFIELD DMPULSE; /*!< USB Positive pulse on the UDM Line Generated */ +} USBCNTRL_REG_0; + +/*! + * @brief This variable is used to access the USBCNTRL_REG_0 hardware register. + * + * This variable defines how to access all of the fields within the + * USBCNTRL_REG_0 hardware register. The initial values consist of the offset + * and mask values needed to access each of the register fields. + */ +static const USBCNTRL_REG_0 regUSB0 = { + {0, 0x000001}, /*!< FSENB */ + {1, 0x000002}, /*!< USB_SUSPEND */ + {2, 0x000004}, /*!< USB_PU */ + {3, 0x000008}, /*!< UDP_PD */ + {4, 0x000010}, /*!< UDM_PD */ + {5, 0x000020}, /*!< DP150K_PU */ + {6, 0x000040}, /*!< VBUSPDENB */ + {7, 0x000380}, /*!< CURRENT_LIMIT */ + {10, 0x000400}, /*!< DLP_SRP */ + {11, 0x000800}, /*!< SE0_CONN */ + {12, 0x001000}, /*!< USBXCVREN */ + {13, 0x002000}, /*!< PULLOVR */ + {14, 0x01c000}, /*!< INTERFACE_MODE */ + {17, 0x020000}, /*!< DATSE0 */ + {18, 0x040000}, /*!< BIDIR */ + {19, 0x080000}, /*!< USBCNTRL */ + {20, 0x100000}, /*!< IDPD */ + {21, 0x200000}, /*!< IDPULSE */ + {22, 0x400000}, /*!< IDPUCNTRL */ + {23, 0x800000} /*!< DMPULSE */ + +}; + +/*! + * @brief This structure is used to identify the fields in the USBCNTRL_REG_1 hardware register. + * + * This structure lists all of the fields within the USBCNTRL_REG_1 hardware + * register. + */ +typedef struct { + REGFIELD VUSBIN; /*!< Controls The Input Source For VUSB */ + REGFIELD VUSB; /*!< VUSB Output Voltage Select-High=3.3V Low=2.775V */ + REGFIELD VUSBEN; /*!< VUSB Output Enable- */ + REGFIELD VBUSEN; /*!< VBUS Output Enable- */ + REGFIELD RSPOL; /*!< Low=RS232 TX on UDM, RX on UDP + High= RS232 TX on UDP, RX on UDM */ + REGFIELD RSTRI; /*!< TX Forced To Tristate in RS232 Mode Only */ + REGFIELD ID100kPU; /*!< 100k UID Pullup Enabled */ +} USBCNTRL_REG_1; + +/*! + * @brief This variable is used to access the USBCNTRL_REG_1 hardware register. + * + * This variable defines how to access all of the fields within the + * USBCNTRL_REG_1 hardware register. The initial values consist of the offset + * and mask values needed to access each of the register fields. + */ +static const USBCNTRL_REG_1 regUSB1 = { + {0, 0x000003}, /*!< VUSBIN-2 Bits */ + {2, 0x000004}, /*!< VUSB */ + {3, 0x000008}, /*!< VUSBEN */ + /*{4, 0x000010} *//*!< Reserved */ + {5, 0x000020}, /*!< VBUSEN */ + {6, 0x000040}, /*!< RSPOL */ + {7, 0x000080}, /*!< RSTRI */ + {8, 0x000100} /*!< ID100kPU */ + /*!< 9-23 Unused */ +}; + +/*! Define a mask to access the entire hardware register. */ +static const unsigned int REG_FULLMASK = 0xffffff; + +/*! Define the mc13783 USBCNTRL_REG_0 register power on reset state. */ +static const unsigned int RESET_USBCNTRL_REG_0 = 0x080060; + +/*! Define the mc13783 USBCNTRL_REG_1 register power on reset state. */ +static const unsigned int RESET_USBCNTRL_REG_1 = 0x000006; + +static pmic_event_callback_t eventNotify; + +/*! + * @brief This structure is used to maintain the current device driver state. + * + * This structure maintains the current state of the connectivity driver. This + * includes both the PMIC hardware state as well as the device handle and + * callback states. + */ + +typedef struct { + PMIC_CONVITY_HANDLE handle; /*!< Device handle. */ + HANDLE_STATE handle_state; /*!< Device handle + state. */ + PMIC_CONVITY_MODE mode; /*!< Device mode. */ + PMIC_CONVITY_CALLBACK callback; /*!< Event callback function pointer. */ + PMIC_CONVITY_EVENTS eventMask; /*!< Event mask. */ + PMIC_CONVITY_USB_SPEED usbSpeed; /*!< USB connection + speed. */ + PMIC_CONVITY_USB_MODE usbMode; /*!< USB connection + mode. */ + PMIC_CONVITY_USB_POWER_IN usbPowerIn; /*!< USB transceiver + power source. */ + PMIC_CONVITY_USB_POWER_OUT usbPowerOut; /*!< USB transceiver + power output + level. */ + PMIC_CONVITY_USB_TRANSCEIVER_MODE usbXcvrMode; /*!< USB transceiver + mode. */ + unsigned int usbDlpDuration; /*!< USB Data Line + Pulsing duration. */ + PMIC_CONVITY_USB_OTG_CONFIG usbOtgCfg; /*!< USB OTG + configuration + options. */ + PMIC_CONVITY_RS232_INTERNAL rs232CfgInternal; /*!< RS-232 internal + connections. */ + PMIC_CONVITY_RS232_EXTERNAL rs232CfgExternal; /*!< RS-232 external + connections. */ +} pmic_convity_state_struct; + +/*! + * @brief This structure is used to maintain the current device driver state. + * + * This structure maintains the current state of the driver in USB mode. This + * includes both the PMIC hardware state as well as the device handle and + * callback states. + */ + +typedef struct { + PMIC_CONVITY_HANDLE handle; /*!< Device handle. */ + HANDLE_STATE handle_state; /*!< Device handle + state. */ + PMIC_CONVITY_MODE mode; /*!< Device mode. */ + PMIC_CONVITY_CALLBACK callback; /*!< Event callback function pointer. */ + PMIC_CONVITY_EVENTS eventMask; /*!< Event mask. */ + PMIC_CONVITY_USB_SPEED usbSpeed; /*!< USB connection + speed. */ + PMIC_CONVITY_USB_MODE usbMode; /*!< USB connection + mode. */ + PMIC_CONVITY_USB_POWER_IN usbPowerIn; /*!< USB transceiver + power source. */ + PMIC_CONVITY_USB_POWER_OUT usbPowerOut; /*!< USB transceiver + power output + level. */ + PMIC_CONVITY_USB_TRANSCEIVER_MODE usbXcvrMode; /*!< USB transceiver + mode. */ + unsigned int usbDlpDuration; /*!< USB Data Line + Pulsing duration. */ + PMIC_CONVITY_USB_OTG_CONFIG usbOtgCfg; /*!< USB OTG + configuration + options. */ +} pmic_convity_usb_state; + +/*! + * @brief This structure is used to maintain the current device driver state. + * + * This structure maintains the current state of the driver in RS_232 mode. This + * includes both the PMIC hardware state as well as the device handle and + * callback states. + */ + +typedef struct { + PMIC_CONVITY_HANDLE handle; /*!< Device handle. */ + HANDLE_STATE handle_state; /*!< Device handle + state. */ + PMIC_CONVITY_MODE mode; /*!< Device mode. */ + PMIC_CONVITY_CALLBACK callback; /*!< Event callback function pointer. */ + PMIC_CONVITY_EVENTS eventMask; /*!< Event mask. */ + PMIC_CONVITY_RS232_INTERNAL rs232CfgInternal; /*!< RS-232 internal + connections. */ + PMIC_CONVITY_RS232_EXTERNAL rs232CfgExternal; /*!< RS-232 external + connections. */ +} pmic_convity_rs232_state; + +/*! + * @brief This structure is used to maintain the current device driver state. + * + * This structure maintains the current state of the driver in cea-936 mode. This + * includes both the PMIC hardware state as well as the device handle and + * callback states. + */ + +typedef struct { + PMIC_CONVITY_HANDLE handle; /*!< Device handle. */ + HANDLE_STATE handle_state; /*!< Device handle + state. */ + PMIC_CONVITY_MODE mode; /*!< Device mode. */ + PMIC_CONVITY_CALLBACK callback; /*!< Event callback function pointer. */ + PMIC_CONVITY_EVENTS eventMask; /*!< Event mask. */ + +} pmic_convity_cea936_state; + +/*! + * @brief Identifies the hardware interrupt source. + * + * This enumeration identifies which of the possible hardware interrupt + * sources actually caused the current interrupt handler to be called. + */ +typedef enum { + CORE_EVENT_4V4 = 1, /*!< Detected USB 4.4 V event. */ + CORE_EVENT_2V0 = 2, /*!< Detected USB 2.0 V event. */ + CORE_EVENT_0V8 = 4, /*!< Detected USB 0.8 V event. */ + CORE_EVENT_ABDET = 8 /*!< Detected USB mini A-B connector event. */ +} PMIC_CORE_EVENT; + +/*! + * @brief This structure defines the reset/power on state for the Connectivity driver. + */ +static const pmic_convity_state_struct reset = { + 0, + HANDLE_FREE, + USB, + NULL, + 0, + USB_FULL_SPEED, + USB_PERIPHERAL, + USB_POWER_INTERNAL, + USB_POWER_3V3, + USB_TRANSCEIVER_OFF, + 0, + USB_PULL_OVERRIDE | USB_VBUS_CURRENT_LIMIT_HIGH, + RS232_TX_USE0VM_RX_UDATVP, + RS232_TX_UDM_RX_UDP +}; + +/*! + * @brief This structure maintains the current state of the Connectivity driver. + * + * The initial values must be identical to the reset state defined by the + * #reset variable. + */ +static pmic_convity_usb_state usb = { + 0, + HANDLE_FREE, + USB, + NULL, + 0, + USB_FULL_SPEED, + USB_PERIPHERAL, + USB_POWER_INTERNAL, + USB_POWER_3V3, + USB_TRANSCEIVER_OFF, + 0, + USB_PULL_OVERRIDE | USB_VBUS_CURRENT_LIMIT_HIGH, +}; + +/*! + * @brief This structure maintains the current state of the Connectivity driver. + * + * The initial values must be identical to the reset state defined by the + * #reset variable. + */ +static pmic_convity_rs232_state rs_232 = { + 0, + HANDLE_FREE, + RS232_1, + NULL, + 0, + RS232_TX_USE0VM_RX_UDATVP, + RS232_TX_UDM_RX_UDP +}; + +/*! + * @brief This structure maintains the current state of the Connectivity driver. + * + * The initial values must be identical to the reset state defined by the + * #reset variable. + */ +static pmic_convity_cea936_state cea_936 = { + 0, + HANDLE_FREE, + CEA936_MONO, + NULL, + 0, +}; + +/*! + * @brief This spinlock is used to provide mutual exclusion. + * + * Create a spinlock that can be used to provide mutually exclusive + * read/write access to the globally accessible "convity" data structure + * that was defined above. Mutually exclusive access is required to + * ensure that the convity data structure is consistent at all times + * when possibly accessed by multiple threads of execution (for example, + * while simultaneously handling a user request and an interrupt event). + * + * We need to use a spinlock sometimes because we need to provide mutual + * exclusion while handling a hardware interrupt. + */ +static DEFINE_SPINLOCK(lock); + +/*! + * @brief This mutex is used to provide mutual exclusion. + * + * Create a mutex that can be used to provide mutually exclusive + * read/write access to the globally accessible data structures + * that were defined above. Mutually exclusive access is required to + * ensure that the Connectivity data structures are consistent at all + * times when possibly accessed by multiple threads of execution. + * + * Note that we use a mutex instead of the spinlock whenever disabling + * interrupts while in the critical section is not required. This helps + * to minimize kernel interrupt handling latency. + */ +static DECLARE_MUTEX(mutex); + +/* Prototype for the connectivity driver tasklet function. */ +static void pmic_convity_tasklet(struct work_struct *work); + +/*! + * @brief Tasklet handler for the connectivity driver. + * + * Declare a tasklet that will do most of the processing for all of the + * connectivity-related interrupt events (USB4.4VI, USB2.0VI, USB0.8VI, + * and AB_DETI). Note that we cannot do all of the required processing + * within the interrupt handler itself because we may need to call the + * ADC driver to measure voltages as well as calling any user-registered + * callback functions. + */ +DECLARE_WORK(convityTasklet, pmic_convity_tasklet); + +/*! + * @brief Global variable to track currently active interrupt events. + * + * This global variable is used to keep track of all of the currently + * active interrupt events for the connectivity driver. Note that access + * to this variable may occur while within an interrupt context and, + * therefore, must be guarded by using a spinlock. + */ +static PMIC_CORE_EVENT eventID; + +/* Prototypes for all static connectivity driver functions. */ +static PMIC_STATUS pmic_convity_set_mode_internal(const PMIC_CONVITY_MODE mode); +static PMIC_STATUS pmic_convity_deregister_all(void); +static void pmic_convity_event_handler(void *param); + +/************************************************************************** + * General setup and configuration functions. + ************************************************************************** + */ + +/*! + * @name General Setup and Configuration Connectivity APIs + * Functions for setting up and configuring the connectivity hardware. + */ +/*@{*/ + +/*! + * Attempt to open and gain exclusive access to the PMIC connectivity + * hardware. An initial operating mode must also be specified. + * + * If the open request is successful, then a numeric handle is returned + * and this handle must be used in all subsequent function calls. The + * same handle must also be used in the pmic_convity_close() call when use + * of the PMIC connectivity hardware is no longer required. + * + * @param handle device handle from open() call + * @param mode initial connectivity operating mode + * + * @return PMIC_SUCCESS if the open request was successful + */ +PMIC_STATUS pmic_convity_open(PMIC_CONVITY_HANDLE * const handle, + const PMIC_CONVITY_MODE mode) +{ + PMIC_STATUS rc = PMIC_ERROR; + + if (handle == (PMIC_CONVITY_HANDLE *) NULL) { + /* Do not dereference a NULL pointer. */ + return PMIC_ERROR; + } + + /* We only need to acquire a mutex here because the interrupt handler + * never modifies the device handle or device handle state. Therefore, + * we don't need to worry about conflicts with the interrupt handler + * or the need to execute in an interrupt context. + * + * But we do need a critical section here to avoid problems in case + * multiple calls to pmic_convity_open() are made since we can only + * allow one of them to succeed. + */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + /* Check the current device handle state and acquire the handle if + * it is available. + */ + if ((usb.handle_state != HANDLE_FREE) + && (rs_232.handle_state != HANDLE_FREE) + && (cea_936.handle_state != HANDLE_FREE)) { + + /* Cannot open the PMIC connectivity hardware at this time or an invalid + * mode was requested. + */ + *handle = reset.handle; + } else { + + if (mode == USB) { + usb.handle = (PMIC_CONVITY_HANDLE) (&usb); + usb.handle_state = HANDLE_IN_USE; + } else if ((mode == RS232_1) || (mode == RS232_2)) { + rs_232.handle = (PMIC_CONVITY_HANDLE) (&rs_232); + rs_232.handle_state = HANDLE_IN_USE; + } else if ((mode == CEA936_STEREO) || (mode == CEA936_MONO) + || (mode == CEA936_TEST_LEFT) + || (mode == CEA936_TEST_RIGHT)) { + cea_936.handle = (PMIC_CONVITY_HANDLE) (&cea_936); + cea_936.handle_state = HANDLE_IN_USE; + + } + /* Let's begin by acquiring the connectivity device handle. */ + /* Then we can try to set the desired operating mode. */ + rc = pmic_convity_set_mode_internal(mode); + + if (rc == PMIC_SUCCESS) { + /* Successfully set the desired operating mode, now return the + * handle to the caller. + */ + if (mode == USB) { + *handle = usb.handle; + } else if ((mode == RS232_1) || (mode == RS232_2)) { + *handle = rs_232.handle; + } else if ((mode == CEA936_STEREO) + || (mode == CEA936_MONO) + || (mode == CEA936_TEST_LEFT) + || (mode == CEA936_TEST_RIGHT)) { + *handle = cea_936.handle; + } + } else { + /* Failed to set the desired mode, return the handle to an unused + * state. + */ + if (mode == USB) { + usb.handle = reset.handle; + usb.handle_state = reset.handle_state; + } else if ((mode == RS232_1) || (mode == RS232_2)) { + rs_232.handle = reset.handle; + rs_232.handle_state = reset.handle_state; + } else if ((mode == CEA936_STEREO) + || (mode == CEA936_MONO) + || (mode == CEA936_TEST_LEFT) + || (mode == CEA936_TEST_RIGHT)) { + cea_936.handle = reset.handle; + cea_936.handle_state = reset.handle_state; + } + + *handle = reset.handle; + } + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * Terminate further access to the PMIC connectivity hardware. Also allows + * another process to call pmic_convity_open() to gain access. + * + * @param handle device handle from open() call + * + * @return PMIC_SUCCESS if the close request was successful + */ +PMIC_STATUS pmic_convity_close(const PMIC_CONVITY_HANDLE handle) +{ + PMIC_STATUS rc = PMIC_ERROR; + + /* Begin a critical section here to avoid the possibility of race + * conditions if multiple threads happen to call this function and + * pmic_convity_open() at the same time. + */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + /* Confirm that the device handle matches the one assigned in the + * pmic_convity_open() call and then close the connection. + */ + if (((handle == usb.handle) && + (usb.handle_state == HANDLE_IN_USE)) || ((handle == rs_232.handle) + && (rs_232.handle_state == + HANDLE_IN_USE)) + || ((handle == cea_936.handle) + && (cea_936.handle_state == HANDLE_IN_USE))) { + rc = PMIC_SUCCESS; + + /* Deregister for all existing callbacks if necessary and make sure + * that the event handling settings are consistent following the + * close operation. + */ + if ((usb.callback != reset.callback) + || (rs_232.callback != reset.callback) + || (cea_936.callback != reset.callback)) { + /* Deregister the existing callback function and all registered + * events before we completely close the handle. + */ + rc = pmic_convity_deregister_all(); + if (rc == PMIC_SUCCESS) { + + } else if (usb.eventMask != reset.eventMask) { + /* Having a non-zero eventMask without a callback function being + * defined should never occur but let's just make sure here that + * we keep things consistent. + */ + usb.eventMask = reset.eventMask; + /* Mark the connectivity device handle as being closed. */ + usb.handle = reset.handle; + usb.handle_state = reset.handle_state; + + } else if (rs_232.eventMask != reset.eventMask) { + + rs_232.eventMask = reset.eventMask; + /* Mark the connectivity device handle as being closed. */ + rs_232.handle = reset.handle; + rs_232.handle_state = reset.handle_state; + + } else if (cea_936.eventMask != reset.eventMask) { + cea_936.eventMask = reset.eventMask; + /* Mark the connectivity device handle as being closed. */ + cea_936.handle = reset.handle; + cea_936.handle_state = reset.handle_state; + + } + + } + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * Change the current operating mode of the PMIC connectivity hardware. + * The available connectivity operating modes is hardware dependent and + * consists of one or more of the following: USB (including USB On-the-Go), + * RS-232, and CEA-936. Requesting an operating mode that is not supported + * by the PMIC hardware will return PMIC_NOT_SUPPORTED. + * + * @param handle device handle from + open() call + * @param mode desired operating mode + * + * @return PMIC_SUCCESS if the requested mode was successfully set + */ +PMIC_STATUS pmic_convity_set_mode(const PMIC_CONVITY_HANDLE handle, + const PMIC_CONVITY_MODE mode) +{ + PMIC_STATUS rc = PMIC_ERROR; + + /* Use a critical section to maintain a consistent state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if (((handle == usb.handle) && + (usb.handle_state == HANDLE_IN_USE)) || ((handle == rs_232.handle) + && (rs_232.handle_state == + HANDLE_IN_USE)) + || ((handle == cea_936.handle) + && (cea_936.handle_state == HANDLE_IN_USE))) { + rc = pmic_convity_set_mode_internal(mode); + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * Get the current operating mode for the PMIC connectivity hardware. + * + * @param handle device handle from open() call + * @param mode the current PMIC connectivity operating mode + * + * @return PMIC_SUCCESS if the requested mode was successfully set + */ +PMIC_STATUS pmic_convity_get_mode(const PMIC_CONVITY_HANDLE handle, + PMIC_CONVITY_MODE * const mode) +{ + PMIC_STATUS rc = PMIC_ERROR; + + /* Use a critical section to maintain a consistent state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((((handle == usb.handle) && + (usb.handle_state == HANDLE_IN_USE)) || ((handle == rs_232.handle) + && (rs_232. + handle_state == + HANDLE_IN_USE)) + || ((handle == cea_936.handle) + && (cea_936.handle_state == HANDLE_IN_USE))) + && (mode != (PMIC_CONVITY_MODE *) NULL)) { + + *mode = usb.mode; + + rc = PMIC_SUCCESS; + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * Restore all registers to the initial power-on/reset state. + * + * @param handle device handle from open() call + * + * @return PMIC_SUCCESS if the reset was successful + */ +PMIC_STATUS pmic_convity_reset(const PMIC_CONVITY_HANDLE handle) +{ + PMIC_STATUS rc = PMIC_ERROR; + + /* Use a critical section to maintain a consistent state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + if (((handle == usb.handle) && + (usb.handle_state == HANDLE_IN_USE)) || ((handle == rs_232.handle) + && (rs_232.handle_state == + HANDLE_IN_USE)) + || ((handle == cea_936.handle) + && (cea_936.handle_state == HANDLE_IN_USE))) { + + /* Reset the PMIC Connectivity register to it's power on state. */ + rc = pmic_write_reg(REG_USB, RESET_USBCNTRL_REG_0, + REG_FULLMASK); + + rc = pmic_write_reg(REG_CHARGE_USB_SPARE, + RESET_USBCNTRL_REG_1, REG_FULLMASK); + + if (rc == PMIC_SUCCESS) { + /* Also reset the device driver state data structure. */ + + } + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * Register a callback function that will be used to signal PMIC connectivity + * events. For example, the USB subsystem should register a callback function + * in order to be notified of device connect/disconnect events. Note, however, + * that non-USB events may also be signalled depending upon the PMIC hardware + * capabilities. Therefore, the callback function must be able to properly + * handle all of the possible events if support for non-USB peripherals is + * also to be included. + * + * @param handle device handle from open() call + * @param func a pointer to the callback function + * @param eventMask a mask selecting events to be notified + * + * @return PMIC_SUCCESS if the callback was successful registered + */ +PMIC_STATUS pmic_convity_set_callback(const PMIC_CONVITY_HANDLE handle, + const PMIC_CONVITY_CALLBACK func, + const PMIC_CONVITY_EVENTS eventMask) +{ + unsigned long flags; + PMIC_STATUS rc = PMIC_ERROR; + + /* We need to start a critical section here to ensure a consistent state + * in case simultaneous calls to pmic_convity_set_callback() are made. In + * that case, we must serialize the calls to ensure that the "callback" + * and "eventMask" state variables are always consistent. + * + * Note that we don't actually need to acquire the spinlock until later + * when we are finally ready to update the "callback" and "eventMask" + * state variables which are shared with the interrupt handler. + */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == usb.handle) && (usb.handle_state == HANDLE_IN_USE)) { + + /* Return an error if either the callback function or event mask + * is not properly defined. + * + * It is also considered an error if a callback function has already + * been defined. If you wish to register for a new set of events, + * then you must first call pmic_convity_clear_callback() to + * deregister the existing callback function and list of events + * before trying to register a new callback function. + */ + if ((func == NULL) || (eventMask == 0) + || (usb.callback != NULL)) { + rc = PMIC_ERROR; + + /* Register for PMIC events from the core protocol driver. */ + } else { + + if ((eventMask & USB_DETECT_4V4_RISE) || + (eventMask & USB_DETECT_4V4_FALL)) { + /* We need to register for the 4.4V interrupt. + EVENT_USBI or EVENT_USB_44VI */ + eventNotify.func = pmic_convity_event_handler; + eventNotify.param = (void *)(CORE_EVENT_4V4); + rc = pmic_event_subscribe(EVENT_USBI, + eventNotify); + + if (rc != PMIC_SUCCESS) { + return rc; + } + } + + if ((eventMask & USB_DETECT_2V0_RISE) || + (eventMask & USB_DETECT_2V0_FALL)) { + /* We need to register for the 2.0V interrupt. + EVENT_USB_20VI or EVENT_USBI */ + eventNotify.func = pmic_convity_event_handler; + eventNotify.param = (void *)(CORE_EVENT_2V0); + rc = pmic_event_subscribe(EVENT_USBI, + eventNotify); + + if (rc != PMIC_SUCCESS) { + goto Cleanup_4V4; + } + } + + if ((eventMask & USB_DETECT_0V8_RISE) || + (eventMask & USB_DETECT_0V8_FALL)) { + /* We need to register for the 0.8V interrupt. + EVENT_USB_08VI or EVENT_USBI */ + eventNotify.func = pmic_convity_event_handler; + eventNotify.param = (void *)(CORE_EVENT_0V8); + rc = pmic_event_subscribe(EVENT_USBI, + eventNotify); + + if (rc != PMIC_SUCCESS) { + goto Cleanup_2V0; + } + } + + if ((eventMask & USB_DETECT_MINI_A) || + (eventMask & USB_DETECT_MINI_B) + || (eventMask & USB_DETECT_NON_USB_ACCESSORY) + || (eventMask & USB_DETECT_FACTORY_MODE)) { + /* We need to register for the AB_DET interrupt. + EVENT_AB_DETI or EVENT_IDI */ + eventNotify.func = pmic_convity_event_handler; + eventNotify.param = (void *)(CORE_EVENT_ABDET); + rc = pmic_event_subscribe(EVENT_IDI, + eventNotify); + + if (rc != PMIC_SUCCESS) { + goto Cleanup_0V8; + } + } + + /* Use a critical section to maintain a consistent state. */ + spin_lock_irqsave(&lock, flags); + + /* Successfully registered for all events. */ + usb.callback = func; + usb.eventMask = eventMask; + spin_unlock_irqrestore(&lock, flags); + + goto End; + + /* This section unregisters any already registered events if we should + * encounter an error partway through the registration process. Note + * that we don't check the return status here since it is already set + * to PMIC_ERROR before we get here. + */ + Cleanup_0V8: + + if ((eventMask & USB_DETECT_0V8_RISE) || + (eventMask & USB_DETECT_0V8_FALL)) { + /* EVENT_USB_08VI or EVENT_USBI */ + eventNotify.func = pmic_convity_event_handler; + eventNotify.param = (void *)(CORE_EVENT_0V8); + pmic_event_unsubscribe(EVENT_USBI, eventNotify); + goto End; + } + + Cleanup_2V0: + + if ((eventMask & USB_DETECT_2V0_RISE) || + (eventMask & USB_DETECT_2V0_FALL)) { + /* EVENT_USB_20VI or EVENT_USBI */ + eventNotify.func = pmic_convity_event_handler; + eventNotify.param = (void *)(CORE_EVENT_2V0); + pmic_event_unsubscribe(EVENT_USBI, eventNotify); + goto End; + } + + Cleanup_4V4: + + if ((eventMask & USB_DETECT_4V4_RISE) || + (eventMask & USB_DETECT_4V4_FALL)) { + /* EVENT_USB_44VI or EVENT_USBI */ + eventNotify.func = pmic_convity_event_handler; + eventNotify.param = (void *)(CORE_EVENT_4V4); + pmic_event_unsubscribe(EVENT_USBI, eventNotify); + } + } + /* Exit the critical section. */ + + } + End:up(&mutex); + return rc; + +} + +/*! + * Clears the current callback function. If this function returns successfully + * then all future Connectivity events will only be handled by the default + * handler within the Connectivity driver. + * + * @param handle device handle from open() call + * + * @return PMIC_SUCCESS if the callback was successful cleared + */ +PMIC_STATUS pmic_convity_clear_callback(const PMIC_CONVITY_HANDLE handle) +{ + PMIC_STATUS rc = PMIC_ERROR; + + /* Use a critical section to maintain a consistent state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + if (((handle == usb.handle) && + (usb.handle_state == HANDLE_IN_USE)) || ((handle == rs_232.handle) + && (rs_232.handle_state == + HANDLE_IN_USE)) + || ((handle == cea_936.handle) + && (cea_936.handle_state == HANDLE_IN_USE))) { + + rc = pmic_convity_deregister_all(); + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * Get the current callback function and event mask. + * + * @param handle device handle from open() call + * @param func the current callback function + * @param eventMask the current event selection mask + * + * @return PMIC_SUCCESS if the callback information was successful + * retrieved + */ +PMIC_STATUS pmic_convity_get_callback(const PMIC_CONVITY_HANDLE handle, + PMIC_CONVITY_CALLBACK * const func, + PMIC_CONVITY_EVENTS * const eventMask) +{ + PMIC_STATUS rc = PMIC_ERROR; + + /* Use a critical section to maintain a consistent state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + if ((((handle == usb.handle) && + (usb.handle_state == HANDLE_IN_USE)) || ((handle == rs_232.handle) + && (rs_232. + handle_state == + HANDLE_IN_USE)) + || ((handle == cea_936.handle) + && (cea_936.handle_state == HANDLE_IN_USE))) + && (func != (PMIC_CONVITY_CALLBACK *) NULL) + && (eventMask != (PMIC_CONVITY_EVENTS *) NULL)) { + *func = usb.callback; + *eventMask = usb.eventMask; + + rc = PMIC_SUCCESS; + } + + /* Exit the critical section. */ + + up(&mutex); + + return rc; +} + +/*@*/ + +/************************************************************************** + * USB-specific configuration and setup functions. + ************************************************************************** + */ + +/*! + * @name USB and USB-OTG Connectivity APIs + * Functions for controlling USB and USB-OTG connectivity. + */ +/*@{*/ + +/*! + * Set the USB transceiver speed. + * + * @param handle device handle from open() call + * @param speed the desired USB transceiver speed + * + * @return PMIC_SUCCESS if the transceiver speed was successfully set + */ +PMIC_STATUS pmic_convity_usb_set_speed(const PMIC_CONVITY_HANDLE handle, + const PMIC_CONVITY_USB_SPEED speed) +{ + PMIC_STATUS rc = PMIC_ERROR; + unsigned int reg_value = 0; + unsigned int reg_mask = SET_BITS(regUSB0, FSENB, 1); + + /* Use a critical section to maintain a consistent state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if (handle == (rs_232.handle || cea_936.handle)) { + return PMIC_PARAMETER_ERROR; + } else { + if ((handle == usb.handle) && + (usb.handle_state == HANDLE_IN_USE)) { + /* Validate the function parameters and if they are valid, then + * configure the pull-up and pull-down resistors as required for + * the desired operating mode. + */ + if ((speed == USB_HIGH_SPEED)) { + /* + * The USB transceiver also does not support the high speed mode + * (which is also optional under the USB OTG specification). + */ + rc = PMIC_NOT_SUPPORTED; + } else if ((speed != USB_LOW_SPEED) + && (speed != USB_FULL_SPEED)) { + /* Final validity check on the speed parameter. */ + rc = PMIC_ERROR;; + } else { + /* First configure the D+ and D- pull-up/pull-down resistors as + * per the USB OTG specification. + */ + if (speed == USB_FULL_SPEED) { + /* Activate pull-up on D+ and pull-down on D-. */ + reg_value = + SET_BITS(regUSB0, UDM_PD, 1); + } else if (speed == USB_LOW_SPEED) { + /* Activate pull-up on D+ and pull-down on D-. */ + reg_value = SET_BITS(regUSB0, FSENB, 1); + } + + /* Now set the desired USB transceiver speed. Note that + * USB_FULL_SPEED simply requires FSENB=0 (which it + * already is). + */ + + rc = pmic_write_reg(REG_USB, reg_value, + reg_mask); + + if (rc == PMIC_SUCCESS) { + usb.usbSpeed = speed; + } + } + } + } + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * Get the USB transceiver speed. + * + * @param handle device handle from open() call + * @param speed the current USB transceiver speed + * @param mode the current USB transceiver mode + * + * @return PMIC_SUCCESS if the transceiver speed was successfully + * obtained + */ +PMIC_STATUS pmic_convity_usb_get_speed(const PMIC_CONVITY_HANDLE handle, + PMIC_CONVITY_USB_SPEED * const speed, + PMIC_CONVITY_USB_MODE * const mode) +{ + PMIC_STATUS rc = PMIC_ERROR; + + /* Use a critical section to maintain a consistent state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == usb.handle) && + (usb.handle_state == HANDLE_IN_USE) && + (speed != (PMIC_CONVITY_USB_SPEED *) NULL) && + (mode != (PMIC_CONVITY_USB_MODE *) NULL)) { + *speed = usb.usbSpeed; + *mode = usb.usbMode; + + rc = PMIC_SUCCESS; + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * This function enables/disables VUSB and VBUS output. + * This API configures the VUSBEN and VBUSEN bits of USB register + * + * @param handle device handle from open() call + * @param out_type true, for VBUS + * false, for VUSB + * @param out if true, output is enabled + * if false, output is disabled + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_convity_set_output(const PMIC_CONVITY_HANDLE handle, + bool out_type, bool out) +{ + + PMIC_STATUS rc = PMIC_ERROR; + unsigned int reg_value = 0; + + unsigned int reg_mask = 0; + + /* Use a critical section to maintain a consistent state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == usb.handle) && (usb.handle_state == HANDLE_IN_USE)) { + + if ((out_type == 0) && (out == 1)) { + + reg_value = SET_BITS(regUSB1, VUSBEN, 1); + reg_mask = SET_BITS(regUSB1, VUSBEN, 1); + + rc = pmic_write_reg(REG_CHARGE_USB_SPARE, + reg_value, reg_mask); + } else if (out_type == 0 && out == 0) { + reg_mask = SET_BITS(regUSB1, VBUSEN, 1); + + rc = pmic_write_reg(REG_CHARGE_USB_SPARE, + reg_value, reg_mask); + } else if (out_type == 1 && out == 1) { + + reg_value = SET_BITS(regUSB1, VBUSEN, 1); + reg_mask = SET_BITS(regUSB1, VBUSEN, 1); + + rc = pmic_write_reg(REG_CHARGE_USB_SPARE, + reg_value, reg_mask); + } + + else if (out_type == 1 && out == 0) { + + reg_mask = SET_BITS(regUSB1, VBUSEN, 1); + rc = pmic_write_reg(REG_CHARGE_USB_SPARE, + reg_value, reg_mask); + } + + /*else { + + rc = pmic_write_reg(REG_CHARGE_USB_SPARE, + reg_value, reg_mask); + } */ + } + + up(&mutex); + + return rc; +} + +/*! + * Set the USB transceiver's power supply configuration. + * + * @param handle device handle from open() call + * @param pwrin USB transceiver regulator input power source + * @param pwrout USB transceiver regulator output power level + * + * @return PMIC_SUCCESS if the USB transceiver's power supply + * configuration was successfully set + */ +PMIC_STATUS pmic_convity_usb_set_power_source(const PMIC_CONVITY_HANDLE handle, + const PMIC_CONVITY_USB_POWER_IN + pwrin, + const PMIC_CONVITY_USB_POWER_OUT + pwrout) +{ + PMIC_STATUS rc = PMIC_ERROR; + unsigned int reg_value = 0; + unsigned int reg_mask = 0; + + /* Use a critical section to maintain a consistent state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == usb.handle) && (usb.handle_state == HANDLE_IN_USE)) { + + if (pwrin == USB_POWER_INTERNAL_BOOST) { + reg_value |= SET_BITS(regUSB1, VUSBIN, 0); + reg_mask = SET_BITS(regUSB1, VUSBIN, 1); + } else if (pwrin == USB_POWER_VBUS) { + reg_value |= SET_BITS(regUSB1, VUSBIN, 1); + reg_mask = SET_BITS(regUSB1, VUSBIN, 1); + } + + else if (pwrin == USB_POWER_INTERNAL) { + reg_value |= SET_BITS(regUSB1, VUSBIN, 2); + reg_mask = SET_BITS(regUSB1, VUSBIN, 1); + } + + if (pwrout == USB_POWER_3V3) { + reg_value |= SET_BITS(regUSB1, VUSB, 1); + reg_mask |= SET_BITS(regUSB1, VUSB, 1); + } + + else if (pwrout == USB_POWER_2V775) { + reg_value |= SET_BITS(regUSB1, VUSB, 0); + reg_mask |= SET_BITS(regUSB1, VUSB, 1); + } + rc = pmic_write_reg(REG_CHARGE_USB_SPARE, reg_value, reg_mask); + + if (rc == PMIC_SUCCESS) { + usb.usbPowerIn = pwrin; + usb.usbPowerOut = pwrout; + } + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * Get the USB transceiver's current power supply configuration. + * + * @param handle device handle from open() call + * @param pwrin USB transceiver regulator input power source + * @param pwrout USB transceiver regulator output power level + * + * @return PMIC_SUCCESS if the USB transceiver's power supply + * configuration was successfully retrieved + */ +PMIC_STATUS pmic_convity_usb_get_power_source(const PMIC_CONVITY_HANDLE handle, + PMIC_CONVITY_USB_POWER_IN * + const pwrin, + PMIC_CONVITY_USB_POWER_OUT * + const pwrout) +{ + PMIC_STATUS rc = PMIC_ERROR; + + /* Use a critical section to maintain a consistent state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == usb.handle) && + (usb.handle_state == HANDLE_IN_USE) && + (pwrin != (PMIC_CONVITY_USB_POWER_IN *) NULL) && + (pwrout != (PMIC_CONVITY_USB_POWER_OUT *) NULL)) { + *pwrin = usb.usbPowerIn; + *pwrout = usb.usbPowerOut; + + rc = PMIC_SUCCESS; + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * Set the USB transceiver's operating mode. + * + * @param handle device handle from open() call + * @param mode desired operating mode + * + * @return PMIC_SUCCESS if the USB transceiver's operating mode + * was successfully configured + */ +PMIC_STATUS pmic_convity_usb_set_xcvr(const PMIC_CONVITY_HANDLE handle, + const PMIC_CONVITY_USB_TRANSCEIVER_MODE + mode) +{ + PMIC_STATUS rc = PMIC_ERROR; + unsigned int reg_value = 0; + unsigned int reg_mask = 0; + + /* Use a critical section to maintain a consistent state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == usb.handle) && (usb.handle_state == HANDLE_IN_USE)) { + + if (mode == USB_TRANSCEIVER_OFF) { + reg_value = SET_BITS(regUSB0, USBXCVREN, 0); + reg_mask |= SET_BITS(regUSB0, USB_SUSPEND, 1); + + rc = pmic_write_reg(REG_USB, reg_value, reg_mask); + + } + + if (mode == USB_SINGLE_ENDED_UNIDIR) { + reg_value |= + SET_BITS(regUSB0, DATSE0, 1) | SET_BITS(regUSB0, + BIDIR, 0); + reg_mask |= + SET_BITS(regUSB0, USB_SUSPEND, + 1) | SET_BITS(regUSB0, DATSE0, + 1) | SET_BITS(regUSB0, BIDIR, + 1); + } else if (mode == USB_SINGLE_ENDED_BIDIR) { + reg_value |= + SET_BITS(regUSB0, DATSE0, 1) | SET_BITS(regUSB0, + BIDIR, 1); + reg_mask |= + SET_BITS(regUSB0, USB_SUSPEND, + 1) | SET_BITS(regUSB0, DATSE0, + 1) | SET_BITS(regUSB0, BIDIR, + 1); + } else if (mode == USB_DIFFERENTIAL_UNIDIR) { + reg_value |= + SET_BITS(regUSB0, DATSE0, 0) | SET_BITS(regUSB0, + BIDIR, 0); + reg_mask |= + SET_BITS(regUSB0, USB_SUSPEND, + 1) | SET_BITS(regUSB0, DATSE0, + 1) | SET_BITS(regUSB0, BIDIR, + 1); + } else if (mode == USB_DIFFERENTIAL_BIDIR) { + reg_value |= + SET_BITS(regUSB0, DATSE0, 0) | SET_BITS(regUSB0, + BIDIR, 1); + reg_mask |= + SET_BITS(regUSB0, USB_SUSPEND, + 1) | SET_BITS(regUSB0, DATSE0, + 1) | SET_BITS(regUSB0, BIDIR, + 1); + } + + if (mode == USB_SUSPEND_ON) { + reg_value |= SET_BITS(regUSB0, USB_SUSPEND, 1); + reg_mask |= SET_BITS(regUSB0, USB_SUSPEND, 1); + } else if (mode == USB_SUSPEND_OFF) { + reg_value |= SET_BITS(regUSB0, USB_SUSPEND, 0); + reg_mask |= SET_BITS(regUSB0, USB_SUSPEND, 1); + } + + if (mode == USB_OTG_SRP_DLP_START) { + reg_value |= SET_BITS(regUSB0, USB_PU, 0); + reg_mask |= SET_BITS(regUSB0, USB_SUSPEND, 1); + } else if (mode == USB_OTG_SRP_DLP_STOP) { + reg_value &= SET_BITS(regUSB0, USB_PU, 1); + reg_mask |= SET_BITS(regUSB0, USB_PU, 1); + } + + rc = pmic_write_reg(REG_USB, reg_value, reg_mask); + + if (rc == PMIC_SUCCESS) { + usb.usbXcvrMode = mode; + } + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * Get the USB transceiver's current operating mode. + * + * @param handle device handle from open() call + * @param mode current operating mode + * + * @return PMIC_SUCCESS if the USB transceiver's operating mode + * was successfully retrieved + */ +PMIC_STATUS pmic_convity_usb_get_xcvr(const PMIC_CONVITY_HANDLE handle, + PMIC_CONVITY_USB_TRANSCEIVER_MODE * + const mode) +{ + PMIC_STATUS rc = PMIC_ERROR; + + /* Use a critical section to maintain a consistent state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == usb.handle) && + (usb.handle_state == HANDLE_IN_USE) && + (mode != (PMIC_CONVITY_USB_TRANSCEIVER_MODE *) NULL)) { + *mode = usb.usbXcvrMode; + + rc = PMIC_SUCCESS; + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * Set the Data Line Pulse duration (in milliseconds) for the USB OTG + * Session Request Protocol. + * + * For mc13783, this feature is not supported.So return PMIC_NOT_SUPPORTED + * + * @param handle device handle from open() call + * @param duration the data line pulse duration (ms) + * + * @return PMIC_SUCCESS if the pulse duration was successfully set + */ +PMIC_STATUS pmic_convity_usb_otg_set_dlp_duration(const PMIC_CONVITY_HANDLE + handle, + const unsigned int duration) +{ + PMIC_STATUS rc = PMIC_NOT_SUPPORTED; + + /* The setting of the dlp duration is not supported by the mc13783 PMIC hardware. */ + + /* No critical section is required. */ + + if ((handle != usb.handle) + || (usb.handle_state != HANDLE_IN_USE)) { + /* Must return error indication for invalid handle parameter to be + * consistent with other APIs. + */ + rc = PMIC_ERROR; + } + + return rc; +} + +/*! + * Get the current Data Line Pulse duration (in milliseconds) for the USB + * OTG Session Request Protocol. + * + * @param handle device handle from open() call + * @param duration the data line pulse duration (ms) + * + * @return PMIC_SUCCESS if the pulse duration was successfully obtained + */ +PMIC_STATUS pmic_convity_usb_otg_get_dlp_duration(const PMIC_CONVITY_HANDLE + handle, + unsigned int *const duration) +{ + PMIC_STATUS rc = PMIC_NOT_SUPPORTED; + + /* The setting of dlp duration is not supported by the mc13783 PMIC hardware. */ + + /* No critical section is required. */ + + if ((handle != usb.handle) + || (usb.handle_state != HANDLE_IN_USE)) { + /* Must return error indication for invalid handle parameter to be + * consistent with other APIs. + */ + rc = PMIC_ERROR; + } + + return rc; +} + +/*! + * Set the USB On-The-Go (OTG) configuration. + * + * @param handle device handle from open() call + * @param cfg desired USB OTG configuration + * + * @return PMIC_SUCCESS if the OTG configuration was successfully set + */ +PMIC_STATUS pmic_convity_usb_otg_set_config(const PMIC_CONVITY_HANDLE handle, + const PMIC_CONVITY_USB_OTG_CONFIG + cfg) +{ + PMIC_STATUS rc = PMIC_ERROR; + unsigned int reg_value = 0; + unsigned int reg_mask = 0; + + /* Use a critical section to maintain a consistent state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == usb.handle) && (usb.handle_state == HANDLE_IN_USE)) { + if (cfg & USB_OTG_SE0CONN) { + reg_value = SET_BITS(regUSB0, SE0_CONN, 1); + reg_mask = SET_BITS(regUSB0, SE0_CONN, 1); + } + if (cfg & USBXCVREN) { + reg_value |= SET_BITS(regUSB0, USBXCVREN, 1); + reg_mask |= SET_BITS(regUSB0, USBXCVREN, 1); + } + + if (cfg & USB_OTG_DLP_SRP) { + reg_value |= SET_BITS(regUSB0, DLP_SRP, 1); + reg_mask |= SET_BITS(regUSB0, DLP_SRP, 1); + } + + if (cfg & USB_PULL_OVERRIDE) { + reg_value |= SET_BITS(regUSB0, PULLOVR, 1); + reg_mask |= SET_BITS(regUSB0, PULLOVR, 1); + } + + if (cfg & USB_PU) { + reg_value |= SET_BITS(regUSB0, USB_PU, 1); + reg_mask |= SET_BITS(regUSB0, USB_PU, 1); + } + + if (cfg & USB_UDM_PD) { + reg_value |= SET_BITS(regUSB0, UDM_PD, 1); + reg_mask |= SET_BITS(regUSB0, UDM_PD, 1); + } + + if (cfg & USB_UDP_PD) { + reg_value |= SET_BITS(regUSB0, UDP_PD, 1); + reg_mask |= SET_BITS(regUSB0, UDP_PD, 1); + } + + if (cfg & USB_DP150K_PU) { + reg_value |= SET_BITS(regUSB0, DP150K_PU, 1); + reg_mask |= SET_BITS(regUSB0, DP150K_PU, 1); + } + + if (cfg & USB_USBCNTRL) { + reg_value |= SET_BITS(regUSB0, USBCNTRL, 1); + reg_mask |= SET_BITS(regUSB0, USBCNTRL, 1); + } + + if (cfg & USB_VBUS_CURRENT_LIMIT_HIGH) { + reg_value |= SET_BITS(regUSB0, CURRENT_LIMIT, 0); + } else if (cfg & USB_VBUS_CURRENT_LIMIT_LOW_10MS) { + reg_value |= SET_BITS(regUSB0, CURRENT_LIMIT, 1); + } else if (cfg & USB_VBUS_CURRENT_LIMIT_LOW_20MS) { + reg_value |= SET_BITS(regUSB0, CURRENT_LIMIT, 2); + } else if (cfg & USB_VBUS_CURRENT_LIMIT_LOW_30MS) { + reg_value |= SET_BITS(regUSB0, CURRENT_LIMIT, 3); + } else if (cfg & USB_VBUS_CURRENT_LIMIT_LOW_40MS) { + reg_value |= SET_BITS(regUSB0, CURRENT_LIMIT, 4); + } else if (cfg & USB_VBUS_CURRENT_LIMIT_LOW_50MS) { + reg_value |= SET_BITS(regUSB0, CURRENT_LIMIT, 5); + } else if (cfg & USB_VBUS_CURRENT_LIMIT_LOW_60MS) { + reg_value |= SET_BITS(regUSB0, CURRENT_LIMIT, 6); + } + if (cfg & USB_VBUS_CURRENT_LIMIT_LOW) { + reg_value |= SET_BITS(regUSB0, CURRENT_LIMIT, 7); + reg_mask |= SET_BITS(regUSB0, CURRENT_LIMIT, 7); + } + + if (cfg & USB_VBUS_PULLDOWN) { + reg_value |= SET_BITS(regUSB0, VBUSPDENB, 1); + reg_mask |= SET_BITS(regUSB0, VBUSPDENB, 1); + } + + rc = pmic_write_reg(REG_USB, reg_value, reg_mask); + + if (rc == PMIC_SUCCESS) { + if ((cfg & USB_VBUS_CURRENT_LIMIT_HIGH) || + (cfg & USB_VBUS_CURRENT_LIMIT_LOW) || + (cfg & USB_VBUS_CURRENT_LIMIT_LOW_10MS) || + (cfg & USB_VBUS_CURRENT_LIMIT_LOW_20MS) || + (cfg & USB_VBUS_CURRENT_LIMIT_LOW_30MS) || + (cfg & USB_VBUS_CURRENT_LIMIT_LOW_40MS) || + (cfg & USB_VBUS_CURRENT_LIMIT_LOW_50MS) || + (cfg & USB_VBUS_CURRENT_LIMIT_LOW_60MS)) { + /* Make sure that the VBUS current limit state is + * correctly set to either USB_VBUS_CURRENT_LIMIT_HIGH + * or USB_VBUS_CURRENT_LIMIT_LOW but never both at the + * same time. + * + * We guarantee this by first clearing both of the + * status bits and then resetting the correct one. + */ + usb.usbOtgCfg &= + ~(USB_VBUS_CURRENT_LIMIT_HIGH | + USB_VBUS_CURRENT_LIMIT_LOW | + USB_VBUS_CURRENT_LIMIT_LOW_10MS | + USB_VBUS_CURRENT_LIMIT_LOW_20MS | + USB_VBUS_CURRENT_LIMIT_LOW_30MS | + USB_VBUS_CURRENT_LIMIT_LOW_40MS | + USB_VBUS_CURRENT_LIMIT_LOW_50MS | + USB_VBUS_CURRENT_LIMIT_LOW_60MS); + } + + usb.usbOtgCfg |= cfg; + } + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * Clears the USB On-The-Go (OTG) configuration. Multiple configuration settings + * may be OR'd together in a single call. However, selecting conflicting + * settings (e.g., multiple VBUS current limits) will result in undefined + * behavior. + * + * @param handle Device handle from open() call. + * @param cfg USB OTG configuration settings to be cleared. + * + * @retval PMIC_SUCCESS If the OTG configuration was successfully + * cleared. + * @retval PMIC_PARAMETER_ERROR If the handle is invalid. + * @retval PMIC_NOT_SUPPORTED If the desired USB OTG configuration is + * not supported by the PMIC hardware. + */ +PMIC_STATUS pmic_convity_usb_otg_clear_config(const PMIC_CONVITY_HANDLE handle, + const PMIC_CONVITY_USB_OTG_CONFIG + cfg) +{ + PMIC_STATUS rc = PMIC_ERROR; + unsigned int reg_value = 0; + unsigned int reg_mask = 0; + + /* Use a critical section to maintain a consistent state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == usb.handle) && (usb.handle_state == HANDLE_IN_USE)) { + /* if ((cfg & USB_VBUS_CURRENT_LIMIT_LOW_10MS) || + (cfg & USB_VBUS_CURRENT_LIMIT_LOW_20MS) || + (cfg & USB_VBUS_CURRENT_LIMIT_LOW_30MS) || + (cfg & USB_VBUS_CURRENT_LIMIT_LOW_40MS) || + (cfg & USB_VBUS_CURRENT_LIMIT_LOW_50MS) || + (cfg & USB_VBUS_CURRENT_LIMIT_LOW_60MS)) + { + rc = PMIC_NOT_SUPPORTED; + } */ + + if (cfg & USB_OTG_SE0CONN) { + reg_mask = SET_BITS(regUSB0, SE0_CONN, 1); + } + + if (cfg & USB_OTG_DLP_SRP) { + reg_mask |= SET_BITS(regUSB0, DLP_SRP, 1); + } + + if (cfg & USB_DP150K_PU) { + reg_mask |= SET_BITS(regUSB0, DP150K_PU, 1); + } + + if (cfg & USB_PULL_OVERRIDE) { + reg_mask |= SET_BITS(regUSB0, PULLOVR, 1); + } + + if (cfg & USB_PU) { + + reg_mask |= SET_BITS(regUSB0, USB_PU, 1); + } + + if (cfg & USB_UDM_PD) { + + reg_mask |= SET_BITS(regUSB0, UDM_PD, 1); + } + + if (cfg & USB_UDP_PD) { + + reg_mask |= SET_BITS(regUSB0, UDP_PD, 1); + } + + if (cfg & USB_USBCNTRL) { + reg_mask |= SET_BITS(regUSB0, USBCNTRL, 1); + } + + if (cfg & USB_VBUS_CURRENT_LIMIT_HIGH) { + reg_mask |= SET_BITS(regUSB0, CURRENT_LIMIT, 0); + } else if (cfg & USB_VBUS_CURRENT_LIMIT_LOW_10MS) { + reg_mask |= SET_BITS(regUSB0, CURRENT_LIMIT, 1); + } else if (cfg & USB_VBUS_CURRENT_LIMIT_LOW_20MS) { + reg_mask |= SET_BITS(regUSB0, CURRENT_LIMIT, 2); + } else if (cfg & USB_VBUS_CURRENT_LIMIT_LOW_30MS) { + reg_mask |= SET_BITS(regUSB0, CURRENT_LIMIT, 3); + } else if (cfg & USB_VBUS_CURRENT_LIMIT_LOW_40MS) { + reg_mask |= SET_BITS(regUSB0, CURRENT_LIMIT, 4); + } else if (cfg & USB_VBUS_CURRENT_LIMIT_LOW_50MS) { + reg_mask |= SET_BITS(regUSB0, CURRENT_LIMIT, 5); + } else if (cfg & USB_VBUS_CURRENT_LIMIT_LOW_60MS) { + reg_mask |= SET_BITS(regUSB0, CURRENT_LIMIT, 6); + } + + if (cfg & USB_VBUS_PULLDOWN) { + reg_mask |= SET_BITS(regUSB0, VBUSPDENB, 1); + } + + rc = pmic_write_reg(REG_USB, reg_value, reg_mask); + + if (rc == PMIC_SUCCESS) { + usb.usbOtgCfg &= ~cfg; + } + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * Get the current USB On-The-Go (OTG) configuration. + * + * @param handle device handle from open() call + * @param cfg the current USB OTG configuration + * + * @return PMIC_SUCCESS if the OTG configuration was successfully + * retrieved + */ +PMIC_STATUS pmic_convity_usb_otg_get_config(const PMIC_CONVITY_HANDLE handle, + PMIC_CONVITY_USB_OTG_CONFIG * + const cfg) +{ + PMIC_STATUS rc = PMIC_ERROR; + + /* Use a critical section to maintain a consistent state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == usb.handle) && + (usb.handle_state == HANDLE_IN_USE) && + (cfg != (PMIC_CONVITY_USB_OTG_CONFIG *) NULL)) { + *cfg = usb.usbOtgCfg; + + rc = PMIC_SUCCESS; + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*@}*/ + +/************************************************************************** + * RS-232-specific configuration and setup functions. + ************************************************************************** + */ + +/*! + * @name RS-232 Serial Connectivity APIs + * Functions for controlling RS-232 serial connectivity. + */ +/*@{*/ + +/*! + * Set the connectivity interface to the selected RS-232 operating + * configuration. Note that the RS-232 operating mode will be automatically + * overridden if the USB_EN is asserted at any time (e.g., when a USB device + * is attached). However, we will also automatically return to the RS-232 + * mode once the USB device is detached. + * + * @param handle device handle from open() call + * @param cfgInternal RS-232 transceiver internal connections + * @param cfgExternal RS-232 transceiver external connections + * + * @return PMIC_SUCCESS if the requested mode was set + */ +PMIC_STATUS pmic_convity_rs232_set_config(const PMIC_CONVITY_HANDLE handle, + const PMIC_CONVITY_RS232_INTERNAL + cfgInternal, + const PMIC_CONVITY_RS232_EXTERNAL + cfgExternal) +{ + PMIC_STATUS rc = PMIC_ERROR; + unsigned int reg_value0 = 0, reg_value1 = 0; + unsigned int reg_mask = SET_BITS(regUSB1, RSPOL, 1); + + /* Use a critical section to maintain a consistent state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == rs_232.handle) && (rs_232.handle_state == HANDLE_IN_USE)) { + rc = PMIC_SUCCESS; + + /* Validate the calling parameters. */ + /*if ((cfgInternal != RS232_TX_USE0VM_RX_UDATVP) && + (cfgInternal != RS232_TX_RX_INTERNAL_DEFAULT) && (cfgInternal != RS232_TX_UDATVP_RX_URXVM)) + { + + rc = PMIC_NOT_SUPPORTED; + } */ + if (cfgInternal == RS232_TX_USE0VM_RX_UDATVP) { + + reg_value0 = SET_BITS(regUSB0, INTERFACE_MODE, 1); + + } else if (cfgInternal == RS232_TX_RX_INTERNAL_DEFAULT) { + + reg_value0 = SET_BITS(regUSB0, INTERFACE_MODE, 1); + reg_mask |= SET_BITS(regUSB1, RSPOL, 1); + + } else if (cfgInternal == RS232_TX_UDATVP_RX_URXVM) { + + reg_value0 = SET_BITS(regUSB0, INTERFACE_MODE, 2); + reg_value1 |= SET_BITS(regUSB1, RSPOL, 1); + + } else if ((cfgExternal == RS232_TX_UDM_RX_UDP) || + (cfgExternal == RS232_TX_RX_EXTERNAL_DEFAULT)) { + /* Configure for TX on D+ and RX on D-. */ + reg_value0 |= SET_BITS(regUSB0, INTERFACE_MODE, 1); + reg_value1 |= SET_BITS(regUSB1, RSPOL, 0); + } else if (cfgExternal != RS232_TX_UDM_RX_UDP) { + /* Any other RS-232 configuration is an error. */ + rc = PMIC_ERROR; + } + + if (rc == PMIC_SUCCESS) { + /* Configure for TX on D- and RX on D+. */ + rc = pmic_write_reg(REG_USB, reg_value0, reg_mask); + + rc = pmic_write_reg(REG_CHARGE_USB_SPARE, + reg_value1, reg_mask); + + if (rc == PMIC_SUCCESS) { + rs_232.rs232CfgInternal = cfgInternal; + rs_232.rs232CfgExternal = cfgExternal; + } + } + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*! + * Get the connectivity interface's current RS-232 operating configuration. + * + * @param handle device handle from open() call + * @param cfgInternal RS-232 transceiver internal connections + * @param cfgExternal RS-232 transceiver external connections + * + * @return PMIC_SUCCESS if the requested mode was retrieved + */ +PMIC_STATUS pmic_convity_rs232_get_config(const PMIC_CONVITY_HANDLE handle, + PMIC_CONVITY_RS232_INTERNAL * + const cfgInternal, + PMIC_CONVITY_RS232_EXTERNAL * + const cfgExternal) +{ + PMIC_STATUS rc = PMIC_ERROR; + + /* Use a critical section to maintain a consistent state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle == rs_232.handle) && + (rs_232.handle_state == HANDLE_IN_USE) && + (cfgInternal != (PMIC_CONVITY_RS232_INTERNAL *) NULL) && + (cfgExternal != (PMIC_CONVITY_RS232_EXTERNAL *) NULL)) { + *cfgInternal = rs_232.rs232CfgInternal; + *cfgExternal = rs_232.rs232CfgExternal; + + rc = PMIC_SUCCESS; + } + + /* Exit the critical section. */ + up(&mutex); + + return rc; +} + +/*@}*/ + +/************************************************************************** + * CEA-936-specific configuration and setup functions. + ************************************************************************** + */ + +/*! + * @name CEA-936 Connectivity APIs + * Functions for controlling CEA-936 connectivity. + */ +/*@{*/ + +/*! + * Signal the attached device to exit the current CEA-936 operating mode. + * Returns an error if the current operating mode is not CEA-936. + * + * @param handle device handle from open() call + * @param signal type of exit signal to be sent + * + * @return PMIC_SUCCESS if exit signal was sent + */ +PMIC_STATUS pmic_convity_cea936_exit_signal(const PMIC_CONVITY_HANDLE handle, + const + PMIC_CONVITY_CEA936_EXIT_SIGNAL + signal) +{ + PMIC_STATUS rc = PMIC_ERROR; + unsigned int reg_value = 0; + unsigned int reg_mask = + SET_BITS(regUSB0, IDPD, 1) | SET_BITS(regUSB0, IDPULSE, 1); + + /* Use a critical section to maintain a consistent state. */ + if (down_interruptible(&mutex)) + return PMIC_SYSTEM_ERROR_EINTR; + + if ((handle != cea_936.handle) + || (cea_936.handle_state != HANDLE_IN_USE)) { + /* Must return error indication for invalid handle parameter to be + * consistent with other APIs. + */ + rc = PMIC_ERROR; + } else if (signal == CEA936_UID_PULLDOWN_6MS) { + reg_value = + SET_BITS(regUSB0, IDPULSE, 0) | SET_BITS(regUSB0, IDPD, 0); + } else if (signal == CEA936_UID_PULLDOWN_6MS) { + reg_value = SET_BITS(regUSB0, IDPULSE, 1); + } else if (signal == CEA936_UID_PULLDOWN) { + reg_value = SET_BITS(regUSB0, IDPD, 1); + } else if (signal == CEA936_UDMPULSE) { + reg_value = SET_BITS(regUSB0, DMPULSE, 1); + } + + rc = pmic_write_reg(REG_USB, reg_value, reg_mask); + + up(&mutex); + + return rc; +} + +/*@}*/ + +/************************************************************************** + * Static functions. + ************************************************************************** + */ + +/*! + * @name Connectivity Driver Internal Support Functions + * These non-exported internal functions are used to support the functionality + * of the exported connectivity APIs. + */ +/*@{*/ + +/*! + * This internal helper function sets the desired operating mode (either USB + * OTG or RS-232). It must be called with the mutex already acquired. + * + * @param mode the desired operating mode (USB or RS232) + * + * @return PMIC_SUCCESS if the desired operating mode was set + * @return PMIC_NOT_SUPPORTED if the desired operating mode is invalid + */ +static PMIC_STATUS pmic_convity_set_mode_internal(const PMIC_CONVITY_MODE mode) +{ + unsigned int reg_value0 = 0, reg_value1 = 0; + unsigned int reg_mask0 = 0, reg_mask1 = 0; + + PMIC_STATUS rc = PMIC_SUCCESS; + + switch (mode) { + case USB: + /* For the USB mode, we start by tri-stating the USB bus (by + * setting VBUSEN = 0) until a device is connected (i.e., + * until we receive a 4.4V rising edge event). All pull-up + * and pull-down resistors are also disabled until a USB + * device is actually connected and we have determined which + * device is the host and the desired USB bus speed. + * + * Also tri-state the RS-232 buffers (by setting RSTRI = 1). + * This prevents the hardware from automatically returning to + * the RS-232 mode when the USB device is detached. + */ + + reg_value0 = SET_BITS(regUSB0, INTERFACE_MODE, 0); + reg_mask0 = SET_BITS(regUSB0, INTERFACE_MODE, 7); + + /*reg_value1 = SET_BITS(regUSB1, RSTRI, 1); */ + + rc = pmic_write_reg(REG_USB, reg_value0, reg_mask0); + /* if (rc == PMIC_SUCCESS) { + CHECK_ERROR(pmic_write_reg + (REG_CHARGE_USB_SPARE, + reg_value1, reg_mask1)); + } */ + + break; + + case RS232_1: + /* For the RS-232 mode, we tri-state the USB bus (by setting + * VBUSEN = 0) and enable the RS-232 transceiver (by setting + * RS232ENB = 0). + * + * Note that even in the RS-232 mode, if a USB device is + * plugged in, we will receive a 4.4V rising edge event which + * will automatically disable the RS-232 transceiver and + * tri-state the RS-232 buffers. This allows us to temporarily + * switch over to USB mode while the USB device is attached. + * The RS-232 transceiver and buffers will be automatically + * re-enabled when the USB device is detached. + */ + + /* Explicitly disconnect all of the USB pull-down resistors + * and the VUSB power regulator here just to be safe. + * + * But we do connect the internal pull-up resistor on USB_D+ + * to avoid having an extra load on the USB_D+ line when in + * RS-232 mode. + */ + + reg_value0 |= SET_BITS(regUSB0, INTERFACE_MODE, 1) | + SET_BITS(regUSB0, VBUSPDENB, 1) | + SET_BITS(regUSB0, USB_PU, 1); + reg_mask0 = + SET_BITS(regUSB0, INTERFACE_MODE, 7) | SET_BITS(regUSB0, + VBUSPDENB, + 1) | + SET_BITS(regUSB0, USB_PU, 1); + + reg_value1 = SET_BITS(regUSB1, RSPOL, 0); + + rc = pmic_write_reg(REG_USB, reg_value0, reg_mask0); + + if (rc == PMIC_SUCCESS) { + CHECK_ERROR(pmic_write_reg + (REG_CHARGE_USB_SPARE, + reg_value1, reg_mask1)); + } + break; + + case RS232_2: + reg_value0 |= SET_BITS(regUSB0, INTERFACE_MODE, 2) | + SET_BITS(regUSB0, VBUSPDENB, 1) | + SET_BITS(regUSB0, USB_PU, 1); + reg_mask0 = + SET_BITS(regUSB0, INTERFACE_MODE, 7) | SET_BITS(regUSB0, + VBUSPDENB, + 1) | + SET_BITS(regUSB0, USB_PU, 1); + + reg_value1 = SET_BITS(regUSB1, RSPOL, 1); + + rc = pmic_write_reg(REG_USB, reg_value0, reg_mask0); + + if (rc == PMIC_SUCCESS) { + CHECK_ERROR(pmic_write_reg + (REG_CHARGE_USB_SPARE, + reg_value1, reg_mask1)); + } + break; + + case CEA936_MONO: + reg_value0 |= SET_BITS(regUSB0, INTERFACE_MODE, 4); + + rc = pmic_write_reg(REG_USB, reg_value0, reg_mask0); + break; + + case CEA936_STEREO: + reg_value0 |= SET_BITS(regUSB0, INTERFACE_MODE, 5); + reg_mask0 = SET_BITS(regUSB0, INTERFACE_MODE, 7); + + rc = pmic_write_reg(REG_USB, reg_value0, reg_mask0); + break; + + case CEA936_TEST_RIGHT: + reg_value0 |= SET_BITS(regUSB0, INTERFACE_MODE, 6); + reg_mask0 = SET_BITS(regUSB0, INTERFACE_MODE, 7); + + rc = pmic_write_reg(REG_USB, reg_value0, reg_mask0); + break; + + case CEA936_TEST_LEFT: + reg_value0 |= SET_BITS(regUSB0, INTERFACE_MODE, 7); + reg_mask0 = SET_BITS(regUSB0, INTERFACE_MODE, 7); + + rc = pmic_write_reg(REG_USB, reg_value0, reg_mask0); + break; + + default: + rc = PMIC_NOT_SUPPORTED; + } + + if (rc == PMIC_SUCCESS) { + if (mode == USB) { + usb.mode = mode; + } else if ((mode == RS232_1) || (mode == RS232_1)) { + rs_232.mode = mode; + } else if ((mode == CEA936_MONO) || (mode == CEA936_STEREO) || + (mode == CEA936_TEST_RIGHT) + || (mode == CEA936_TEST_LEFT)) { + cea_936.mode = mode; + } + } + + return rc; +} + +/*! + * This internal helper function deregisters all of the currently registered + * callback events. It must be called with the mutual exclusion spinlock + * already acquired. + * + * We've defined the event and callback deregistration code here as a separate + * function because it can be called by either the pmic_convity_close() or the + * pmic_convity_clear_callback() APIs. We also wanted to avoid any possible + * issues with having the same thread calling spin_lock_irq() twice. + * + * Note that the mutex must have already been acquired. We will also acquire + * the spinlock here to avoid any possible race conditions with the interrupt + * handler. + * + * @return PMIC_SUCCESS if all of the callback events were cleared + */ +static PMIC_STATUS pmic_convity_deregister_all(void) +{ + unsigned long flags; + PMIC_STATUS rc = PMIC_SUCCESS; + + /* Deregister each of the PMIC events that we had previously + * registered for by using pmic_event_subscribe(). + */ + + if ((usb.eventMask & USB_DETECT_MINI_A) || + (usb.eventMask & USB_DETECT_MINI_B) || + (usb.eventMask & USB_DETECT_NON_USB_ACCESSORY) || + (usb.eventMask & USB_DETECT_FACTORY_MODE)) { + /* EVENT_AB_DETI or EVENT_IDI */ + eventNotify.func = pmic_convity_event_handler; + eventNotify.param = (void *)(CORE_EVENT_ABDET); + + if (pmic_event_unsubscribe(EVENT_IDI, eventNotify) == + PMIC_SUCCESS) { + /* Also acquire the spinlock here to avoid any possible race + * conditions with the interrupt handler. + */ + + spin_lock_irqsave(&lock, flags); + + usb.eventMask &= ~(USB_DETECT_MINI_A | + USB_DETECT_MINI_B | + USB_DETECT_NON_USB_ACCESSORY | + USB_DETECT_FACTORY_MODE); + + spin_unlock_irqrestore(&lock, flags); + } else { + pr_debug + ("%s: pmic_event_unsubscribe() for EVENT_AB_DETI failed\n", + __FILE__); + rc = PMIC_ERROR; + } + } + + else if ((usb.eventMask & USB_DETECT_0V8_RISE) || + (usb.eventMask & USB_DETECT_0V8_FALL)) { + /* EVENT_USB_08VI or EVENT_USBI */ + eventNotify.func = pmic_convity_event_handler; + eventNotify.param = (void *)(CORE_EVENT_0V8); + if (pmic_event_unsubscribe(EVENT_USBI, eventNotify) == + PMIC_SUCCESS) { + /* Also acquire the spinlock here to avoid any possible race + * conditions with the interrupt handler. + */ + spin_lock_irqsave(&lock, flags); + + usb.eventMask &= ~(USB_DETECT_0V8_RISE | + USB_DETECT_0V8_FALL); + + spin_unlock_irqrestore(&lock, flags); + } else { + pr_debug + ("%s: pmic_event_unsubscribe() for EVENT_USB_08VI failed\n", + __FILE__); + rc = PMIC_ERROR; + } + + } + + else if ((usb.eventMask & USB_DETECT_2V0_RISE) || + (usb.eventMask & USB_DETECT_2V0_FALL)) { + /* EVENT_USB_20VI or EVENT_USBI */ + eventNotify.func = pmic_convity_event_handler; + eventNotify.param = (void *)(CORE_EVENT_2V0); + if (pmic_event_unsubscribe(EVENT_USBI, eventNotify) == + PMIC_SUCCESS) { + /* Also acquire the spinlock here to avoid any possible race + * conditions with the interrupt handler. + */ + spin_lock_irqsave(&lock, flags); + + usb.eventMask &= ~(USB_DETECT_2V0_RISE | + USB_DETECT_2V0_FALL); + + spin_unlock_irqrestore(&lock, flags); + } else { + pr_debug + ("%s: pmic_event_unsubscribe() for EVENT_USB_20VI failed\n", + __FILE__); + rc = PMIC_ERROR; + } + } + + else if ((usb.eventMask & USB_DETECT_4V4_RISE) || + (usb.eventMask & USB_DETECT_4V4_FALL)) { + + /* EVENT_USB_44VI or EVENT_USBI */ + eventNotify.func = pmic_convity_event_handler; + eventNotify.param = (void *)(CORE_EVENT_4V4); + + if (pmic_event_unsubscribe(EVENT_USBI, eventNotify) == + PMIC_SUCCESS) { + + /* Also acquire the spinlock here to avoid any possible race + * conditions with the interrupt handler. + */ + spin_lock_irqsave(&lock, flags); + + usb.eventMask &= ~(USB_DETECT_4V4_RISE | + USB_DETECT_4V4_FALL); + + spin_unlock_irqrestore(&lock, flags); + } else { + pr_debug + ("%s: pmic_event_unsubscribe() for EVENT_USB_44VI failed\n", + __FILE__); + rc = PMIC_ERROR; + } + } + + if (rc == PMIC_SUCCESS) { + /* Also acquire the spinlock here to avoid any possible race + * conditions with the interrupt handler. + */ + spin_lock_irqsave(&lock, flags); + + /* Restore the initial reset values for the callback function + * and event mask parameters. This should be NULL and zero, + * respectively. + * + * Note that we wait until the end here to fully reset everything + * just in case some of the pmic_event_unsubscribe() calls above + * failed for some reason (which normally shouldn't happen). + */ + usb.callback = reset.callback; + usb.eventMask = reset.eventMask; + + spin_unlock_irqrestore(&lock, flags); + } + return rc; +} + +/*! + * This is the default event handler for all connectivity-related events + * and hardware interrupts. + * + * @param param event ID + */ +static void pmic_convity_event_handler(void *param) +{ + unsigned long flags; + + /* Update the global list of active interrupt events. */ + spin_lock_irqsave(&lock, flags); + eventID |= (PMIC_CORE_EVENT) (param); + spin_unlock_irqrestore(&lock, flags); + + /* Schedule the tasklet to be run as soon as it is convenient to do so. */ + schedule_work(&convityTasklet); +} + +/*! + * @brief This is the connectivity driver tasklet that handles interrupt events. + * + * This function is scheduled by the connectivity driver interrupt handler + * pmic_convity_event_handler() to complete the processing of all of the + * connectivity-related interrupt events. + * + * Since this tasklet runs with interrupts enabled, we can safely call + * the ADC driver, if necessary, to properly detect the type of USB connection + * that is being made and to call any user-registered callback functions. + * + * @param arg The parameter that was provided above in + * the DECLARE_TASKLET() macro (unused). + */ +static void pmic_convity_tasklet(struct work_struct *work) +{ + + PMIC_CONVITY_EVENTS activeEvents = 0; + unsigned long flags = 0; + + /* Check the interrupt sense bits to determine exactly what + * event just occurred. + */ + if (eventID & CORE_EVENT_4V4) { + spin_lock_irqsave(&lock, flags); + eventID &= ~CORE_EVENT_4V4; + spin_unlock_irqrestore(&lock, flags); + + activeEvents |= pmic_check_sensor(SENSE_USB4V4S) ? + USB_DETECT_4V4_RISE : USB_DETECT_4V4_FALL; + + if (activeEvents & ~usb.eventMask) { + /* The default handler for 4.4 V rising/falling edge detection + * is to simply ignore the event. + */ + ; + } + } + if (eventID & CORE_EVENT_2V0) { + spin_lock_irqsave(&lock, flags); + eventID &= ~CORE_EVENT_2V0; + spin_unlock_irqrestore(&lock, flags); + + activeEvents |= pmic_check_sensor(SENSE_USB2V0S) ? + USB_DETECT_2V0_RISE : USB_DETECT_2V0_FALL; + if (activeEvents & ~usb.eventMask) { + /* The default handler for 2.0 V rising/falling edge detection + * is to simply ignore the event. + */ + ; + } + } + if (eventID & CORE_EVENT_0V8) { + spin_lock_irqsave(&lock, flags); + eventID &= ~CORE_EVENT_0V8; + spin_unlock_irqrestore(&lock, flags); + + activeEvents |= pmic_check_sensor(SENSE_USB0V8S) ? + USB_DETECT_0V8_RISE : USB_DETECT_0V8_FALL; + + if (activeEvents & ~usb.eventMask) { + /* The default handler for 0.8 V rising/falling edge detection + * is to simply ignore the event. + */ + ; + } + } + if (eventID & CORE_EVENT_ABDET) { + spin_lock_irqsave(&lock, flags); + eventID &= ~CORE_EVENT_ABDET; + spin_unlock_irqrestore(&lock, flags); + + activeEvents |= pmic_check_sensor(SENSE_ID_GNDS) ? + USB_DETECT_MINI_A : 0; + + activeEvents |= pmic_check_sensor(SENSE_ID_FLOATS) ? + USB_DETECT_MINI_B : 0; + } + + /* Begin a critical section here so that we don't register/deregister + * for events or open/close the connectivity driver while the existing + * event handler (if it is currently defined) is in the middle of handling + * the current event. + */ + spin_lock_irqsave(&lock, flags); + + /* Finally, call the user-defined callback function if required. */ + if ((usb.handle_state == HANDLE_IN_USE) && + (usb.callback != NULL) && (activeEvents & usb.eventMask)) { + (*usb.callback) (activeEvents); + } + + spin_unlock_irqrestore(&lock, flags); +} + +/*@}*/ + +/************************************************************************** + * Module initialization and termination functions. + * + * Note that if this code is compiled into the kernel, then the + * module_init() function will be called within the device_initcall() + * group. + ************************************************************************** + */ + +/*! + * @name Connectivity Driver Loading/Unloading Functions + * These non-exported internal functions are used to support the connectivity + * device driver initialization and de-initialization operations. + */ +/*@{*/ + +/*! + * @brief This is the connectivity device driver initialization function. + * + * This function is called by the kernel when this device driver is first + * loaded. + */ +static int __init mc13783_pmic_convity_init(void) +{ + printk(KERN_INFO "PMIC Connectivity driver loading..\n"); + + return 0; +} + +/*! + * @brief This is the Connectivity device driver de-initialization function. + * + * This function is called by the kernel when this device driver is about + * to be unloaded. + */ +static void __exit mc13783_pmic_convity_exit(void) +{ + printk(KERN_INFO "PMIC Connectivity driver unloading\n"); + + /* Close the device handle if it is still open. This will also + * deregister any callbacks that may still be active. + */ + if (usb.handle_state == HANDLE_IN_USE) { + pmic_convity_close(usb.handle); + } else if (usb.handle_state == HANDLE_IN_USE) { + pmic_convity_close(rs_232.handle); + } else if (usb.handle_state == HANDLE_IN_USE) { + pmic_convity_close(cea_936.handle); + } + + /* Reset the PMIC Connectivity register to it's power on state. + * We should do this when unloading the module so that we don't + * leave the hardware in a state which could cause problems when + * no device driver is loaded. + */ + pmic_write_reg(REG_USB, RESET_USBCNTRL_REG_0, REG_FULLMASK); + pmic_write_reg(REG_CHARGE_USB_SPARE, RESET_USBCNTRL_REG_1, + REG_FULLMASK); + /* Note that there is no need to reset the "convity" device driver + * state structure to the reset state since we are in the final + * stage of unloading the device driver. The device driver state + * structure will be automatically and properly reinitialized if + * this device driver is reloaded. + */ +} + +/*@}*/ + +/* + * Module entry points and description information. + */ + +module_init(mc13783_pmic_convity_init); +module_exit(mc13783_pmic_convity_exit); + +MODULE_DESCRIPTION("mc13783 Connectivity device driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/pmic/mc13783/pmic_light.c b/drivers/mxc/pmic/mc13783/pmic_light.c new file mode 100644 index 000000000000..46c13aab2a78 --- /dev/null +++ b/drivers/mxc/pmic/mc13783/pmic_light.c @@ -0,0 +1,2764 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mc13783/pmic_light.c + * @brief This is the main file of PMIC(mc13783) Light and Backlight driver. + * + * @ingroup PMIC_LIGHT + */ + +/* + * Includes + */ +#include +#include +#include +#include +#include +#include +#include +#include "pmic_light_defs.h" + +#define NB_LIGHT_REG 6 + +static int pmic_light_major; + +/*! + * Number of users waiting in suspendq + */ +static int swait; + +/*! + * To indicate whether any of the light devices are suspending + */ +static int suspend_flag; + +/*! + * The suspendq is used to block application calls + */ +static wait_queue_head_t suspendq; + +static struct class *pmic_light_class; + +/* EXPORTED FUNCTIONS */ +EXPORT_SYMBOL(pmic_bklit_tcled_master_enable); +EXPORT_SYMBOL(pmic_bklit_tcled_master_disable); +EXPORT_SYMBOL(pmic_bklit_master_enable); +EXPORT_SYMBOL(pmic_bklit_master_disable); +EXPORT_SYMBOL(pmic_bklit_set_current); +EXPORT_SYMBOL(pmic_bklit_get_current); +EXPORT_SYMBOL(pmic_bklit_set_dutycycle); +EXPORT_SYMBOL(pmic_bklit_get_dutycycle); +EXPORT_SYMBOL(pmic_bklit_set_cycle_time); +EXPORT_SYMBOL(pmic_bklit_get_cycle_time); +EXPORT_SYMBOL(pmic_bklit_set_mode); +EXPORT_SYMBOL(pmic_bklit_get_mode); +EXPORT_SYMBOL(pmic_bklit_rampup); +EXPORT_SYMBOL(pmic_bklit_off_rampup); +EXPORT_SYMBOL(pmic_bklit_rampdown); +EXPORT_SYMBOL(pmic_bklit_off_rampdown); +EXPORT_SYMBOL(pmic_bklit_enable_edge_slow); +EXPORT_SYMBOL(pmic_bklit_disable_edge_slow); +EXPORT_SYMBOL(pmic_bklit_get_edge_slow); +EXPORT_SYMBOL(pmic_bklit_set_strobemode); +EXPORT_SYMBOL(pmic_tcled_enable); +EXPORT_SYMBOL(pmic_tcled_disable); +EXPORT_SYMBOL(pmic_tcled_get_mode); +EXPORT_SYMBOL(pmic_tcled_ind_set_current); +EXPORT_SYMBOL(pmic_tcled_ind_get_current); +EXPORT_SYMBOL(pmic_tcled_ind_set_blink_pattern); +EXPORT_SYMBOL(pmic_tcled_ind_get_blink_pattern); +EXPORT_SYMBOL(pmic_tcled_fun_set_current); +EXPORT_SYMBOL(pmic_tcled_fun_get_current); +EXPORT_SYMBOL(pmic_tcled_fun_set_cycletime); +EXPORT_SYMBOL(pmic_tcled_fun_get_cycletime); +EXPORT_SYMBOL(pmic_tcled_fun_set_dutycycle); +EXPORT_SYMBOL(pmic_tcled_fun_get_dutycycle); +EXPORT_SYMBOL(pmic_tcled_fun_blendedramps); +EXPORT_SYMBOL(pmic_tcled_fun_sawramps); +EXPORT_SYMBOL(pmic_tcled_fun_blendedbowtie); +EXPORT_SYMBOL(pmic_tcled_fun_chasinglightspattern); +EXPORT_SYMBOL(pmic_tcled_fun_strobe); +EXPORT_SYMBOL(pmic_tcled_fun_rampup); +EXPORT_SYMBOL(pmic_tcled_get_fun_rampup); +EXPORT_SYMBOL(pmic_tcled_fun_rampdown); +EXPORT_SYMBOL(pmic_tcled_get_fun_rampdown); +EXPORT_SYMBOL(pmic_tcled_fun_triode_on); +EXPORT_SYMBOL(pmic_tcled_fun_triode_off); +EXPORT_SYMBOL(pmic_tcled_enable_edge_slow); +EXPORT_SYMBOL(pmic_tcled_disable_edge_slow); +EXPORT_SYMBOL(pmic_tcled_enable_half_current); +EXPORT_SYMBOL(pmic_tcled_disable_half_current); +EXPORT_SYMBOL(pmic_tcled_enable_audio_modulation); +EXPORT_SYMBOL(pmic_tcled_disable_audio_modulation); +EXPORT_SYMBOL(pmic_bklit_set_boost_mode); +EXPORT_SYMBOL(pmic_bklit_get_boost_mode); +EXPORT_SYMBOL(pmic_bklit_config_boost_mode); +EXPORT_SYMBOL(pmic_bklit_gets_boost_mode); + +/*! + * This is the suspend of power management for the pmic light API. + * It suports SAVE and POWER_DOWN state. + * + * @param pdev the device + * @param state the state + * + * @return This function returns 0 if successful. + */ +static int pmic_light_suspend(struct platform_device *dev, pm_message_t state) +{ + suspend_flag = 1; + /* switch off all leds and backlights */ + CHECK_ERROR(pmic_light_init_reg()); + + return 0; +}; + +/*! + * This is the resume of power management for the pmic light API. + * It suports RESTORE state. + * + * @param dev the device + * + * @return This function returns 0 if successful. + */ +static int pmic_light_resume(struct platform_device *pdev) +{ + suspend_flag = 0; + while (swait > 0) { + swait--; + wake_up_interruptible(&suspendq); + } + + return 0; +}; + +/*! + * This function enables backlight & tcled. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_bklit_tcled_master_enable(void) +{ + unsigned int reg_value = 0; + unsigned int mask = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + reg_value = BITFVAL(BIT_LEDEN, 1); + mask = BITFMASK(BIT_LEDEN); + CHECK_ERROR(pmic_write_reg(LREG_0, reg_value, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function disables backlight & tcled. + * + * @return This function returns PMIC_SUCCESS if successful + */ +PMIC_STATUS pmic_bklit_tcled_master_disable(void) +{ + unsigned int reg_value = 0; + unsigned int mask = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + reg_value = BITFVAL(BIT_LEDEN, 0); + mask = BITFMASK(BIT_LEDEN); + CHECK_ERROR(pmic_write_reg(LREG_0, reg_value, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function enables backlight. Not supported on mc13783 + * Use pmic_bklit_tcled_master_enable. + * + * @return This function returns PMIC_NOT_SUPPORTED + */ +PMIC_STATUS pmic_bklit_master_enable(void) +{ + return PMIC_NOT_SUPPORTED; +} + +/*! + * This function disables backlight. Not supported on mc13783 + * Use pmic_bklit_tcled_master_enable. + * + * @return This function returns PMIC_NOT_SUPPORTED + */ +PMIC_STATUS pmic_bklit_master_disable(void) +{ + return PMIC_NOT_SUPPORTED; +} + +/*! + * This function sets backlight current level. + * + * @param channel Backlight channel + * @param level Backlight current level, as the following table. + * @verbatim + * level main & aux keyboard + * ------ ----------- -------- + * 0 0 mA 0 mA + * 1 3 mA 12 mA + * 2 6 mA 24 mA + * 3 9 mA 36 mA + * 4 12 mA 48 mA + * 5 15 mA 60 mA + * 6 18 mA 72 mA + * 7 21 mA 84 mA + * @endverbatim + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_bklit_set_current(t_bklit_channel channel, unsigned char level) +{ + unsigned int mask; + unsigned int value; + + if (suspend_flag == 1) { + return -EBUSY; + } + + switch (channel) { + case BACKLIGHT_LED1: + value = BITFVAL(BIT_CL_MAIN, level); + mask = BITFMASK(BIT_CL_MAIN); + break; + case BACKLIGHT_LED2: + value = BITFVAL(BIT_CL_AUX, level); + mask = BITFMASK(BIT_CL_AUX); + break; + case BACKLIGHT_LED3: + value = BITFVAL(BIT_CL_KEY, level); + mask = BITFMASK(BIT_CL_KEY); + break; + default: + return PMIC_PARAMETER_ERROR; + } + CHECK_ERROR(pmic_write_reg(LREG_2, value, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function retrives backlight current level. + * The channels are not individually adjustable, hence + * the channel parameter is ignored. + * + * @param channel Backlight channel (Ignored because the + * channels are not individually adjustable) + * @param level Pointer to store backlight current level result. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_bklit_get_current(t_bklit_channel channel, + unsigned char *level) +{ + unsigned int reg_value = 0; + unsigned int mask = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + switch (channel) { + case BACKLIGHT_LED1: + mask = BITFMASK(BIT_CL_MAIN); + break; + case BACKLIGHT_LED2: + mask = BITFMASK(BIT_CL_AUX); + break; + case BACKLIGHT_LED3: + mask = BITFMASK(BIT_CL_KEY); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_read_reg(LREG_2, ®_value, mask)); + + switch (channel) { + case BACKLIGHT_LED1: + *level = BITFEXT(reg_value, BIT_CL_MAIN); + break; + case BACKLIGHT_LED2: + *level = BITFEXT(reg_value, BIT_CL_AUX); + break; + case BACKLIGHT_LED3: + *level = BITFEXT(reg_value, BIT_CL_KEY); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + return PMIC_SUCCESS; +} + +/*! + * This function sets a backlight channel duty cycle. + * LED perceived brightness for each zone may be individually set by setting + * duty cycle. The default setting is for 0% duty cycle; this keeps all zone + * drivers turned off even after the master enable command. Each LED current + * sink can be turned on and adjusted for brightness with an independent 4 bit + * word for a duty cycle ranging from 0% to 100% in approximately 6.7% steps. + * + * @param channel Backlight channel. + * @param dc Backlight duty cycle, as the following table. + * @verbatim + * dc Duty Cycle (% On-time over Cycle Time) + * ------ --------------------------------------- + * 0 0% + * 1 6.7% + * 2 13.3% + * 3 20% + * 4 26.7% + * 5 33.3% + * 6 40% + * 7 46.7% + * 8 53.3% + * 9 60% + * 10 66.7% + * 11 73.3% + * 12 80% + * 13 86.7% + * 14 93.3% + * 15 100% + * @endverbatim + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_bklit_set_dutycycle(t_bklit_channel channel, unsigned char dc) +{ + unsigned int reg_value = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + if (dc > 15) { + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_read_reg(LREG_2, ®_value, PMIC_ALL_BITS)); + + switch (channel) { + case BACKLIGHT_LED1: + reg_value = reg_value & (~MASK_DUTY_CYCLE); + reg_value = reg_value | (dc << BIT_DUTY_CYCLE); + break; + case BACKLIGHT_LED2: + reg_value = reg_value & (~(MASK_DUTY_CYCLE << INDEX_AUX)); + reg_value = reg_value | (dc << (BIT_DUTY_CYCLE + INDEX_AUX)); + break; + case BACKLIGHT_LED3: + reg_value = reg_value & (~(MASK_DUTY_CYCLE << INDEX_KYD)); + reg_value = reg_value | (dc << (BIT_DUTY_CYCLE + INDEX_KYD)); + break; + default: + return PMIC_PARAMETER_ERROR; + } + CHECK_ERROR(pmic_write_reg(LREG_2, reg_value, PMIC_ALL_BITS)); + return PMIC_SUCCESS; + +} + +/*! + * This function retrives a backlight channel duty cycle. + * + * @param channel Backlight channel. + * @param dc Pointer to backlight duty cycle. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_bklit_get_dutycycle(t_bklit_channel channel, unsigned char *dc) +{ + unsigned int reg_value = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + CHECK_ERROR(pmic_read_reg(LREG_2, ®_value, PMIC_ALL_BITS)); + + switch (channel) { + case BACKLIGHT_LED1: + *dc = (int)((reg_value & (MASK_DUTY_CYCLE)) + >> BIT_DUTY_CYCLE); + + break; + case BACKLIGHT_LED2: + *dc = (int)((reg_value & (MASK_DUTY_CYCLE << INDEX_AUX)) + >> (BIT_DUTY_CYCLE + INDEX_AUX)); + break; + case BACKLIGHT_LED3: + *dc = (int)((reg_value & (MASK_DUTY_CYCLE << + INDEX_KYD)) >> (BIT_DUTY_CYCLE + + INDEX_KYD)); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + return PMIC_SUCCESS; +} + +/*! + * This function sets a backlight channel cycle time. + * Cycle Time is defined as the period of a complete cycle of + * Time_on + Time_off. The default Cycle Time is set to 0.01 seconds such that + * the 100 Hz on-off cycling is averaged out by the eye to eliminate + * flickering. Additionally, the Cycle Time can be programmed to intentionally + * extend the period of on-off cycles for a visual pulsating or blinking effect. + * + * @param period Backlight cycle time, as the following table. + * @verbatim + * period Cycle Time + * -------- ------------ + * 0 0.01 seconds + * 1 0.1 seconds + * 2 0.5 seconds + * 3 2 seconds + * @endverbatim + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_bklit_set_cycle_time(unsigned char period) +{ + unsigned int mask; + unsigned int value; + + if (suspend_flag == 1) { + return -EBUSY; + } + if (period > 3) { + return PMIC_PARAMETER_ERROR; + } + mask = BITFMASK(BIT_PERIOD); + value = BITFVAL(BIT_PERIOD, period); + CHECK_ERROR(pmic_write_reg(LREG_2, value, mask)); + return PMIC_SUCCESS; +} + +/*! + * This function retrives a backlight channel cycle time setting. + * + * @param period Pointer to save backlight cycle time setting result. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_bklit_get_cycle_time(unsigned char *period) +{ + unsigned int mask; + unsigned int value; + + if (suspend_flag == 1) { + return -EBUSY; + } + mask = BITFMASK(BIT_PERIOD); + CHECK_ERROR(pmic_read_reg(LREG_2, &value, mask)); + *period = BITFEXT(value, BIT_PERIOD); + return PMIC_SUCCESS; +} + +/*! + * This function sets backlight operation mode. There are two modes of + * operations: current control and triode mode. + * The Duty Cycle/Cycle Time control is retained in Triode Mode. Audio + * coupling is not available in Triode Mode. + * + * @param channel Backlight channel. + * @param mode Backlight operation mode. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_bklit_set_mode(t_bklit_channel channel, t_bklit_mode mode) +{ + unsigned int reg_value = 0; + unsigned int clear_val = 0; + unsigned int triode_val = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + CHECK_ERROR(pmic_read_reg(LREG_0, ®_value, PMIC_ALL_BITS)); + + switch (channel) { + case BACKLIGHT_LED1: + clear_val = ~(MASK_TRIODE_MAIN_BL); + triode_val = MASK_TRIODE_MAIN_BL; + break; + case BACKLIGHT_LED2: + clear_val = ~(MASK_TRIODE_MAIN_BL << INDEX_AUXILIARY); + triode_val = (MASK_TRIODE_MAIN_BL << INDEX_AUXILIARY); + break; + case BACKLIGHT_LED3: + clear_val = ~(MASK_TRIODE_MAIN_BL << INDEX_KEYPAD); + triode_val = (MASK_TRIODE_MAIN_BL << INDEX_KEYPAD); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + reg_value = (reg_value & clear_val); + + if (mode == BACKLIGHT_TRIODE_MODE) { + reg_value = (reg_value | triode_val); + } + + CHECK_ERROR(pmic_write_reg(LREG_0, reg_value, PMIC_ALL_BITS)); + return PMIC_SUCCESS; +} + +/*! + * This function gets backlight operation mode. There are two modes of + * operations: current control and triode mode. + * The Duty Cycle/Cycle Time control is retained in Triode Mode. Audio + * coupling is not available in Triode Mode. + * + * @param channel Backlight channel. + * @param mode Backlight operation mode. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_bklit_get_mode(t_bklit_channel channel, t_bklit_mode *mode) +{ + unsigned int reg_value = 0; + unsigned int mask = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + switch (channel) { + case BACKLIGHT_LED1: + mask = BITFMASK(BIT_TRIODE_MAIN_BL); + break; + case BACKLIGHT_LED2: + mask = BITFMASK(BIT_TRIODE_AUX_BL); + break; + case BACKLIGHT_LED3: + mask = BITFMASK(BIT_TRIODE_KEY_BL); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_read_reg(LREG_0, ®_value, mask)); + + switch (channel) { + case BACKLIGHT_LED1: + *mode = BITFEXT(reg_value, BIT_TRIODE_MAIN_BL); + break; + case BACKLIGHT_LED2: + *mode = BITFEXT(reg_value, BIT_TRIODE_AUX_BL); + break; + case BACKLIGHT_LED3: + *mode = BITFEXT(reg_value, BIT_TRIODE_KEY_BL); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + return PMIC_SUCCESS; +} + +/*! + * This function starts backlight brightness ramp up function; ramp time is + * fixed at 0.5 seconds. + * + * @param channel Backlight channel. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_bklit_rampup(t_bklit_channel channel) +{ + unsigned int reg_value = 0; + unsigned int mask = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + switch (channel) { + case BACKLIGHT_LED1: + mask = BITFMASK(BIT_UP_MAIN_BL); + reg_value = BITFVAL(BIT_UP_MAIN_BL, 1); + break; + case BACKLIGHT_LED2: + mask = BITFMASK(BIT_UP_AUX_BL); + reg_value = BITFVAL(BIT_UP_AUX_BL, 1); + break; + case BACKLIGHT_LED3: + mask = BITFMASK(BIT_UP_KEY_BL); + reg_value = BITFVAL(BIT_UP_KEY_BL, 1); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(LREG_0, reg_value, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function stops backlight brightness ramp up function; + * + * @param channel Backlight channel. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_bklit_off_rampup(t_bklit_channel channel) +{ + unsigned int reg_value = 0; + unsigned int mask = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + switch (channel) { + case BACKLIGHT_LED1: + mask = BITFMASK(BIT_UP_MAIN_BL); + break; + case BACKLIGHT_LED2: + mask = BITFMASK(BIT_UP_AUX_BL); + break; + case BACKLIGHT_LED3: + mask = BITFMASK(BIT_UP_KEY_BL); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(LREG_0, reg_value, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function starts backlight brightness ramp down function; ramp time is + * fixed at 0.5 seconds. + * + * @param channel Backlight channel. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_bklit_rampdown(t_bklit_channel channel) +{ + unsigned int reg_value = 0; + unsigned int mask = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + switch (channel) { + case BACKLIGHT_LED1: + mask = BITFMASK(BIT_DOWN_MAIN_BL); + reg_value = BITFVAL(BIT_DOWN_MAIN_BL, 1); + break; + case BACKLIGHT_LED2: + mask = BITFMASK(BIT_DOWN_AUX_BL); + reg_value = BITFVAL(BIT_DOWN_AUX_BL, 1); + break; + case BACKLIGHT_LED3: + mask = BITFMASK(BIT_DOWN_KEY_BL); + reg_value = BITFVAL(BIT_DOWN_KEY_BL, 1); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(LREG_0, reg_value, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function stops backlight brightness ramp down function. + * + * @param channel Backlight channel. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_bklit_off_rampdown(t_bklit_channel channel) +{ + unsigned int reg_value = 0; + unsigned int mask = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + switch (channel) { + case BACKLIGHT_LED1: + mask = BITFMASK(BIT_DOWN_MAIN_BL); + break; + case BACKLIGHT_LED2: + mask = BITFMASK(BIT_DOWN_AUX_BL); + break; + case BACKLIGHT_LED3: + mask = BITFMASK(BIT_DOWN_KEY_BL); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(LREG_0, reg_value, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function enables backlight analog edge slowing mode. Analog Edge + * Slowing slows down the transient edges to reduce the chance of coupling LED + * modulation activity into other circuits. Rise and fall times will be targeted + * for approximately 50usec. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_bklit_enable_edge_slow(void) +{ + unsigned int mask; + unsigned int value; + + if (suspend_flag == 1) { + return -EBUSY; + } + mask = BITFMASK(BIT_SLEWLIMBL); + value = BITFVAL(BIT_SLEWLIMBL, 1); + CHECK_ERROR(pmic_write_reg(LREG_2, value, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function disables backlight analog edge slowing mode. The backlight + * drivers will default to an <93>Instant On<94> mode. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_bklit_disable_edge_slow(void) +{ + unsigned int mask; + + if (suspend_flag == 1) { + return -EBUSY; + } + mask = BITFMASK(BIT_SLEWLIMBL); + CHECK_ERROR(pmic_write_reg(LREG_2, 0, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function gets backlight analog edge slowing mode. DThe backlight + * + * @param edge Edge slowing mode. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_bklit_get_edge_slow(bool *edge) +{ + unsigned int mask; + unsigned int value; + + if (suspend_flag == 1) { + return -EBUSY; + } + mask = BITFMASK(BIT_SLEWLIMBL); + CHECK_ERROR(pmic_read_reg(LREG_2, &value, mask)); + *edge = (bool) BITFEXT(value, BIT_SLEWLIMBL); + + return PMIC_SUCCESS; +} + +/*! + * This function sets backlight Strobe Light Pulsing mode. + * + * @param channel Backlight channel. + * @param mode Strobe Light Pulsing mode. + * + * @return This function returns PMIC_NOT_SUPPORTED. + */ +PMIC_STATUS pmic_bklit_set_strobemode(t_bklit_channel channel, + t_bklit_strobe_mode mode) +{ + return PMIC_NOT_SUPPORTED; +} + +/*! + * This function enables tri-color LED. + * + * @param mode Tri-color LED operation mode. + * @param bank Selected tri-color bank + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_enable(t_tcled_mode mode, t_funlight_bank bank) +{ + unsigned int mask = 0; + unsigned int value = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + switch (mode) { + case TCLED_FUN_MODE: + switch (bank) { + case TCLED_FUN_BANK1: + mask = MASK_BK1_FL; + value = MASK_BK1_FL; + break; + case TCLED_FUN_BANK2: + mask = MASK_BK2_FL; + value = MASK_BK2_FL; + break; + case TCLED_FUN_BANK3: + mask = MASK_BK3_FL; + value = MASK_BK3_FL; + break; + default: + return PMIC_PARAMETER_ERROR; + } + break; + case TCLED_IND_MODE: + mask = MASK_BK1_FL | MASK_BK2_FL | MASK_BK3_FL; + break; + } + + CHECK_ERROR(pmic_write_reg(LREG_0, value, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function disables tri-color LED. + * + * @param bank Selected tri-color bank + * + * @return This function returns PMIC_SUCCESS if successful. + * + */ +PMIC_STATUS pmic_tcled_disable(t_funlight_bank bank) +{ + unsigned int mask = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + switch (bank) { + case TCLED_FUN_BANK1: + mask = MASK_BK1_FL; + break; + case TCLED_FUN_BANK2: + mask = MASK_BK2_FL; + break; + case TCLED_FUN_BANK3: + mask = MASK_BK3_FL; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(LREG_0, 0, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function retrives tri-color LED operation mode. + * + * @param mode Pointer to Tri-color LED operation mode. + * @param bank Selected tri-color bank + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_get_mode(t_tcled_mode *mode, t_funlight_bank bank) +{ + unsigned int val; + unsigned int mask; + + if (suspend_flag == 1) { + return -EBUSY; + } + + switch (bank) { + case TCLED_FUN_BANK1: + mask = MASK_BK1_FL; + break; + case TCLED_FUN_BANK2: + mask = MASK_BK2_FL; + break; + case TCLED_FUN_BANK3: + mask = MASK_BK3_FL; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_read_reg(LREG_0, &val, mask)); + + if (val) { + *mode = TCLED_FUN_MODE; + } else { + *mode = TCLED_IND_MODE; + } + + return PMIC_SUCCESS; +} + +/*! + * This function sets a tri-color LED channel current level in indicator mode. + * + * @param channel Tri-color LED channel. + * @param level Current level. + * @param bank Selected tri-color bank + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_ind_set_current(t_ind_channel channel, + t_tcled_cur_level level, + t_funlight_bank bank) +{ + unsigned int reg_conf = 0; + unsigned int mask; + unsigned int value; + + if (suspend_flag == 1) { + return -EBUSY; + } + + if (level > TCLED_CUR_LEVEL_4) { + return PMIC_PARAMETER_ERROR; + } + + switch (bank) { + case TCLED_FUN_BANK1: + reg_conf = LREG_3; + break; + case TCLED_FUN_BANK2: + reg_conf = LREG_4; + break; + case TCLED_FUN_BANK3: + reg_conf = LREG_5; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + switch (channel) { + case TCLED_IND_RED: + value = BITFVAL(BITS_CL_RED, level); + mask = BITFMASK(BITS_CL_RED); + break; + case TCLED_IND_GREEN: + value = BITFVAL(BITS_CL_GREEN, level); + mask = BITFMASK(BITS_CL_GREEN); + break; + case TCLED_IND_BLUE: + value = BITFVAL(BITS_CL_BLUE, level); + mask = BITFMASK(BITS_CL_BLUE); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(reg_conf, value, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function retrives a tri-color LED channel current level + * in indicator mode. + * + * @param channel Tri-color LED channel. + * @param level Pointer to current level. + * @param bank Selected tri-color bank + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_ind_get_current(t_ind_channel channel, + t_tcled_cur_level *level, + t_funlight_bank bank) +{ + unsigned int reg_conf = 0; + unsigned int mask = 0; + unsigned int value = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + switch (bank) { + case TCLED_FUN_BANK1: + reg_conf = LREG_3; + break; + case TCLED_FUN_BANK2: + reg_conf = LREG_4; + break; + case TCLED_FUN_BANK3: + reg_conf = LREG_5; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + switch (channel) { + case TCLED_IND_RED: + mask = BITFMASK(BITS_CL_RED); + break; + case TCLED_IND_GREEN: + mask = BITFMASK(BITS_CL_GREEN); + break; + case TCLED_IND_BLUE: + mask = BITFMASK(BITS_CL_BLUE); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_read_reg(reg_conf, &value, mask)); + + switch (channel) { + case TCLED_IND_RED: + *level = BITFEXT(value, BITS_CL_RED); + break; + case TCLED_IND_GREEN: + *level = BITFEXT(value, BITS_CL_GREEN); + break; + case TCLED_IND_BLUE: + *level = BITFEXT(value, BITS_CL_BLUE); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + return PMIC_SUCCESS; +} + +/*! + * This function sets a tri-color LED channel blinking pattern in indication + * mode. + * + * @param channel Tri-color LED channel. + * @param pattern Blinking pattern. + * @param skip If true, skip a cycle after each cycle. + * @param bank Selected tri-color bank + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_ind_set_blink_pattern(t_ind_channel channel, + t_tcled_ind_blink_pattern pattern, + bool skip, t_funlight_bank bank) +{ + unsigned int reg_conf = 0; + unsigned int mask = 0; + unsigned int value = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + if (skip == true) { + return PMIC_NOT_SUPPORTED; + } + + switch (bank) { + case TCLED_FUN_BANK1: + reg_conf = LREG_3; + break; + case TCLED_FUN_BANK2: + reg_conf = LREG_4; + break; + case TCLED_FUN_BANK3: + reg_conf = LREG_5; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + switch (channel) { + case TCLED_IND_RED: + value = BITFVAL(BITS_DC_RED, pattern); + mask = BITFMASK(BITS_DC_RED); + break; + case TCLED_IND_GREEN: + value = BITFVAL(BITS_DC_GREEN, pattern); + mask = BITFMASK(BITS_DC_GREEN); + break; + case TCLED_IND_BLUE: + value = BITFVAL(BITS_DC_BLUE, pattern); + mask = BITFMASK(BITS_DC_BLUE); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(reg_conf, value, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function retrives a tri-color LED channel blinking pattern in + * indication mode. + * + * @param channel Tri-color LED channel. + * @param pattern Pointer to Blinking pattern. + * @param skip Pointer to a boolean varible indicating if skip + * @param bank Selected tri-color bank + * a cycle after each cycle. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_ind_get_blink_pattern(t_ind_channel channel, + t_tcled_ind_blink_pattern * + pattern, bool *skip, + t_funlight_bank bank) +{ + unsigned int reg_conf = 0; + unsigned int mask = 0; + unsigned int value = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + switch (bank) { + case TCLED_FUN_BANK1: + reg_conf = LREG_3; + break; + case TCLED_FUN_BANK2: + reg_conf = LREG_4; + break; + case TCLED_FUN_BANK3: + reg_conf = LREG_5; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + switch (channel) { + case TCLED_IND_RED: + mask = BITFMASK(BITS_DC_RED); + break; + case TCLED_IND_GREEN: + mask = BITFMASK(BITS_DC_GREEN); + break; + case TCLED_IND_BLUE: + mask = BITFMASK(BITS_DC_BLUE); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_read_reg(reg_conf, &value, mask)); + + switch (channel) { + case TCLED_IND_RED: + *pattern = BITFEXT(value, BITS_DC_RED); + break; + case TCLED_IND_GREEN: + *pattern = BITFEXT(value, BITS_DC_GREEN); + break; + case TCLED_IND_BLUE: + *pattern = BITFEXT(value, BITS_DC_BLUE); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + return PMIC_SUCCESS; +} + +/*! + * This function sets a tri-color LED channel current level in Fun Light mode. + * + * @param bank Tri-color LED bank + * @param channel Tri-color LED channel. + * @param level Current level. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_fun_set_current(t_funlight_bank bank, + t_funlight_channel channel, + t_tcled_cur_level level) +{ + unsigned int reg_conf = 0; + unsigned int mask; + unsigned int value; + + if (suspend_flag == 1) { + return -EBUSY; + } + + if (level > TCLED_CUR_LEVEL_4) { + return PMIC_PARAMETER_ERROR; + } + + switch (bank) { + case TCLED_FUN_BANK1: + reg_conf = LREG_3; + break; + case TCLED_FUN_BANK2: + reg_conf = LREG_4; + break; + case TCLED_FUN_BANK3: + reg_conf = LREG_5; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + switch (channel) { + case TCLED_FUN_CHANNEL1: + value = BITFVAL(BITS_CL_RED, level); + mask = BITFMASK(BITS_CL_RED); + break; + case TCLED_FUN_CHANNEL2: + value = BITFVAL(BITS_CL_GREEN, level); + mask = BITFMASK(BITS_CL_GREEN); + break; + case TCLED_FUN_CHANNEL3: + value = BITFVAL(BITS_CL_BLUE, level); + mask = BITFMASK(BITS_CL_BLUE); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(reg_conf, value, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function retrives a tri-color LED channel current level + * in Fun Light mode. + * + * @param bank Tri-color LED bank + * @param channel Tri-color LED channel. + * @param level Pointer to current level. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_fun_get_current(t_funlight_bank bank, + t_funlight_channel channel, + t_tcled_cur_level *level) +{ + unsigned int reg_conf = 0; + unsigned int mask = 0; + unsigned int value = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + switch (bank) { + case TCLED_FUN_BANK1: + reg_conf = LREG_3; + break; + case TCLED_FUN_BANK2: + reg_conf = LREG_4; + break; + case TCLED_FUN_BANK3: + reg_conf = LREG_5; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + switch (channel) { + case TCLED_FUN_CHANNEL1: + mask = BITFMASK(BITS_CL_RED); + break; + case TCLED_FUN_CHANNEL2: + mask = BITFMASK(BITS_CL_GREEN); + break; + case TCLED_FUN_CHANNEL3: + mask = BITFMASK(BITS_CL_BLUE); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_read_reg(reg_conf, &value, mask)); + + switch (channel) { + case TCLED_FUN_CHANNEL1: + *level = BITFEXT(value, BITS_CL_RED); + break; + case TCLED_FUN_CHANNEL2: + *level = BITFEXT(value, BITS_CL_GREEN); + break; + case TCLED_FUN_CHANNEL3: + *level = BITFEXT(value, BITS_CL_BLUE); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + return PMIC_SUCCESS; +} + +/*! + * This function sets tri-color LED cycle time. + * + * @param bank Tri-color LED bank + * @param ct Cycle time. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_fun_set_cycletime(t_funlight_bank bank, + t_tcled_fun_cycle_time ct) +{ + unsigned int reg_conf = 0; + unsigned int mask; + unsigned int value; + + if (suspend_flag == 1) { + return -EBUSY; + } + + if (ct > TC_CYCLE_TIME_4) { + return PMIC_PARAMETER_ERROR; + } + + switch (bank) { + case TCLED_FUN_BANK1: + reg_conf = LREG_3; + break; + case TCLED_FUN_BANK2: + reg_conf = LREG_4; + break; + case TCLED_FUN_BANK3: + reg_conf = LREG_5; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + value = BITFVAL(BIT_PERIOD, ct); + mask = BITFMASK(BIT_PERIOD); + + CHECK_ERROR(pmic_write_reg(reg_conf, value, mask)); + return PMIC_SUCCESS; +} + +/*! + * This function retrives tri-color LED cycle time in Fun Light mode. + * + * @param bank Tri-color LED bank + * @param ct Pointer to cycle time. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_fun_get_cycletime(t_funlight_bank bank, + t_tcled_fun_cycle_time *ct) +{ + unsigned int reg_conf = 0; + unsigned int mask; + unsigned int value; + + if (suspend_flag == 1) { + return -EBUSY; + } + + if (*ct > TC_CYCLE_TIME_4) { + return PMIC_PARAMETER_ERROR; + } + + switch (bank) { + case TCLED_FUN_BANK1: + reg_conf = LREG_3; + break; + case TCLED_FUN_BANK2: + reg_conf = LREG_4; + break; + case TCLED_FUN_BANK3: + reg_conf = LREG_5; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + mask = BITFMASK(BIT_PERIOD); + CHECK_ERROR(pmic_read_reg(reg_conf, &value, mask)); + + *ct = BITFVAL(BIT_PERIOD, value); + + return PMIC_SUCCESS; +} + +/*! + * This function sets a tri-color LED channel duty cycle in Fun Light mode. + * + * @param bank Tri-color LED bank + * @param channel Tri-color LED channel. + * @param dc Duty cycle. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_fun_set_dutycycle(t_funlight_bank bank, + t_funlight_channel channel, + unsigned char dc) +{ + unsigned int reg_conf = 0; + unsigned int mask = 0; + unsigned int value = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + switch (bank) { + case TCLED_FUN_BANK1: + reg_conf = LREG_3; + break; + case TCLED_FUN_BANK2: + reg_conf = LREG_4; + break; + case TCLED_FUN_BANK3: + reg_conf = LREG_5; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + switch (channel) { + case TCLED_FUN_CHANNEL1: + value = BITFVAL(BITS_DC_RED, dc); + mask = BITFMASK(BITS_DC_RED); + break; + case TCLED_FUN_CHANNEL2: + value = BITFVAL(BITS_DC_GREEN, dc); + mask = BITFMASK(BITS_DC_GREEN); + break; + case TCLED_FUN_CHANNEL3: + value = BITFVAL(BITS_DC_BLUE, dc); + mask = BITFMASK(BITS_DC_BLUE); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(reg_conf, value, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function retrives a tri-color LED channel duty cycle in Fun Light mode. + * + * @param bank Tri-color LED bank + * @param channel Tri-color LED channel. + * @param dc Pointer to duty cycle. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_fun_get_dutycycle(t_funlight_bank bank, + t_funlight_channel channel, + unsigned char *dc) +{ + unsigned int reg_conf = 0; + unsigned int mask = 0; + unsigned int value = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + switch (bank) { + case TCLED_FUN_BANK1: + reg_conf = LREG_3; + break; + case TCLED_FUN_BANK2: + reg_conf = LREG_4; + break; + case TCLED_FUN_BANK3: + reg_conf = LREG_5; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + switch (channel) { + case TCLED_FUN_CHANNEL1: + mask = BITFMASK(BITS_DC_RED); + break; + case TCLED_FUN_CHANNEL2: + mask = BITFMASK(BITS_DC_GREEN); + break; + case TCLED_FUN_CHANNEL3: + mask = BITFMASK(BITS_DC_BLUE); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_read_reg(reg_conf, &value, mask)); + + switch (channel) { + case TCLED_FUN_CHANNEL1: + *dc = BITFEXT(value, BITS_DC_RED); + break; + case TCLED_FUN_CHANNEL2: + *dc = BITFEXT(value, BITS_DC_GREEN); + break; + case TCLED_FUN_CHANNEL3: + *dc = BITFEXT(value, BITS_DC_BLUE); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + return PMIC_SUCCESS; +} + +/*! + * This function initiates Blended Ramp fun light pattern. + * + * @param bank Tri-color LED bank + * @param speed Speed of pattern. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_fun_blendedramps(t_funlight_bank bank, + t_tcled_fun_speed speed) +{ + unsigned int mask = 0; + unsigned int value = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + switch (speed) { + case TC_OFF: + value = BITFVAL(BITS_FUN_LIGHT, FUN_LIGHTS_OFF); + break; + case TC_SLOW: + value = BITFVAL(BITS_FUN_LIGHT, BLENDED_RAMPS_SLOW); + break; + case TC_FAST: + value = BITFVAL(BITS_FUN_LIGHT, BLENDED_RAMPS_FAST); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + mask = BITFMASK(BITS_FUN_LIGHT); + CHECK_ERROR(pmic_write_reg(LREG_0, value, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function initiates Saw Ramp fun light pattern. + * + * @param bank Tri-color LED bank + * @param speed Speed of pattern. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_fun_sawramps(t_funlight_bank bank, + t_tcled_fun_speed speed) +{ + unsigned int mask = 0; + unsigned int value = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + switch (speed) { + case TC_OFF: + value = BITFVAL(BITS_FUN_LIGHT, FUN_LIGHTS_OFF); + break; + case TC_SLOW: + value = BITFVAL(BITS_FUN_LIGHT, SAW_RAMPS_SLOW); + break; + case TC_FAST: + value = BITFVAL(BITS_FUN_LIGHT, SAW_RAMPS_FAST); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + mask = BITFMASK(BITS_FUN_LIGHT); + CHECK_ERROR(pmic_write_reg(LREG_0, value, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function initiates Blended Bowtie fun light pattern. + * + * @param bank Tri-color LED bank + * @param speed Speed of pattern. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_fun_blendedbowtie(t_funlight_bank bank, + t_tcled_fun_speed speed) +{ + unsigned int mask = 0; + unsigned int value = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + switch (speed) { + case TC_OFF: + value = BITFVAL(BITS_FUN_LIGHT, FUN_LIGHTS_OFF); + break; + case TC_SLOW: + value = BITFVAL(BITS_FUN_LIGHT, BLENDED_INVERSE_RAMPS_SLOW); + break; + case TC_FAST: + value = BITFVAL(BITS_FUN_LIGHT, BLENDED_INVERSE_RAMPS_FAST); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + mask = BITFMASK(BITS_FUN_LIGHT); + CHECK_ERROR(pmic_write_reg(LREG_0, value, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function initiates Chasing Lights fun light pattern. + * + * @param bank Tri-color LED bank + * @param pattern Chasing light pattern mode. + * @param speed Speed of pattern. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_fun_chasinglightspattern(t_funlight_bank bank, + t_chaselight_pattern pattern, + t_tcled_fun_speed speed) +{ + unsigned int mask = 0; + unsigned int value = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + if (pattern > BGR) { + return PMIC_PARAMETER_ERROR; + } + + switch (speed) { + case TC_OFF: + value = BITFVAL(BITS_FUN_LIGHT, FUN_LIGHTS_OFF); + break; + case TC_SLOW: + if (pattern == PMIC_RGB) { + value = + BITFVAL(BITS_FUN_LIGHT, CHASING_LIGHTS_RGB_SLOW); + } else { + value = + BITFVAL(BITS_FUN_LIGHT, CHASING_LIGHTS_BGR_SLOW); + } + break; + case TC_FAST: + if (pattern == PMIC_RGB) { + value = + BITFVAL(BITS_FUN_LIGHT, CHASING_LIGHTS_RGB_FAST); + } else { + value = + BITFVAL(BITS_FUN_LIGHT, CHASING_LIGHTS_BGR_FAST); + } + break; + default: + return PMIC_PARAMETER_ERROR; + } + + mask = BITFMASK(BITS_FUN_LIGHT); + CHECK_ERROR(pmic_write_reg(LREG_0, value, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function initiates Strobe Mode fun light pattern. + * + * @param bank Tri-color LED bank + * @param channel Tri-color LED channel. + * @param speed Speed of pattern. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_fun_strobe(t_funlight_bank bank, + t_funlight_channel channel, + t_tcled_fun_strobe_speed speed) +{ + /* not supported on mc13783 */ + + return PMIC_NOT_SUPPORTED; +} + +/*! + * This function initiates Tri-color LED brightness Ramp Up function; Ramp time + * is fixed at 1 second. + * + * @param bank Tri-color LED bank + * @param channel Tri-color LED channel. + * @param rampup Ramp-up configuration. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_fun_rampup(t_funlight_bank bank, + t_funlight_channel channel, bool rampup) +{ + unsigned int mask = 0; + unsigned int value = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + switch (bank) { + case TCLED_FUN_BANK1: + mask = LEDR1RAMPUP; + value = LEDR1RAMPUP; + break; + case TCLED_FUN_BANK2: + mask = LEDR2RAMPUP; + value = LEDR2RAMPUP; + break; + case TCLED_FUN_BANK3: + mask = LEDR3RAMPUP; + value = LEDR3RAMPUP; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + switch (channel) { + case TCLED_FUN_CHANNEL1: + mask = mask; + value = value; + break; + case TCLED_FUN_CHANNEL2: + mask = mask * 2; + value = value * 2; + break; + case TCLED_FUN_CHANNEL3: + mask = mask * 4; + value = value * 4; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + if (!rampup) { + value = 0; + } + + CHECK_ERROR(pmic_write_reg(LREG_1, value, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function gets Tri-color LED brightness Ramp Up function; Ramp time + * is fixed at 1 second. + * + * @param bank Tri-color LED bank + * @param channel Tri-color LED channel. + * @param rampup Ramp-up configuration. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_get_fun_rampup(t_funlight_bank bank, + t_funlight_channel channel, bool *rampup) +{ + unsigned int mask = 0; + unsigned int value = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + switch (bank) { + case TCLED_FUN_BANK1: + mask = LEDR1RAMPUP; + break; + case TCLED_FUN_BANK2: + mask = LEDR2RAMPUP; + break; + case TCLED_FUN_BANK3: + mask = LEDR3RAMPUP; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + switch (channel) { + case TCLED_FUN_CHANNEL1: + mask = mask; + break; + case TCLED_FUN_CHANNEL2: + mask = mask * 2; + break; + case TCLED_FUN_CHANNEL3: + mask = mask * 4; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_read_reg(LREG_1, &value, mask)); + if (value) { + *rampup = true; + } else { + *rampup = false; + } + + return PMIC_SUCCESS; +} + +/*! + * This function initiates Tri-color LED brightness Ramp Down function; Ramp + * time is fixed at 1 second. + * + * @param bank Tri-color LED bank + * @param channel Tri-color LED channel. + * @param rampdown Ramp-down configuration. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_fun_rampdown(t_funlight_bank bank, + t_funlight_channel channel, bool rampdown) +{ + unsigned int mask = 0; + unsigned int value = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + switch (bank) { + case TCLED_FUN_BANK1: + mask = LEDR1RAMPDOWN; + value = LEDR1RAMPDOWN; + break; + case TCLED_FUN_BANK2: + mask = LEDR2RAMPDOWN; + value = LEDR2RAMPDOWN; + break; + case TCLED_FUN_BANK3: + mask = LEDR3RAMPDOWN; + value = LEDR3RAMPDOWN; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + switch (channel) { + case TCLED_FUN_CHANNEL1: + mask = mask; + value = value; + break; + case TCLED_FUN_CHANNEL2: + mask = mask * 2; + value = value * 2; + break; + case TCLED_FUN_CHANNEL3: + mask = mask * 4; + value = value * 4; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + if (!rampdown) { + value = 0; + } + + CHECK_ERROR(pmic_write_reg(LREG_1, value, mask)); + return PMIC_SUCCESS; +} + +/*! + * This function initiates Tri-color LED brightness Ramp Down function; Ramp + * time is fixed at 1 second. + * + * @param bank Tri-color LED bank + * @param channel Tri-color LED channel. + * @param rampdown Ramp-down configuration. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_get_fun_rampdown(t_funlight_bank bank, + t_funlight_channel channel, + bool *rampdown) +{ + unsigned int mask = 0; + unsigned int value = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + switch (bank) { + case TCLED_FUN_BANK1: + mask = LEDR1RAMPDOWN; + break; + case TCLED_FUN_BANK2: + mask = LEDR2RAMPDOWN; + break; + case TCLED_FUN_BANK3: + mask = LEDR3RAMPDOWN; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + switch (channel) { + case TCLED_FUN_CHANNEL1: + mask = mask; + break; + case TCLED_FUN_CHANNEL2: + mask = mask * 2; + break; + case TCLED_FUN_CHANNEL3: + mask = mask * 4; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_read_reg(LREG_1, &value, mask)); + if (value) { + *rampdown = true; + } else { + *rampdown = false; + } + return PMIC_SUCCESS; +} + +/*! + * This function enables a Tri-color channel triode mode. + * + * @param bank Tri-color LED bank + * @param channel Tri-color LED channel. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_fun_triode_on(t_funlight_bank bank, + t_funlight_channel channel) +{ + unsigned int mask = 0; + unsigned int value = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + switch (bank) { + case TCLED_FUN_BANK1: + mask = MASK_BK1_FL; + value = ENABLE_BK1_FL; + break; + case TCLED_FUN_BANK2: + mask = MASK_BK2_FL; + value = ENABLE_BK2_FL; + break; + case TCLED_FUN_BANK3: + mask = MASK_BK3_FL; + value = ENABLE_BK2_FL; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(LREG_0, value, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function disables a Tri-color LED channel triode mode. + * + * @param bank Tri-color LED bank + * @param channel Tri-color LED channel. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_fun_triode_off(t_funlight_bank bank, + t_funlight_channel channel) +{ + unsigned int mask = 0; + unsigned int value = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + switch (bank) { + case TCLED_FUN_BANK1: + mask = MASK_BK1_FL; + break; + case TCLED_FUN_BANK2: + mask = MASK_BK2_FL; + break; + case TCLED_FUN_BANK3: + mask = MASK_BK3_FL; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(LREG_0, value, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function enables Tri-color LED edge slowing. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_enable_edge_slow(void) +{ + unsigned int mask = 0; + unsigned int value = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + value = BITFVAL(BIT_SLEWLIMTC, 1); + mask = BITFMASK(BIT_SLEWLIMTC); + + CHECK_ERROR(pmic_write_reg(LREG_1, value, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function disables Tri-color LED edge slowing. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_disable_edge_slow(void) +{ + unsigned int mask = 0; + unsigned int value = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + value = BITFVAL(BIT_SLEWLIMTC, 0); + mask = BITFMASK(BIT_SLEWLIMTC); + + CHECK_ERROR(pmic_write_reg(LREG_1, value, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function enables Tri-color LED half current mode. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_enable_half_current(void) +{ + unsigned int mask = 0; + unsigned int value = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + value = BITFVAL(BIT_TC1HALF, 1); + mask = BITFMASK(BIT_TC1HALF); + + CHECK_ERROR(pmic_write_reg(LREG_1, value, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function disables Tri-color LED half current mode. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_tcled_disable_half_current(void) +{ + unsigned int mask = 0; + unsigned int value = 0; + + if (suspend_flag == 1) { + return -EBUSY; + } + + value = BITFVAL(BIT_TC1HALF, 0); + mask = BITFMASK(BIT_TC1HALF); + + CHECK_ERROR(pmic_write_reg(LREG_1, value, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function enables backlight or Tri-color LED audio modulation. + * + * @return This function returns PMIC_NOT_SUPPORTED. + */ +PMIC_STATUS pmic_tcled_enable_audio_modulation(t_led_channel channel, + t_aud_path path, + t_aud_gain gain, bool lpf_bypass) +{ + return PMIC_NOT_SUPPORTED; +} + +/*! + * This function disables backlight or Tri-color LED audio modulation. + * + * @return This function returns PMIC_NOT_SUPPORTED. + */ +PMIC_STATUS pmic_tcled_disable_audio_modulation(void) +{ + return PMIC_NOT_SUPPORTED; +} + +/*! + * This function enables the boost mode. + * Only on mc13783 2.0 or higher + * + * @param en_dis Enable or disable the boost mode + * + * @return This function returns 0 if successful. + */ +PMIC_STATUS pmic_bklit_set_boost_mode(bool en_dis) +{ + + pmic_version_t mc13783_ver; + unsigned int mask; + unsigned int value; + mc13783_ver = pmic_get_version(); + if (mc13783_ver.revision >= 20) { + + if (suspend_flag == 1) { + return -EBUSY; + } + + value = BITFVAL(BIT_BOOSTEN, en_dis); + mask = BITFMASK(BIT_BOOSTEN); + CHECK_ERROR(pmic_write_reg(LREG_0, value, mask)); + return PMIC_SUCCESS; + } else { + return PMIC_NOT_SUPPORTED; + } +} + +/*! + * This function gets the boost mode. + * Only on mc13783 2.0 or higher + * + * @param en_dis Enable or disable the boost mode + * + * @return This function returns 0 if successful. + */ +PMIC_STATUS pmic_bklit_get_boost_mode(bool *en_dis) +{ + pmic_version_t mc13783_ver; + unsigned int mask; + unsigned int value; + mc13783_ver = pmic_get_version(); + if (mc13783_ver.revision >= 20) { + + if (suspend_flag == 1) { + return -EBUSY; + } + mask = BITFMASK(BIT_BOOSTEN); + CHECK_ERROR(pmic_read_reg(LREG_0, &value, mask)); + *en_dis = BITFEXT(value, BIT_BOOSTEN); + return PMIC_SUCCESS; + } else { + return PMIC_NOT_SUPPORTED; + } +} + +/*! + * This function sets boost mode configuration + * Only on mc13783 2.0 or higher + * + * @param abms Define adaptive boost mode selection + * @param abr Define adaptive boost reference + * + * @return This function returns 0 if successful. + */ +PMIC_STATUS pmic_bklit_config_boost_mode(unsigned int abms, unsigned int abr) +{ + unsigned int conf_boost = 0; + unsigned int mask; + unsigned int value; + pmic_version_t mc13783_ver; + + mc13783_ver = pmic_get_version(); + if (mc13783_ver.revision >= 20) { + if (suspend_flag == 1) { + return -EBUSY; + } + + if (abms > MAX_BOOST_ABMS) { + return PMIC_PARAMETER_ERROR; + } + + if (abr > MAX_BOOST_ABR) { + return PMIC_PARAMETER_ERROR; + } + + conf_boost = abms | (abr << 3); + + value = BITFVAL(BITS_BOOST, conf_boost); + mask = BITFMASK(BITS_BOOST); + CHECK_ERROR(pmic_write_reg(LREG_0, value, mask)); + + return PMIC_SUCCESS; + } else { + return PMIC_NOT_SUPPORTED; + } +} + +/*! + * This function gets boost mode configuration + * Only on mc13783 2.0 or higher + * + * @param abms Define adaptive boost mode selection + * @param abr Define adaptive boost reference + * + * @return This function returns 0 if successful. + */ +PMIC_STATUS pmic_bklit_gets_boost_mode(unsigned int *abms, unsigned int *abr) +{ + unsigned int mask; + unsigned int value; + pmic_version_t mc13783_ver; + mc13783_ver = pmic_get_version(); + if (mc13783_ver.revision >= 20) { + if (suspend_flag == 1) { + return -EBUSY; + } + + mask = BITFMASK(BITS_BOOST_ABMS); + CHECK_ERROR(pmic_read_reg(LREG_0, &value, mask)); + *abms = BITFEXT(value, BITS_BOOST_ABMS); + + mask = BITFMASK(BITS_BOOST_ABR); + CHECK_ERROR(pmic_read_reg(LREG_0, &value, mask)); + *abr = BITFEXT(value, BITS_BOOST_ABR); + return PMIC_SUCCESS; + } else { + return PMIC_NOT_SUPPORTED; + } +} + +/*! + * This function implements IOCTL controls on a PMIC Light device. + * + + * @param inode pointer on the node + * @param file pointer on the file + * @param cmd the command + * @param arg the parameter + * @return This function returns 0 if successful. + */ +static int pmic_light_ioctl(struct inode *inode, struct file *file, + unsigned int cmd, unsigned long arg) +{ + t_bklit_setting_param *bklit_setting = NULL; + t_tcled_enable_param *tcled_setting; + t_fun_param *fun_param; + t_tcled_ind_param *tcled_ind; + + if (_IOC_TYPE(cmd) != 'p') + return -ENOTTY; + + bklit_setting = kmalloc(sizeof(t_bklit_setting_param), GFP_KERNEL); + tcled_setting = kmalloc(sizeof(t_tcled_enable_param), GFP_KERNEL); + fun_param = kmalloc(sizeof(t_fun_param), GFP_KERNEL); + tcled_ind = kmalloc(sizeof(t_tcled_ind_param), GFP_KERNEL); + switch (cmd) { + case PMIC_BKLIT_TCLED_ENABLE: + pmic_bklit_tcled_master_enable(); + break; + + case PMIC_BKLIT_TCLED_DISABLE: + pmic_bklit_tcled_master_disable(); + break; + + case PMIC_BKLIT_ENABLE: + pmic_bklit_master_enable(); + break; + + case PMIC_BKLIT_DISABLE: + pmic_bklit_master_disable(); + break; + + case PMIC_SET_BKLIT: + if (bklit_setting == NULL) + return -ENOMEM; + + if (copy_from_user(bklit_setting, (t_bklit_setting_param *) arg, + sizeof(t_bklit_setting_param))) { + kfree(bklit_setting); + return -EFAULT; + } + + CHECK_ERROR_KFREE(pmic_bklit_set_mode(bklit_setting->channel, + bklit_setting->mode), + (kfree(bklit_setting))); + + CHECK_ERROR_KFREE(pmic_bklit_set_current(bklit_setting->channel, + bklit_setting-> + current_level), + (kfree(bklit_setting))); + CHECK_ERROR_KFREE(pmic_bklit_set_dutycycle + (bklit_setting->channel, + bklit_setting->duty_cycle), + (kfree(bklit_setting))); + CHECK_ERROR_KFREE(pmic_bklit_set_cycle_time + (bklit_setting->cycle_time), + (kfree(bklit_setting))); + CHECK_ERROR_KFREE(pmic_bklit_set_boost_mode + (bklit_setting->en_dis), + (kfree(bklit_setting))); + CHECK_ERROR_KFREE(pmic_bklit_config_boost_mode + (bklit_setting->abms, bklit_setting->abr), + (kfree(bklit_setting))); + if (bklit_setting->edge_slow != false) { + CHECK_ERROR_KFREE(pmic_bklit_enable_edge_slow(), + (kfree(bklit_setting))); + } else { + CHECK_ERROR_KFREE(pmic_bklit_disable_edge_slow(), + (kfree(bklit_setting))); + } + + kfree(bklit_setting); + break; + + case PMIC_GET_BKLIT: + if (bklit_setting == NULL) + return -ENOMEM; + + if (copy_from_user(bklit_setting, (t_bklit_setting_param *) arg, + sizeof(t_bklit_setting_param))) { + kfree(bklit_setting); + return -EFAULT; + } + + CHECK_ERROR_KFREE(pmic_bklit_get_current(bklit_setting->channel, + &bklit_setting-> + current_level), + (kfree(bklit_setting))); + CHECK_ERROR_KFREE(pmic_bklit_get_cycle_time + (&bklit_setting->cycle_time), + (kfree(bklit_setting))); + CHECK_ERROR_KFREE(pmic_bklit_get_dutycycle + (bklit_setting->channel, + &bklit_setting->duty_cycle), + (kfree(bklit_setting))); + bklit_setting->strobe = BACKLIGHT_STROBE_NONE; + CHECK_ERROR_KFREE(pmic_bklit_get_mode(bklit_setting->channel, + &bklit_setting->mode), + (kfree(bklit_setting))); + CHECK_ERROR_KFREE(pmic_bklit_get_edge_slow + (&bklit_setting->edge_slow), + (kfree(bklit_setting))); + CHECK_ERROR_KFREE(pmic_bklit_get_boost_mode + (&bklit_setting->en_dis), + (kfree(bklit_setting))); + CHECK_ERROR_KFREE(pmic_bklit_gets_boost_mode + (&bklit_setting->abms, &bklit_setting->abr), + (kfree(bklit_setting))); + + if (copy_to_user((t_bklit_setting_param *) arg, bklit_setting, + sizeof(t_bklit_setting_param))) { + kfree(bklit_setting); + return -EFAULT; + } + kfree(bklit_setting); + break; + + case PMIC_RAMPUP_BKLIT: + CHECK_ERROR(pmic_bklit_rampup((t_bklit_channel) arg)); + break; + + case PMIC_RAMPDOWN_BKLIT: + CHECK_ERROR(pmic_bklit_rampdown((t_bklit_channel) arg)); + break; + + case PMIC_OFF_RAMPUP_BKLIT: + CHECK_ERROR(pmic_bklit_off_rampup((t_bklit_channel) arg)); + break; + + case PMIC_OFF_RAMPDOWN_BKLIT: + CHECK_ERROR(pmic_bklit_off_rampdown((t_bklit_channel) arg)); + break; + + case PMIC_TCLED_ENABLE: + if (tcled_setting == NULL) + return -ENOMEM; + + if (copy_from_user(tcled_setting, (t_tcled_enable_param *) arg, + sizeof(t_tcled_enable_param))) { + kfree(tcled_setting); + return -EFAULT; + } + CHECK_ERROR_KFREE(pmic_tcled_enable(tcled_setting->mode, + tcled_setting->bank), + (kfree(bklit_setting))); + break; + + case PMIC_TCLED_DISABLE: + CHECK_ERROR(pmic_tcled_disable((t_funlight_bank) arg)); + break; + + case PMIC_TCLED_PATTERN: + if (fun_param == NULL) + return -ENOMEM; + + if (copy_from_user(fun_param, + (t_fun_param *) arg, sizeof(t_fun_param))) { + kfree(fun_param); + return -EFAULT; + } + + switch (fun_param->pattern) { + case BLENDED_RAMPS_SLOW: + CHECK_ERROR_KFREE(pmic_tcled_fun_blendedramps + (fun_param->bank, TC_SLOW), + (kfree(fun_param))); + break; + + case BLENDED_RAMPS_FAST: + CHECK_ERROR_KFREE(pmic_tcled_fun_blendedramps + (fun_param->bank, TC_FAST), + (kfree(fun_param))); + break; + + case SAW_RAMPS_SLOW: + CHECK_ERROR_KFREE(pmic_tcled_fun_sawramps + (fun_param->bank, TC_SLOW), + (kfree(fun_param))); + break; + + case SAW_RAMPS_FAST: + CHECK_ERROR_KFREE(pmic_tcled_fun_sawramps + (fun_param->bank, TC_FAST), + (kfree(fun_param))); + break; + + case BLENDED_BOWTIE_SLOW: + CHECK_ERROR_KFREE(pmic_tcled_fun_blendedbowtie + (fun_param->bank, TC_SLOW), + (kfree(fun_param))); + break; + + case BLENDED_BOWTIE_FAST: + CHECK_ERROR_KFREE(pmic_tcled_fun_blendedbowtie + (fun_param->bank, TC_FAST), + (kfree(fun_param))); + break; + + case STROBE_SLOW: + CHECK_ERROR_KFREE(pmic_tcled_fun_strobe + (fun_param->bank, fun_param->channel, + TC_STROBE_SLOW), (kfree(fun_param))); + break; + + case STROBE_FAST: + CHECK_ERROR_KFREE(pmic_tcled_fun_strobe + (fun_param->bank, + fun_param->channel, TC_STROBE_SLOW), + (kfree(fun_param))); + break; + + case CHASING_LIGHT_RGB_SLOW: + CHECK_ERROR_KFREE(pmic_tcled_fun_chasinglightspattern + (fun_param->bank, PMIC_RGB, TC_SLOW), + (kfree(fun_param))); + break; + + case CHASING_LIGHT_RGB_FAST: + CHECK_ERROR_KFREE(pmic_tcled_fun_chasinglightspattern + (fun_param->bank, PMIC_RGB, TC_FAST), + (kfree(fun_param))); + break; + + case CHASING_LIGHT_BGR_SLOW: + CHECK_ERROR_KFREE(pmic_tcled_fun_chasinglightspattern + (fun_param->bank, BGR, TC_SLOW), + (kfree(fun_param))); + break; + + case CHASING_LIGHT_BGR_FAST: + CHECK_ERROR_KFREE(pmic_tcled_fun_chasinglightspattern + (fun_param->bank, BGR, TC_FAST), + (kfree(fun_param))); + break; + } + + kfree(fun_param); + break; + + case PMIC_SET_TCLED: + if (tcled_ind == NULL) + return -ENOMEM; + + if (copy_from_user(tcled_ind, (t_tcled_ind_param *) arg, + sizeof(t_tcled_ind_param))) { + kfree(tcled_ind); + return -EFAULT; + } + CHECK_ERROR_KFREE(pmic_tcled_ind_set_current(tcled_ind->channel, + tcled_ind->level, + tcled_ind->bank), + (kfree(tcled_ind))); + CHECK_ERROR_KFREE(pmic_tcled_ind_set_blink_pattern + (tcled_ind->channel, tcled_ind->pattern, + tcled_ind->skip, tcled_ind->bank), + (kfree(tcled_ind))); + CHECK_ERROR_KFREE(pmic_tcled_fun_rampup + (tcled_ind->bank, tcled_ind->channel, + tcled_ind->rampup), (kfree(tcled_ind))); + CHECK_ERROR_KFREE(pmic_tcled_fun_rampdown + (tcled_ind->bank, tcled_ind->channel, + tcled_ind->rampdown), (kfree(tcled_ind))); + if (tcled_ind->half_current) { + CHECK_ERROR_KFREE(pmic_tcled_enable_half_current(), + (kfree(tcled_ind))); + } else { + CHECK_ERROR_KFREE(pmic_tcled_disable_half_current(), + (kfree(tcled_ind))); + } + + kfree(tcled_ind); + break; + + case PMIC_GET_TCLED: + if (tcled_ind == NULL) + return -ENOMEM; + + if (copy_from_user(tcled_ind, (t_tcled_ind_param *) arg, + sizeof(t_tcled_ind_param))) { + kfree(tcled_ind); + return -EFAULT; + } + CHECK_ERROR_KFREE(pmic_tcled_ind_get_current(tcled_ind->channel, + &tcled_ind->level, + tcled_ind->bank), + (kfree(tcled_ind))); + CHECK_ERROR_KFREE(pmic_tcled_ind_get_blink_pattern + (tcled_ind->channel, &tcled_ind->pattern, + &tcled_ind->skip, tcled_ind->bank), + (kfree(tcled_ind))); + CHECK_ERROR_KFREE(pmic_tcled_get_fun_rampup + (tcled_ind->bank, tcled_ind->channel, + &tcled_ind->rampup), (kfree(tcled_ind))); + CHECK_ERROR_KFREE(pmic_tcled_get_fun_rampdown + (tcled_ind->bank, tcled_ind->channel, + &tcled_ind->rampdown), (kfree(tcled_ind))); + if (copy_to_user + ((t_tcled_ind_param *) arg, tcled_ind, + sizeof(t_tcled_ind_param))) { + return -EFAULT; + } + kfree(tcled_ind); + + break; + + default: + return -EINVAL; + } + return 0; +} + +/*! + * This function initialize Light registers of mc13783 with 0. + * + * @return This function returns 0 if successful. + */ +int pmic_light_init_reg(void) +{ + CHECK_ERROR(pmic_write_reg(LREG_0, 0, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(LREG_1, 0, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(LREG_2, 0, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(LREG_3, 0, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(LREG_4, 0, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(LREG_5, 0, PMIC_ALL_BITS)); + return 0; +} + +/*! + * This function implements the open method on a mc13783 light device. + * + * @param inode pointer on the node + * @param file pointer on the file + * @return This function returns 0. + */ +static int pmic_light_open(struct inode *inode, struct file *file) +{ + while (suspend_flag == 1) { + swait++; + /* Block if the device is suspended */ + if (wait_event_interruptible(suspendq, (suspend_flag == 0))) { + return -ERESTARTSYS; + } + } + return 0; +} + +/*! + * This function implements the release method on a mc13783 light device. + * + * @param inode pointer on the node + * @param file pointer on the file + * @return This function returns 0. + */ +static int pmic_light_release(struct inode *inode, struct file *file) +{ + while (suspend_flag == 1) { + swait++; + /* Block if the device is suspended */ + if (wait_event_interruptible(suspendq, (suspend_flag == 0))) { + return -ERESTARTSYS; + } + } + return 0; +} + +static struct file_operations pmic_light_fops = { + .owner = THIS_MODULE, + .ioctl = pmic_light_ioctl, + .open = pmic_light_open, + .release = pmic_light_release, +}; + +static int pmic_light_remove(struct platform_device *pdev) +{ + device_destroy(pmic_light_class, MKDEV(pmic_light_major, 0)); + class_destroy(pmic_light_class); + unregister_chrdev(pmic_light_major, "pmic_light"); + return 0; +} + +static int pmic_light_probe(struct platform_device *pdev) +{ + int ret = 0; + struct device *temp_class; + + while (suspend_flag == 1) { + swait++; + /* Block if the device is suspended */ + if (wait_event_interruptible(suspendq, (suspend_flag == 0))) { + return -ERESTARTSYS; + } + } + pmic_light_major = register_chrdev(0, "pmic_light", &pmic_light_fops); + + if (pmic_light_major < 0) { + printk(KERN_ERR "Unable to get a major for pmic_light\n"); + return pmic_light_major; + } + init_waitqueue_head(&suspendq); + + pmic_light_class = class_create(THIS_MODULE, "pmic_light"); + if (IS_ERR(pmic_light_class)) { + printk(KERN_ERR "Error creating pmic_light class.\n"); + ret = PTR_ERR(pmic_light_class); + goto err_out1; + } + + temp_class = device_create(pmic_light_class, NULL, + MKDEV(pmic_light_major, 0), NULL, + "pmic_light"); + if (IS_ERR(temp_class)) { + printk(KERN_ERR "Error creating pmic_light class device.\n"); + ret = PTR_ERR(temp_class); + goto err_out2; + } + + ret = pmic_light_init_reg(); + if (ret != PMIC_SUCCESS) { + goto err_out3; + } + + printk(KERN_INFO "PMIC Light successfully loaded\n"); + return ret; + + err_out3: + device_destroy(pmic_light_class, MKDEV(pmic_light_major, 0)); + err_out2: + class_destroy(pmic_light_class); + err_out1: + unregister_chrdev(pmic_light_major, "pmic_light"); + return ret; +} + +static struct platform_driver pmic_light_driver_ldm = { + .driver = { + .name = "pmic_light", + }, + .suspend = pmic_light_suspend, + .resume = pmic_light_resume, + .probe = pmic_light_probe, + .remove = pmic_light_remove, +}; + +/* + * Initialization and Exit + */ + +static int __init pmic_light_init(void) +{ + pr_debug("PMIC Light driver loading...\n"); + return platform_driver_register(&pmic_light_driver_ldm); +} +static void __exit pmic_light_exit(void) +{ + platform_driver_unregister(&pmic_light_driver_ldm); + pr_debug("PMIC Light driver successfully unloaded\n"); +} + +/* + * Module entry points + */ + +subsys_initcall(pmic_light_init); +module_exit(pmic_light_exit); + +MODULE_DESCRIPTION("PMIC_LIGHT"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/pmic/mc13783/pmic_light_defs.h b/drivers/mxc/pmic/mc13783/pmic_light_defs.h new file mode 100644 index 000000000000..34602015a34d --- /dev/null +++ b/drivers/mxc/pmic/mc13783/pmic_light_defs.h @@ -0,0 +1,144 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mc13783/pmic_light_defs.h + * @brief This is the internal header PMIC(mc13783) Light and Backlight driver. + * + * @ingroup PMIC_LIGHT + */ + +#ifndef __MC13783_LIGHT_DEFS_H__ +#define __MC13783_LIGHT_DEFS_H__ + +#define LREG_0 REG_LED_CONTROL_0 +#define LREG_1 REG_LED_CONTROL_1 +#define LREG_2 REG_LED_CONTROL_2 +#define LREG_3 REG_LED_CONTROL_3 +#define LREG_4 REG_LED_CONTROL_4 +#define LREG_5 REG_LED_CONTROL_5 + +/* REG_LED_CONTROL_0 */ + +#define BIT_LEDEN_LSH 0 +#define BIT_LEDEN_WID 1 +#define MASK_TRIODE_MAIN_BL 0x080 +#define INDEX_AUXILIARY 1 +#define INDEX_KEYPAD 2 +#define BITS_FUN_LIGHT_LSH 17 +#define BITS_FUN_LIGHT_WID 4 +#define MASK_FUN_LIGHT 0x1E0000 +#define MASK_BK1_FL 0x200000 +#define ENABLE_BK1_FL 0x200000 +#define MASK_BK2_FL 0x400000 +#define ENABLE_BK2_FL 0x400000 +#define MASK_BK3_FL 0x800000 +#define ENABLE_BK3_FL 0x800000 +#define BIT_UP_MAIN_BL_LSH 1 +#define BIT_UP_MAIN_BL_WID 1 +#define BIT_UP_AUX_BL_LSH 2 +#define BIT_UP_AUX_BL_WID 1 +#define BIT_UP_KEY_BL_LSH 3 +#define BIT_UP_KEY_BL_WID 1 +#define BIT_DOWN_MAIN_BL_LSH 4 +#define BIT_DOWN_MAIN_BL_WID 1 +#define BIT_DOWN_AUX_BL_LSH 5 +#define BIT_DOWN_AUX_BL_WID 1 +#define BIT_DOWN_KEY_BL_LSH 6 +#define BIT_DOWN_KEY_BL_WID 1 +#define BIT_TRIODE_MAIN_BL_LSH 7 +#define BIT_TRIODE_MAIN_BL_WID 1 +#define BIT_TRIODE_AUX_BL_LSH 8 +#define BIT_TRIODE_AUX_BL_WID 1 +#define BIT_TRIODE_KEY_BL_LSH 9 +#define BIT_TRIODE_KEY_BL_WID 1 + +#define BIT_BOOSTEN_LSH 10 +#define BIT_BOOSTEN_WID 1 +#define BITS_BOOST_LSH 11 +#define BITS_BOOST_WID 5 +#define BITS_BOOST_ABMS_LSH 11 +#define BITS_BOOST_ABMS_WID 3 +#define BITS_BOOST_ABR_LSH 14 +#define BITS_BOOST_ABR_WID 2 + +#define MAX_BOOST_ABMS 7 +#define MAX_BOOST_ABR 3 + +/* REG_LED_CONTROL_1 */ + +#define BIT_SLEWLIMTC_LSH 23 +#define BIT_SLEWLIMTC_WID 1 +#define BIT_TC1HALF_LSH 18 +#define BIT_TC1HALF_WID 1 +#define LEDR1RAMPUP 0x000001 +#define LEDR2RAMPUP 0x000040 +#define LEDR3RAMPUP 0x001000 +#define LEDR1RAMPDOWN 0x000008 +#define LEDR2RAMPDOWN 0x000200 +#define LEDR3RAMPDOWN 0x008000 + +/* REG_LED_CONTROL_2 */ + +#define BIT_SLEWLIMBL_LSH 23 +#define BIT_SLEWLIMBL_WID 1 +#define BIT_DUTY_CYCLE 9 +#define MASK_DUTY_CYCLE 0x001E00 +#define INDEX_AUX 4 +#define INDEX_KYD 8 +#define BIT_CL_MAIN_LSH 0 +#define BIT_CL_MAIN_WID 3 +#define BIT_CL_AUX_LSH 3 +#define BIT_CL_AUX_WID 3 +#define BIT_CL_KEY_LSH 6 +#define BIT_CL_KEY_WID 3 + +/* REG_LED_CONTROL_3 4 5 */ +#define BITS_CL_RED_LSH 0 +#define BITS_CL_RED_WID 2 +#define BITS_CL_GREEN_LSH 2 +#define BITS_CL_GREEN_WID 2 +#define BITS_CL_BLUE_LSH 4 +#define BITS_CL_BLUE_WID 2 +#define BITS_DC_RED_LSH 6 +#define BITS_DC_RED_WID 5 +#define BITS_DC_GREEN_LSH 11 +#define BITS_DC_GREEN_WID 5 +#define BITS_DC_BLUE_LSH 16 +#define BITS_DC_BLUE_WID 5 +#define BIT_PERIOD_LSH 21 +#define BIT_PERIOD_WID 2 + +#define DUTY_CYCLE_MAX 31 + +/* Fun light pattern */ +#define BLENDED_RAMPS_SLOW 0 +#define BLENDED_RAMPS_FAST 1 +#define SAW_RAMPS_SLOW 2 +#define SAW_RAMPS_FAST 3 +#define BLENDED_INVERSE_RAMPS_SLOW 4 +#define BLENDED_INVERSE_RAMPS_FAST 5 +#define CHASING_LIGHTS_RGB_SLOW 6 +#define CHASING_LIGHTS_RGB_FAST 7 +#define CHASING_LIGHTS_BGR_SLOW 8 +#define CHASING_LIGHTS_BGR_FAST 9 +#define FUN_LIGHTS_OFF 15 + +/*! + * This function initialize Light registers of mc13783 with 0. + * + * @return This function returns 0 if successful. + */ +int pmic_light_init_reg(void); + +#endif /* __MC13783_LIGHT_DEFS_H__ */ diff --git a/drivers/mxc/pmic/mc13783/pmic_power.c b/drivers/mxc/pmic/mc13783/pmic_power.c new file mode 100644 index 000000000000..c67fe773703d --- /dev/null +++ b/drivers/mxc/pmic/mc13783/pmic_power.c @@ -0,0 +1,3146 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mc13783/pmic_power.c + * @brief This is the main file of PMIC(mc13783) Power driver. + * + * @ingroup PMIC_POWER + */ + +/* + * Includes + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "pmic_power_defs.h" + +#ifdef CONFIG_MXC_HWEVENT +#include +#endif + +#include + +#define MC13783_REGCTRL_GPOx_MASK 0x18000 + +static bool VBKUP1_EN; +static bool VBKUP2_EN; + +/* + * Power Pmic API + */ + +/* EXPORTED FUNCTIONS */ +EXPORT_SYMBOL(pmic_power_off); +EXPORT_SYMBOL(pmic_power_set_pc_config); +EXPORT_SYMBOL(pmic_power_get_pc_config); +EXPORT_SYMBOL(pmic_power_regulator_on); +EXPORT_SYMBOL(pmic_power_regulator_off); +EXPORT_SYMBOL(pmic_power_regulator_set_voltage); +EXPORT_SYMBOL(pmic_power_regulator_get_voltage); +EXPORT_SYMBOL(pmic_power_regulator_set_config); +EXPORT_SYMBOL(pmic_power_regulator_get_config); +EXPORT_SYMBOL(pmic_power_vbkup2_auto_en); +EXPORT_SYMBOL(pmic_power_get_vbkup2_auto_state); +EXPORT_SYMBOL(pmic_power_bat_det_en); +EXPORT_SYMBOL(pmic_power_get_bat_det_state); +EXPORT_SYMBOL(pmic_power_vib_pin_en); +EXPORT_SYMBOL(pmic_power_gets_vib_pin_state); +EXPORT_SYMBOL(pmic_power_get_power_mode_sense); +EXPORT_SYMBOL(pmic_power_set_regen_assig); +EXPORT_SYMBOL(pmic_power_get_regen_assig); +EXPORT_SYMBOL(pmic_power_set_regen_inv); +EXPORT_SYMBOL(pmic_power_get_regen_inv); +EXPORT_SYMBOL(pmic_power_esim_v_en); +EXPORT_SYMBOL(pmic_power_gets_esim_v_state); +EXPORT_SYMBOL(pmic_power_set_auto_reset_en); +EXPORT_SYMBOL(pmic_power_get_auto_reset_en); +EXPORT_SYMBOL(pmic_power_set_conf_button); +EXPORT_SYMBOL(pmic_power_get_conf_button); +EXPORT_SYMBOL(pmic_power_event_sub); +EXPORT_SYMBOL(pmic_power_event_unsub); + +/*! + * This function is called to put the power in a low power state. + * Switching off the platform cannot be decided by + * the power module. It has to be handled by the + * client application. + * + * @param pdev the device structure used to give information on which power + * device (0 through 3 channels) to suspend + * @param state the power state the device is entering + * + * @return The function always returns 0. + */ +static int pmic_power_suspend(struct platform_device *pdev, pm_message_t state) +{ + return 0; +}; + +/*! + * This function is called to resume the power from a low power state. + * + * @param pdev the device structure used to give information on which power + * device (0 through 3 channels) to suspend + * + * @return The function always returns 0. + */ +static int pmic_power_resume(struct platform_device *pdev) +{ + return 0; +}; + +/*! + * This function sets user power off in power control register and thus powers + * off the phone. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +void pmic_power_off(void) +{ + unsigned int mask, value; + + mask = BITFMASK(MC13783_PWRCTRL_USER_OFF_SPI); + value = BITFVAL(MC13783_PWRCTRL_USER_OFF_SPI, + MC13783_PWRCTRL_USER_OFF_SPI_ENABLE); + + pmic_write_reg(REG_POWER_CONTROL_0, value, mask); +} + +/*! + * This function sets the power control configuration. + * + * @param pc_config power control configuration. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_set_pc_config(t_pc_config *pc_config) +{ + unsigned int pwrctrl_val_reg0 = 0; + unsigned int pwrctrl_val_reg1 = 0; + unsigned int pwrctrl_mask_reg0 = 0; + unsigned int pwrctrl_mask_reg1 = 0; + + if (pc_config == NULL) { + return PMIC_PARAMETER_ERROR; + } + + if (pc_config->pc_enable != false) { + pwrctrl_val_reg0 |= BITFVAL(MC13783_PWRCTRL_PCEN, + MC13783_PWRCTRL_PCEN_ENABLE); + pwrctrl_val_reg1 |= BITFVAL(MC13783_PWRCTRL_PCT, + pc_config->pc_timer); + } else { + pwrctrl_val_reg0 |= BITFVAL(MC13783_PWRCTRL_PCEN, + MC13783_PWRCTRL_PCEN_DISABLE); + } + pwrctrl_mask_reg0 |= BITFMASK(MC13783_PWRCTRL_PCEN); + pwrctrl_mask_reg1 |= BITFMASK(MC13783_PWRCTRL_PCT); + + if (pc_config->pc_count_enable != false) { + + pwrctrl_val_reg0 |= BITFVAL(MC13783_PWRCTRL_PC_COUNT_EN, + MC13783_PWRCTRL_PC_COUNT_EN_ENABLE); + pwrctrl_val_reg1 |= BITFVAL(MC13783_PWRCTRL_PC_COUNT, + pc_config->pc_count); + pwrctrl_val_reg1 |= BITFVAL(MC13783_PWRCTRL_PC_MAX_CNT, + pc_config->pc_max_count); + } else { + pwrctrl_val_reg0 |= BITFVAL(MC13783_PWRCTRL_PC_COUNT_EN, + MC13783_PWRCTRL_PC_COUNT_EN_DISABLE); + } + pwrctrl_mask_reg0 |= BITFMASK(MC13783_PWRCTRL_PC_COUNT_EN); + pwrctrl_mask_reg1 |= BITFMASK(MC13783_PWRCTRL_PC_MAX_CNT) | + BITFMASK(MC13783_PWRCTRL_PC_COUNT); + + if (pc_config->warm_enable != false) { + pwrctrl_val_reg0 |= BITFVAL(MC13783_PWRCTRL_WARM_EN, + MC13783_PWRCTRL_WARM_EN_ENABLE); + } else { + pwrctrl_val_reg0 |= BITFVAL(MC13783_PWRCTRL_WARM_EN, + MC13783_PWRCTRL_WARM_EN_DISABLE); + } + pwrctrl_mask_reg0 |= BITFMASK(MC13783_PWRCTRL_WARM_EN); + + if (pc_config->user_off_pc != false) { + pwrctrl_val_reg0 |= BITFVAL(MC13783_PWRCTRL_USER_OFF_PC, + MC13783_PWRCTRL_USER_OFF_PC_ENABLE); + } else { + pwrctrl_val_reg0 |= BITFVAL(MC13783_PWRCTRL_WARM_EN, + MC13783_PWRCTRL_USER_OFF_PC_DISABLE); + } + pwrctrl_mask_reg0 |= BITFMASK(MC13783_PWRCTRL_USER_OFF_PC); + + if (pc_config->clk_32k_user_off != false) { + pwrctrl_val_reg0 |= BITFVAL(MC13783_PWRCTRL_32OUT_USER_OFF, + MC13783_PWRCTRL_32OUT_USER_OFF_ENABLE); + } else { + pwrctrl_val_reg0 |= BITFVAL(MC13783_PWRCTRL_32OUT_USER_OFF, + MC13783_PWRCTRL_32OUT_USER_OFF_DISABLE); + } + pwrctrl_mask_reg0 |= BITFMASK(MC13783_PWRCTRL_32OUT_USER_OFF); + + if (pc_config->clk_32k_enable != false) { + pwrctrl_val_reg0 |= BITFVAL(MC13783_PWRCTRL_32OUT_EN, + MC13783_PWRCTRL_32OUT_EN_ENABLE); + } else { + pwrctrl_val_reg0 |= BITFVAL(MC13783_PWRCTRL_32OUT_EN, + MC13783_PWRCTRL_32OUT_EN_DISABLE); + } + pwrctrl_mask_reg0 |= BITFMASK(MC13783_PWRCTRL_32OUT_EN); + + if (pc_config->en_vbkup1 != false) { + pwrctrl_val_reg0 |= BITFVAL(MC13783_PWRCTRL_VBKUP1_EN, + MC13783_PWRCTRL_VBKUP_ENABLE); + VBKUP1_EN = true; + } else { + pwrctrl_val_reg0 |= BITFVAL(MC13783_PWRCTRL_VBKUP1_EN, + MC13783_PWRCTRL_VBKUP_DISABLE); + VBKUP1_EN = false; + } + pwrctrl_mask_reg0 |= BITFMASK(MC13783_PWRCTRL_VBKUP1_EN); + + if (pc_config->en_vbkup2 != false) { + pwrctrl_val_reg0 |= BITFVAL(MC13783_PWRCTRL_VBKUP2_EN, + MC13783_PWRCTRL_VBKUP_ENABLE); + VBKUP2_EN = true; + } else { + pwrctrl_val_reg0 |= BITFVAL(MC13783_PWRCTRL_VBKUP2_EN, + MC13783_PWRCTRL_VBKUP_DISABLE); + VBKUP2_EN = false; + } + pwrctrl_mask_reg0 |= BITFMASK(MC13783_PWRCTRL_VBKUP2_EN); + + if (pc_config->auto_en_vbkup1 != false) { + pwrctrl_val_reg0 |= BITFVAL(MC13783_PWRCTRL_VBKUP1_AUTO_EN, + MC13783_PWRCTRL_VBKUP_ENABLE); + } else { + pwrctrl_val_reg0 |= BITFVAL(MC13783_PWRCTRL_VBKUP1_AUTO_EN, + MC13783_PWRCTRL_VBKUP_DISABLE); + } + pwrctrl_mask_reg0 |= BITFMASK(MC13783_PWRCTRL_VBKUP1_AUTO_EN); + + if (pc_config->auto_en_vbkup2 != false) { + pwrctrl_val_reg0 |= BITFVAL(MC13783_PWRCTRL_VBKUP2_AUTO_EN, + MC13783_PWRCTRL_VBKUP_ENABLE); + } else { + pwrctrl_val_reg0 |= BITFVAL(MC13783_PWRCTRL_VBKUP2_AUTO_EN, + MC13783_PWRCTRL_VBKUP_DISABLE); + } + pwrctrl_mask_reg0 |= BITFMASK(MC13783_PWRCTRL_VBKUP2_AUTO_EN); + + if (VBKUP1_EN != false) { + if (pc_config->vhold_voltage > 3 + || pc_config->vhold_voltage < 0) { + return PMIC_PARAMETER_ERROR; + } else { + + pwrctrl_val_reg0 |= BITFVAL(MC13783_PWRCTRL_VBKUP1, + pc_config->vhold_voltage); + } + } + if (VBKUP2_EN != false) { + if (pc_config->vhold_voltage > 3 + || pc_config->vhold_voltage < 0) { + return PMIC_PARAMETER_ERROR; + } else { + pwrctrl_val_reg0 |= BITFVAL(MC13783_PWRCTRL_VBKUP2, + pc_config->vhold_voltage2); + } + } + pwrctrl_mask_reg0 |= BITFMASK(MC13783_PWRCTRL_VBKUP1) | + BITFMASK(MC13783_PWRCTRL_VBKUP2); + + if (pc_config->mem_allon != false) { + pwrctrl_val_reg1 |= BITFVAL(MC13783_PWRCTRL_MEM_ALLON, + MC13783_PWRCTRL_MEM_ALLON_ENABLE); + pwrctrl_val_reg1 |= BITFVAL(MC13783_PWRCTRL_MEM_TMR, + pc_config->mem_timer); + } else { + pwrctrl_val_reg1 |= BITFVAL(MC13783_PWRCTRL_MEM_ALLON, + MC13783_PWRCTRL_MEM_ALLON_DISABLE); + } + pwrctrl_mask_reg1 |= BITFMASK(MC13783_PWRCTRL_MEM_ALLON) | + BITFMASK(MC13783_PWRCTRL_MEM_TMR); + + CHECK_ERROR(pmic_write_reg(REG_POWER_CONTROL_0, + pwrctrl_val_reg0, pwrctrl_mask_reg0)); + CHECK_ERROR(pmic_write_reg(REG_POWER_CONTROL_1, + pwrctrl_val_reg1, pwrctrl_mask_reg1)); + + return PMIC_SUCCESS; +} + +/*! + * This function retrives the power control configuration. + * + * @param pc_config pointer to power control configuration. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_get_pc_config(t_pc_config *pc_config) +{ + unsigned int pwrctrl_val_reg0 = 0; + unsigned int pwrctrl_val_reg1 = 0; + + if (pc_config == NULL) { + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_read_reg(REG_POWER_CONTROL_0, + &pwrctrl_val_reg0, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_read_reg(REG_POWER_CONTROL_1, + &pwrctrl_val_reg1, PMIC_ALL_BITS)); + + if (BITFEXT(pwrctrl_val_reg0, MC13783_PWRCTRL_PCEN) + == MC13783_PWRCTRL_PCEN_ENABLE) { + pc_config->pc_enable = true; + pc_config->pc_timer = BITFEXT(pwrctrl_val_reg1, + MC13783_PWRCTRL_PCT); + + } else { + pc_config->pc_enable = false; + pc_config->pc_timer = 0; + } + + if (BITFEXT(pwrctrl_val_reg0, MC13783_PWRCTRL_PC_COUNT_EN) + == MC13783_PWRCTRL_PCEN_ENABLE) { + pc_config->pc_count_enable = true; + pc_config->pc_count = BITFEXT(pwrctrl_val_reg1, + MC13783_PWRCTRL_PC_COUNT); + pc_config->pc_max_count = BITFEXT(pwrctrl_val_reg1, + MC13783_PWRCTRL_PC_MAX_CNT); + } else { + pc_config->pc_count_enable = false; + pc_config->pc_count = 0; + pc_config->pc_max_count = 0; + } + + if (BITFEXT(pwrctrl_val_reg0, MC13783_PWRCTRL_WARM_EN) + == MC13783_PWRCTRL_WARM_EN_ENABLE) { + pc_config->warm_enable = true; + } else { + pc_config->warm_enable = false; + } + + if (BITFEXT(pwrctrl_val_reg0, MC13783_PWRCTRL_USER_OFF_PC) + == MC13783_PWRCTRL_USER_OFF_PC_ENABLE) { + pc_config->user_off_pc = true; + } else { + pc_config->user_off_pc = false; + } + + if (BITFEXT(pwrctrl_val_reg0, MC13783_PWRCTRL_32OUT_USER_OFF) + == MC13783_PWRCTRL_32OUT_USER_OFF_ENABLE) { + pc_config->clk_32k_user_off = true; + } else { + pc_config->clk_32k_user_off = false; + } + + if (BITFEXT(pwrctrl_val_reg0, MC13783_PWRCTRL_32OUT_EN) + == MC13783_PWRCTRL_32OUT_EN_ENABLE) { + pc_config->clk_32k_enable = true; + } else { + pc_config->clk_32k_enable = false; + } + + if (BITFEXT(pwrctrl_val_reg0, MC13783_PWRCTRL_VBKUP1_AUTO_EN) + == MC13783_PWRCTRL_VBKUP_ENABLE) { + pc_config->auto_en_vbkup1 = true; + } else { + pc_config->auto_en_vbkup1 = false; + } + + if (BITFEXT(pwrctrl_val_reg0, MC13783_PWRCTRL_VBKUP2_AUTO_EN) + == MC13783_PWRCTRL_VBKUP_ENABLE) { + pc_config->auto_en_vbkup2 = true; + } else { + pc_config->auto_en_vbkup2 = false; + } + + if (BITFEXT(pwrctrl_val_reg0, MC13783_PWRCTRL_VBKUP1_EN) + == MC13783_PWRCTRL_VBKUP_ENABLE) { + pc_config->en_vbkup1 = true; + pc_config->vhold_voltage = BITFEXT(pwrctrl_val_reg0, + MC13783_PWRCTRL_VBKUP1); + } else { + pc_config->en_vbkup1 = false; + pc_config->vhold_voltage = 0; + } + + if (BITFEXT(pwrctrl_val_reg0, MC13783_PWRCTRL_VBKUP2_EN) + == MC13783_PWRCTRL_VBKUP_ENABLE) { + pc_config->en_vbkup2 = true; + pc_config->vhold_voltage2 = BITFEXT(pwrctrl_val_reg0, + MC13783_PWRCTRL_VBKUP2); + } else { + pc_config->en_vbkup2 = false; + pc_config->vhold_voltage2 = 0; + } + + if (BITFEXT(pwrctrl_val_reg1, MC13783_PWRCTRL_MEM_ALLON) == + MC13783_PWRCTRL_MEM_ALLON_ENABLE) { + pc_config->mem_allon = true; + pc_config->mem_timer = BITFEXT(pwrctrl_val_reg1, + MC13783_PWRCTRL_MEM_TMR); + } else { + pc_config->mem_allon = false; + pc_config->mem_timer = 0; + } + + return PMIC_SUCCESS; +} + +/*! + * This function turns on a regulator. + * + * @param regulator The regulator to be truned on. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_regulator_on(t_pmic_regulator regulator) +{ + unsigned int reg_val = 0, reg_mask = 0; + unsigned int reg; + + switch (regulator) { + case SW_PLL: + reg_val = BITFVAL(MC13783_SWCTRL_PLL_EN, + MC13783_SWCTRL_PLL_EN_ENABLE); + reg_mask = BITFMASK(MC13783_SWCTRL_PLL_EN); + reg = REG_SWITCHERS_4; + break; + case SW_SW3: + reg_val = BITFVAL(MC13783_SWCTRL_SW3_EN, + MC13783_SWCTRL_SW3_EN_ENABLE); + reg_mask = BITFMASK(MC13783_SWCTRL_SW3_EN); + reg = REG_SWITCHERS_5; + break; + case REGU_VAUDIO: + reg_val = BITFVAL(MC13783_REGCTRL_VAUDIO_EN, + MC13783_REGCTRL_VAUDIO_EN_ENABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VAUDIO_EN); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VIOHI: + reg_val = BITFVAL(MC13783_REGCTRL_VIOHI_EN, + MC13783_REGCTRL_VIOHI_EN_ENABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VIOHI_EN); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VIOLO: + reg_val = BITFVAL(MC13783_REGCTRL_VIOLO_EN, + MC13783_REGCTRL_VIOLO_EN_ENABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VIOLO_EN); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VDIG: + reg_val = BITFVAL(MC13783_REGCTRL_VDIG_EN, + MC13783_REGCTRL_VDIG_EN_ENABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VDIG_EN); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VGEN: + reg_val = BITFVAL(MC13783_REGCTRL_VGEN_EN, + MC13783_REGCTRL_VGEN_EN_ENABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VGEN_EN); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VRFDIG: + reg_val = BITFVAL(MC13783_REGCTRL_VRFDIG_EN, + MC13783_REGCTRL_VRFDIG_EN_ENABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VRFDIG_EN); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VRFREF: + reg_val = BITFVAL(MC13783_REGCTRL_VRFREF_EN, + MC13783_REGCTRL_VRFREF_EN_ENABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VRFREF_EN); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VRFCP: + reg_val = BITFVAL(MC13783_REGCTRL_VRFCP_EN, + MC13783_REGCTRL_VRFCP_EN_ENABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VRFCP_EN); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VSIM: + reg_val = BITFVAL(MC13783_REGCTRL_VSIM_EN, + MC13783_REGCTRL_VSIM_EN_ENABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VSIM_EN); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VESIM: + reg_val = BITFVAL(MC13783_REGCTRL_VESIM_EN, + MC13783_REGCTRL_VESIM_EN_ENABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VESIM_EN); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VCAM: + reg_val = BITFVAL(MC13783_REGCTRL_VCAM_EN, + MC13783_REGCTRL_VCAM_EN_ENABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VCAM_EN); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VRFBG: + reg_val = BITFVAL(MC13783_REGCTRL_VRFBG_EN, + MC13783_REGCTRL_VRFBG_EN_ENABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VRFBG_EN); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VVIB: + reg_val = BITFVAL(MC13783_REGCTRL_VVIB_EN, + MC13783_REGCTRL_VVIB_EN_ENABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VVIB_EN); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VRF1: + reg_val = BITFVAL(MC13783_REGCTRL_VRF1_EN, + MC13783_REGCTRL_VRF1_EN_ENABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VRF1_EN); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VRF2: + reg_val = BITFVAL(MC13783_REGCTRL_VRF2_EN, + MC13783_REGCTRL_VRF2_EN_ENABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VRF2_EN); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VMMC1: + reg_val = BITFVAL(MC13783_REGCTRL_VMMC1_EN, + MC13783_REGCTRL_VMMC1_EN_ENABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VMMC1_EN); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VMMC2: + reg_val = BITFVAL(MC13783_REGCTRL_VMMC2_EN, + MC13783_REGCTRL_VMMC2_EN_ENABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VMMC2_EN); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_GPO1: + reg_val = BITFVAL(MC13783_REGCTRL_GPO1_EN, + MC13783_REGCTRL_GPO1_EN_ENABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_GPO1_EN); + reg = REG_POWER_MISCELLANEOUS; + break; + case REGU_GPO2: + reg_val = BITFVAL(MC13783_REGCTRL_GPO2_EN, + MC13783_REGCTRL_GPO2_EN_ENABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_GPO2_EN); + reg = REG_POWER_MISCELLANEOUS; + break; + case REGU_GPO3: + reg_val = BITFVAL(MC13783_REGCTRL_GPO3_EN, + MC13783_REGCTRL_GPO3_EN_ENABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_GPO3_EN); + reg = REG_POWER_MISCELLANEOUS; + break; + case REGU_GPO4: + reg_val = BITFVAL(MC13783_REGCTRL_GPO4_EN, + MC13783_REGCTRL_GPO4_EN_ENABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_GPO4_EN); + reg = REG_POWER_MISCELLANEOUS; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(reg, reg_val, reg_mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function turns off a regulator. + * + * @param regulator The regulator to be truned off. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_regulator_off(t_pmic_regulator regulator) +{ + unsigned int reg_val = 0, reg_mask = 0; + unsigned int reg; + + switch (regulator) { + case SW_PLL: + reg_val = BITFVAL(MC13783_SWCTRL_PLL_EN, + MC13783_SWCTRL_PLL_EN_DISABLE); + reg_mask = BITFMASK(MC13783_SWCTRL_PLL_EN); + reg = REG_SWITCHERS_4; + break; + case SW_SW3: + reg_val = BITFVAL(MC13783_SWCTRL_SW3_EN, + MC13783_SWCTRL_SW3_EN_DISABLE); + reg_mask = BITFMASK(MC13783_SWCTRL_SW3_EN); + reg = REG_SWITCHERS_5; + break; + case REGU_VAUDIO: + reg_val = BITFVAL(MC13783_REGCTRL_VAUDIO_EN, + MC13783_REGCTRL_VAUDIO_EN_DISABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VAUDIO_EN); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VIOHI: + reg_val = BITFVAL(MC13783_REGCTRL_VIOHI_EN, + MC13783_REGCTRL_VIOHI_EN_DISABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VIOHI_EN); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VIOLO: + reg_val = BITFVAL(MC13783_REGCTRL_VIOLO_EN, + MC13783_REGCTRL_VIOLO_EN_DISABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VIOLO_EN); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VDIG: + reg_val = BITFVAL(MC13783_REGCTRL_VDIG_EN, + MC13783_REGCTRL_VDIG_EN_DISABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VDIG_EN); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VGEN: + reg_val = BITFVAL(MC13783_REGCTRL_VGEN_EN, + MC13783_REGCTRL_VGEN_EN_DISABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VGEN_EN); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VRFDIG: + reg_val = BITFVAL(MC13783_REGCTRL_VRFDIG_EN, + MC13783_REGCTRL_VRFDIG_EN_DISABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VRFDIG_EN); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VRFREF: + reg_val = BITFVAL(MC13783_REGCTRL_VRFREF_EN, + MC13783_REGCTRL_VRFREF_EN_DISABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VRFREF_EN); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VRFCP: + reg_val = BITFVAL(MC13783_REGCTRL_VRFCP_EN, + MC13783_REGCTRL_VRFCP_EN_DISABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VRFCP_EN); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VSIM: + reg_val = BITFVAL(MC13783_REGCTRL_VSIM_EN, + MC13783_REGCTRL_VSIM_EN_DISABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VSIM_EN); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VESIM: + reg_val = BITFVAL(MC13783_REGCTRL_VESIM_EN, + MC13783_REGCTRL_VESIM_EN_DISABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VESIM_EN); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VCAM: + reg_val = BITFVAL(MC13783_REGCTRL_VCAM_EN, + MC13783_REGCTRL_VCAM_EN_DISABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VCAM_EN); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VRFBG: + reg_val = BITFVAL(MC13783_REGCTRL_VRFBG_EN, + MC13783_REGCTRL_VRFBG_EN_DISABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VRFBG_EN); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VVIB: + reg_val = BITFVAL(MC13783_REGCTRL_VVIB_EN, + MC13783_REGCTRL_VVIB_EN_DISABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VVIB_EN); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VRF1: + reg_val = BITFVAL(MC13783_REGCTRL_VRF1_EN, + MC13783_REGCTRL_VRF1_EN_DISABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VRF1_EN); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VRF2: + reg_val = BITFVAL(MC13783_REGCTRL_VRF2_EN, + MC13783_REGCTRL_VRF2_EN_DISABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VRF2_EN); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VMMC1: + reg_val = BITFVAL(MC13783_REGCTRL_VMMC1_EN, + MC13783_REGCTRL_VMMC1_EN_DISABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VMMC1_EN); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VMMC2: + reg_val = BITFVAL(MC13783_REGCTRL_VMMC2_EN, + MC13783_REGCTRL_VMMC2_EN_DISABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_VMMC2_EN); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_GPO1: + reg_val = BITFVAL(MC13783_REGCTRL_GPO1_EN, + MC13783_REGCTRL_GPO1_EN_DISABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_GPO1_EN); + reg = REG_POWER_MISCELLANEOUS; + break; + case REGU_GPO2: + reg_val = BITFVAL(MC13783_REGCTRL_GPO2_EN, + MC13783_REGCTRL_GPO2_EN_DISABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_GPO2_EN); + reg = REG_POWER_MISCELLANEOUS; + break; + case REGU_GPO3: + reg_val = BITFVAL(MC13783_REGCTRL_GPO3_EN, + MC13783_REGCTRL_GPO3_EN_DISABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_GPO3_EN); + reg = REG_POWER_MISCELLANEOUS; + break; + case REGU_GPO4: + reg_val = BITFVAL(MC13783_REGCTRL_GPO4_EN, + MC13783_REGCTRL_GPO4_EN_DISABLE); + reg_mask = BITFMASK(MC13783_REGCTRL_GPO4_EN); + reg = REG_POWER_MISCELLANEOUS; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(reg, reg_val, reg_mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function sets the regulator output voltage. + * + * @param regulator The regulator to be configured. + * @param voltage The regulator output voltage. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_regulator_set_voltage(t_pmic_regulator regulator, + t_regulator_voltage voltage) +{ + unsigned int reg_val = 0, reg_mask = 0; + unsigned int reg; + + switch (regulator) { + case SW_SW1A: + if ((voltage.sw1a < SW1A_0_9V) || (voltage.sw1a > SW1A_2_2V)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_SWSET_SW1A, voltage.sw1a); + reg_mask = BITFMASK(MC13783_SWSET_SW1A); + reg = REG_SWITCHERS_0; + break; + case SW_SW1B: + if ((voltage.sw1b < SW1B_0_9V) || (voltage.sw1b > SW1B_2_2V)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_SWSET_SW1B, voltage.sw1b); + reg_mask = BITFMASK(MC13783_SWSET_SW1B); + reg = REG_SWITCHERS_1; + break; + case SW_SW2A: + if ((voltage.sw2a < SW2A_0_9V) || (voltage.sw2a > SW2A_2_2V)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_SWSET_SW2A, voltage.sw1a); + reg_mask = BITFMASK(MC13783_SWSET_SW2A); + reg = REG_SWITCHERS_2; + break; + case SW_SW2B: + if ((voltage.sw2b < SW2B_0_9V) || (voltage.sw2b > SW2B_2_2V)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_SWSET_SW2B, voltage.sw2b); + reg_mask = BITFMASK(MC13783_SWSET_SW1A); + reg = REG_SWITCHERS_3; + break; + case SW_SW3: + if (voltage.sw3 != SW3_5V) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_SWSET_SW3, voltage.sw3); + reg_mask = BITFMASK(MC13783_SWSET_SW3); + reg = REG_SWITCHERS_5; + break; + case REGU_VIOLO: + if ((voltage.violo < VIOLO_1_2V) || + (voltage.violo > VIOLO_1_8V)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_REGSET_VIOLO, voltage.violo); + reg_mask = BITFMASK(MC13783_REGSET_VIOLO); + reg = REG_REGULATOR_SETTING_0; + break; + case REGU_VDIG: + if ((voltage.vdig < VDIG_1_2V) || (voltage.vdig > VDIG_1_8V)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_REGSET_VDIG, voltage.vdig); + reg_mask = BITFMASK(MC13783_REGSET_VDIG); + reg = REG_REGULATOR_SETTING_0; + break; + case REGU_VGEN: + if ((voltage.vgen < VGEN_1_2V) || (voltage.vgen > VGEN_2_4V)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_REGSET_VGEN, voltage.vgen); + reg_mask = BITFMASK(MC13783_REGSET_VGEN); + reg = REG_REGULATOR_SETTING_0; + break; + case REGU_VRFDIG: + if ((voltage.vrfdig < VRFDIG_1_2V) || + (voltage.vrfdig > VRFDIG_1_875V)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_REGSET_VRFDIG, voltage.vrfdig); + reg_mask = BITFMASK(MC13783_REGSET_VRFDIG); + reg = REG_REGULATOR_SETTING_0; + break; + case REGU_VRFREF: + if ((voltage.vrfref < VRFREF_2_475V) || + (voltage.vrfref > VRFREF_2_775V)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_REGSET_VRFREF, voltage.vrfref); + reg_mask = BITFMASK(MC13783_REGSET_VRFREF); + reg = REG_REGULATOR_SETTING_0; + break; + case REGU_VRFCP: + if ((voltage.vrfcp < VRFCP_2_7V) || + (voltage.vrfcp > VRFCP_2_775V)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_REGSET_VRFCP, voltage.vrfcp); + reg_mask = BITFMASK(MC13783_REGSET_VRFCP); + reg = REG_REGULATOR_SETTING_0; + break; + case REGU_VSIM: + if ((voltage.vsim < VSIM_1_8V) || (voltage.vsim > VSIM_2_9V)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_REGSET_VSIM, voltage.vsim); + reg_mask = BITFMASK(MC13783_REGSET_VSIM); + reg = REG_REGULATOR_SETTING_0; + break; + case REGU_VESIM: + if ((voltage.vesim < VESIM_1_8V) || + (voltage.vesim > VESIM_2_9V)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_REGSET_VESIM, voltage.vesim); + reg_mask = BITFMASK(MC13783_REGSET_VESIM); + reg = REG_REGULATOR_SETTING_0; + break; + case REGU_VCAM: + if ((voltage.vcam < VCAM_1_5V) || (voltage.vcam > VCAM_3V)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_REGSET_VCAM, voltage.vcam); + reg_mask = BITFMASK(MC13783_REGSET_VCAM); + reg = REG_REGULATOR_SETTING_0; + break; + case REGU_VVIB: + if ((voltage.vvib < VVIB_1_3V) || (voltage.vvib > VVIB_3V)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_REGSET_VVIB, voltage.vvib); + reg_mask = BITFMASK(MC13783_REGSET_VVIB); + reg = REG_REGULATOR_SETTING_1; + break; + case REGU_VRF1: + if ((voltage.vrf1 < VRF1_1_5V) || (voltage.vrf1 > VRF1_2_775V)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_REGSET_VRF1, voltage.vrf1); + reg_mask = BITFMASK(MC13783_REGSET_VRF1); + reg = REG_REGULATOR_SETTING_1; + break; + case REGU_VRF2: + if ((voltage.vrf2 < VRF2_1_5V) || (voltage.vrf2 > VRF2_2_775V)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_REGSET_VRF2, voltage.vrf2); + reg_mask = BITFMASK(MC13783_REGSET_VRF2); + reg = REG_REGULATOR_SETTING_1; + break; + case REGU_VMMC1: + if ((voltage.vmmc1 < VMMC1_1_6V) || (voltage.vmmc1 > VMMC1_3V)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_REGSET_VMMC1, voltage.vmmc1); + reg_mask = BITFMASK(MC13783_REGSET_VMMC1); + reg = REG_REGULATOR_SETTING_1; + break; + case REGU_VMMC2: + if ((voltage.vmmc2 < VMMC2_1_6V) || (voltage.vmmc2 > VMMC2_3V)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_REGSET_VMMC2, voltage.vmmc2); + reg_mask = BITFMASK(MC13783_REGSET_VMMC2); + reg = REG_REGULATOR_SETTING_1; + break; + case REGU_VAUDIO: + case REGU_VIOHI: + case REGU_VRFBG: + case REGU_GPO1: + case REGU_GPO2: + case REGU_GPO3: + case REGU_GPO4: + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(reg, reg_val, reg_mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function retrives the regulator output voltage. + * + * @param regulator The regulator to be truned off. + * @param voltage Pointer to regulator output voltage. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_regulator_get_voltage(t_pmic_regulator regulator, + t_regulator_voltage *voltage) +{ + unsigned int reg_val = 0; + + if (regulator == SW_SW1A) { + CHECK_ERROR(pmic_read_reg(REG_SWITCHERS_0, + ®_val, PMIC_ALL_BITS)); + } else if (regulator == SW_SW1B) { + CHECK_ERROR(pmic_read_reg(REG_SWITCHERS_1, + ®_val, PMIC_ALL_BITS)); + } else if (regulator == SW_SW2A) { + CHECK_ERROR(pmic_read_reg(REG_SWITCHERS_2, + ®_val, PMIC_ALL_BITS)); + } else if (regulator == SW_SW2B) { + CHECK_ERROR(pmic_read_reg(REG_SWITCHERS_3, + ®_val, PMIC_ALL_BITS)); + } else if (regulator == SW_SW3) { + CHECK_ERROR(pmic_read_reg(REG_SWITCHERS_5, + ®_val, PMIC_ALL_BITS)); + } else if ((regulator == REGU_VIOLO) || (regulator == REGU_VDIG) || + (regulator == REGU_VGEN) || + (regulator == REGU_VRFDIG) || + (regulator == REGU_VRFREF) || + (regulator == REGU_VRFCP) || + (regulator == REGU_VSIM) || + (regulator == REGU_VESIM) || (regulator == REGU_VCAM)) { + CHECK_ERROR(pmic_read_reg(REG_REGULATOR_SETTING_0, + ®_val, PMIC_ALL_BITS)); + } else if ((regulator == REGU_VVIB) || (regulator == REGU_VRF1) || + (regulator == REGU_VRF2) || + (regulator == REGU_VMMC1) || (regulator == REGU_VMMC2)) { + CHECK_ERROR(pmic_read_reg(REG_REGULATOR_SETTING_1, + ®_val, PMIC_ALL_BITS)); + } + + switch (regulator) { + case SW_SW1A: + voltage->sw1a = BITFEXT(reg_val, MC13783_SWSET_SW1A); + break; + case SW_SW1B: + voltage->sw1b = BITFEXT(reg_val, MC13783_SWSET_SW1B); + break; + case SW_SW2A: + voltage->sw2a = BITFEXT(reg_val, MC13783_SWSET_SW2A); + break; + case SW_SW2B: + voltage->sw2b = BITFEXT(reg_val, MC13783_SWSET_SW2B); + break; + case SW_SW3: + voltage->sw3 = BITFEXT(reg_val, MC13783_SWSET_SW3); + break; + case REGU_VIOLO: + voltage->violo = BITFEXT(reg_val, MC13783_REGSET_VIOLO); + break; + case REGU_VDIG: + voltage->vdig = BITFEXT(reg_val, MC13783_REGSET_VDIG); + break; + case REGU_VGEN: + voltage->vgen = BITFEXT(reg_val, MC13783_REGSET_VGEN); + break; + case REGU_VRFDIG: + voltage->vrfdig = BITFEXT(reg_val, MC13783_REGSET_VRFDIG); + break; + case REGU_VRFREF: + voltage->vrfref = BITFEXT(reg_val, MC13783_REGSET_VRFREF); + break; + case REGU_VRFCP: + voltage->vrfcp = BITFEXT(reg_val, MC13783_REGSET_VRFCP); + break; + case REGU_VSIM: + voltage->vsim = BITFEXT(reg_val, MC13783_REGSET_VSIM); + break; + case REGU_VESIM: + voltage->vesim = BITFEXT(reg_val, MC13783_REGSET_VESIM); + break; + case REGU_VCAM: + voltage->vcam = BITFEXT(reg_val, MC13783_REGSET_VCAM); + break; + case REGU_VVIB: + voltage->vvib = BITFEXT(reg_val, MC13783_REGSET_VVIB); + break; + case REGU_VRF1: + voltage->vrf1 = BITFEXT(reg_val, MC13783_REGSET_VRF1); + break; + case REGU_VRF2: + voltage->vrf2 = BITFEXT(reg_val, MC13783_REGSET_VRF2); + break; + case REGU_VMMC1: + voltage->vmmc1 = BITFEXT(reg_val, MC13783_REGSET_VMMC1); + break; + case REGU_VMMC2: + voltage->vmmc2 = BITFEXT(reg_val, MC13783_REGSET_VMMC2); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + return PMIC_SUCCESS; +} + +/*! + * This function sets the DVS voltage + * + * @param regulator The regulator to be configured. + * @param dvs The switch Dynamic Voltage Scaling + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_switcher_set_dvs(t_pmic_regulator regulator, + t_regulator_voltage dvs) +{ + unsigned int reg_val = 0, reg_mask = 0; + unsigned int reg; + + switch (regulator) { + case SW_SW1A: + if ((dvs.sw1a < SW1A_0_9V) || (dvs.sw1a > SW1A_2_2V)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_SWSET_SW1A_DVS, dvs.sw1a); + reg_mask = BITFMASK(MC13783_SWSET_SW1A_DVS); + reg = REG_SWITCHERS_0; + break; + case SW_SW1B: + if ((dvs.sw1b < SW1B_0_9V) || (dvs.sw1b > SW1B_2_2V)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_SWSET_SW1B_DVS, dvs.sw1b); + reg_mask = BITFMASK(MC13783_SWSET_SW1B_DVS); + reg = REG_SWITCHERS_1; + break; + case SW_SW2A: + if ((dvs.sw2a < SW2A_0_9V) || (dvs.sw2a > SW2A_2_2V)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_SWSET_SW2A_DVS, dvs.sw2a); + reg_mask = BITFMASK(MC13783_SWSET_SW2A_DVS); + reg = REG_SWITCHERS_2; + break; + case SW_SW2B: + if ((dvs.sw2b < SW2B_0_9V) || (dvs.sw2b > SW2B_2_2V)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_SWSET_SW2B_DVS, dvs.sw2b); + reg_mask = BITFMASK(MC13783_SWSET_SW2B_DVS); + reg = REG_SWITCHERS_3; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(reg, reg_val, reg_mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function gets the DVS voltage + * + * @param regulator The regulator to be handled. + * @param dvs The switch Dynamic Voltage Scaling + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_switcher_get_dvs(t_pmic_regulator regulator, + t_regulator_voltage *dvs) +{ + unsigned int reg_val = 0, reg_mask = 0; + unsigned int reg; + + switch (regulator) { + case SW_SW1A: + reg_mask = BITFMASK(MC13783_SWSET_SW1A_DVS); + reg = REG_SWITCHERS_0; + break; + case SW_SW1B: + reg_mask = BITFMASK(MC13783_SWSET_SW1B_DVS); + reg = REG_SWITCHERS_1; + break; + case SW_SW2A: + reg_mask = BITFMASK(MC13783_SWSET_SW2A_DVS); + reg = REG_SWITCHERS_2; + break; + case SW_SW2B: + reg_mask = BITFMASK(MC13783_SWSET_SW2B_DVS); + reg = REG_SWITCHERS_3; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_read_reg(reg, ®_val, reg_mask)); + + switch (regulator) { + case SW_SW1A: + *dvs = (t_regulator_voltage) BITFEXT(reg_val, + MC13783_SWSET_SW1A_DVS); + break; + case SW_SW1B: + *dvs = (t_regulator_voltage) BITFEXT(reg_val, + MC13783_SWSET_SW1B_DVS); + break; + case SW_SW2A: + *dvs = (t_regulator_voltage) BITFEXT(reg_val, + MC13783_SWSET_SW2A_DVS); + break; + case SW_SW2B: + *dvs = (t_regulator_voltage) BITFEXT(reg_val, + MC13783_SWSET_SW2B_DVS); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + return PMIC_SUCCESS; +} + +/*! + * This function sets the standiby voltage + * + * @param regulator The regulator to be configured. + * @param stby The switch standby voltage + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_switcher_set_stby(t_pmic_regulator regulator, + t_regulator_voltage stby) +{ + unsigned int reg_val = 0, reg_mask = 0; + unsigned int reg; + + switch (regulator) { + case SW_SW1A: + if ((stby.sw1a < SW1A_0_9V) || (stby.sw1a > SW1A_2_2V)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_SWSET_SW1A_STDBY, stby.sw1a); + reg_mask = BITFMASK(MC13783_SWSET_SW1A_STDBY); + reg = REG_SWITCHERS_0; + break; + case SW_SW1B: + if ((stby.sw1b < SW1B_0_9V) || (stby.sw1b > SW1B_2_2V)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_SWSET_SW1B_STDBY, stby.sw1b); + reg_mask = BITFMASK(MC13783_SWSET_SW1B_STDBY); + reg = REG_SWITCHERS_1; + break; + case SW_SW2A: + if ((stby.sw2a < SW2A_0_9V) || (stby.sw2a > SW2A_2_2V)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_SWSET_SW2A_STDBY, stby.sw2a); + reg_mask = BITFMASK(MC13783_SWSET_SW2A_STDBY); + reg = REG_SWITCHERS_2; + break; + case SW_SW2B: + if ((stby.sw2b < SW2B_0_9V) || (stby.sw2b > SW2B_2_2V)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_SWSET_SW2B_STDBY, stby.sw2b); + reg_mask = BITFMASK(MC13783_SWSET_SW2B_STDBY); + reg = REG_SWITCHERS_3; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(reg, reg_val, reg_mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function gets the standiby voltage + * + * @param regulator The regulator to be handled. + * @param stby The switch standby voltage + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_switcher_get_stby(t_pmic_regulator regulator, + t_regulator_voltage *stby) +{ + unsigned int reg_val = 0, reg_mask = 0; + unsigned int reg; + + switch (regulator) { + case SW_SW1A: + reg_mask = BITFMASK(MC13783_SWSET_SW1A_STDBY); + reg = REG_SWITCHERS_0; + break; + case SW_SW1B: + reg_mask = BITFMASK(MC13783_SWSET_SW1B_STDBY); + reg = REG_SWITCHERS_1; + break; + case SW_SW2A: + reg_mask = BITFMASK(MC13783_SWSET_SW2A_STDBY); + reg = REG_SWITCHERS_2; + break; + case SW_SW2B: + reg_mask = BITFMASK(MC13783_SWSET_SW2B_STDBY); + reg = REG_SWITCHERS_3; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_read_reg(reg, ®_val, reg_mask)); + + switch (regulator) { + case SW_SW1A: + *stby = (t_regulator_voltage) BITFEXT(reg_val, + MC13783_SWSET_SW1A_STDBY); + break; + case SW_SW1B: + *stby = (t_regulator_voltage) BITFEXT(reg_val, + MC13783_SWSET_SW1B_STDBY); + break; + case SW_SW2A: + *stby = (t_regulator_voltage) BITFEXT(reg_val, + MC13783_SWSET_SW2A_STDBY); + break; + case SW_SW2B: + *stby = (t_regulator_voltage) BITFEXT(reg_val, + MC13783_SWSET_SW2B_STDBY); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + return PMIC_SUCCESS; +} + +/*! + * This function sets the switchers mode. + * + * @param regulator The regulator to be configured. + * @param mode The switcher mode + * @param stby Switch between main and standby. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_switcher_set_mode(t_pmic_regulator regulator, + t_regulator_sw_mode mode, bool stby) +{ + unsigned int reg_val = 0, reg_mask = 0; + unsigned int reg; + unsigned int l_mode; + + if (mode == SYNC_RECT) { + l_mode = MC13783_SWCTRL_SW_MODE_SYNC_RECT_EN; + } else if (mode == NO_PULSE_SKIP) { + l_mode = MC13783_SWCTRL_SW_MODE_PULSE_NO_SKIP_EN; + } else if (mode == PULSE_SKIP) { + l_mode = MC13783_SWCTRL_SW_MODE_PULSE_SKIP_EN; + } else if (mode == LOW_POWER) { + l_mode = MC13783_SWCTRL_SW_MODE_LOW_POWER_EN; + } else { + return PMIC_PARAMETER_ERROR; + } + + switch (regulator) { + case SW_SW1A: + if (stby) { + reg_val = + BITFVAL(MC13783_SWCTRL_SW1A_STBY_MODE, l_mode); + reg_mask = BITFMASK(MC13783_SWCTRL_SW1A_STBY_MODE); + } else { + reg_val = BITFVAL(MC13783_SWCTRL_SW1A_MODE, l_mode); + reg_mask = BITFMASK(MC13783_SWCTRL_SW1A_MODE); + } + reg = REG_SWITCHERS_4; + break; + case SW_SW1B: + if (stby) { + reg_val = + BITFVAL(MC13783_SWCTRL_SW1B_STBY_MODE, l_mode); + reg_mask = BITFMASK(MC13783_SWCTRL_SW1B_STBY_MODE); + } else { + reg_val = BITFVAL(MC13783_SWCTRL_SW1B_MODE, l_mode); + reg_mask = BITFMASK(MC13783_SWCTRL_SW1B_MODE); + } + reg = REG_SWITCHERS_4; + break; + case SW_SW2A: + if (stby) { + reg_val = + BITFVAL(MC13783_SWCTRL_SW2A_STBY_MODE, l_mode); + reg_mask = BITFMASK(MC13783_SWCTRL_SW2A_STBY_MODE); + } else { + reg_val = BITFVAL(MC13783_SWCTRL_SW2A_MODE, l_mode); + reg_mask = BITFMASK(MC13783_SWCTRL_SW2A_MODE); + } + reg = REG_SWITCHERS_5; + break; + case SW_SW2B: + if (stby) { + reg_val = + BITFVAL(MC13783_SWCTRL_SW2B_STBY_MODE, l_mode); + reg_mask = BITFMASK(MC13783_SWCTRL_SW2B_STBY_MODE); + } else { + reg_val = BITFVAL(MC13783_SWCTRL_SW2B_MODE, l_mode); + reg_mask = BITFMASK(MC13783_SWCTRL_SW2B_MODE); + } + reg = REG_SWITCHERS_5; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(reg, reg_val, reg_mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function gets the switchers mode. + * + * @param regulator The regulator to be handled. + * @param mode The switcher mode. + * @param stby Switch between main and standby. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_switcher_get_mode(t_pmic_regulator regulator, + t_regulator_sw_mode *mode, bool stby) +{ + unsigned int reg_val = 0, reg_mask = 0; + unsigned int reg = 0; + unsigned int l_mode = 0; + + switch (regulator) { + case SW_SW1A: + if (stby) { + reg_mask = BITFMASK(MC13783_SWCTRL_SW1A_STBY_MODE); + } else { + reg_mask = BITFMASK(MC13783_SWCTRL_SW1A_MODE); + } + reg = REG_SWITCHERS_4; + break; + case SW_SW1B: + if (stby) { + reg_mask = BITFMASK(MC13783_SWCTRL_SW1B_STBY_MODE); + } else { + reg_mask = BITFMASK(MC13783_SWCTRL_SW1B_MODE); + } + reg = REG_SWITCHERS_4; + break; + case SW_SW2A: + if (stby) { + reg_mask = BITFMASK(MC13783_SWCTRL_SW2A_STBY_MODE); + } else { + reg_mask = BITFMASK(MC13783_SWCTRL_SW2A_MODE); + } + reg = REG_SWITCHERS_5; + break; + case SW_SW2B: + if (stby) { + reg_mask = BITFMASK(MC13783_SWCTRL_SW2B_STBY_MODE); + } else { + reg_mask = BITFMASK(MC13783_SWCTRL_SW2B_MODE); + } + reg = REG_SWITCHERS_5; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_read_reg(reg, ®_val, reg_mask)); + + switch (regulator) { + case SW_SW1A: + if (stby) { + l_mode = + BITFEXT(reg_val, MC13783_SWCTRL_SW1A_STBY_MODE); + } else { + l_mode = BITFEXT(reg_val, MC13783_SWCTRL_SW1A_MODE); + } + break; + case SW_SW1B: + if (stby) { + l_mode = + BITFEXT(reg_val, MC13783_SWCTRL_SW1B_STBY_MODE); + } else { + l_mode = BITFEXT(reg_val, MC13783_SWCTRL_SW1B_MODE); + } + break; + case SW_SW2A: + if (stby) { + l_mode = + BITFEXT(reg_val, MC13783_SWCTRL_SW2A_STBY_MODE); + } else { + l_mode = BITFEXT(reg_val, MC13783_SWCTRL_SW2A_MODE); + } + break; + case SW_SW2B: + if (stby) { + l_mode = + BITFEXT(reg_val, MC13783_SWCTRL_SW2B_STBY_MODE); + } else { + l_mode = BITFEXT(reg_val, MC13783_SWCTRL_SW2B_MODE); + } + break; + default: + return PMIC_PARAMETER_ERROR; + } + + if (l_mode == MC13783_SWCTRL_SW_MODE_SYNC_RECT_EN) { + *mode = SYNC_RECT; + } else if (l_mode == MC13783_SWCTRL_SW_MODE_PULSE_NO_SKIP_EN) { + *mode = NO_PULSE_SKIP; + } else if (l_mode == MC13783_SWCTRL_SW_MODE_PULSE_SKIP_EN) { + *mode = PULSE_SKIP; + } else if (l_mode == MC13783_SWCTRL_SW_MODE_LOW_POWER_EN) { + *mode = LOW_POWER; + } else { + return PMIC_PARAMETER_ERROR; + } + + return PMIC_SUCCESS; +} + +/*! + * This function sets the switch dvs speed + * + * @param regulator The regulator to be configured. + * @param speed The dvs speed. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_switcher_set_dvs_speed(t_pmic_regulator regulator, + t_switcher_dvs_speed speed) +{ + unsigned int reg_val = 0, reg_mask = 0; + unsigned int reg; + if (speed > 3 || speed < 0) { + return PMIC_PARAMETER_ERROR; + } + + switch (regulator) { + case SW_SW1A: + reg_val = BITFVAL(MC13783_SWCTRL_SW1A_DVS_SPEED, speed); + reg_mask = BITFMASK(MC13783_SWCTRL_SW1A_DVS_SPEED); + reg = REG_SWITCHERS_4; + break; + case SW_SW1B: + reg_val = BITFVAL(MC13783_SWCTRL_SW2B_DVS_SPEED, speed); + reg_mask = BITFMASK(MC13783_SWCTRL_SW1B_DVS_SPEED); + reg = REG_SWITCHERS_4; + break; + case SW_SW2A: + reg_val = BITFVAL(MC13783_SWCTRL_SW2A_DVS_SPEED, speed); + reg_mask = BITFMASK(MC13783_SWCTRL_SW2A_DVS_SPEED); + reg = REG_SWITCHERS_5; + break; + case SW_SW2B: + reg_val = BITFVAL(MC13783_SWCTRL_SW2B_DVS_SPEED, speed); + reg_mask = BITFMASK(MC13783_SWCTRL_SW2B_DVS_SPEED); + reg = REG_SWITCHERS_5; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(reg, reg_val, reg_mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function gets the switch dvs speed + * + * @param regulator The regulator to be handled. + * @param speed The dvs speed. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_switcher_get_dvs_speed(t_pmic_regulator regulator, + t_switcher_dvs_speed *speed) +{ + unsigned int reg_val = 0, reg_mask = 0; + unsigned int reg; + + switch (regulator) { + case SW_SW1A: + reg_mask = BITFMASK(MC13783_SWCTRL_SW1A_DVS_SPEED); + reg = REG_SWITCHERS_4; + break; + case SW_SW1B: + reg_mask = BITFMASK(MC13783_SWCTRL_SW1B_DVS_SPEED); + reg = REG_SWITCHERS_4; + break; + case SW_SW2A: + reg_mask = BITFMASK(MC13783_SWCTRL_SW2A_DVS_SPEED); + reg = REG_SWITCHERS_5; + break; + case SW_SW2B: + reg_mask = BITFMASK(MC13783_SWCTRL_SW2B_DVS_SPEED); + reg = REG_SWITCHERS_5; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_read_reg(reg, ®_val, reg_mask)); + + switch (regulator) { + case SW_SW1A: + *speed = BITFEXT(reg_val, MC13783_SWCTRL_SW1A_DVS_SPEED); + break; + case SW_SW1B: + *speed = BITFEXT(reg_val, MC13783_SWCTRL_SW1B_DVS_SPEED); + break; + case SW_SW2A: + *speed = BITFEXT(reg_val, MC13783_SWCTRL_SW2A_DVS_SPEED); + break; + case SW_SW2B: + *speed = BITFEXT(reg_val, MC13783_SWCTRL_SW2B_DVS_SPEED); + break; + default: + break; + } + + return PMIC_SUCCESS; +} + +/*! + * This function sets the switch panic mode + * + * @param regulator The regulator to be configured. + * @param panic_mode Enable or disable panic mode + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_switcher_set_panic_mode(t_pmic_regulator regulator, + bool panic_mode) +{ + unsigned int reg_val = 0, reg_mask = 0; + unsigned int reg; + + switch (regulator) { + case SW_SW1A: + reg_val = BITFVAL(MC13783_SWCTRL_SW1A_PANIC_MODE, panic_mode); + reg_mask = BITFMASK(MC13783_SWCTRL_SW1A_PANIC_MODE); + reg = REG_SWITCHERS_4; + break; + case SW_SW1B: + reg_val = BITFVAL(MC13783_SWCTRL_SW2B_PANIC_MODE, panic_mode); + reg_mask = BITFMASK(MC13783_SWCTRL_SW1B_PANIC_MODE); + reg = REG_SWITCHERS_4; + break; + case SW_SW2A: + reg_val = BITFVAL(MC13783_SWCTRL_SW2A_PANIC_MODE, panic_mode); + reg_mask = BITFMASK(MC13783_SWCTRL_SW2A_PANIC_MODE); + reg = REG_SWITCHERS_5; + break; + case SW_SW2B: + reg_val = BITFVAL(MC13783_SWCTRL_SW2B_PANIC_MODE, panic_mode); + reg_mask = BITFMASK(MC13783_SWCTRL_SW2B_PANIC_MODE); + reg = REG_SWITCHERS_5; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(reg, reg_val, reg_mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function gets the switch panic mode + * + * @param regulator The regulator to be handled + * @param panic_mode Enable or disable panic mode + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_switcher_get_panic_mode(t_pmic_regulator regulator, + bool *panic_mode) +{ + unsigned int reg_val = 0, reg_mask = 0; + unsigned int reg; + + switch (regulator) { + case SW_SW1A: + reg_mask = BITFMASK(MC13783_SWCTRL_SW1A_PANIC_MODE); + reg = REG_SWITCHERS_4; + break; + case SW_SW1B: + reg_mask = BITFMASK(MC13783_SWCTRL_SW1B_PANIC_MODE); + reg = REG_SWITCHERS_4; + break; + case SW_SW2A: + reg_mask = BITFMASK(MC13783_SWCTRL_SW2A_PANIC_MODE); + reg = REG_SWITCHERS_5; + break; + case SW_SW2B: + reg_mask = BITFMASK(MC13783_SWCTRL_SW2B_PANIC_MODE); + reg = REG_SWITCHERS_5; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_read_reg(reg, ®_val, reg_mask)); + + switch (regulator) { + case SW_SW1A: + *panic_mode = BITFEXT(reg_val, MC13783_SWCTRL_SW1A_PANIC_MODE); + break; + case SW_SW1B: + *panic_mode = BITFEXT(reg_val, MC13783_SWCTRL_SW1B_PANIC_MODE); + break; + case SW_SW2A: + *panic_mode = BITFEXT(reg_val, MC13783_SWCTRL_SW2A_PANIC_MODE); + break; + case SW_SW2B: + *panic_mode = BITFEXT(reg_val, MC13783_SWCTRL_SW2B_PANIC_MODE); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + return PMIC_SUCCESS; +} + +/*! + * This function sets the switch softstart mode + * + * @param regulator The regulator to be configured. + * @param softstart Enable or disable softstart. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_switcher_set_softstart(t_pmic_regulator regulator, + bool softstart) +{ + unsigned int reg_val = 0, reg_mask = 0; + unsigned int reg; + + switch (regulator) { + case SW_SW1A: + reg_val = BITFVAL(MC13783_SWCTRL_SW1A_SOFTSTART, softstart); + reg_mask = BITFMASK(MC13783_SWCTRL_SW1A_SOFTSTART); + reg = REG_SWITCHERS_4; + break; + case SW_SW1B: + reg_val = BITFVAL(MC13783_SWCTRL_SW2B_SOFTSTART, softstart); + reg_mask = BITFMASK(MC13783_SWCTRL_SW1B_SOFTSTART); + reg = REG_SWITCHERS_4; + break; + case SW_SW2A: + reg_val = BITFVAL(MC13783_SWCTRL_SW2A_SOFTSTART, softstart); + reg_mask = BITFMASK(MC13783_SWCTRL_SW2A_SOFTSTART); + reg = REG_SWITCHERS_5; + break; + case SW_SW2B: + reg_val = BITFVAL(MC13783_SWCTRL_SW2B_SOFTSTART, softstart); + reg_mask = BITFMASK(MC13783_SWCTRL_SW2B_SOFTSTART); + reg = REG_SWITCHERS_5; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(reg, reg_val, reg_mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function gets the switch softstart mode + * + * @param regulator The regulator to be handled + * @param softstart Enable or disable softstart. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_switcher_get_softstart(t_pmic_regulator regulator, + bool *softstart) +{ + unsigned int reg_val = 0, reg_mask = 0; + unsigned int reg; + + switch (regulator) { + case SW_SW1A: + reg_mask = BITFMASK(MC13783_SWCTRL_SW1A_SOFTSTART); + reg = REG_SWITCHERS_4; + break; + case SW_SW1B: + reg_mask = BITFMASK(MC13783_SWCTRL_SW1B_SOFTSTART); + reg = REG_SWITCHERS_4; + break; + case SW_SW2A: + reg_mask = BITFMASK(MC13783_SWCTRL_SW2A_SOFTSTART); + reg = REG_SWITCHERS_5; + break; + case SW_SW2B: + reg_mask = BITFMASK(MC13783_SWCTRL_SW2B_SOFTSTART); + reg = REG_SWITCHERS_5; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_read_reg(reg, ®_val, reg_mask)); + + switch (regulator) { + case SW_SW1A: + *softstart = BITFEXT(reg_val, MC13783_SWCTRL_SW1A_SOFTSTART); + break; + case SW_SW1B: + *softstart = BITFEXT(reg_val, MC13783_SWCTRL_SW2B_SOFTSTART); + break; + case SW_SW2A: + *softstart = BITFEXT(reg_val, MC13783_SWCTRL_SW2A_SOFTSTART); + break; + case SW_SW2B: + *softstart = BITFEXT(reg_val, MC13783_SWCTRL_SW2B_SOFTSTART); + break; + default: + break; + } + + return PMIC_SUCCESS; +} + +/*! + * This function sets the PLL multiplication factor + * + * @param regulator The regulator to be configured. + * @param factor The multiplication factor. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_switcher_set_factor(t_pmic_regulator regulator, + t_switcher_factor factor) +{ + unsigned int reg_val = 0, reg_mask = 0; + + if (regulator != SW_PLL) { + return PMIC_PARAMETER_ERROR; + } + if (factor < FACTOR_28 || factor > FACTOR_35) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_SWCTRL_PLL_FACTOR, factor); + reg_mask = BITFMASK(MC13783_SWCTRL_PLL_FACTOR); + + CHECK_ERROR(pmic_write_reg(REG_SWITCHERS_4, reg_val, reg_mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function gets the PLL multiplication factor + * + * @param regulator The regulator to be handled + * @param factor The multiplication factor. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_switcher_get_factor(t_pmic_regulator regulator, + t_switcher_factor *factor) +{ + unsigned int reg_val = 0, reg_mask = 0; + + if (regulator != SW_PLL) { + return PMIC_PARAMETER_ERROR; + } + reg_mask = BITFMASK(MC13783_SWCTRL_PLL_FACTOR); + + CHECK_ERROR(pmic_read_reg(REG_SWITCHERS_4, ®_val, reg_mask)); + + *factor = BITFEXT(reg_val, MC13783_SWCTRL_PLL_FACTOR); + + return PMIC_SUCCESS; +} + +/*! + * This function enables or disables low power mode. + * + * @param regulator The regulator to be configured. + * @param lp_mode Select nominal or low power mode. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_regulator_set_lp_mode(t_pmic_regulator regulator, + t_regulator_lp_mode lp_mode) +{ + unsigned int reg_val = 0, reg_mask = 0; + unsigned int reg; + unsigned int l_mode, l_stby; + + if (lp_mode == LOW_POWER_DISABLED) { + l_mode = MC13783_REGTRL_LP_MODE_DISABLE; + l_stby = MC13783_REGTRL_STBY_MODE_DISABLE; + } else if (lp_mode == LOW_POWER_CTRL_BY_PIN) { + l_mode = MC13783_REGTRL_LP_MODE_DISABLE; + l_stby = MC13783_REGTRL_STBY_MODE_ENABLE; + } else if (lp_mode == LOW_POWER_EN) { + l_mode = MC13783_REGTRL_LP_MODE_ENABLE; + l_stby = MC13783_REGTRL_STBY_MODE_DISABLE; + } else if (lp_mode == LOW_POWER_AND_LOW_POWER_CTRL_BY_PIN) { + l_mode = MC13783_REGTRL_LP_MODE_ENABLE; + l_stby = MC13783_REGTRL_STBY_MODE_ENABLE; + } else { + return PMIC_PARAMETER_ERROR; + } + + switch (regulator) { + case SW_SW3: + reg_val = BITFVAL(MC13783_SWCTRL_SW3_MODE, l_mode) | + BITFVAL(MC13783_SWCTRL_SW3_STBY, l_stby); + reg_mask = BITFMASK(MC13783_SWCTRL_SW3_MODE) | + BITFMASK(MC13783_SWCTRL_SW3_STBY); + reg = REG_SWITCHERS_5; + break; + case REGU_VAUDIO: + reg_val = BITFVAL(MC13783_REGCTRL_VAUDIO_MODE, l_mode) | + BITFVAL(MC13783_REGCTRL_VAUDIO_STBY, l_stby); + reg_mask = BITFMASK(MC13783_REGCTRL_VAUDIO_MODE) | + BITFMASK(MC13783_REGCTRL_VAUDIO_STBY); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VIOHI: + reg_val = BITFVAL(MC13783_REGCTRL_VIOHI_MODE, l_mode) | + BITFVAL(MC13783_REGCTRL_VIOHI_STBY, l_stby); + reg_mask = BITFMASK(MC13783_REGCTRL_VIOHI_MODE) | + BITFMASK(MC13783_REGCTRL_VIOHI_STBY); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VIOLO: + reg_val = BITFVAL(MC13783_REGCTRL_VIOLO_MODE, l_mode) | + BITFVAL(MC13783_REGCTRL_VIOLO_STBY, l_stby); + reg_mask = BITFMASK(MC13783_REGCTRL_VIOLO_MODE) | + BITFMASK(MC13783_REGCTRL_VIOLO_STBY); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VDIG: + reg_val = BITFVAL(MC13783_REGCTRL_VDIG_MODE, l_mode) | + BITFVAL(MC13783_REGCTRL_VDIG_STBY, l_stby); + reg_mask = BITFMASK(MC13783_REGCTRL_VDIG_MODE) | + BITFMASK(MC13783_REGCTRL_VDIG_STBY); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VGEN: + reg_val = BITFVAL(MC13783_REGCTRL_VGEN_MODE, l_mode) | + BITFVAL(MC13783_REGCTRL_VGEN_STBY, l_stby); + reg_mask = BITFMASK(MC13783_REGCTRL_VGEN_MODE) | + BITFMASK(MC13783_REGCTRL_VGEN_STBY); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VRFDIG: + reg_val = BITFVAL(MC13783_REGCTRL_VRFDIG_MODE, l_mode) | + BITFVAL(MC13783_REGCTRL_VRFDIG_STBY, l_stby); + reg_mask = BITFMASK(MC13783_REGCTRL_VRFDIG_MODE) | + BITFMASK(MC13783_REGCTRL_VRFDIG_STBY); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VRFREF: + reg_val = BITFVAL(MC13783_REGCTRL_VRFREF_MODE, l_mode) | + BITFVAL(MC13783_REGCTRL_VRFREF_STBY, l_stby); + reg_mask = BITFMASK(MC13783_REGCTRL_VRFREF_MODE) | + BITFMASK(MC13783_REGCTRL_VRFREF_STBY); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VRFCP: + reg_val = BITFVAL(MC13783_REGCTRL_VRFCP_MODE, l_mode) | + BITFVAL(MC13783_REGCTRL_VRFCP_STBY, l_stby); + reg_mask = BITFMASK(MC13783_REGCTRL_VRFCP_MODE) | + BITFMASK(MC13783_REGCTRL_VRFCP_STBY); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VSIM: + reg_val = BITFVAL(MC13783_REGCTRL_VSIM_MODE, l_mode) | + BITFVAL(MC13783_REGCTRL_VSIM_STBY, l_stby); + reg_mask = BITFMASK(MC13783_REGCTRL_VSIM_MODE) | + BITFMASK(MC13783_REGCTRL_VSIM_STBY); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VESIM: + reg_val = BITFVAL(MC13783_REGCTRL_VESIM_MODE, l_mode) | + BITFVAL(MC13783_REGCTRL_VESIM_STBY, l_stby); + reg_mask = BITFMASK(MC13783_REGCTRL_VESIM_MODE) | + BITFMASK(MC13783_REGCTRL_VESIM_STBY); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VCAM: + reg_val = BITFVAL(MC13783_REGCTRL_VCAM_MODE, l_mode) | + BITFVAL(MC13783_REGCTRL_VCAM_STBY, l_stby); + reg_mask = BITFMASK(MC13783_REGCTRL_VCAM_MODE) | + BITFMASK(MC13783_REGCTRL_VCAM_STBY); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VRFBG: + if ((lp_mode == LOW_POWER) || + (lp_mode == LOW_POWER_AND_LOW_POWER_CTRL_BY_PIN)) { + return PMIC_PARAMETER_ERROR; + } + reg_val = BITFVAL(MC13783_REGCTRL_VRFBG_STBY, l_mode); + reg_mask = BITFMASK(MC13783_REGCTRL_VRFBG_STBY); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VRF1: + reg_val = BITFVAL(MC13783_REGCTRL_VRF1_MODE, l_mode) | + BITFVAL(MC13783_REGCTRL_VRF1_STBY, l_stby); + reg_mask = BITFMASK(MC13783_REGCTRL_VRF1_MODE) | + BITFMASK(MC13783_REGCTRL_VRF1_STBY); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VRF2: + reg_val = BITFVAL(MC13783_REGCTRL_VRF2_MODE, l_mode) | + BITFVAL(MC13783_REGCTRL_VRF2_STBY, l_stby); + reg_mask = BITFMASK(MC13783_REGCTRL_VRF2_MODE) | + BITFMASK(MC13783_REGCTRL_VRF2_STBY); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VMMC1: + reg_val = BITFVAL(MC13783_REGCTRL_VMMC1_MODE, l_mode) | + BITFVAL(MC13783_REGCTRL_VMMC1_STBY, l_stby); + reg_mask = BITFMASK(MC13783_REGCTRL_VMMC1_MODE) | + BITFMASK(MC13783_REGCTRL_VMMC1_STBY); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VMMC2: + reg_val = BITFVAL(MC13783_REGCTRL_VMMC2_MODE, l_mode) | + BITFVAL(MC13783_REGCTRL_VMMC2_STBY, l_stby); + reg_mask = BITFMASK(MC13783_REGCTRL_VMMC2_MODE) | + BITFMASK(MC13783_REGCTRL_VMMC2_STBY); + reg = REG_REGULATOR_MODE_1; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(reg, reg_val, reg_mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function gets low power mode. + * + * @param regulator The regulator to be handled + * @param lp_mode Select nominal or low power mode. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_regulator_get_lp_mode(t_pmic_regulator regulator, + t_regulator_lp_mode *lp_mode) +{ + unsigned int reg_val = 0, reg_mask = 0; + unsigned int reg; + unsigned int l_mode, l_stby; + + switch (regulator) { + case SW_SW3: + reg_mask = BITFMASK(MC13783_SWCTRL_SW3_MODE) | + BITFMASK(MC13783_SWCTRL_SW3_STBY); + reg = REG_SWITCHERS_5; + break; + case REGU_VAUDIO: + reg_mask = BITFMASK(MC13783_REGCTRL_VAUDIO_MODE) | + BITFMASK(MC13783_REGCTRL_VAUDIO_STBY); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VIOHI: + reg_mask = BITFMASK(MC13783_REGCTRL_VIOHI_MODE) | + BITFMASK(MC13783_REGCTRL_VIOHI_STBY); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VIOLO: + reg_mask = BITFMASK(MC13783_REGCTRL_VIOLO_MODE) | + BITFMASK(MC13783_REGCTRL_VIOLO_STBY); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VDIG: + reg_mask = BITFMASK(MC13783_REGCTRL_VDIG_MODE) | + BITFMASK(MC13783_REGCTRL_VDIG_STBY); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VGEN: + reg_mask = BITFMASK(MC13783_REGCTRL_VGEN_MODE) | + BITFMASK(MC13783_REGCTRL_VGEN_STBY); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VRFDIG: + reg_mask = BITFMASK(MC13783_REGCTRL_VRFDIG_MODE) | + BITFMASK(MC13783_REGCTRL_VRFDIG_STBY); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VRFREF: + reg_mask = BITFMASK(MC13783_REGCTRL_VRFREF_MODE) | + BITFMASK(MC13783_REGCTRL_VRFREF_STBY); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VRFCP: + reg_mask = BITFMASK(MC13783_REGCTRL_VRFCP_MODE) | + BITFMASK(MC13783_REGCTRL_VRFCP_STBY); + reg = REG_REGULATOR_MODE_0; + break; + case REGU_VSIM: + reg_mask = BITFMASK(MC13783_REGCTRL_VSIM_MODE) | + BITFMASK(MC13783_REGCTRL_VSIM_STBY); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VESIM: + reg_mask = BITFMASK(MC13783_REGCTRL_VESIM_MODE) | + BITFMASK(MC13783_REGCTRL_VESIM_STBY); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VCAM: + reg_mask = BITFMASK(MC13783_REGCTRL_VCAM_MODE) | + BITFMASK(MC13783_REGCTRL_VCAM_STBY); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VRFBG: + reg_mask = BITFMASK(MC13783_REGCTRL_VRFBG_STBY); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VRF1: + reg_mask = BITFMASK(MC13783_REGCTRL_VRF1_MODE) | + BITFMASK(MC13783_REGCTRL_VRF1_STBY); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VRF2: + reg_mask = BITFMASK(MC13783_REGCTRL_VRF2_MODE) | + BITFMASK(MC13783_REGCTRL_VRF2_STBY); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VMMC1: + reg_mask = BITFMASK(MC13783_REGCTRL_VMMC1_MODE) | + BITFMASK(MC13783_REGCTRL_VMMC1_STBY); + reg = REG_REGULATOR_MODE_1; + break; + case REGU_VMMC2: + reg_mask = BITFMASK(MC13783_REGCTRL_VMMC2_MODE) | + BITFMASK(MC13783_REGCTRL_VMMC2_STBY); + reg = REG_REGULATOR_MODE_1; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_read_reg(reg, ®_val, reg_mask)); + + switch (regulator) { + case SW_SW3: + l_mode = BITFEXT(reg_val, MC13783_SWCTRL_SW3_MODE); + l_stby = BITFEXT(reg_val, MC13783_SWCTRL_SW3_STBY); + break; + case REGU_VAUDIO: + l_mode = BITFEXT(reg_val, MC13783_REGCTRL_VAUDIO_MODE); + l_stby = BITFEXT(reg_val, MC13783_REGCTRL_VAUDIO_STBY); + break; + case REGU_VIOHI: + l_mode = BITFEXT(reg_val, MC13783_REGCTRL_VIOHI_MODE); + l_stby = BITFEXT(reg_val, MC13783_REGCTRL_VIOHI_STBY); + break; + case REGU_VIOLO: + l_mode = BITFEXT(reg_val, MC13783_REGCTRL_VIOLO_MODE); + l_stby = BITFEXT(reg_val, MC13783_REGCTRL_VIOLO_STBY); + break; + case REGU_VDIG: + l_mode = BITFEXT(reg_val, MC13783_REGCTRL_VDIG_MODE); + l_stby = BITFEXT(reg_val, MC13783_REGCTRL_VDIG_STBY); + break; + case REGU_VGEN: + l_mode = BITFEXT(reg_val, MC13783_REGCTRL_VGEN_MODE); + l_stby = BITFEXT(reg_val, MC13783_REGCTRL_VGEN_STBY); + break; + case REGU_VRFDIG: + l_mode = BITFEXT(reg_val, MC13783_REGCTRL_VRFDIG_MODE); + l_stby = BITFEXT(reg_val, MC13783_REGCTRL_VRFDIG_STBY); + break; + case REGU_VRFREF: + l_mode = BITFEXT(reg_val, MC13783_REGCTRL_VRFREF_MODE); + l_stby = BITFEXT(reg_val, MC13783_REGCTRL_VRFREF_STBY); + break; + case REGU_VRFCP: + l_mode = BITFEXT(reg_val, MC13783_REGCTRL_VRFCP_MODE); + l_stby = BITFEXT(reg_val, MC13783_REGCTRL_VRFCP_STBY); + break; + case REGU_VSIM: + l_mode = BITFEXT(reg_val, MC13783_REGCTRL_VSIM_MODE); + l_stby = BITFEXT(reg_val, MC13783_REGCTRL_VSIM_STBY); + break; + case REGU_VESIM: + l_mode = BITFEXT(reg_val, MC13783_REGCTRL_VESIM_MODE); + l_stby = BITFEXT(reg_val, MC13783_REGCTRL_VESIM_STBY); + break; + case REGU_VCAM: + l_mode = BITFEXT(reg_val, MC13783_REGCTRL_VCAM_MODE); + l_stby = BITFEXT(reg_val, MC13783_REGCTRL_VCAM_STBY); + break; + case REGU_VRFBG: + l_mode = MC13783_REGTRL_LP_MODE_DISABLE; + l_stby = BITFEXT(reg_val, MC13783_REGCTRL_VRFBG_STBY); + break; + case REGU_VRF1: + l_mode = BITFEXT(reg_val, MC13783_REGCTRL_VRF1_MODE); + l_stby = BITFEXT(reg_val, MC13783_REGCTRL_VRF1_STBY); + break; + case REGU_VRF2: + l_mode = BITFEXT(reg_val, MC13783_REGCTRL_VRF2_MODE); + l_stby = BITFEXT(reg_val, MC13783_REGCTRL_VRF2_STBY); + break; + case REGU_VMMC1: + l_mode = BITFEXT(reg_val, MC13783_REGCTRL_VMMC1_MODE); + l_stby = BITFEXT(reg_val, MC13783_REGCTRL_VMMC1_STBY); + break; + case REGU_VMMC2: + l_mode = BITFEXT(reg_val, MC13783_REGCTRL_VMMC2_MODE); + l_stby = BITFEXT(reg_val, MC13783_REGCTRL_VMMC2_STBY); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + if ((l_mode == MC13783_REGTRL_LP_MODE_DISABLE) && + (l_stby == MC13783_REGTRL_STBY_MODE_DISABLE)) { + *lp_mode = LOW_POWER_DISABLED; + } else if ((l_mode == MC13783_REGTRL_LP_MODE_DISABLE) && + (l_stby == MC13783_REGTRL_STBY_MODE_ENABLE)) { + *lp_mode = LOW_POWER_CTRL_BY_PIN; + } else if ((l_mode == MC13783_REGTRL_LP_MODE_ENABLE) && + (l_stby == MC13783_REGTRL_STBY_MODE_DISABLE)) { + *lp_mode = LOW_POWER_EN; + } else { + *lp_mode = LOW_POWER_AND_LOW_POWER_CTRL_BY_PIN; + } + + return PMIC_SUCCESS; +} + +/*! + * This function sets the regulator configuration. + * + * @param regulator The regulator to be configured. + * @param config The regulator output configuration. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_regulator_set_config(t_pmic_regulator regulator, + t_regulator_config *config) +{ + if (config == NULL) { + return PMIC_ERROR; + } + + switch (regulator) { + case SW_SW1A: + case SW_SW1B: + case SW_SW2A: + case SW_SW2B: + CHECK_ERROR(pmic_power_regulator_set_voltage + (regulator, config->voltage)); + CHECK_ERROR(pmic_power_switcher_set_dvs + (regulator, config->voltage_lvs)); + CHECK_ERROR(pmic_power_switcher_set_stby + (regulator, config->voltage_stby)); + CHECK_ERROR(pmic_power_switcher_set_mode + (regulator, config->mode, false)); + CHECK_ERROR(pmic_power_switcher_set_mode + (regulator, config->stby_mode, true)); + CHECK_ERROR(pmic_power_switcher_set_dvs_speed + (regulator, config->dvs_speed)); + CHECK_ERROR(pmic_power_switcher_set_panic_mode + (regulator, config->panic_mode)); + CHECK_ERROR(pmic_power_switcher_set_softstart + (regulator, config->softstart)); + break; + case SW_PLL: + CHECK_ERROR(pmic_power_switcher_set_factor + (regulator, config->factor)); + break; + case SW_SW3: + case REGU_VIOLO: + case REGU_VDIG: + case REGU_VGEN: + case REGU_VRFDIG: + case REGU_VRFREF: + case REGU_VRFCP: + case REGU_VSIM: + case REGU_VESIM: + case REGU_VCAM: + case REGU_VRF1: + case REGU_VRF2: + case REGU_VMMC1: + case REGU_VMMC2: + CHECK_ERROR(pmic_power_regulator_set_voltage + (regulator, config->voltage)); + CHECK_ERROR(pmic_power_regulator_set_lp_mode + (regulator, config->lp_mode)); + break; + case REGU_VVIB: + CHECK_ERROR(pmic_power_regulator_set_voltage + (regulator, config->voltage)); + break; + case REGU_VAUDIO: + case REGU_VIOHI: + case REGU_VRFBG: + CHECK_ERROR(pmic_power_regulator_set_lp_mode + (regulator, config->lp_mode)); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + return PMIC_SUCCESS; +} + +/*! + * This function retrives the regulator output configuration. + * + * @param regulator The regulator to be truned off. + * @param config Pointer to regulator configuration. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_regulator_get_config(t_pmic_regulator regulator, + t_regulator_config *config) +{ + if (config == NULL) { + return PMIC_ERROR; + } + + switch (regulator) { + case SW_SW1A: + case SW_SW1B: + case SW_SW2A: + case SW_SW2B: + CHECK_ERROR(pmic_power_regulator_get_voltage + (regulator, &config->voltage)); + CHECK_ERROR(pmic_power_switcher_get_dvs + (regulator, &config->voltage_lvs)); + CHECK_ERROR(pmic_power_switcher_get_stby + (regulator, &config->voltage_stby)); + CHECK_ERROR(pmic_power_switcher_get_mode + (regulator, &config->mode, false)); + CHECK_ERROR(pmic_power_switcher_get_mode + (regulator, &config->stby_mode, true)); + CHECK_ERROR(pmic_power_switcher_get_dvs_speed + (regulator, &config->dvs_speed)); + CHECK_ERROR(pmic_power_switcher_get_panic_mode + (regulator, &config->panic_mode)); + CHECK_ERROR(pmic_power_switcher_get_softstart + (regulator, &config->softstart)); + break; + case SW_PLL: + CHECK_ERROR(pmic_power_switcher_get_factor + (regulator, &config->factor)); + break; + case SW_SW3: + case REGU_VIOLO: + case REGU_VDIG: + case REGU_VGEN: + case REGU_VRFDIG: + case REGU_VRFREF: + case REGU_VRFCP: + case REGU_VSIM: + case REGU_VESIM: + case REGU_VCAM: + case REGU_VRF1: + case REGU_VRF2: + case REGU_VMMC1: + case REGU_VMMC2: + CHECK_ERROR(pmic_power_regulator_get_voltage + (regulator, &config->voltage)); + CHECK_ERROR(pmic_power_regulator_get_lp_mode + (regulator, &config->lp_mode)); + break; + case REGU_VVIB: + CHECK_ERROR(pmic_power_regulator_get_voltage + (regulator, &config->voltage)); + break; + case REGU_VAUDIO: + case REGU_VIOHI: + case REGU_VRFBG: + CHECK_ERROR(pmic_power_regulator_get_lp_mode + (regulator, &config->lp_mode)); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + return PMIC_SUCCESS; +} + +/*! + * This function enables automatically VBKUP2 in the memory hold modes. + * Only on mc13783 2.0 or higher + * + * @param en if true, enable VBKUP2AUTOMH + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_vbkup2_auto_en(bool en) +{ + unsigned int reg_val = 0, reg_mask = 0; + pmic_version_t mc13783_ver; + mc13783_ver = pmic_get_version(); + if (mc13783_ver.revision >= 20) { + reg_val = BITFVAL(MC13783_REGCTRL_VBKUP2AUTOMH, en); + reg_mask = BITFMASK(MC13783_REGCTRL_VBKUP2AUTOMH); + + CHECK_ERROR(pmic_write_reg(REG_POWER_CONTROL_0, + reg_val, reg_mask)); + return PMIC_SUCCESS; + } else { + return PMIC_NOT_SUPPORTED; + } +} + +/*! + * This function gets state of automatically VBKUP2. + * Only on mc13783 2.0 or higher + * + * @param en if true, VBKUP2AUTOMH is enabled + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_get_vbkup2_auto_state(bool *en) +{ + unsigned int reg_val = 0, reg_mask = 0; + pmic_version_t mc13783_ver; + mc13783_ver = pmic_get_version(); + if (mc13783_ver.revision >= 20) { + reg_mask = BITFMASK(MC13783_REGCTRL_VBKUP2AUTOMH); + CHECK_ERROR(pmic_read_reg(REG_POWER_CONTROL_0, + ®_val, reg_mask)); + *en = BITFEXT(reg_val, MC13783_REGCTRL_VBKUP2AUTOMH); + + return PMIC_SUCCESS; + } else { + return PMIC_NOT_SUPPORTED; + } +} + +/*! + * This function enables battery detect function. + * Only on mc13783 2.0 or higher + * + * @param en if true, enable BATTDETEN + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_bat_det_en(bool en) +{ + unsigned int reg_val = 0, reg_mask = 0; + pmic_version_t mc13783_ver; + mc13783_ver = pmic_get_version(); + if (mc13783_ver.revision >= 20) { + reg_val = BITFVAL(MC13783_REGCTRL_BATTDETEN, en); + reg_mask = BITFMASK(MC13783_REGCTRL_BATTDETEN); + + CHECK_ERROR(pmic_write_reg(REG_POWER_CONTROL_0, + reg_val, reg_mask)); + return PMIC_SUCCESS; + } else { + return PMIC_NOT_SUPPORTED; + } +} + +/*! + * This function gets state of battery detect function. + * Only on mc13783 2.0 or higher + * + * @param en if true, BATTDETEN is enabled + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_get_bat_det_state(bool *en) +{ + unsigned int reg_val = 0, reg_mask = 0; + pmic_version_t mc13783_ver; + mc13783_ver = pmic_get_version(); + if (mc13783_ver.revision >= 20) { + reg_mask = BITFMASK(MC13783_REGCTRL_BATTDETEN); + + CHECK_ERROR(pmic_read_reg(REG_POWER_CONTROL_0, + ®_val, reg_mask)); + *en = BITFEXT(reg_val, MC13783_REGCTRL_BATTDETEN); + return PMIC_SUCCESS; + } else { + return PMIC_NOT_SUPPORTED; + } +} + +/*! + * This function enables control of VVIB by VIBEN pin. + * Only on mc13783 2.0 or higher + * + * @param en if true, enable VIBPINCTRL + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_vib_pin_en(bool en) +{ + unsigned int reg_val = 0, reg_mask = 0; + pmic_version_t mc13783_ver; + mc13783_ver = pmic_get_version(); + if (mc13783_ver.revision >= 20) { + reg_val = BITFVAL(MC13783_REGCTRL_VIBPINCTRL, en); + reg_mask = BITFMASK(MC13783_REGCTRL_VIBPINCTRL); + + CHECK_ERROR(pmic_write_reg(REG_POWER_MISCELLANEOUS, + reg_val, reg_mask)); + return PMIC_SUCCESS; + } else { + return PMIC_NOT_SUPPORTED; + } +} + +/*! + * This function gets state of control of VVIB by VIBEN pin. + * Only on mc13783 2.0 or higher + * @param en if true, VIBPINCTRL is enabled + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_gets_vib_pin_state(bool *en) +{ + unsigned int reg_val = 0, reg_mask = 0; + pmic_version_t mc13783_ver; + mc13783_ver = pmic_get_version(); + if (mc13783_ver.revision >= 20) { + reg_mask = BITFMASK(MC13783_REGCTRL_VIBPINCTRL); + CHECK_ERROR(pmic_read_reg(REG_POWER_MISCELLANEOUS, + ®_val, reg_mask)); + *en = BITFEXT(reg_val, MC13783_REGCTRL_VIBPINCTRL); + return PMIC_SUCCESS; + } else { + return PMIC_NOT_SUPPORTED; + } +} + +/*! + * This function returns power up sense value + * + * @param p_up_sense value of power up sense + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_power_get_power_mode_sense(struct t_p_up_sense *p_up_sense) +{ + unsigned int reg_value = 0; + CHECK_ERROR(pmic_read_reg(REG_POWER_UP_MODE_SENSE, + ®_value, PMIC_ALL_BITS)); + p_up_sense->state_ictest = (STATE_ICTEST_MASK & reg_value); + p_up_sense->state_clksel = ((STATE_CLKSEL_MASK & reg_value) + >> STATE_CLKSEL_BIT); + p_up_sense->state_pums1 = ((STATE_PUMS1_MASK & reg_value) + >> STATE_PUMS1_BITS); + p_up_sense->state_pums2 = ((STATE_PUMS2_MASK & reg_value) + >> STATE_PUMS2_BITS); + p_up_sense->state_pums3 = ((STATE_PUMS3_MASK & reg_value) + >> STATE_PUMS3_BITS); + p_up_sense->state_chrgmode0 = ((STATE_CHRGM1_MASK & reg_value) + >> STATE_CHRGM1_BITS); + p_up_sense->state_chrgmode1 = ((STATE_CHRGM2_MASK & reg_value) + >> STATE_CHRGM2_BITS); + p_up_sense->state_umod = ((STATE_UMOD_MASK & reg_value) + >> STATE_UMOD_BITS); + p_up_sense->state_usben = ((STATE_USBEN_MASK & reg_value) + >> STATE_USBEN_BIT); + p_up_sense->state_sw_1a1b_joined = ((STATE_SW1A_J_B_MASK & reg_value) + >> STATE_SW1A_J_B_BIT); + p_up_sense->state_sw_2a2b_joined = ((STATE_SW2A_J_B_MASK & reg_value) + >> STATE_SW2A_J_B_BIT); + return PMIC_SUCCESS; +} + +/*! + * This function configures the Regen assignment for all regulator + * + * @param regulator type of regulator + * @param en_dis if true, the regulator is enabled by regen. + * + * @return This function returns 0 if successful. + */ +PMIC_STATUS pmic_power_set_regen_assig(t_pmic_regulator regulator, bool en_dis) +{ + unsigned int reg_val = 0, reg_mask = 0; + + switch (regulator) { + case REGU_VAUDIO: + reg_val = BITFVAL(MC13783_REGGEN_VAUDIO, en_dis); + reg_mask = BITFMASK(MC13783_REGGEN_VAUDIO); + break; + case REGU_VIOHI: + reg_val = BITFVAL(MC13783_REGGEN_VIOHI, en_dis); + reg_mask = BITFMASK(MC13783_REGGEN_VIOHI); + break; + case REGU_VIOLO: + reg_val = BITFVAL(MC13783_REGGEN_VIOLO, en_dis); + reg_mask = BITFMASK(MC13783_REGGEN_VIOLO); + break; + case REGU_VDIG: + reg_val = BITFVAL(MC13783_REGGEN_VDIG, en_dis); + reg_mask = BITFMASK(MC13783_REGGEN_VDIG); + break; + case REGU_VGEN: + reg_val = BITFVAL(MC13783_REGGEN_VGEN, en_dis); + reg_mask = BITFMASK(MC13783_REGGEN_VGEN); + break; + case REGU_VRFDIG: + reg_val = BITFVAL(MC13783_REGGEN_VRFDIG, en_dis); + reg_mask = BITFMASK(MC13783_REGGEN_VRFDIG); + break; + case REGU_VRFREF: + reg_val = BITFVAL(MC13783_REGGEN_VRFREF, en_dis); + reg_mask = BITFMASK(MC13783_REGGEN_VRFREF); + break; + case REGU_VRFCP: + reg_val = BITFVAL(MC13783_REGGEN_VRFCP, en_dis); + reg_mask = BITFMASK(MC13783_REGGEN_VRFCP); + break; + case REGU_VCAM: + reg_val = BITFVAL(MC13783_REGGEN_VCAM, en_dis); + reg_mask = BITFMASK(MC13783_REGGEN_VCAM); + break; + case REGU_VRFBG: + reg_val = BITFVAL(MC13783_REGGEN_VRFBG, en_dis); + reg_mask = BITFMASK(MC13783_REGGEN_VRFBG); + break; + case REGU_VRF1: + reg_val = BITFVAL(MC13783_REGGEN_VRF1, en_dis); + reg_mask = BITFMASK(MC13783_REGGEN_VRF1); + break; + case REGU_VRF2: + reg_val = BITFVAL(MC13783_REGGEN_VRF2, en_dis); + reg_mask = BITFMASK(MC13783_REGGEN_VRF2); + break; + case REGU_VMMC1: + reg_val = BITFVAL(MC13783_REGGEN_VMMC1, en_dis); + reg_mask = BITFMASK(MC13783_REGGEN_VMMC1); + break; + case REGU_VMMC2: + reg_val = BITFVAL(MC13783_REGGEN_VMMC2, en_dis); + reg_mask = BITFMASK(MC13783_REGGEN_VMMC2); + break; + case REGU_GPO1: + reg_val = BITFVAL(MC13783_REGGEN_GPO1, en_dis); + reg_mask = BITFMASK(MC13783_REGGEN_GPO1); + break; + case REGU_GPO2: + reg_val = BITFVAL(MC13783_REGGEN_GPO2, en_dis); + reg_mask = BITFMASK(MC13783_REGGEN_GPO2); + break; + case REGU_GPO3: + reg_val = BITFVAL(MC13783_REGGEN_GPO3, en_dis); + reg_mask = BITFMASK(MC13783_REGGEN_GPO3); + break; + case REGU_GPO4: + reg_val = BITFVAL(MC13783_REGGEN_GPO4, en_dis); + reg_mask = BITFMASK(MC13783_REGGEN_GPO4); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(REG_REGEN_ASSIGNMENT, reg_val, reg_mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function gets the Regen assignment for all regulator + * + * @param regulator type of regulator + * @param en_dis return value, if true : + * the regulator is enabled by regen. + * @return This function returns 0 if successful. + */ +PMIC_STATUS pmic_power_get_regen_assig(t_pmic_regulator regulator, + bool *en_dis) +{ + unsigned int reg_val = 0, reg_mask = 0; + + switch (regulator) { + case REGU_VAUDIO: + reg_mask = BITFMASK(MC13783_REGGEN_VAUDIO); + break; + case REGU_VIOHI: + reg_mask = BITFMASK(MC13783_REGGEN_VIOHI); + break; + case REGU_VIOLO: + reg_mask = BITFMASK(MC13783_REGGEN_VIOLO); + break; + case REGU_VDIG: + reg_mask = BITFMASK(MC13783_REGGEN_VDIG); + break; + case REGU_VGEN: + reg_mask = BITFMASK(MC13783_REGGEN_VGEN); + break; + case REGU_VRFDIG: + reg_mask = BITFMASK(MC13783_REGGEN_VRFDIG); + break; + case REGU_VRFREF: + reg_mask = BITFMASK(MC13783_REGGEN_VRFREF); + break; + case REGU_VRFCP: + reg_mask = BITFMASK(MC13783_REGGEN_VRFCP); + break; + case REGU_VCAM: + reg_mask = BITFMASK(MC13783_REGGEN_VCAM); + break; + case REGU_VRFBG: + reg_mask = BITFMASK(MC13783_REGGEN_VRFBG); + break; + case REGU_VRF1: + reg_mask = BITFMASK(MC13783_REGGEN_VRF1); + break; + case REGU_VRF2: + reg_mask = BITFMASK(MC13783_REGGEN_VRF2); + break; + case REGU_VMMC1: + reg_mask = BITFMASK(MC13783_REGGEN_VMMC1); + break; + case REGU_VMMC2: + reg_mask = BITFMASK(MC13783_REGGEN_VMMC2); + break; + case REGU_GPO1: + reg_mask = BITFMASK(MC13783_REGGEN_GPO1); + break; + case REGU_GPO2: + reg_mask = BITFMASK(MC13783_REGGEN_GPO2); + break; + case REGU_GPO3: + reg_mask = BITFMASK(MC13783_REGGEN_GPO3); + break; + case REGU_GPO4: + reg_mask = BITFMASK(MC13783_REGGEN_GPO4); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_read_reg(REG_REGEN_ASSIGNMENT, ®_val, reg_mask)); + + switch (regulator) { + case REGU_VAUDIO: + *en_dis = BITFEXT(reg_val, MC13783_REGGEN_VAUDIO); + break; + case REGU_VIOHI: + *en_dis = BITFEXT(reg_val, MC13783_REGGEN_VIOHI); + break; + case REGU_VIOLO: + *en_dis = BITFEXT(reg_val, MC13783_REGGEN_VIOLO); + break; + case REGU_VDIG: + *en_dis = BITFEXT(reg_val, MC13783_REGGEN_VDIG); + break; + case REGU_VGEN: + *en_dis = BITFEXT(reg_val, MC13783_REGGEN_VGEN); + break; + case REGU_VRFDIG: + *en_dis = BITFEXT(reg_val, MC13783_REGGEN_VRFDIG); + break; + case REGU_VRFREF: + *en_dis = BITFEXT(reg_val, MC13783_REGGEN_VRFREF); + break; + case REGU_VRFCP: + *en_dis = BITFEXT(reg_val, MC13783_REGGEN_VRFCP); + break; + case REGU_VCAM: + *en_dis = BITFEXT(reg_val, MC13783_REGGEN_VCAM); + break; + case REGU_VRFBG: + *en_dis = BITFEXT(reg_val, MC13783_REGGEN_VRFBG); + break; + case REGU_VRF1: + *en_dis = BITFEXT(reg_val, MC13783_REGGEN_VRF1); + break; + case REGU_VRF2: + *en_dis = BITFEXT(reg_val, MC13783_REGGEN_VRF2); + break; + case REGU_VMMC1: + *en_dis = BITFEXT(reg_val, MC13783_REGGEN_VMMC1); + break; + case REGU_VMMC2: + *en_dis = BITFEXT(reg_val, MC13783_REGGEN_VMMC2); + break; + case REGU_GPO1: + *en_dis = BITFEXT(reg_val, MC13783_REGGEN_GPO1); + break; + case REGU_GPO2: + *en_dis = BITFEXT(reg_val, MC13783_REGGEN_GPO2); + break; + case REGU_GPO3: + *en_dis = BITFEXT(reg_val, MC13783_REGGEN_GPO3); + break; + case REGU_GPO4: + *en_dis = BITFEXT(reg_val, MC13783_REGGEN_GPO4); + break; + default: + break; + } + + return PMIC_SUCCESS; +} + +/*! + * This function sets the Regen polarity. + * + * @param en_dis If true regen is inverted. + * + * @return This function returns 0 if successful. + */ +PMIC_STATUS pmic_power_set_regen_inv(bool en_dis) +{ + unsigned int reg_val = 0, reg_mask = 0; + + reg_val = BITFVAL(MC13783_REGGEN_INV, en_dis); + reg_mask = BITFMASK(MC13783_REGGEN_INV); + + CHECK_ERROR(pmic_write_reg(REG_REGEN_ASSIGNMENT, reg_val, reg_mask)); + return PMIC_SUCCESS; +} + +/*! + * This function gets the Regen polarity. + * + * @param en_dis If true regen is inverted. + * + * @return This function returns 0 if successful. + */ +PMIC_STATUS pmic_power_get_regen_inv(bool *en_dis) +{ + unsigned int reg_val = 0, reg_mask = 0; + + reg_mask = BITFMASK(MC13783_REGGEN_INV); + CHECK_ERROR(pmic_read_reg(REG_REGEN_ASSIGNMENT, ®_val, reg_mask)); + *en_dis = BITFEXT(reg_val, MC13783_REGGEN_INV); + return PMIC_SUCCESS; +} + +/*! + * This function enables esim control voltage. + * Only on mc13783 2.0 or higher + * + * @param vesim if true, enable VESIMESIMEN + * @param vmmc1 if true, enable VMMC1ESIMEN + * @param vmmc2 if true, enable VMMC2ESIMEN + * + * @return This function returns 0 if successful. + */ +PMIC_STATUS pmic_power_esim_v_en(bool vesim, bool vmmc1, bool vmmc2) +{ + unsigned int reg_val = 0, reg_mask = 0; + pmic_version_t mc13783_ver; + mc13783_ver = pmic_get_version(); + if (mc13783_ver.revision >= 20) { + reg_val = BITFVAL(MC13783_REGGEN_VESIMESIM, vesim) | + BITFVAL(MC13783_REGGEN_VMMC1ESIM, vesim) | + BITFVAL(MC13783_REGGEN_VMMC2ESIM, vesim); + reg_mask = BITFMASK(MC13783_REGGEN_VESIMESIM) | + BITFMASK(MC13783_REGGEN_VMMC1ESIM) | + BITFMASK(MC13783_REGGEN_VMMC2ESIM); + CHECK_ERROR(pmic_write_reg(REG_REGEN_ASSIGNMENT, + reg_val, reg_mask)); + return PMIC_SUCCESS; + } else { + return PMIC_NOT_SUPPORTED; + } +} + +/*! + * This function gets esim control voltage values. + * Only on mc13783 2.0 or higher + * + * @param vesim if true, enable VESIMESIMEN + * @param vmmc1 if true, enable VMMC1ESIMEN + * @param vmmc2 if true, enable VMMC2ESIMEN + * + * @return This function returns 0 if successful. + */ +PMIC_STATUS pmic_power_gets_esim_v_state(bool *vesim, bool *vmmc1, + bool *vmmc2) +{ + unsigned int reg_val = 0, reg_mask = 0; + pmic_version_t mc13783_ver; + mc13783_ver = pmic_get_version(); + if (mc13783_ver.revision >= 20) { + reg_mask = BITFMASK(MC13783_REGGEN_VESIMESIM) | + BITFMASK(MC13783_REGGEN_VMMC1ESIM) | + BITFMASK(MC13783_REGGEN_VMMC2ESIM); + CHECK_ERROR(pmic_read_reg(REG_REGEN_ASSIGNMENT, + ®_val, reg_mask)); + *vesim = BITFEXT(reg_val, MC13783_REGGEN_VESIMESIM); + *vmmc1 = BITFEXT(reg_val, MC13783_REGGEN_VMMC1ESIM); + *vmmc2 = BITFEXT(reg_val, MC13783_REGGEN_VMMC2ESIM); + return PMIC_SUCCESS; + } else { + return PMIC_NOT_SUPPORTED; + } +} + +/*! + * This function enables auto reset after a system reset. + * + * @param en if true, the auto reset is enabled + * + * @return This function returns 0 if successful. + */ +PMIC_STATUS pmic_power_set_auto_reset_en(bool en) +{ + unsigned int reg_val = 0, reg_mask = 0; + + reg_val = BITFVAL(MC13783_AUTO_RESTART, en); + reg_mask = BITFMASK(MC13783_AUTO_RESTART); + + CHECK_ERROR(pmic_write_reg(REG_POWER_CONTROL_2, reg_val, reg_mask)); + return PMIC_SUCCESS; +} + +/*! + * This function gets auto reset configuration. + * + * @param en if true, the auto reset is enabled + * + * @return This function returns 0 if successful. + */ +PMIC_STATUS pmic_power_get_auto_reset_en(bool *en) +{ + unsigned int reg_val = 0, reg_mask = 0; + + reg_mask = BITFMASK(MC13783_AUTO_RESTART); + CHECK_ERROR(pmic_read_reg(REG_POWER_CONTROL_2, ®_val, reg_mask)); + *en = BITFEXT(reg_val, MC13783_AUTO_RESTART); + return PMIC_SUCCESS; +} + +/*! + * This function configures a system reset on a button. + * + * @param bt type of button. + * @param sys_rst if true, enable the system reset on this button + * @param deb_time sets the debounce time on this button pin + * + * @return This function returns 0 if successful. + */ +PMIC_STATUS pmic_power_set_conf_button(t_button bt, bool sys_rst, int deb_time) +{ + int max_val = 0; + unsigned int reg_val = 0, reg_mask = 0; + + max_val = (1 << MC13783_DEB_BT_ON1B_WID) - 1; + if (deb_time > max_val) { + return PMIC_PARAMETER_ERROR; + } + + switch (bt) { + case BT_ON1B: + reg_val = BITFVAL(MC13783_EN_BT_ON1B, sys_rst) | + BITFVAL(MC13783_DEB_BT_ON1B, deb_time); + reg_mask = BITFMASK(MC13783_EN_BT_ON1B) | + BITFMASK(MC13783_DEB_BT_ON1B); + break; + case BT_ON2B: + reg_val = BITFVAL(MC13783_EN_BT_ON2B, sys_rst) | + BITFVAL(MC13783_DEB_BT_ON2B, deb_time); + reg_mask = BITFMASK(MC13783_EN_BT_ON2B) | + BITFMASK(MC13783_DEB_BT_ON2B); + break; + case BT_ON3B: + reg_val = BITFVAL(MC13783_EN_BT_ON3B, sys_rst) | + BITFVAL(MC13783_DEB_BT_ON3B, deb_time); + reg_mask = BITFMASK(MC13783_EN_BT_ON3B) | + BITFMASK(MC13783_DEB_BT_ON3B); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(REG_POWER_CONTROL_2, reg_val, reg_mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function gets configuration of a button. + * + * @param bt type of button. + * @param sys_rst if true, the system reset is enabled on this button + * @param deb_time gets the debounce time on this button pin + * + * @return This function returns 0 if successful. + */ +PMIC_STATUS pmic_power_get_conf_button(t_button bt, + bool *sys_rst, int *deb_time) +{ + unsigned int reg_val = 0, reg_mask = 0; + + switch (bt) { + case BT_ON1B: + reg_mask = BITFMASK(MC13783_EN_BT_ON1B) | + BITFMASK(MC13783_DEB_BT_ON1B); + break; + case BT_ON2B: + reg_mask = BITFMASK(MC13783_EN_BT_ON2B) | + BITFMASK(MC13783_DEB_BT_ON2B); + break; + case BT_ON3B: + reg_mask = BITFMASK(MC13783_EN_BT_ON3B) | + BITFMASK(MC13783_DEB_BT_ON3B); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_read_reg(REG_POWER_CONTROL_2, ®_val, reg_mask)); + + switch (bt) { + case BT_ON1B: + *sys_rst = BITFEXT(reg_val, MC13783_EN_BT_ON1B); + *deb_time = BITFEXT(reg_val, MC13783_DEB_BT_ON1B); + break; + case BT_ON2B: + *sys_rst = BITFEXT(reg_val, MC13783_EN_BT_ON2B); + *deb_time = BITFEXT(reg_val, MC13783_DEB_BT_ON2B); + break; + case BT_ON3B: + *sys_rst = BITFEXT(reg_val, MC13783_EN_BT_ON3B); + *deb_time = BITFEXT(reg_val, MC13783_DEB_BT_ON3B); + break; + default: + return PMIC_PARAMETER_ERROR; + } + return PMIC_SUCCESS; +} + +/*! + * This function is used to un/subscribe on power event IT. + * + * @param event type of event. + * @param callback event callback function. + * @param sub define if Un/subscribe event. + * + * @return This function returns 0 if successful. + */ +PMIC_STATUS pmic_power_event(t_pwr_int event, void *callback, bool sub) +{ + pmic_event_callback_t power_callback; + type_event power_event; + + power_callback.func = callback; + power_callback.param = NULL; + switch (event) { + case PWR_IT_BPONI: + power_event = EVENT_BPONI; + break; + case PWR_IT_LOBATLI: + power_event = EVENT_LOBATLI; + break; + case PWR_IT_LOBATHI: + power_event = EVENT_LOBATHI; + break; + case PWR_IT_ONOFD1I: + power_event = EVENT_ONOFD1I; + break; + case PWR_IT_ONOFD2I: + power_event = EVENT_ONOFD2I; + break; + case PWR_IT_ONOFD3I: + power_event = EVENT_ONOFD3I; + break; + case PWR_IT_SYSRSTI: + power_event = EVENT_SYSRSTI; + break; + case PWR_IT_PWRRDYI: + power_event = EVENT_PWRRDYI; + break; + case PWR_IT_PCI: + power_event = EVENT_PCI; + break; + case PWR_IT_WARMI: + power_event = EVENT_WARMI; + break; + default: + return PMIC_PARAMETER_ERROR; + } + if (sub == true) { + CHECK_ERROR(pmic_event_subscribe(power_event, power_callback)); + } else { + CHECK_ERROR(pmic_event_unsubscribe + (power_event, power_callback)); + } + return PMIC_SUCCESS; +} + +/*! + * This function is used to subscribe on power event IT. + * + * @param event type of event. + * @param callback event callback function. + * + * @return This function returns 0 if successful. + */ +PMIC_STATUS pmic_power_event_sub(t_pwr_int event, void *callback) +{ + return pmic_power_event(event, callback, true); +} + +/*! + * This function is used to un subscribe on power event IT. + * + * @param event type of event. + * @param callback event callback function. + * + * @return This function returns 0 if successful. + */ +PMIC_STATUS pmic_power_event_unsub(t_pwr_int event, void *callback) +{ + return pmic_power_event(event, callback, false); +} + +void pmic_power_key_callback(void) +{ +#ifdef CONFIG_MXC_HWEVENT + /*read the power key is pressed or up */ + t_sensor_bits sense; + struct mxc_hw_event event = { HWE_POWER_KEY, 0 }; + + pmic_get_sensors(&sense); + if (sense.sense_onofd1s) { + pr_debug("PMIC Power key up\n"); + event.args = PWRK_UNPRESS; + } else { + pr_debug("PMIC Power key pressed\n"); + event.args = PWRK_PRESS; + } + /* send hw event */ + hw_event_send(HWE_DEF_PRIORITY, &event); +#endif +} + +static irqreturn_t power_key_int(int irq, void *dev_id) +{ + pr_info(KERN_INFO "on-off key pressed\n"); + + return 0; +} + +extern void gpio_power_key_active(void); + +/* + * Init and Exit + */ + +static int pmic_power_probe(struct platform_device *pdev) +{ + int irq, ret; + struct pmic_platform_data *ppd; + + /* configure on/off button */ + gpio_power_key_active(); + + ppd = pdev->dev.platform_data; + if (ppd) + irq = ppd->power_key_irq; + else + goto done; + + if (irq == 0) { + pr_info(KERN_INFO "PMIC Power has no platform data\n"); + goto done; + } + set_irq_type(irq, IRQF_TRIGGER_RISING); + + ret = request_irq(irq, power_key_int, 0, "power_key", 0); + if (ret) + pr_info(KERN_ERR "register on-off key interrupt failed\n"); + + set_irq_wake(irq, 1); + + done: + pr_info(KERN_INFO "PMIC Power successfully probed\n"); + return 0; +} + +static struct platform_driver pmic_power_driver_ldm = { + .driver = { + .name = "pmic_power", + }, + .suspend = pmic_power_suspend, + .resume = pmic_power_resume, + .probe = pmic_power_probe, + .remove = NULL, +}; + +static int __init pmic_power_init(void) +{ + pr_debug("PMIC Power driver loading..\n"); + pmic_power_event_sub(PWR_IT_ONOFD1I, pmic_power_key_callback); + /* set power off hook to mc13783 power off */ + pm_power_off = pmic_power_off; + return platform_driver_register(&pmic_power_driver_ldm); +} +static void __exit pmic_power_exit(void) +{ + pmic_power_event_unsub(PWR_IT_ONOFD1I, pmic_power_key_callback); + platform_driver_unregister(&pmic_power_driver_ldm); + pr_debug("PMIC Power driver successfully unloaded\n"); +} + +/* + * Module entry points + */ + +subsys_initcall_sync(pmic_power_init); +module_exit(pmic_power_exit); + +MODULE_DESCRIPTION("pmic_power driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/pmic/mc13783/pmic_power_defs.h b/drivers/mxc/pmic/mc13783/pmic_power_defs.h new file mode 100644 index 000000000000..6777f56321e5 --- /dev/null +++ b/drivers/mxc/pmic/mc13783/pmic_power_defs.h @@ -0,0 +1,509 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mc13783/pmic_power_defs.h + * @brief This is the internal header define of PMIC(mc13783) Power driver. + * + * @ingroup PMIC_POWER + */ + +/* + * Includes + */ + +#ifndef __MC13783_POWER_DEFS_H__ +#define __MC13783_POWER_DEFS_H__ + +/* + * Power Up Mode Sense bits + */ + +#define STATE_ICTEST_MASK 0x000001 + +#define STATE_CLKSEL_BIT 1 +#define STATE_CLKSEL_MASK 0x000002 + +#define STATE_PUMS1_BITS 2 +#define STATE_PUMS1_MASK 0x00000C + +#define STATE_PUMS2_BITS 4 +#define STATE_PUMS2_MASK 0x000030 + +#define STATE_PUMS3_BITS 6 +#define STATE_PUMS3_MASK 0x0000C0 + +#define STATE_CHRGM1_BITS 8 +#define STATE_CHRGM1_MASK 0x000300 + +#define STATE_CHRGM2_BITS 10 +#define STATE_CHRGM2_MASK 0x000C00 + +#define STATE_UMOD_BITS 12 +#define STATE_UMOD_MASK 0x003000 + +#define STATE_USBEN_BIT 14 +#define STATE_USBEN_MASK 0x004000 + +#define STATE_SW1A_J_B_BIT 15 +#define STATE_SW1A_J_B_MASK 0x008000 + +#define STATE_SW2A_J_B_BIT 16 +#define STATE_SW2A_J_B_MASK 0x010000 + +#define PC_COUNT_MAX 3 +#define PC_COUNT_MIN 0 +/* + * Reg Regen + */ +#define MC13783_REGGEN_VAUDIO_LSH 0 +#define MC13783_REGGEN_VAUDIO_WID 1 +#define MC13783_REGGEN_VIOHI_LSH 1 +#define MC13783_REGGEN_VIOHI_WID 1 +#define MC13783_REGGEN_VIOLO_LSH 2 +#define MC13783_REGGEN_VIOLO_WID 1 +#define MC13783_REGGEN_VDIG_LSH 3 +#define MC13783_REGGEN_VDIG_WID 1 +#define MC13783_REGGEN_VGEN_LSH 4 +#define MC13783_REGGEN_VGEN_WID 1 +#define MC13783_REGGEN_VRFDIG_LSH 5 +#define MC13783_REGGEN_VRFDIG_WID 1 +#define MC13783_REGGEN_VRFREF_LSH 6 +#define MC13783_REGGEN_VRFREF_WID 1 +#define MC13783_REGGEN_VRFCP_LSH 7 +#define MC13783_REGGEN_VRFCP_WID 1 +#define MC13783_REGGEN_VCAM_LSH 8 +#define MC13783_REGGEN_VCAM_WID 1 +#define MC13783_REGGEN_VRFBG_LSH 9 +#define MC13783_REGGEN_VRFBG_WID 1 +#define MC13783_REGGEN_VRF1_LSH 10 +#define MC13783_REGGEN_VRF1_WID 1 +#define MC13783_REGGEN_VRF2_LSH 11 +#define MC13783_REGGEN_VRF2_WID 1 +#define MC13783_REGGEN_VMMC1_LSH 12 +#define MC13783_REGGEN_VMMC1_WID 1 +#define MC13783_REGGEN_VMMC2_LSH 13 +#define MC13783_REGGEN_VMMC2_WID 1 +#define MC13783_REGGEN_GPO1_LSH 16 +#define MC13783_REGGEN_GPO1_WID 1 +#define MC13783_REGGEN_GPO2_LSH 17 +#define MC13783_REGGEN_GPO2_WID 1 +#define MC13783_REGGEN_GPO3_LSH 18 +#define MC13783_REGGEN_GPO3_WID 1 +#define MC13783_REGGEN_GPO4_LSH 19 +#define MC13783_REGGEN_GPO4_WID 1 +#define MC13783_REGGEN_INV_LSH 20 +#define MC13783_REGGEN_INV_WID 1 +#define MC13783_REGGEN_VESIMESIM_LSH 21 +#define MC13783_REGGEN_VESIMESIM_WID 1 +#define MC13783_REGGEN_VMMC1ESIM_LSH 22 +#define MC13783_REGGEN_VMMC1ESIM_WID 1 +#define MC13783_REGGEN_VMMC2ESIM_LSH 23 +#define MC13783_REGGEN_VMMC2ESIM_WID 1 + +/* + * Reg Power Control 0 + */ +#define MC13783_PWRCTRL_PCEN_LSH 0 +#define MC13783_PWRCTRL_PCEN_WID 1 +#define MC13783_PWRCTRL_PCEN_ENABLE 1 +#define MC13783_PWRCTRL_PCEN_DISABLE 0 +#define MC13783_PWRCTRL_PC_COUNT_EN_LSH 1 +#define MC13783_PWRCTRL_PC_COUNT_EN_WID 1 +#define MC13783_PWRCTRL_PC_COUNT_EN_ENABLE 1 +#define MC13783_PWRCTRL_PC_COUNT_EN_DISABLE 0 +#define MC13783_PWRCTRL_WARM_EN_LSH 2 +#define MC13783_PWRCTRL_WARM_EN_WID 1 +#define MC13783_PWRCTRL_WARM_EN_ENABLE 1 +#define MC13783_PWRCTRL_WARM_EN_DISABLE 0 +#define MC13783_PWRCTRL_USER_OFF_SPI_LSH 3 +#define MC13783_PWRCTRL_USER_OFF_SPI_WID 1 +#define MC13783_PWRCTRL_USER_OFF_SPI_ENABLE 1 +#define MC13783_PWRCTRL_USER_OFF_PC_LSH 4 +#define MC13783_PWRCTRL_USER_OFF_PC_WID 1 +#define MC13783_PWRCTRL_USER_OFF_PC_ENABLE 1 +#define MC13783_PWRCTRL_USER_OFF_PC_DISABLE 0 +#define MC13783_PWRCTRL_32OUT_USER_OFF_LSH 5 +#define MC13783_PWRCTRL_32OUT_USER_OFF_WID 1 +#define MC13783_PWRCTRL_32OUT_USER_OFF_ENABLE 1 +#define MC13783_PWRCTRL_32OUT_USER_OFF_DISABLE 0 +#define MC13783_PWRCTRL_32OUT_EN_LSH 6 +#define MC13783_PWRCTRL_32OUT_EN_WID 1 +#define MC13783_PWRCTRL_32OUT_EN_ENABLE 1 +#define MC13783_PWRCTRL_32OUT_EN_DISABLE 0 +#define MC13783_REGCTRL_VBKUP2AUTOMH_LSH 7 +#define MC13783_REGCTRL_VBKUP2AUTOMH_WID 1 +#define MC13783_PWRCTRL_VBKUP1_EN_LSH 8 +#define MC13783_PWRCTRL_VBKUP1_EN_WID 1 +#define MC13783_PWRCTRL_VBKUP_ENABLE 1 +#define MC13783_PWRCTRL_VBKUP_DISABLE 0 +#define MC13783_PWRCTRL_VBKUP1_AUTO_EN_LSH 9 +#define MC13783_PWRCTRL_VBKUP1_AUTO_EN_WID 1 +#define MC13783_PWRCTRL_VBKUP1_LSH 10 +#define MC13783_PWRCTRL_VBKUP1_WID 2 +#define MC13783_PWRCTRL_VBKUP2_EN_LSH 12 +#define MC13783_PWRCTRL_VBKUP2_EN_WID 1 +#define MC13783_PWRCTRL_VBKUP2_AUTO_EN_LSH 13 +#define MC13783_PWRCTRL_VBKUP2_AUTO_EN_WID 1 +#define MC13783_PWRCTRL_VBKUP2_LSH 14 +#define MC13783_PWRCTRL_VBKUP2_WID 2 +#define MC13783_REGCTRL_BATTDETEN_LSH 19 +#define MC13783_REGCTRL_BATTDETEN_WID 1 + +/* + * Reg Power Control 1 + */ +#define MC13783_PWRCTRL_PCT_LSH 0 +#define MC13783_PWRCTRL_PCT_WID 8 +#define MC13783_PWRCTRL_PC_COUNT_LSH 8 +#define MC13783_PWRCTRL_PC_COUNT_WID 4 +#define MC13783_PWRCTRL_PC_MAX_CNT_LSH 12 +#define MC13783_PWRCTRL_PC_MAX_CNT_WID 4 +#define MC13783_PWRCTRL_MEM_TMR_LSH 16 +#define MC13783_PWRCTRL_MEM_TMR_WID 4 +#define MC13783_PWRCTRL_MEM_ALLON_LSH 20 +#define MC13783_PWRCTRL_MEM_ALLON_WID 1 +#define MC13783_PWRCTRL_MEM_ALLON_ENABLE 1 +#define MC13783_PWRCTRL_MEM_ALLON_DISABLE 0 + +/* + * Reg Power Control 2 + */ +#define MC13783_AUTO_RESTART_LSH 0 +#define MC13783_AUTO_RESTART_WID 1 +#define MC13783_EN_BT_ON1B_LSH 1 +#define MC13783_EN_BT_ON1B_WID 1 +#define MC13783_EN_BT_ON2B_LSH 2 +#define MC13783_EN_BT_ON2B_WID 1 +#define MC13783_EN_BT_ON3B_LSH 3 +#define MC13783_EN_BT_ON3B_WID 1 +#define MC13783_DEB_BT_ON1B_LSH 4 +#define MC13783_DEB_BT_ON1B_WID 2 +#define MC13783_DEB_BT_ON2B_LSH 6 +#define MC13783_DEB_BT_ON2B_WID 2 +#define MC13783_DEB_BT_ON3B_LSH 8 +#define MC13783_DEB_BT_ON3B_WID 2 + +/* + * Reg Regulator Mode 0 + */ +#define MC13783_REGCTRL_VAUDIO_EN_LSH 0 +#define MC13783_REGCTRL_VAUDIO_EN_WID 1 +#define MC13783_REGCTRL_VAUDIO_EN_ENABLE 1 +#define MC13783_REGCTRL_VAUDIO_EN_DISABLE 0 +#define MC13783_REGCTRL_VAUDIO_STBY_LSH 1 +#define MC13783_REGCTRL_VAUDIO_STBY_WID 1 +#define MC13783_REGCTRL_VAUDIO_MODE_LSH 2 +#define MC13783_REGCTRL_VAUDIO_MODE_WID 1 +#define MC13783_REGCTRL_VIOHI_EN_LSH 3 +#define MC13783_REGCTRL_VIOHI_EN_WID 1 +#define MC13783_REGCTRL_VIOHI_EN_ENABLE 1 +#define MC13783_REGCTRL_VIOHI_EN_DISABLE 0 +#define MC13783_REGCTRL_VIOHI_STBY_LSH 4 +#define MC13783_REGCTRL_VIOHI_STBY_WID 1 +#define MC13783_REGCTRL_VIOHI_MODE_LSH 5 +#define MC13783_REGCTRL_VIOHI_MODE_WID 1 +#define MC13783_REGCTRL_VIOLO_EN_LSH 6 +#define MC13783_REGCTRL_VIOLO_EN_WID 1 +#define MC13783_REGCTRL_VIOLO_EN_ENABLE 1 +#define MC13783_REGCTRL_VIOLO_EN_DISABLE 0 +#define MC13783_REGCTRL_VIOLO_STBY_LSH 7 +#define MC13783_REGCTRL_VIOLO_STBY_WID 1 +#define MC13783_REGCTRL_VIOLO_MODE_LSH 8 +#define MC13783_REGCTRL_VIOLO_MODE_WID 1 +#define MC13783_REGCTRL_VDIG_EN_LSH 9 +#define MC13783_REGCTRL_VDIG_EN_WID 1 +#define MC13783_REGCTRL_VDIG_EN_ENABLE 1 +#define MC13783_REGCTRL_VDIG_EN_DISABLE 0 +#define MC13783_REGCTRL_VDIG_STBY_LSH 10 +#define MC13783_REGCTRL_VDIG_STBY_WID 1 +#define MC13783_REGCTRL_VDIG_MODE_LSH 11 +#define MC13783_REGCTRL_VDIG_MODE_WID 1 +#define MC13783_REGCTRL_VGEN_EN_LSH 12 +#define MC13783_REGCTRL_VGEN_EN_WID 1 +#define MC13783_REGCTRL_VGEN_EN_ENABLE 1 +#define MC13783_REGCTRL_VGEN_EN_DISABLE 0 +#define MC13783_REGCTRL_VGEN_STBY_LSH 13 +#define MC13783_REGCTRL_VGEN_STBY_WID 1 +#define MC13783_REGCTRL_VGEN_MODE_LSH 14 +#define MC13783_REGCTRL_VGEN_MODE_WID 1 +#define MC13783_REGCTRL_VRFDIG_EN_LSH 15 +#define MC13783_REGCTRL_VRFDIG_EN_WID 1 +#define MC13783_REGCTRL_VRFDIG_EN_ENABLE 1 +#define MC13783_REGCTRL_VRFDIG_EN_DISABLE 0 +#define MC13783_REGCTRL_VRFDIG_STBY_LSH 16 +#define MC13783_REGCTRL_VRFDIG_STBY_WID 1 +#define MC13783_REGCTRL_VRFDIG_MODE_LSH 17 +#define MC13783_REGCTRL_VRFDIG_MODE_WID 1 +#define MC13783_REGCTRL_VRFREF_EN_LSH 18 +#define MC13783_REGCTRL_VRFREF_EN_WID 1 +#define MC13783_REGCTRL_VRFREF_EN_ENABLE 1 +#define MC13783_REGCTRL_VRFREF_EN_DISABLE 0 +#define MC13783_REGCTRL_VRFREF_STBY_LSH 19 +#define MC13783_REGCTRL_VRFREF_STBY_WID 1 +#define MC13783_REGCTRL_VRFREF_MODE_LSH 20 +#define MC13783_REGCTRL_VRFREF_MODE_WID 1 +#define MC13783_REGCTRL_VRFCP_EN_LSH 21 +#define MC13783_REGCTRL_VRFCP_EN_WID 1 +#define MC13783_REGCTRL_VRFCP_EN_ENABLE 1 +#define MC13783_REGCTRL_VRFCP_EN_DISABLE 0 +#define MC13783_REGCTRL_VRFCP_STBY_LSH 22 +#define MC13783_REGCTRL_VRFCP_STBY_WID 1 +#define MC13783_REGCTRL_VRFCP_MODE_LSH 23 +#define MC13783_REGCTRL_VRFCP_MODE_WID 1 + +/* + * Reg Regulator Mode 1 + */ +#define MC13783_REGCTRL_VSIM_EN_LSH 0 +#define MC13783_REGCTRL_VSIM_EN_WID 1 +#define MC13783_REGCTRL_VSIM_EN_ENABLE 1 +#define MC13783_REGCTRL_VSIM_EN_DISABLE 0 +#define MC13783_REGCTRL_VSIM_STBY_LSH 1 +#define MC13783_REGCTRL_VSIM_STBY_WID 1 +#define MC13783_REGCTRL_VSIM_MODE_LSH 2 +#define MC13783_REGCTRL_VSIM_MODE_WID 1 +#define MC13783_REGCTRL_VESIM_EN_LSH 3 +#define MC13783_REGCTRL_VESIM_EN_WID 1 +#define MC13783_REGCTRL_VESIM_EN_ENABLE 1 +#define MC13783_REGCTRL_VESIM_EN_DISABLE 0 +#define MC13783_REGCTRL_VESIM_STBY_LSH 4 +#define MC13783_REGCTRL_VESIM_STBY_WID 1 +#define MC13783_REGCTRL_VESIM_MODE_LSH 5 +#define MC13783_REGCTRL_VESIM_MODE_WID 1 +#define MC13783_REGCTRL_VCAM_EN_LSH 6 +#define MC13783_REGCTRL_VCAM_EN_WID 1 +#define MC13783_REGCTRL_VCAM_EN_ENABLE 1 +#define MC13783_REGCTRL_VCAM_EN_DISABLE 0 +#define MC13783_REGCTRL_VCAM_STBY_LSH 7 +#define MC13783_REGCTRL_VCAM_STBY_WID 1 +#define MC13783_REGCTRL_VCAM_MODE_LSH 8 +#define MC13783_REGCTRL_VCAM_MODE_WID 1 +#define MC13783_REGCTRL_VRFBG_EN_LSH 9 +#define MC13783_REGCTRL_VRFBG_EN_WID 1 +#define MC13783_REGCTRL_VRFBG_EN_ENABLE 1 +#define MC13783_REGCTRL_VRFBG_EN_DISABLE 0 +#define MC13783_REGCTRL_VRFBG_STBY_LSH 10 +#define MC13783_REGCTRL_VRFBG_STBY_WID 1 +#define MC13783_REGCTRL_VVIB_EN_LSH 11 +#define MC13783_REGCTRL_VVIB_EN_WID 1 +#define MC13783_REGCTRL_VVIB_EN_ENABLE 1 +#define MC13783_REGCTRL_VVIB_EN_DISABLE 0 +#define MC13783_REGCTRL_VRF1_EN_LSH 12 +#define MC13783_REGCTRL_VRF1_EN_WID 1 +#define MC13783_REGCTRL_VRF1_EN_ENABLE 1 +#define MC13783_REGCTRL_VRF1_EN_DISABLE 0 +#define MC13783_REGCTRL_VRF1_STBY_LSH 13 +#define MC13783_REGCTRL_VRF1_STBY_WID 1 +#define MC13783_REGCTRL_VRF1_MODE_LSH 14 +#define MC13783_REGCTRL_VRF1_MODE_WID 1 +#define MC13783_REGCTRL_VRF2_EN_LSH 15 +#define MC13783_REGCTRL_VRF2_EN_WID 1 +#define MC13783_REGCTRL_VRF2_EN_ENABLE 1 +#define MC13783_REGCTRL_VRF2_EN_DISABLE 0 +#define MC13783_REGCTRL_VRF2_STBY_LSH 16 +#define MC13783_REGCTRL_VRF2_STBY_WID 1 +#define MC13783_REGCTRL_VRF2_MODE_LSH 17 +#define MC13783_REGCTRL_VRF2_MODE_WID 1 +#define MC13783_REGCTRL_VMMC1_EN_LSH 18 +#define MC13783_REGCTRL_VMMC1_EN_WID 1 +#define MC13783_REGCTRL_VMMC1_EN_ENABLE 1 +#define MC13783_REGCTRL_VMMC1_EN_DISABLE 0 +#define MC13783_REGCTRL_VMMC1_STBY_LSH 19 +#define MC13783_REGCTRL_VMMC1_STBY_WID 1 +#define MC13783_REGCTRL_VMMC1_MODE_LSH 20 +#define MC13783_REGCTRL_VMMC1_MODE_WID 1 +#define MC13783_REGCTRL_VMMC2_EN_LSH 21 +#define MC13783_REGCTRL_VMMC2_EN_WID 1 +#define MC13783_REGCTRL_VMMC2_EN_ENABLE 1 +#define MC13783_REGCTRL_VMMC2_EN_DISABLE 0 +#define MC13783_REGCTRL_VMMC2_STBY_LSH 22 +#define MC13783_REGCTRL_VMMC2_STBY_WID 1 +#define MC13783_REGCTRL_VMMC2_MODE_LSH 23 +#define MC13783_REGCTRL_VMMC2_MODE_WID 1 + +/* + * Reg Regulator Misc. + */ +#define MC13783_REGCTRL_GPO1_EN_LSH 6 +#define MC13783_REGCTRL_GPO1_EN_WID 1 +#define MC13783_REGCTRL_GPO1_EN_ENABLE 1 +#define MC13783_REGCTRL_GPO1_EN_DISABLE 0 +#define MC13783_REGCTRL_GPO2_EN_LSH 8 +#define MC13783_REGCTRL_GPO2_EN_WID 1 +#define MC13783_REGCTRL_GPO2_EN_ENABLE 1 +#define MC13783_REGCTRL_GPO2_EN_DISABLE 0 +#define MC13783_REGCTRL_GPO3_EN_LSH 10 +#define MC13783_REGCTRL_GPO3_EN_WID 1 +#define MC13783_REGCTRL_GPO3_EN_ENABLE 1 +#define MC13783_REGCTRL_GPO3_EN_DISABLE 0 +#define MC13783_REGCTRL_GPO4_EN_LSH 12 +#define MC13783_REGCTRL_GPO4_EN_WID 1 +#define MC13783_REGCTRL_GPO4_EN_ENABLE 1 +#define MC13783_REGCTRL_GPO4_EN_DISABLE 0 +#define MC13783_REGCTRL_VIBPINCTRL_LSH 14 +#define MC13783_REGCTRL_VIBPINCTRL_WID 1 + +/* + * Reg Regulator Setting 0 + */ +#define MC13783_REGSET_VIOLO_LSH 2 +#define MC13783_REGSET_VIOLO_WID 2 +#define MC13783_REGSET_VDIG_LSH 4 +#define MC13783_REGSET_VDIG_WID 2 +#define MC13783_REGSET_VGEN_LSH 6 +#define MC13783_REGSET_VGEN_WID 3 +#define MC13783_REGSET_VRFDIG_LSH 9 +#define MC13783_REGSET_VRFDIG_WID 2 +#define MC13783_REGSET_VRFREF_LSH 11 +#define MC13783_REGSET_VRFREF_WID 2 +#define MC13783_REGSET_VRFCP_LSH 13 +#define MC13783_REGSET_VRFCP_WID 1 +#define MC13783_REGSET_VSIM_LSH 14 +#define MC13783_REGSET_VSIM_WID 1 +#define MC13783_REGSET_VESIM_LSH 15 +#define MC13783_REGSET_VESIM_WID 1 +#define MC13783_REGSET_VCAM_LSH 16 +#define MC13783_REGSET_VCAM_WID 3 + +/* + * Reg Regulator Setting 1 + */ +#define MC13783_REGSET_VVIB_LSH 0 +#define MC13783_REGSET_VVIB_WID 2 +#define MC13783_REGSET_VRF1_LSH 2 +#define MC13783_REGSET_VRF1_WID 2 +#define MC13783_REGSET_VRF2_LSH 4 +#define MC13783_REGSET_VRF2_WID 2 +#define MC13783_REGSET_VMMC1_LSH 6 +#define MC13783_REGSET_VMMC1_WID 3 +#define MC13783_REGSET_VMMC2_LSH 9 +#define MC13783_REGSET_VMMC2_WID 3 + +/* + * Reg Switcher 0 + */ +#define MC13783_SWSET_SW1A_LSH 0 +#define MC13783_SWSET_SW1A_WID 6 +#define MC13783_SWSET_SW1A_DVS_LSH 6 +#define MC13783_SWSET_SW1A_DVS_WID 6 +#define MC13783_SWSET_SW1A_STDBY_LSH 12 +#define MC13783_SWSET_SW1A_STDBY_WID 6 + +/* + * Reg Switcher 1 + */ +#define MC13783_SWSET_SW1B_LSH 0 +#define MC13783_SWSET_SW1B_WID 6 +#define MC13783_SWSET_SW1B_DVS_LSH 6 +#define MC13783_SWSET_SW1B_DVS_WID 6 +#define MC13783_SWSET_SW1B_STDBY_LSH 12 +#define MC13783_SWSET_SW1B_STDBY_WID 6 + +/* + * Reg Switcher 2 + */ +#define MC13783_SWSET_SW2A_LSH 0 +#define MC13783_SWSET_SW2A_WID 6 +#define MC13783_SWSET_SW2A_DVS_LSH 6 +#define MC13783_SWSET_SW2A_DVS_WID 6 +#define MC13783_SWSET_SW2A_STDBY_LSH 12 +#define MC13783_SWSET_SW2A_STDBY_WID 6 + +/* + * Reg Switcher 3 + */ +#define MC13783_SWSET_SW2B_LSH 0 +#define MC13783_SWSET_SW2B_WID 6 +#define MC13783_SWSET_SW2B_DVS_LSH 6 +#define MC13783_SWSET_SW2B_DVS_WID 6 +#define MC13783_SWSET_SW2B_STDBY_LSH 12 +#define MC13783_SWSET_SW2B_STDBY_WID 6 + +/* + * Reg Switcher 4 + */ +#define MC13783_SWCTRL_SW1A_MODE_LSH 0 +#define MC13783_SWCTRL_SW1A_MODE_WID 2 +#define MC13783_SWCTRL_SW1A_STBY_MODE_LSH 2 +#define MC13783_SWCTRL_SW1A_STBY_MODE_WID 2 +#define MC13783_SWCTRL_SW1A_DVS_SPEED_LSH 6 +#define MC13783_SWCTRL_SW1A_DVS_SPEED_WID 2 +#define MC13783_SWCTRL_SW1A_PANIC_MODE_LSH 8 +#define MC13783_SWCTRL_SW1A_PANIC_MODE_WID 1 +#define MC13783_SWCTRL_SW1A_SOFTSTART_LSH 9 +#define MC13783_SWCTRL_SW1A_SOFTSTART_WID 1 +#define MC13783_SWCTRL_SW1B_MODE_LSH 10 +#define MC13783_SWCTRL_SW1B_MODE_WID 2 +#define MC13783_SWCTRL_SW1B_STBY_MODE_LSH 12 +#define MC13783_SWCTRL_SW1B_STBY_MODE_WID 2 +#define MC13783_SWCTRL_SW1B_DVS_SPEED_LSH 14 +#define MC13783_SWCTRL_SW1B_DVS_SPEED_WID 2 +#define MC13783_SWCTRL_SW1B_PANIC_MODE_LSH 16 +#define MC13783_SWCTRL_SW1B_PANIC_MODE_WID 1 +#define MC13783_SWCTRL_SW1B_SOFTSTART_LSH 17 +#define MC13783_SWCTRL_SW1B_SOFTSTART_WID 1 +#define MC13783_SWCTRL_PLL_EN_LSH 18 +#define MC13783_SWCTRL_PLL_EN_WID 1 +#define MC13783_SWCTRL_PLL_EN_ENABLE 1 +#define MC13783_SWCTRL_PLL_EN_DISABLE 0 +#define MC13783_SWCTRL_PLL_FACTOR_LSH 19 +#define MC13783_SWCTRL_PLL_FACTOR_WID 3 + +/* + * Reg Switcher 5 + */ +#define MC13783_SWCTRL_SW2A_MODE_LSH 0 +#define MC13783_SWCTRL_SW2A_MODE_WID 2 +#define MC13783_SWCTRL_SW2A_STBY_MODE_LSH 2 +#define MC13783_SWCTRL_SW2A_STBY_MODE_WID 2 +#define MC13783_SWCTRL_SW2A_DVS_SPEED_LSH 6 +#define MC13783_SWCTRL_SW2A_DVS_SPEED_WID 2 +#define MC13783_SWCTRL_SW2A_PANIC_MODE_LSH 8 +#define MC13783_SWCTRL_SW2A_PANIC_MODE_WID 1 +#define MC13783_SWCTRL_SW2A_SOFTSTART_LSH 9 +#define MC13783_SWCTRL_SW2A_SOFTSTART_WID 1 +#define MC13783_SWCTRL_SW2B_MODE_LSH 10 +#define MC13783_SWCTRL_SW2B_MODE_WID 2 +#define MC13783_SWCTRL_SW2B_STBY_MODE_LSH 12 +#define MC13783_SWCTRL_SW2B_STBY_MODE_WID 2 +#define MC13783_SWCTRL_SW2B_DVS_SPEED_LSH 14 +#define MC13783_SWCTRL_SW2B_DVS_SPEED_WID 2 +#define MC13783_SWCTRL_SW2B_PANIC_MODE_LSH 16 +#define MC13783_SWCTRL_SW2B_PANIC_MODE_WID 1 +#define MC13783_SWCTRL_SW2B_SOFTSTART_LSH 17 +#define MC13783_SWCTRL_SW2B_SOFTSTART_WID 1 +#define MC13783_SWSET_SW3_LSH 18 +#define MC13783_SWSET_SW3_WID 2 +#define MC13783_SWCTRL_SW3_EN_LSH 20 +#define MC13783_SWCTRL_SW3_EN_WID 2 +#define MC13783_SWCTRL_SW3_EN_ENABLE 1 +#define MC13783_SWCTRL_SW3_EN_DISABLE 0 +#define MC13783_SWCTRL_SW3_STBY_LSH 21 +#define MC13783_SWCTRL_SW3_STBY_WID 1 +#define MC13783_SWCTRL_SW3_MODE_LSH 22 +#define MC13783_SWCTRL_SW3_MODE_WID 1 + +/* + * Switcher configuration + */ +#define MC13783_SWCTRL_SW_MODE_SYNC_RECT_EN 0 +#define MC13783_SWCTRL_SW_MODE_PULSE_NO_SKIP_EN 1 +#define MC13783_SWCTRL_SW_MODE_PULSE_SKIP_EN 2 +#define MC13783_SWCTRL_SW_MODE_LOW_POWER_EN 3 +#define MC13783_REGTRL_LP_MODE_ENABLE 1 +#define MC13783_REGTRL_LP_MODE_DISABLE 0 +#define MC13783_REGTRL_STBY_MODE_ENABLE 1 +#define MC13783_REGTRL_STBY_MODE_DISABLE 0 + +#endif /* __MC13783_POWER_DEFS_H__ */ diff --git a/drivers/mxc/pmic/mc13783/pmic_rtc.c b/drivers/mxc/pmic/mc13783/pmic_rtc.c new file mode 100644 index 000000000000..b55c21b4c4f0 --- /dev/null +++ b/drivers/mxc/pmic/mc13783/pmic_rtc.c @@ -0,0 +1,544 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mc13783/pmic_rtc.c + * @brief This is the main file of PMIC(mc13783) RTC driver. + * + * @ingroup PMIC_RTC + */ + +/* + * Includes + */ +#include +#include +#include +#include +#include +#include + +#include "pmic_rtc_defs.h" + +#define PMIC_LOAD_ERROR_MSG \ +"PMIC card was not correctly detected. Stop loading PMIC RTC driver\n" + +/* + * Global variables + */ +static int pmic_rtc_major; +static void callback_alarm_asynchronous(void *); +static void callback_alarm_synchronous(void *); +static unsigned int pmic_rtc_poll(struct file *file, poll_table * wait); +static DECLARE_WAIT_QUEUE_HEAD(queue_alarm); +static DECLARE_WAIT_QUEUE_HEAD(pmic_rtc_wait); +static pmic_event_callback_t alarm_callback; +static pmic_event_callback_t rtc_callback; +static bool pmic_rtc_done; +static struct class *pmic_rtc_class; + +static DECLARE_MUTEX(mutex); + +/* EXPORTED FUNCTIONS */ +EXPORT_SYMBOL(pmic_rtc_set_time); +EXPORT_SYMBOL(pmic_rtc_get_time); +EXPORT_SYMBOL(pmic_rtc_set_time_alarm); +EXPORT_SYMBOL(pmic_rtc_get_time_alarm); +EXPORT_SYMBOL(pmic_rtc_wait_alarm); +EXPORT_SYMBOL(pmic_rtc_event_sub); +EXPORT_SYMBOL(pmic_rtc_event_unsub); + +/* + * Real Time Clock Pmic API + */ + +/*! + * This is the callback function called on TSI Pmic event, used in asynchronous + * call. + */ +static void callback_alarm_asynchronous(void *unused) +{ + pmic_rtc_done = true; +} + +/*! + * This is the callback function is used in test code for (un)sub. + */ +static void callback_test_sub(void) +{ + printk(KERN_INFO "*****************************************\n"); + printk(KERN_INFO "***** PMIC RTC 'Alarm IT CallBack' ******\n"); + printk(KERN_INFO "*****************************************\n"); +} + +/*! + * This is the callback function called on TSI Pmic event, used in synchronous + * call. + */ +static void callback_alarm_synchronous(void *unused) +{ + printk(KERN_INFO "*** Alarm IT Pmic ***\n"); + wake_up(&queue_alarm); +} + +/*! + * This function wait the Alarm event + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_rtc_wait_alarm(void) +{ + DEFINE_WAIT(wait); + alarm_callback.func = callback_alarm_synchronous; + alarm_callback.param = NULL; + CHECK_ERROR(pmic_event_subscribe(EVENT_TODAI, alarm_callback)); + prepare_to_wait(&queue_alarm, &wait, TASK_UNINTERRUPTIBLE); + schedule(); + finish_wait(&queue_alarm, &wait); + CHECK_ERROR(pmic_event_unsubscribe(EVENT_TODAI, alarm_callback)); + return PMIC_SUCCESS; +} + +/*! + * This function set the real time clock of PMIC + * + * @param pmic_time value of date and time + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_rtc_set_time(struct timeval *pmic_time) +{ + unsigned int tod_reg_val = 0; + unsigned int day_reg_val = 0; + unsigned int mask, value; + + tod_reg_val = pmic_time->tv_sec % 86400; + day_reg_val = pmic_time->tv_sec / 86400; + + mask = BITFMASK(MC13783_RTCTIME_TIME); + value = BITFVAL(MC13783_RTCTIME_TIME, tod_reg_val); + CHECK_ERROR(pmic_write_reg(REG_RTC_TIME, value, mask)); + + mask = BITFMASK(MC13783_RTCDAY_DAY); + value = BITFVAL(MC13783_RTCDAY_DAY, day_reg_val); + CHECK_ERROR(pmic_write_reg(REG_RTC_DAY, value, mask)); + + return PMIC_SUCCESS; +} + +/*! + * This function get the real time clock of PMIC + * + * @param pmic_time return value of date and time + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_rtc_get_time(struct timeval *pmic_time) +{ + unsigned int tod_reg_val = 0; + unsigned int day_reg_val = 0; + unsigned int mask, value; + + mask = BITFMASK(MC13783_RTCTIME_TIME); + CHECK_ERROR(pmic_read_reg(REG_RTC_TIME, &value, mask)); + tod_reg_val = BITFEXT(value, MC13783_RTCTIME_TIME); + + mask = BITFMASK(MC13783_RTCDAY_DAY); + CHECK_ERROR(pmic_read_reg(REG_RTC_DAY, &value, mask)); + day_reg_val = BITFEXT(value, MC13783_RTCDAY_DAY); + + pmic_time->tv_sec = (unsigned long)((unsigned long)(tod_reg_val & + 0x0001FFFF) + + (unsigned long)(day_reg_val * + 86400)); + return PMIC_SUCCESS; +} + +/*! + * This function set the real time clock alarm of PMIC + * + * @param pmic_time value of date and time + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_rtc_set_time_alarm(struct timeval *pmic_time) +{ + unsigned int tod_reg_val = 0; + unsigned int day_reg_val = 0; + unsigned int mask, value; + + if (down_interruptible(&mutex) < 0) + return ret; + + tod_reg_val = pmic_time->tv_sec % 86400; + day_reg_val = pmic_time->tv_sec / 86400; + + mask = BITFMASK(MC13783_RTCALARM_TIME); + value = BITFVAL(MC13783_RTCALARM_TIME, tod_reg_val); + CHECK_ERROR(pmic_write_reg(REG_RTC_ALARM, value, mask)); + + mask = BITFMASK(MC13783_RTCALARM_DAY); + value = BITFVAL(MC13783_RTCALARM_DAY, day_reg_val); + CHECK_ERROR(pmic_write_reg(REG_RTC_DAY_ALARM, value, mask)); + up(&mutex); + return PMIC_SUCCESS; +} + +/*! + * This function get the real time clock alarm of PMIC + * + * @param pmic_time return value of date and time + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_rtc_get_time_alarm(struct timeval *pmic_time) +{ + unsigned int tod_reg_val = 0; + unsigned int day_reg_val = 0; + unsigned int mask, value; + + mask = BITFMASK(MC13783_RTCALARM_TIME); + CHECK_ERROR(pmic_read_reg(REG_RTC_ALARM, &value, mask)); + tod_reg_val = BITFEXT(value, MC13783_RTCALARM_TIME); + + mask = BITFMASK(MC13783_RTCALARM_DAY); + CHECK_ERROR(pmic_read_reg(REG_RTC_DAY_ALARM, &value, mask)); + day_reg_val = BITFEXT(value, MC13783_RTCALARM_DAY); + + pmic_time->tv_sec = (unsigned long)((unsigned long)(tod_reg_val & + 0x0001FFFF) + + (unsigned long)(day_reg_val * + 86400)); + + return PMIC_SUCCESS; +} + +/*! + * This function is used to un/subscribe on RTC event IT. + * + * @param event type of event. + * @param callback event callback function. + * @param sub define if Un/subscribe event. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_rtc_event(t_rtc_int event, void *callback, bool sub) +{ + type_event rtc_event; + if (callback == NULL) { + return PMIC_ERROR; + } else { + rtc_callback.func = callback; + rtc_callback.param = NULL; + } + switch (event) { + case RTC_IT_ALARM: + rtc_event = EVENT_TODAI; + break; + case RTC_IT_1HZ: + rtc_event = EVENT_E1HZI; + break; + case RTC_IT_RST: + rtc_event = EVENT_RTCRSTI; + break; + default: + return PMIC_PARAMETER_ERROR; + } + if (sub == true) { + CHECK_ERROR(pmic_event_subscribe(rtc_event, rtc_callback)); + } else { + CHECK_ERROR(pmic_event_unsubscribe(rtc_event, rtc_callback)); + } + return PMIC_SUCCESS; +} + +/*! + * This function is used to subscribe on RTC event IT. + * + * @param event type of event. + * @param callback event callback function. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_rtc_event_sub(t_rtc_int event, void *callback) +{ + CHECK_ERROR(pmic_rtc_event(event, callback, true)); + return PMIC_SUCCESS; +} + +/*! + * This function is used to un subscribe on RTC event IT. + * + * @param event type of event. + * @param callback event callback function. + * + * @return This function returns PMIC_SUCCESS if successful. + */ +PMIC_STATUS pmic_rtc_event_unsub(t_rtc_int event, void *callback) +{ + CHECK_ERROR(pmic_rtc_event(event, callback, false)); + return PMIC_SUCCESS; +} + +/* Called without the kernel lock - fine */ +static unsigned int pmic_rtc_poll(struct file *file, poll_table * wait) +{ + /*poll_wait(file, &pmic_rtc_wait, wait); */ + + if (pmic_rtc_done) + return POLLIN | POLLRDNORM; + return 0; +} + +/*! + * This function implements IOCTL controls on a PMIC RTC device. + * + * @param inode pointer on the node + * @param file pointer on the file + * @param cmd the command + * @param arg the parameter + * @return This function returns 0 if successful. + */ +static int pmic_rtc_ioctl(struct inode *inode, struct file *file, + unsigned int cmd, unsigned long arg) +{ + struct timeval *pmic_time = NULL; + + if (_IOC_TYPE(cmd) != 'p') + return -ENOTTY; + + if (arg) { + pmic_time = kmalloc(sizeof(struct timeval), GFP_KERNEL); + if (pmic_time == NULL) + return -ENOMEM; + + /* if (copy_from_user(pmic_time, (struct timeval *)arg, + sizeof(struct timeval))) { + return -EFAULT; + } */ + } + + switch (cmd) { + case PMIC_RTC_SET_TIME: + if (copy_from_user(pmic_time, (struct timeval *)arg, + sizeof(struct timeval))) { + return -EFAULT; + } + pr_debug("SET RTC\n"); + CHECK_ERROR(pmic_rtc_set_time(pmic_time)); + break; + case PMIC_RTC_GET_TIME: + if (copy_to_user((struct timeval *)arg, pmic_time, + sizeof(struct timeval))) { + return -EFAULT; + } + pr_debug("GET RTC\n"); + CHECK_ERROR(pmic_rtc_get_time(pmic_time)); + break; + case PMIC_RTC_SET_ALARM: + if (copy_from_user(pmic_time, (struct timeval *)arg, + sizeof(struct timeval))) { + return -EFAULT; + } + pr_debug("SET RTC ALARM\n"); + CHECK_ERROR(pmic_rtc_set_time_alarm(pmic_time)); + break; + case PMIC_RTC_GET_ALARM: + if (copy_to_user((struct timeval *)arg, pmic_time, + sizeof(struct timeval))) { + return -EFAULT; + } + pr_debug("GET RTC ALARM\n"); + CHECK_ERROR(pmic_rtc_get_time_alarm(pmic_time)); + break; + case PMIC_RTC_WAIT_ALARM: + printk(KERN_INFO "WAIT ALARM...\n"); + CHECK_ERROR(pmic_rtc_event_sub(RTC_IT_ALARM, + callback_test_sub)); + CHECK_ERROR(pmic_rtc_wait_alarm()); + printk(KERN_INFO "ALARM DONE\n"); + CHECK_ERROR(pmic_rtc_event_unsub(RTC_IT_ALARM, + callback_test_sub)); + break; + case PMIC_RTC_ALARM_REGISTER: + printk(KERN_INFO "PMIC RTC ALARM REGISTER\n"); + alarm_callback.func = callback_alarm_asynchronous; + alarm_callback.param = NULL; + CHECK_ERROR(pmic_event_subscribe(EVENT_TODAI, alarm_callback)); + break; + case PMIC_RTC_ALARM_UNREGISTER: + printk(KERN_INFO "PMIC RTC ALARM UNREGISTER\n"); + alarm_callback.func = callback_alarm_asynchronous; + alarm_callback.param = NULL; + CHECK_ERROR(pmic_event_unsubscribe + (EVENT_TODAI, alarm_callback)); + pmic_rtc_done = false; + break; + default: + pr_debug("%d unsupported ioctl command\n", (int)cmd); + return -EINVAL; + } + + if (arg) { + if (copy_to_user((struct timeval *)arg, pmic_time, + sizeof(struct timeval))) { + return -EFAULT; + } + kfree(pmic_time); + } + + return 0; +} + +/*! + * This function implements the open method on a PMIC RTC device. + * + * @param inode pointer on the node + * @param file pointer on the file + * @return This function returns 0. + */ +static int pmic_rtc_open(struct inode *inode, struct file *file) +{ + return 0; +} + +/*! + * This function implements the release method on a PMIC RTC device. + * + * @param inode pointer on the node + * @param file pointer on the file + * @return This function returns 0. + */ +static int pmic_rtc_release(struct inode *inode, struct file *file) +{ + return 0; +} + +/*! + * This function is called to put the RTC in a low power state. + * There is no need for power handlers for the RTC device. + * The RTC cannot be suspended. + * + * @param pdev the device structure used to give information on which RTC + * device (0 through 3 channels) to suspend + * @param state the power state the device is entering + * + * @return The function always returns 0. + */ +static int pmic_rtc_suspend(struct platform_device *pdev, pm_message_t state) +{ + return 0; +} + +/*! + * This function is called to resume the RTC from a low power state. + * + * @param pdev the device structure used to give information on which RTC + * device (0 through 3 channels) to suspend + * + * @return The function always returns 0. + */ +static int pmic_rtc_resume(struct platform_device *pdev) +{ + return 0; +} + +/*! + * This structure contains pointers to the power management callback functions. + */ + +static struct file_operations pmic_rtc_fops = { + .owner = THIS_MODULE, + .ioctl = pmic_rtc_ioctl, + .poll = pmic_rtc_poll, + .open = pmic_rtc_open, + .release = pmic_rtc_release, +}; + +static int pmic_rtc_remove(struct platform_device *pdev) +{ + device_destroy(pmic_rtc_class, MKDEV(pmic_rtc_major, 0)); + class_destroy(pmic_rtc_class); + unregister_chrdev(pmic_rtc_major, "pmic_rtc"); + return 0; +} + +static int pmic_rtc_probe(struct platform_device *pdev) +{ + int ret = 0; + struct device *temp_class; + + pmic_rtc_major = register_chrdev(0, "pmic_rtc", &pmic_rtc_fops); + if (pmic_rtc_major < 0) { + printk(KERN_ERR "Unable to get a major for pmic_rtc\n"); + return pmic_rtc_major; + } + + pmic_rtc_class = class_create(THIS_MODULE, "pmic_rtc"); + if (IS_ERR(pmic_rtc_class)) { + printk(KERN_ERR "Error creating pmic rtc class.\n"); + ret = PTR_ERR(pmic_rtc_class); + goto err_out1; + } + + temp_class = device_create(pmic_rtc_class, NULL, + MKDEV(pmic_rtc_major, 0), NULL, + "pmic_rtc"); + if (IS_ERR(temp_class)) { + printk(KERN_ERR "Error creating pmic rtc class device.\n"); + ret = PTR_ERR(temp_class); + goto err_out2; + } + + printk(KERN_INFO "PMIC RTC successfully probed\n"); + return ret; + + err_out2: + class_destroy(pmic_rtc_class); + err_out1: + unregister_chrdev(pmic_rtc_major, "pmic_rtc"); + return ret; +} + +static struct platform_driver pmic_rtc_driver_ldm = { + .driver = { + .name = "pmic_rtc", + .owner = THIS_MODULE, + }, + .suspend = pmic_rtc_suspend, + .resume = pmic_rtc_resume, + .probe = pmic_rtc_probe, + .remove = pmic_rtc_remove, +}; + +static int __init pmic_rtc_init(void) +{ + pr_debug("PMIC RTC driver loading...\n"); + return platform_driver_register(&pmic_rtc_driver_ldm); +} +static void __exit pmic_rtc_exit(void) +{ + platform_driver_unregister(&pmic_rtc_driver_ldm); + pr_debug("PMIC RTC driver successfully unloaded\n"); +} + +/* + * Module entry points + */ + +subsys_initcall(pmic_rtc_init); +module_exit(pmic_rtc_exit); + +MODULE_DESCRIPTION("Pmic_rtc driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/pmic/mc13783/pmic_rtc_defs.h b/drivers/mxc/pmic/mc13783/pmic_rtc_defs.h new file mode 100644 index 000000000000..e20596a932ed --- /dev/null +++ b/drivers/mxc/pmic/mc13783/pmic_rtc_defs.h @@ -0,0 +1,47 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#ifndef __MC13783_RTC_DEFS_H__ +#define __MC13783_RTC_DEFS_H__ + +/*! + * @file mc13783/pmic_rtc_defs.h + * @brief This is the internal header of PMIC(mc13783) RTC driver. + * + * @ingroup PMIC_RTC + */ + +/* + * RTC Time + */ +#define MC13783_RTCTIME_TIME_LSH 0 +#define MC13783_RTCTIME_TIME_WID 17 + +/* + * RTC Alarm + */ +#define MC13783_RTCALARM_TIME_LSH 0 +#define MC13783_RTCALARM_TIME_WID 17 + +/* + * RTC Day + */ +#define MC13783_RTCDAY_DAY_LSH 0 +#define MC13783_RTCDAY_DAY_WID 15 + +/* + * RTC Day alarm + */ +#define MC13783_RTCALARM_DAY_LSH 0 +#define MC13783_RTCALARM_DAY_WID 15 + +#endif /* __MC13783_RTC_DEFS_H__ */ diff --git a/drivers/mxc/pmic/mc13892/Kconfig b/drivers/mxc/pmic/mc13892/Kconfig new file mode 100644 index 000000000000..930e06ab2282 --- /dev/null +++ b/drivers/mxc/pmic/mc13892/Kconfig @@ -0,0 +1,48 @@ +# +# PMIC Modules configuration +# + +config MXC_MC13892_ADC + tristate "MC13892 ADC support" + depends on MXC_PMIC_MC13892 + ---help--- + This is the MC13892 ADC module driver. This module provides kernel API + for the ADC system of MC13892. + It controls also the touch screen interface. + If you want MC13892 ADC support, you should say Y here + +config MXC_MC13892_RTC + tristate "MC13892 Real Time Clock (RTC) support" + depends on MXC_PMIC_MC13892 + ---help--- + This is the MC13892 RTC module driver. This module provides kernel API + for RTC part of MC13892. + If you want MC13892 RTC support, you should say Y here +config MXC_MC13892_LIGHT + tristate "MC13892 Light and Backlight support" + depends on MXC_PMIC_MC13892 + ---help--- + This is the MC13892 Light module driver. This module provides kernel API + for led and backlight control part of MC13892. + If you want MC13892 Light support, you should say Y here +config MXC_MC13892_BATTERY + tristate "MC13892 Battery API support" + depends on MXC_PMIC_MC13892 + ---help--- + This is the MC13892 battery module driver. This module provides kernel API + for battery control part of MC13892. + If you want MC13892 battery support, you should say Y here +config MXC_MC13892_CONNECTIVITY + tristate "MC13892 Connectivity API support" + depends on MXC_PMIC_MC13892 + ---help--- + This is the MC13892 connectivity module driver. This module provides kernel API + for USB/RS232 connectivity control part of MC13892. + If you want MC13892 connectivity support, you should say Y here +config MXC_MC13892_POWER + tristate "MC13892 Power API support" + depends on MXC_PMIC_MC13892 + ---help--- + This is the MC13892 power and supplies module driver. This module provides kernel API + for power and regulator control part of MC13892. + If you want MC13892 power support, you should say Y here diff --git a/drivers/mxc/pmic/mc13892/Makefile b/drivers/mxc/pmic/mc13892/Makefile new file mode 100644 index 000000000000..0ed2b7eb4c11 --- /dev/null +++ b/drivers/mxc/pmic/mc13892/Makefile @@ -0,0 +1,10 @@ +# +# Makefile for the mc13783 pmic drivers. +# + +obj-$(CONFIG_MXC_MC13892_ADC) += pmic_adc.o +#obj-$(CONFIG_MXC_MC13892_RTC) += pmic_rtc.o +obj-$(CONFIG_MXC_MC13892_LIGHT) += pmic_light.o +obj-$(CONFIG_MXC_MC13892_BATTERY) += pmic_battery.o +#obj-$(CONFIG_MXC_MC13892_CONNECTIVITY) += pmic_convity.o +#obj-$(CONFIG_MXC_MC13892_POWER) += pmic_power.o diff --git a/drivers/mxc/pmic/mc13892/pmic_adc.c b/drivers/mxc/pmic/mc13892/pmic_adc.c new file mode 100644 index 000000000000..a24446c22003 --- /dev/null +++ b/drivers/mxc/pmic/mc13892/pmic_adc.c @@ -0,0 +1,984 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "../core/pmic.h" + +#define DEF_ADC_0 0x008000 +#define DEF_ADC_3 0x0001c0 + +#define ADC_NB_AVAILABLE 2 + +#define MAX_CHANNEL 7 + +#define MC13892_ADC0_TS_M_LSH 14 +#define MC13892_ADC0_TS_M_WID 3 + +/* + * Maximun allowed variation in the three X/Y co-ordinates acquired from + * touch-screen + */ +#define DELTA_Y_MAX 50 +#define DELTA_X_MAX 50 + +/* + * ADC 0 + */ +#define ADC_WAIT_TSI_0 0x001400 + +#define ADC_INC 0x030000 +#define ADC_BIS 0x800000 +#define ADC_CHRGRAW_D5 0x008000 + +/* + * ADC 1 + */ + +#define ADC_EN 0x000001 +#define ADC_SGL_CH 0x000002 +#define ADC_ADSEL 0x000008 +#define ADC_CH_0_POS 5 +#define ADC_CH_0_MASK 0x0000E0 +#define ADC_CH_1_POS 8 +#define ADC_CH_1_MASK 0x000700 +#define ADC_DELAY_POS 11 +#define ADC_DELAY_MASK 0x07F800 +#define ADC_ATO 0x080000 +#define ASC_ADC 0x100000 +#define ADC_WAIT_TSI_1 0x200001 +#define ADC_NO_ADTRIG 0x200000 + +/* + * ADC 2 - 4 + */ +#define ADD1_RESULT_MASK 0x00000FFC +#define ADD2_RESULT_MASK 0x00FFC000 +#define ADC_TS_MASK 0x00FFCFFC + +#define ADC_WCOMP 0x040000 +#define ADC_WCOMP_H_POS 0 +#define ADC_WCOMP_L_POS 9 +#define ADC_WCOMP_H_MASK 0x00003F +#define ADC_WCOMP_L_MASK 0x007E00 + +#define ADC_MODE_MASK 0x00003F + +#define ADC_INT_BISDONEI 0x02 +#define ADC_TSMODE_MASK 0x007000 + +typedef enum adc_state { + ADC_FREE, + ADC_USED, + ADC_MONITORING, +} t_adc_state; + +typedef enum reading_mode { + /*! + * Enables lithium cell reading + */ + M_LITHIUM_CELL = 0x000001, + /*! + * Enables charge current reading + */ + M_CHARGE_CURRENT = 0x000002, + /*! + * Enables battery current reading + */ + M_BATTERY_CURRENT = 0x000004, +} t_reading_mode; + +typedef struct { + /*! + * Delay before first conversion + */ + unsigned int delay; + /*! + * sets the ATX bit for delay on all conversion + */ + bool conv_delay; + /*! + * Sets the single channel mode + */ + bool single_channel; + /*! + * Channel selection 1 + */ + t_channel channel_0; + /*! + * Channel selection 2 + */ + t_channel channel_1; + /*! + * Used to configure ADC mode with t_reading_mode + */ + t_reading_mode read_mode; + /*! + * Sets the Touch screen mode + */ + bool read_ts; + /*! + * Wait TSI event before touch screen reading + */ + bool wait_tsi; + /*! + * Sets CHRGRAW scaling to divide by 5 + * Only supported on 2.0 and higher + */ + bool chrgraw_devide_5; + /*! + * Return ADC values + */ + unsigned int value[8]; + /*! + * Return touch screen values + */ + t_touch_screen ts_value; +} t_adc_param; + +static int pmic_adc_filter(t_touch_screen *ts_curr); +int mc13892_adc_request(bool read_ts); +int mc13892_adc_release(int adc_index); +t_reading_mode mc13892_set_read_mode(t_channel channel); +PMIC_STATUS mc13892_adc_read_ts(t_touch_screen *touch_sample, int wait_tsi); + +/* internal function */ +static void callback_tsi(void *); +static void callback_adcdone(void *); +static void callback_adcbisdone(void *); + +static int swait; + +static int suspend_flag; + +static wait_queue_head_t suspendq; + +/* EXPORTED FUNCTIONS */ +EXPORT_SYMBOL(pmic_adc_init); +EXPORT_SYMBOL(pmic_adc_deinit); +EXPORT_SYMBOL(pmic_adc_convert); +EXPORT_SYMBOL(pmic_adc_convert_8x); +EXPORT_SYMBOL(pmic_adc_set_touch_mode); +EXPORT_SYMBOL(pmic_adc_get_touch_mode); +EXPORT_SYMBOL(pmic_adc_get_touch_sample); + +static DECLARE_COMPLETION(adcdone_it); +static DECLARE_COMPLETION(adcbisdone_it); +static DECLARE_COMPLETION(adc_tsi); +static pmic_event_callback_t tsi_event; +static pmic_event_callback_t event_adc; +static pmic_event_callback_t event_adc_bis; +static bool data_ready_adc_1; +static bool data_ready_adc_2; +static bool adc_ts; +static bool wait_ts; +static bool monitor_en; +static bool monitor_adc; +static DECLARE_MUTEX(convert_mutex); + +static DECLARE_WAIT_QUEUE_HEAD(queue_adc_busy); +static t_adc_state adc_dev[2]; + +static unsigned channel_num[] = { + 0, + 1, + 3, + 4, + 2, + 0, + 1, + 3, + 4, + -1, + 5, + 6, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1 +}; + +static bool pmic_adc_ready; + +int is_pmic_adc_ready() +{ + return pmic_adc_ready; +} +EXPORT_SYMBOL(is_pmic_adc_ready); + + +static int pmic_adc_suspend(struct platform_device *pdev, pm_message_t state) +{ + suspend_flag = 1; + CHECK_ERROR(pmic_write_reg(REG_ADC0, DEF_ADC_0, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(REG_ADC1, 0, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(REG_ADC2, 0, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(REG_ADC3, DEF_ADC_3, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(REG_ADC4, 0, PMIC_ALL_BITS)); + + return 0; +}; + +static int pmic_adc_resume(struct platform_device *pdev) +{ + /* nothing for mc13892 adc */ + unsigned int adc_0_reg, adc_1_reg, reg_mask; + suspend_flag = 0; + + /* let interrupt of TSI again */ + adc_0_reg = ADC_WAIT_TSI_0; + reg_mask = ADC_WAIT_TSI_0; + CHECK_ERROR(pmic_write_reg(REG_ADC0, adc_0_reg, reg_mask)); + adc_1_reg = ADC_WAIT_TSI_1 | (ADC_BIS * adc_ts); + CHECK_ERROR(pmic_write_reg(REG_ADC1, adc_1_reg, PMIC_ALL_BITS)); + + while (swait > 0) { + swait--; + wake_up_interruptible(&suspendq); + } + + return 0; +}; + +static void callback_tsi(void *unused) +{ + pr_debug("*** TSI IT mc13892 PMIC_ADC_GET_TOUCH_SAMPLE ***\n"); + if (wait_ts) { + complete(&adc_tsi); + pmic_event_mask(EVENT_TSI); + } +} + +static void callback_adcdone(void *unused) +{ + if (data_ready_adc_1) + complete(&adcdone_it); +} + +static void callback_adcbisdone(void *unused) +{ + pr_debug("* adcdone bis it callback *\n"); + if (data_ready_adc_2) + complete(&adcbisdone_it); +} + +static int pmic_adc_filter(t_touch_screen *ts_curr) +{ + unsigned int ydiff, xdiff; + unsigned int sample_sumx, sample_sumy; + + if (ts_curr->contact_resistance == 0) { + ts_curr->x_position = 0; + ts_curr->y_position = 0; + return 0; + } + + ydiff = abs(ts_curr->y_position1 - ts_curr->y_position2); + if (ydiff > DELTA_Y_MAX) { + pr_debug("pmic_adc_filter: Ret pos y\n"); + return -1; + } + + xdiff = abs(ts_curr->x_position1 - ts_curr->x_position2); + if (xdiff > DELTA_X_MAX) { + pr_debug("mc13892_adc_filter: Ret pos x\n"); + return -1; + } + + sample_sumx = ts_curr->x_position1 + ts_curr->x_position2; + sample_sumy = ts_curr->y_position1 + ts_curr->y_position2; + + ts_curr->y_position = sample_sumy / 2; + ts_curr->x_position = sample_sumx / 2; + + return 0; +} + +int pmic_adc_init(void) +{ + unsigned int reg_value = 0, i = 0; + + if (suspend_flag == 1) + return -EBUSY; + + for (i = 0; i < ADC_NB_AVAILABLE; i++) + adc_dev[i] = ADC_FREE; + + CHECK_ERROR(pmic_write_reg(REG_ADC0, DEF_ADC_0, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(REG_ADC1, 0, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(REG_ADC2, 0, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(REG_ADC3, DEF_ADC_3, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(REG_ADC4, 0, PMIC_ALL_BITS)); + reg_value = 0x001000; + + data_ready_adc_1 = false; + data_ready_adc_2 = false; + adc_ts = false; + wait_ts = false; + monitor_en = false; + monitor_adc = false; + + /* sub to ADCDone IT */ + event_adc.param = NULL; + event_adc.func = callback_adcdone; + CHECK_ERROR(pmic_event_subscribe(EVENT_ADCDONEI, event_adc)); + + /* sub to ADCDoneBis IT */ + event_adc_bis.param = NULL; + event_adc_bis.func = callback_adcbisdone; + CHECK_ERROR(pmic_event_subscribe(EVENT_ADCBISDONEI, event_adc_bis)); + + /* sub to Touch Screen IT */ + tsi_event.param = NULL; + tsi_event.func = callback_tsi; + CHECK_ERROR(pmic_event_subscribe(EVENT_TSI, tsi_event)); + + return PMIC_SUCCESS; +} + +PMIC_STATUS pmic_adc_deinit(void) +{ + CHECK_ERROR(pmic_event_unsubscribe(EVENT_ADCDONEI, event_adc)); + CHECK_ERROR(pmic_event_unsubscribe(EVENT_ADCBISDONEI, event_adc_bis)); + CHECK_ERROR(pmic_event_unsubscribe(EVENT_TSI, tsi_event)); + + return PMIC_SUCCESS; +} + +int mc13892_adc_init_param(t_adc_param *adc_param) +{ + int i = 0; + + if (suspend_flag == 1) + return -EBUSY; + + adc_param->delay = 0; + adc_param->conv_delay = false; + adc_param->single_channel = false; + adc_param->channel_0 = BATTERY_VOLTAGE; + adc_param->channel_1 = BATTERY_VOLTAGE; + adc_param->read_mode = 0; + adc_param->wait_tsi = 0; + adc_param->chrgraw_devide_5 = true; + adc_param->read_ts = false; + adc_param->ts_value.x_position = 0; + adc_param->ts_value.y_position = 0; + adc_param->ts_value.contact_resistance = 0; + for (i = 0; i <= MAX_CHANNEL; i++) + adc_param->value[i] = 0; + + return 0; +} + +PMIC_STATUS mc13892_adc_convert(t_adc_param *adc_param) +{ + bool use_bis = false; + unsigned int adc_0_reg = 0, adc_1_reg = 0, reg_1 = 0, result_reg = + 0, i = 0; + unsigned int result = 0, temp = 0; + pmic_version_t mc13892_ver; + pr_debug("mc13892 ADC - mc13892_adc_convert ....\n"); + if (suspend_flag == 1) + return -EBUSY; + + if (adc_param->wait_tsi) { + /* configure adc to wait tsi interrupt */ + INIT_COMPLETION(adc_tsi); + + /*for ts don't use bis */ + /*put ts in interrupt mode */ + /* still kep reference? */ + adc_0_reg = 0x001400 | (ADC_BIS * 0); + pmic_event_unmask(EVENT_TSI); + CHECK_ERROR(pmic_write_reg(REG_ADC0, adc_0_reg, PMIC_ALL_BITS)); + /*for ts don't use bis */ + adc_1_reg = 0x200001 | (ADC_BIS * 0); + CHECK_ERROR(pmic_write_reg(REG_ADC1, adc_1_reg, PMIC_ALL_BITS)); + pr_debug("wait tsi ....\n"); + wait_ts = true; + wait_for_completion_interruptible(&adc_tsi); + wait_ts = false; + } + down(&convert_mutex); + use_bis = mc13892_adc_request(adc_param->read_ts); + if (use_bis < 0) { + pr_debug("process has received a signal and got interrupted\n"); + return -EINTR; + } + + /* CONFIGURE ADC REG 0 */ + adc_0_reg = 0; + adc_1_reg = 0; + if (adc_param->read_ts == false) { + adc_0_reg = adc_param->read_mode & 0x00003F; + /* add auto inc */ + adc_0_reg |= ADC_INC; + if (use_bis) { + /* add adc bis */ + adc_0_reg |= ADC_BIS; + } + mc13892_ver = pmic_get_version(); + if (mc13892_ver.revision >= 20) + if (adc_param->chrgraw_devide_5) + adc_0_reg |= ADC_CHRGRAW_D5; + + if (adc_param->single_channel) + adc_1_reg |= ADC_SGL_CH; + + if (adc_param->conv_delay) + adc_1_reg |= ADC_ATO; + + if (adc_param->single_channel) + adc_1_reg |= ADC_SGL_CH; + + adc_1_reg |= (adc_param->channel_0 << ADC_CH_0_POS) & + ADC_CH_0_MASK; + adc_1_reg |= (adc_param->channel_1 << ADC_CH_1_POS) & + ADC_CH_1_MASK; + } else { + adc_0_reg = 0x002400 | (ADC_BIS * use_bis) | ADC_INC; + } + pr_debug("Write Reg %i = %x\n", REG_ADC0, adc_0_reg); + /*Change has been made here */ + CHECK_ERROR(pmic_write_reg(REG_ADC0, adc_0_reg, + ADC_INC | ADC_BIS | ADC_CHRGRAW_D5 | + 0xfff00ff)); + /* CONFIGURE ADC REG 1 */ + if (adc_param->read_ts == false) { + adc_1_reg |= ADC_NO_ADTRIG; + adc_1_reg |= ADC_EN; + adc_1_reg |= (adc_param->delay << ADC_DELAY_POS) & + ADC_DELAY_MASK; + if (use_bis) + adc_1_reg |= ADC_BIS; + } else { + /* configure and start convert to read x and y position */ + /* configure to read 2 value in channel selection 1 & 2 */ + adc_1_reg = 0x100409 | (ADC_BIS * use_bis) | ADC_NO_ADTRIG; + /* set ATOx = 5, it could be better for ts ADC */ + adc_1_reg |= 0x002800; + } + reg_1 = adc_1_reg; + if (use_bis == 0) { + data_ready_adc_1 = false; + adc_1_reg |= ASC_ADC; + data_ready_adc_1 = true; + pr_debug("Write Reg %i = %x\n", REG_ADC1, adc_1_reg); + INIT_COMPLETION(adcdone_it); + CHECK_ERROR(pmic_write_reg(REG_ADC1, adc_1_reg, + ADC_SGL_CH | ADC_ATO | ADC_ADSEL + | ADC_CH_0_MASK | ADC_CH_1_MASK | + ADC_NO_ADTRIG | ADC_EN | + ADC_DELAY_MASK | ASC_ADC | ADC_BIS)); + pr_debug("wait adc done \n"); + wait_for_completion_interruptible(&adcdone_it); + data_ready_adc_1 = false; + } else { + data_ready_adc_2 = false; + adc_1_reg |= ASC_ADC; + data_ready_adc_2 = true; + INIT_COMPLETION(adcbisdone_it); + CHECK_ERROR(pmic_write_reg(REG_ADC1, adc_1_reg, 0xFFFFFF)); + temp = 0x800000; + CHECK_ERROR(pmic_write_reg(REG_ADC3, temp, 0xFFFFFF)); + pr_debug("wait adc done bis\n"); + wait_for_completion_interruptible(&adcbisdone_it); + data_ready_adc_2 = false; + } + /* read result and store in adc_param */ + result = 0; + if (use_bis == 0) + result_reg = REG_ADC2; + else + result_reg = REG_ADC4; + + CHECK_ERROR(pmic_write_reg(REG_ADC1, 4 << ADC_CH_1_POS, + ADC_CH_0_MASK | ADC_CH_1_MASK)); + + for (i = 0; i <= 3; i++) { + CHECK_ERROR(pmic_read_reg(result_reg, &result, PMIC_ALL_BITS)); + adc_param->value[i] = ((result & ADD1_RESULT_MASK) >> 2); + adc_param->value[i + 4] = ((result & ADD2_RESULT_MASK) >> 14); + pr_debug("value[%d] = %d, value[%d] = %d\n", + i, adc_param->value[i], + i + 4, adc_param->value[i + 4]); + } + if (adc_param->read_ts) { + adc_param->ts_value.x_position = adc_param->value[0]; + adc_param->ts_value.x_position1 = adc_param->value[0]; + adc_param->ts_value.x_position2 = adc_param->value[1]; + adc_param->ts_value.y_position = adc_param->value[3]; + adc_param->ts_value.y_position1 = adc_param->value[3]; + adc_param->ts_value.y_position2 = adc_param->value[4]; + adc_param->ts_value.contact_resistance = adc_param->value[6]; + CHECK_ERROR(pmic_write_reg(REG_ADC0, 0x0, + ADC_TSMODE_MASK)); + } + + /*if (adc_param->read_ts) { + adc_param->ts_value.x_position = adc_param->value[2]; + adc_param->ts_value.y_position = adc_param->value[5]; + adc_param->ts_value.contact_resistance = adc_param->value[6]; + } */ + mc13892_adc_release(use_bis); + up(&convert_mutex); + + return PMIC_SUCCESS; +} + +t_reading_mode mc13892_set_read_mode(t_channel channel) +{ + t_reading_mode read_mode = 0; + + switch (channel) { + case CHARGE_CURRENT: + read_mode = M_CHARGE_CURRENT; + break; + case BATTERY_CURRENT: + read_mode = M_BATTERY_CURRENT; + break; + default: + read_mode = 0; + } + + return read_mode; +} + +PMIC_STATUS pmic_adc_convert(t_channel channel, unsigned short *result) +{ + t_adc_param adc_param; + PMIC_STATUS ret; + + if (suspend_flag == 1) + return -EBUSY; + + channel = channel_num[channel]; + if (channel == -1) { + pr_debug("Wrong channel ID\n"); + return PMIC_PARAMETER_ERROR; + } + mc13892_adc_init_param(&adc_param); + pr_debug("pmic_adc_convert\n"); + adc_param.read_ts = false; + adc_param.single_channel = true; + adc_param.read_mode = mc13892_set_read_mode(channel); + + /* Find the group */ + if (channel <= 7) + adc_param.channel_0 = channel; + else + return PMIC_PARAMETER_ERROR; + + ret = mc13892_adc_convert(&adc_param); + *result = adc_param.value[0]; + return ret; +} + +PMIC_STATUS pmic_adc_convert_8x(t_channel channel, unsigned short *result) +{ + t_adc_param adc_param; + int i; + PMIC_STATUS ret; + if (suspend_flag == 1) + return -EBUSY; + + channel = channel_num[channel]; + + if (channel == -1) { + pr_debug("Wrong channel ID\n"); + return PMIC_PARAMETER_ERROR; + } + mc13892_adc_init_param(&adc_param); + pr_debug("pmic_adc_convert_8x\n"); + adc_param.read_ts = false; + adc_param.single_channel = true; + adc_param.read_mode = mc13892_set_read_mode(channel); + + if (channel <= 7) { + adc_param.channel_0 = channel; + adc_param.channel_1 = channel; + } else + return PMIC_PARAMETER_ERROR; + + ret = mc13892_adc_convert(&adc_param); + for (i = 0; i <= 7; i++) + result[i] = adc_param.value[i]; + + return ret; +} + +PMIC_STATUS pmic_adc_set_touch_mode(t_touch_mode touch_mode) +{ + if (suspend_flag == 1) + return -EBUSY; + + CHECK_ERROR(pmic_write_reg(REG_ADC0, + BITFVAL(MC13892_ADC0_TS_M, touch_mode), + BITFMASK(MC13892_ADC0_TS_M))); + return PMIC_SUCCESS; +} + +PMIC_STATUS pmic_adc_get_touch_mode(t_touch_mode *touch_mode) +{ + unsigned int value; + if (suspend_flag == 1) + return -EBUSY; + + CHECK_ERROR(pmic_read_reg(REG_ADC0, &value, PMIC_ALL_BITS)); + + *touch_mode = BITFEXT(value, MC13892_ADC0_TS_M); + + return PMIC_SUCCESS; +} + +PMIC_STATUS pmic_adc_get_touch_sample(t_touch_screen *touch_sample, int wait) +{ + if (mc13892_adc_read_ts(touch_sample, wait) != 0) + return PMIC_ERROR; + if (0 == pmic_adc_filter(touch_sample)) + return PMIC_SUCCESS; + else + return PMIC_ERROR; +} + +PMIC_STATUS mc13892_adc_read_ts(t_touch_screen *ts_value, int wait_tsi) +{ + t_adc_param param; + pr_debug("mc13892_adc : mc13892_adc_read_ts\n"); + if (suspend_flag == 1) + return -EBUSY; + + if (wait_ts) { + pr_debug("mc13892_adc : error TS busy \n"); + return PMIC_ERROR; + } + mc13892_adc_init_param(¶m); + param.wait_tsi = wait_tsi; + param.read_ts = true; + if (mc13892_adc_convert(¶m) != 0) + return PMIC_ERROR; + /* check if x-y is ok */ + if (param.ts_value.contact_resistance < 1000) { + ts_value->x_position = param.ts_value.x_position; + ts_value->x_position1 = param.ts_value.x_position1; + ts_value->x_position2 = param.ts_value.x_position2; + + ts_value->y_position = param.ts_value.y_position; + ts_value->y_position1 = param.ts_value.y_position1; + ts_value->y_position2 = param.ts_value.y_position2; + + ts_value->contact_resistance = + param.ts_value.contact_resistance + 1; + + } else { + ts_value->x_position = 0; + ts_value->y_position = 0; + ts_value->contact_resistance = 0; + + } + return PMIC_SUCCESS; +} + +int mc13892_adc_request(bool read_ts) +{ + int adc_index = -1; + if (read_ts != 0) { + /*for ts we use bis=0 */ + if (adc_dev[0] == ADC_USED) + return -1; + /*no wait here */ + adc_dev[0] = ADC_USED; + adc_index = 0; + } else { + /*for other adc use bis = 1 */ + if (adc_dev[1] == ADC_USED) { + return -1; + /*no wait here */ + } + adc_dev[1] = ADC_USED; + adc_index = 1; + } + pr_debug("mc13892_adc : request ADC %d\n", adc_index); + return adc_index; +} + +int mc13892_adc_release(int adc_index) +{ + while (suspend_flag == 1) { + swait++; + /* Block if the device is suspended */ + if (wait_event_interruptible(suspendq, (suspend_flag == 0))) + return -ERESTARTSYS; + } + + pr_debug("mc13892_adc : release ADC %d\n", adc_index); + if ((adc_dev[adc_index] == ADC_MONITORING) || + (adc_dev[adc_index] == ADC_USED)) { + adc_dev[adc_index] = ADC_FREE; + wake_up(&queue_adc_busy); + return 0; + } + return -1; +} + +#ifdef DEBUG +static t_adc_param adc_param_db; + +static ssize_t adc_info(struct device *dev, struct device_attribute *attr, + char *buf) +{ + int *value = adc_param_db.value; + + pr_debug("adc_info\n"); + + pr_debug("ch0\t\t%d\n", adc_param_db.channel_0); + pr_debug("ch1\t\t%d\n", adc_param_db.channel_1); + pr_debug("d5\t\t%d\n", adc_param_db.chrgraw_devide_5); + pr_debug("conv delay\t%d\n", adc_param_db.conv_delay); + pr_debug("delay\t\t%d\n", adc_param_db.delay); + pr_debug("read mode\t%d\n", adc_param_db.read_mode); + pr_debug("read ts\t\t%d\n", adc_param_db.read_ts); + pr_debug("single ch\t%d\n", adc_param_db.single_channel); + pr_debug("wait ts int\t%d\n", adc_param_db.wait_tsi); + pr_debug("value0-3:\t%d\t%d\t%d\t%d\n", value[0], value[1], + value[2], value[3]); + pr_debug("value4-7:\t%d\t%d\t%d\t%d\n", value[4], value[5], + value[6], value[7]); + + return 0; +} + +enum { + ADC_SET_CH0 = 0, + ADC_SET_CH1, + ADC_SET_DV5, + ADC_SET_CON_DELAY, + ADC_SET_DELAY, + ADC_SET_RM, + ADC_SET_RT, + ADC_SET_S_CH, + ADC_SET_WAIT_TS, + ADC_INIT_P, + ADC_START, + ADC_TS, + ADC_TS_READ, + ADC_TS_CAL, + ADC_CMD_MAX +}; + +static const char *const adc_cmd[ADC_CMD_MAX] = { + [ADC_SET_CH0] = "ch0", + [ADC_SET_CH1] = "ch1", + [ADC_SET_DV5] = "dv5", + [ADC_SET_CON_DELAY] = "cd", + [ADC_SET_DELAY] = "dl", + [ADC_SET_RM] = "rm", + [ADC_SET_RT] = "rt", + [ADC_SET_S_CH] = "sch", + [ADC_SET_WAIT_TS] = "wt", + [ADC_INIT_P] = "init", + [ADC_START] = "start", + [ADC_TS] = "touch", + [ADC_TS_READ] = "touchr", + [ADC_TS_CAL] = "cal" +}; + +static int cmd(unsigned int index, int value) +{ + t_touch_screen ts; + + switch (index) { + case ADC_SET_CH0: + adc_param_db.channel_0 = value; + break; + case ADC_SET_CH1: + adc_param_db.channel_1 = value; + break; + case ADC_SET_DV5: + adc_param_db.chrgraw_devide_5 = value; + break; + case ADC_SET_CON_DELAY: + adc_param_db.conv_delay = value; + break; + case ADC_SET_RM: + adc_param_db.read_mode = value; + break; + case ADC_SET_RT: + adc_param_db.read_ts = value; + break; + case ADC_SET_S_CH: + adc_param_db.single_channel = value; + break; + case ADC_SET_WAIT_TS: + adc_param_db.wait_tsi = value; + break; + case ADC_INIT_P: + mc13892_adc_init_param(&adc_param_db); + break; + case ADC_START: + mc13892_adc_convert(&adc_param_db); + break; + case ADC_TS: + pmic_adc_get_touch_sample(&ts, 1); + pr_debug("x = %d\n", ts.x_position); + pr_debug("y = %d\n", ts.y_position); + pr_debug("p = %d\n", ts.contact_resistance); + break; + case ADC_TS_READ: + pmic_adc_get_touch_sample(&ts, 0); + pr_debug("x = %d\n", ts.x_position); + pr_debug("y = %d\n", ts.y_position); + pr_debug("p = %d\n", ts.contact_resistance); + break; + case ADC_TS_CAL: + break; + default: + pr_debug("error command\n"); + break; + } + return 0; +} + +static ssize_t adc_ctl(struct device *dev, struct device_attribute *attr, + const char *buf, size_t count) +{ + int state = 0; + const char *const *s; + char *p, *q; + int error; + int len, value = 0; + + pr_debug("adc_ctl\n"); + + q = NULL; + q = memchr(buf, ' ', count); + + if (q != NULL) { + len = q - buf; + q += 1; + value = simple_strtoul(q, NULL, 10); + } else { + p = memchr(buf, '\n', count); + len = p ? p - buf : count; + } + + for (s = &adc_cmd[state]; state < ADC_CMD_MAX; s++, state++) { + if (*s && !strncmp(buf, *s, len)) + break; + } + if (state < ADC_CMD_MAX && *s) + error = cmd(state, value); + else + error = -EINVAL; + + return count; +} + +#else +static ssize_t adc_info(struct device *dev, struct device_attribute *attr, + char *buf) +{ + return 0; +} + +static ssize_t adc_ctl(struct device *dev, struct device_attribute *attr, + const char *buf, size_t count) +{ + return count; +} + +#endif + +static DEVICE_ATTR(adc, 0644, adc_info, adc_ctl); + +static int pmic_adc_module_probe(struct platform_device *pdev) +{ + int ret = 0; + + pr_debug("PMIC ADC start probe\n"); + ret = device_create_file(&(pdev->dev), &dev_attr_adc); + if (ret) { + pr_debug("Can't create device file!\n"); + return -ENODEV; + } + + init_waitqueue_head(&suspendq); + + ret = pmic_adc_init(); + if (ret != PMIC_SUCCESS) { + pr_debug("Error in pmic_adc_init.\n"); + goto rm_dev_file; + } + + pmic_adc_ready = 1; + pr_debug("PMIC ADC successfully probed\n"); + return 0; + + rm_dev_file: + device_remove_file(&(pdev->dev), &dev_attr_adc); + return ret; +} + +static int pmic_adc_module_remove(struct platform_device *pdev) +{ + pmic_adc_deinit(); + pmic_adc_ready = 0; + pr_debug("PMIC ADC successfully removed\n"); + return 0; +} + +static struct platform_driver pmic_adc_driver_ldm = { + .driver = { + .name = "pmic_adc", + }, + .suspend = pmic_adc_suspend, + .resume = pmic_adc_resume, + .probe = pmic_adc_module_probe, + .remove = pmic_adc_module_remove, +}; + +static int __init pmic_adc_module_init(void) +{ + pr_debug("PMIC ADC driver loading...\n"); + return platform_driver_register(&pmic_adc_driver_ldm); +} + +static void __exit pmic_adc_module_exit(void) +{ + platform_driver_unregister(&pmic_adc_driver_ldm); + pr_debug("PMIC ADC driver successfully unloaded\n"); +} + +module_init(pmic_adc_module_init); +module_exit(pmic_adc_module_exit); + +MODULE_DESCRIPTION("PMIC ADC device driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/pmic/mc13892/pmic_battery.c b/drivers/mxc/pmic/mc13892/pmic_battery.c new file mode 100644 index 000000000000..905ffd17a1c5 --- /dev/null +++ b/drivers/mxc/pmic/mc13892/pmic_battery.c @@ -0,0 +1,634 @@ +/* + * Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/* + * Includes + */ +#include +#include +#include +#include +#include +#include +#include +#include + +#define BIT_CHG_VOL_LSH 0 +#define BIT_CHG_VOL_WID 3 + +#define BIT_CHG_CURR_LSH 3 +#define BIT_CHG_CURR_WID 4 + +#define BIT_CHG_PLIM_LSH 15 +#define BIT_CHG_PLIM_WID 2 + +#define BIT_CHG_DETS_LSH 6 +#define BIT_CHG_DETS_WID 1 +#define BIT_CHG_CURRS_LSH 11 +#define BIT_CHG_CURRS_WID 1 + +#define TRICKLE_CHG_EN_LSH 7 +#define LOW_POWER_BOOT_ACK_LSH 8 +#define BAT_TH_CHECK_DIS_LSH 9 +#define BATTFET_CTL_EN_LSH 10 +#define BATTFET_CTL_LSH 11 +#define REV_MOD_EN_LSH 13 +#define PLIM_DIS_LSH 17 +#define CHG_LED_EN_LSH 18 +#define RESTART_CHG_STAT_LSH 20 +#define AUTO_CHG_DIS_LSH 21 +#define CYCLING_DIS_LSH 22 +#define VI_PROGRAM_EN_LSH 23 + +#define TRICKLE_CHG_EN_WID 1 +#define LOW_POWER_BOOT_ACK_WID 1 +#define BAT_TH_CHECK_DIS_WID 1 +#define BATTFET_CTL_EN_WID 1 +#define BATTFET_CTL_WID 1 +#define REV_MOD_EN_WID 1 +#define PLIM_DIS_WID 1 +#define CHG_LED_EN_WID 1 +#define RESTART_CHG_STAT_WID 1 +#define AUTO_CHG_DIS_WID 1 +#define CYCLING_DIS_WID 1 +#define VI_PROGRAM_EN_WID 1 + +#define ACC_STARTCC_LSH 0 +#define ACC_STARTCC_WID 1 +#define ACC_RSTCC_LSH 1 +#define ACC_RSTCC_WID 1 +#define ACC_CCFAULT_LSH 7 +#define ACC_CCFAULT_WID 7 +#define ACC_CCOUT_LSH 8 +#define ACC_CCOUT_WID 16 +#define ACC1_ONEC_LSH 0 +#define ACC1_ONEC_WID 15 + +#define ACC_CALIBRATION 0x17 +#define ACC_START_COUNTER 0x07 +#define ACC_STOP_COUNTER 0x2 +#define ACC_CONTROL_BIT_MASK 0x1f +#define ACC_ONEC_VALUE 2621 +#define ACC_COULOMB_PER_LSB 1 +#define ACC_CALIBRATION_DURATION_MSECS 20 + +#define BAT_VOLTAGE_UNIT_UV 4692 +#define BAT_CURRENT_UNIT_UA 5870 +#define CHG_VOLTAGE_UINT_UV 23474 +#define CHG_MIN_CURRENT_UA 3500 + +#define COULOMB_TO_UAH(c) (10000 * c / 36) + +enum chg_setting { + TRICKLE_CHG_EN, + LOW_POWER_BOOT_ACK, + BAT_TH_CHECK_DIS, + BATTFET_CTL_EN, + BATTFET_CTL, + REV_MOD_EN, + PLIM_DIS, + CHG_LED_EN, + RESTART_CHG_STAT, + AUTO_CHG_DIS, + CYCLING_DIS, + VI_PROGRAM_EN +}; + +static int pmic_set_chg_current(unsigned short curr) +{ + unsigned int mask; + unsigned int value; + + value = BITFVAL(BIT_CHG_CURR, curr); + mask = BITFMASK(BIT_CHG_CURR); + CHECK_ERROR(pmic_write_reg(REG_CHARGE, value, mask)); + + return 0; +} + +static int pmic_set_chg_misc(enum chg_setting type, unsigned short flag) +{ + + unsigned int reg_value = 0; + unsigned int mask = 0; + + switch (type) { + case TRICKLE_CHG_EN: + reg_value = BITFVAL(TRICKLE_CHG_EN, flag); + mask = BITFMASK(TRICKLE_CHG_EN); + break; + case LOW_POWER_BOOT_ACK: + reg_value = BITFVAL(LOW_POWER_BOOT_ACK, flag); + mask = BITFMASK(LOW_POWER_BOOT_ACK); + break; + case BAT_TH_CHECK_DIS: + reg_value = BITFVAL(BAT_TH_CHECK_DIS, flag); + mask = BITFMASK(BAT_TH_CHECK_DIS); + break; + case BATTFET_CTL_EN: + reg_value = BITFVAL(BATTFET_CTL_EN, flag); + mask = BITFMASK(BATTFET_CTL_EN); + break; + case BATTFET_CTL: + reg_value = BITFVAL(BATTFET_CTL, flag); + mask = BITFMASK(BATTFET_CTL); + break; + case REV_MOD_EN: + reg_value = BITFVAL(REV_MOD_EN, flag); + mask = BITFMASK(REV_MOD_EN); + break; + case PLIM_DIS: + reg_value = BITFVAL(PLIM_DIS, flag); + mask = BITFMASK(PLIM_DIS); + break; + case CHG_LED_EN: + reg_value = BITFVAL(CHG_LED_EN, flag); + mask = BITFMASK(CHG_LED_EN); + break; + case RESTART_CHG_STAT: + reg_value = BITFVAL(RESTART_CHG_STAT, flag); + mask = BITFMASK(RESTART_CHG_STAT); + break; + case AUTO_CHG_DIS: + reg_value = BITFVAL(AUTO_CHG_DIS, flag); + mask = BITFMASK(AUTO_CHG_DIS); + break; + case CYCLING_DIS: + reg_value = BITFVAL(CYCLING_DIS, flag); + mask = BITFMASK(CYCLING_DIS); + break; + case VI_PROGRAM_EN: + reg_value = BITFVAL(VI_PROGRAM_EN, flag); + mask = BITFMASK(VI_PROGRAM_EN); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_write_reg(REG_CHARGE, reg_value, mask)); + + return 0; +} + +static int pmic_get_batt_voltage(unsigned short *voltage) +{ + t_channel channel; + unsigned short result[8]; + + channel = BATTERY_VOLTAGE; + CHECK_ERROR(pmic_adc_convert(channel, result)); + *voltage = result[0]; + + return 0; +} + +static int pmic_get_batt_current(unsigned short *curr) +{ + t_channel channel; + unsigned short result[8]; + + channel = BATTERY_CURRENT; + CHECK_ERROR(pmic_adc_convert(channel, result)); + *curr = result[0]; + + return 0; +} + +static int coulomb_counter_calibration; +static unsigned int coulomb_counter_start_time_msecs; + +static int pmic_start_coulomb_counter(void) +{ + /* set scaler */ + CHECK_ERROR(pmic_write_reg(REG_ACC1, + ACC_COULOMB_PER_LSB * ACC_ONEC_VALUE, BITFMASK(ACC1_ONEC))); + + CHECK_ERROR(pmic_write_reg( + REG_ACC0, ACC_START_COUNTER, ACC_CONTROL_BIT_MASK)); + coulomb_counter_start_time_msecs = jiffies_to_msecs(jiffies); + pr_debug("coulomb counter start time %u\n", + coulomb_counter_start_time_msecs); + return 0; +} + +static int pmic_stop_coulomb_counter(void) +{ + CHECK_ERROR(pmic_write_reg( + REG_ACC0, ACC_STOP_COUNTER, ACC_CONTROL_BIT_MASK)); + return 0; +} + +static int pmic_calibrate_coulomb_counter(void) +{ + int ret; + unsigned int value; + + /* set scaler */ + CHECK_ERROR(pmic_write_reg(REG_ACC1, + 0x1, BITFMASK(ACC1_ONEC))); + + CHECK_ERROR(pmic_write_reg( + REG_ACC0, ACC_CALIBRATION, ACC_CONTROL_BIT_MASK)); + msleep(ACC_CALIBRATION_DURATION_MSECS); + + ret = pmic_read_reg(REG_ACC0, &value, BITFMASK(ACC_CCOUT)); + if (ret != 0) + return -1; + value = BITFEXT(value, ACC_CCOUT); + pr_debug("calibrate value = %x\n", value); + coulomb_counter_calibration = (int)((s16)((u16) value)); + pr_debug("coulomb_counter_calibration = %d\n", + coulomb_counter_calibration); + + return 0; + +} + +static int pmic_get_charger_coulomb(int *coulomb) +{ + int ret; + unsigned int value; + int calibration; + unsigned int time_diff_msec; + + ret = pmic_read_reg(REG_ACC0, &value, BITFMASK(ACC_CCOUT)); + if (ret != 0) + return -1; + value = BITFEXT(value, ACC_CCOUT); + pr_debug("counter value = %x\n", value); + *coulomb = ((s16)((u16)value)) * ACC_COULOMB_PER_LSB; + + if (abs(*coulomb) >= ACC_COULOMB_PER_LSB) { + /* calibrate */ + time_diff_msec = jiffies_to_msecs(jiffies); + time_diff_msec = + (time_diff_msec > coulomb_counter_start_time_msecs) ? + (time_diff_msec - coulomb_counter_start_time_msecs) : + (0xffffffff - coulomb_counter_start_time_msecs + + time_diff_msec); + calibration = coulomb_counter_calibration * (int)time_diff_msec + / (ACC_ONEC_VALUE * ACC_CALIBRATION_DURATION_MSECS); + *coulomb -= calibration; + } + + return 0; +} + +static int pmic_restart_charging(void) +{ + pmic_set_chg_misc(BAT_TH_CHECK_DIS, 1); + pmic_set_chg_misc(AUTO_CHG_DIS, 0); + pmic_set_chg_misc(VI_PROGRAM_EN, 1); + pmic_set_chg_current(0x8); + pmic_set_chg_misc(RESTART_CHG_STAT, 1); + return 0; +} + +struct mc13892_dev_info { + struct device *dev; + + unsigned short voltage_raw; + int voltage_uV; + unsigned short current_raw; + int current_uA; + int battery_status; + int full_counter; + int charger_online; + int charger_voltage_uV; + int accum_current_uAh; + + struct power_supply bat; + struct power_supply charger; + + struct workqueue_struct *monitor_wqueue; + struct delayed_work monitor_work; +}; + +#define mc13892_SENSER 25 +#define to_mc13892_dev_info(x) container_of((x), struct mc13892_dev_info, \ + bat); + +static enum power_supply_property mc13892_battery_props[] = { + POWER_SUPPLY_PROP_VOLTAGE_NOW, + POWER_SUPPLY_PROP_CURRENT_NOW, + POWER_SUPPLY_PROP_CHARGE_NOW, + POWER_SUPPLY_PROP_STATUS, +}; + +static enum power_supply_property mc13892_charger_props[] = { + POWER_SUPPLY_PROP_ONLINE, +}; + +static int mc13892_charger_update_status(struct mc13892_dev_info *di) +{ + int ret; + unsigned int value; + int online; + + ret = pmic_read_reg(REG_INT_SENSE0, &value, BITFMASK(BIT_CHG_DETS)); + + if (ret == 0) { + online = BITFEXT(value, BIT_CHG_DETS); + if (online != di->charger_online) { + di->charger_online = online; + dev_info(di->charger.dev, "charger status: %s\n", + online ? "online" : "offline"); + power_supply_changed(&di->charger); + + cancel_delayed_work(&di->monitor_work); + queue_delayed_work(di->monitor_wqueue, + &di->monitor_work, HZ / 10); + if (online) { + pmic_start_coulomb_counter(); + pmic_restart_charging(); + } else + pmic_stop_coulomb_counter(); + } + } + + return ret; +} + +static int mc13892_charger_get_property(struct power_supply *psy, + enum power_supply_property psp, + union power_supply_propval *val) +{ + struct mc13892_dev_info *di = + container_of((psy), struct mc13892_dev_info, charger); + + switch (psp) { + case POWER_SUPPLY_PROP_ONLINE: + val->intval = di->charger_online; + return 0; + default: + break; + } + return -EINVAL; +} + +static int mc13892_battery_read_status(struct mc13892_dev_info *di) +{ + int retval; + int coulomb; + retval = pmic_get_batt_voltage(&(di->voltage_raw)); + if (retval == 0) + di->voltage_uV = di->voltage_raw * BAT_VOLTAGE_UNIT_UV; + + retval = pmic_get_batt_current(&(di->current_raw)); + if (retval == 0) { + if (di->current_raw & 0x200) + di->current_uA = + (0x1FF - (di->current_raw & 0x1FF)) * + BAT_CURRENT_UNIT_UA * (-1); + else + di->current_uA = + (di->current_raw & 0x1FF) * BAT_CURRENT_UNIT_UA; + } + retval = pmic_get_charger_coulomb(&coulomb); + if (retval == 0) + di->accum_current_uAh = COULOMB_TO_UAH(coulomb); + + return retval; +} + +static void mc13892_battery_update_status(struct mc13892_dev_info *di) +{ + unsigned int value; + int retval; + int old_battery_status = di->battery_status; + + if (di->battery_status == POWER_SUPPLY_STATUS_UNKNOWN) + di->full_counter = 0; + + if (di->charger_online) { + retval = pmic_read_reg(REG_INT_SENSE0, + &value, BITFMASK(BIT_CHG_CURRS)); + + if (retval == 0) { + value = BITFEXT(value, BIT_CHG_CURRS); + if (value) + di->battery_status = + POWER_SUPPLY_STATUS_CHARGING; + else + di->battery_status = + POWER_SUPPLY_STATUS_NOT_CHARGING; + } + + if (di->battery_status == POWER_SUPPLY_STATUS_NOT_CHARGING) + di->full_counter++; + else + di->full_counter = 0; + } else { + di->battery_status = POWER_SUPPLY_STATUS_DISCHARGING; + di->full_counter = 0; + } + + dev_dbg(di->bat.dev, "bat status: %d\n", + di->battery_status); + + if (di->battery_status != old_battery_status) + power_supply_changed(&di->bat); +} + +static void mc13892_battery_work(struct work_struct *work) +{ + struct mc13892_dev_info *di = container_of(work, + struct mc13892_dev_info, + monitor_work.work); + const int interval = HZ * 60; + + dev_dbg(di->dev, "%s\n", __func__); + + mc13892_battery_update_status(di); + queue_delayed_work(di->monitor_wqueue, &di->monitor_work, interval); +} + +static void charger_online_event_callback(void *para) +{ + struct mc13892_dev_info *di = (struct mc13892_dev_info *) para; + pr_info("\n\n DETECTED charger plug/unplug event\n"); + mc13892_charger_update_status(di); +} + + +static int mc13892_battery_get_property(struct power_supply *psy, + enum power_supply_property psp, + union power_supply_propval *val) +{ + struct mc13892_dev_info *di = to_mc13892_dev_info(psy); + switch (psp) { + case POWER_SUPPLY_PROP_STATUS: + if (di->battery_status == POWER_SUPPLY_STATUS_UNKNOWN) { + mc13892_charger_update_status(di); + mc13892_battery_update_status(di); + } + val->intval = di->battery_status; + return 0; + default: + break; + } + + mc13892_battery_read_status(di); + + switch (psp) { + case POWER_SUPPLY_PROP_VOLTAGE_NOW: + val->intval = di->voltage_uV; + break; + case POWER_SUPPLY_PROP_CURRENT_NOW: + val->intval = di->current_uA; + break; + case POWER_SUPPLY_PROP_CHARGE_NOW: + val->intval = di->accum_current_uAh; + break; + case POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN: + val->intval = 3800000; + break; + case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN: + val->intval = 3300000; + break; + default: + return -EINVAL; + } + + return 0; +} + +static int pmic_battery_remove(struct platform_device *pdev) +{ + pmic_event_callback_t bat_event_callback; + struct mc13892_dev_info *di = platform_get_drvdata(pdev); + + bat_event_callback.func = charger_online_event_callback; + bat_event_callback.param = (void *) di; + pmic_event_unsubscribe(EVENT_CHGDETI, bat_event_callback); + + cancel_rearming_delayed_workqueue(di->monitor_wqueue, + &di->monitor_work); + destroy_workqueue(di->monitor_wqueue); + power_supply_unregister(&di->bat); + power_supply_unregister(&di->charger); + + kfree(di); + + return 0; +} + +static int pmic_battery_probe(struct platform_device *pdev) +{ + int retval = 0; + struct mc13892_dev_info *di; + pmic_event_callback_t bat_event_callback; + pmic_version_t pmic_version; + + /* Only apply battery driver for MC13892 V2.0 due to ENGR108085 */ + pmic_version = pmic_get_version(); + if (pmic_version.revision < 20) { + pr_debug("Battery driver is only applied for MC13892 V2.0\n"); + return -1; + } + if (machine_is_mx51_babbage() || machine_is_mx50_arm2()) { + pr_debug("mc13892 charger is not used for this platform\n"); + return -1; + } + + di = kzalloc(sizeof(*di), GFP_KERNEL); + if (!di) { + retval = -ENOMEM; + goto di_alloc_failed; + } + + platform_set_drvdata(pdev, di); + + di->dev = &pdev->dev; + di->bat.name = "mc13892_bat"; + di->bat.type = POWER_SUPPLY_TYPE_BATTERY; + di->bat.properties = mc13892_battery_props; + di->bat.num_properties = ARRAY_SIZE(mc13892_battery_props); + di->bat.get_property = mc13892_battery_get_property; + di->bat.use_for_apm = 1; + + di->battery_status = POWER_SUPPLY_STATUS_UNKNOWN; + + retval = power_supply_register(&pdev->dev, &di->bat); + if (retval) { + dev_err(di->dev, "failed to register battery\n"); + goto batt_failed; + } + di->charger.name = "mc13892_charger"; + di->charger.type = POWER_SUPPLY_TYPE_MAINS; + di->charger.properties = mc13892_charger_props; + di->charger.num_properties = ARRAY_SIZE(mc13892_charger_props); + di->charger.get_property = mc13892_charger_get_property; + retval = power_supply_register(&pdev->dev, &di->charger); + if (retval) { + dev_err(di->dev, "failed to register charger\n"); + goto charger_failed; + } + INIT_DELAYED_WORK(&di->monitor_work, mc13892_battery_work); + di->monitor_wqueue = create_singlethread_workqueue(dev_name(&pdev->dev)); + if (!di->monitor_wqueue) { + retval = -ESRCH; + goto workqueue_failed; + } + queue_delayed_work(di->monitor_wqueue, &di->monitor_work, HZ * 10); + + bat_event_callback.func = charger_online_event_callback; + bat_event_callback.param = (void *) di; + pmic_event_subscribe(EVENT_CHGDETI, bat_event_callback); + + pmic_stop_coulomb_counter(); + pmic_calibrate_coulomb_counter(); + goto success; + +workqueue_failed: + power_supply_unregister(&di->charger); +charger_failed: + power_supply_unregister(&di->bat); +batt_failed: + kfree(di); +di_alloc_failed: +success: + dev_dbg(di->dev, "%s battery probed!\n", __func__); + return retval; + + + return 0; +} + +static struct platform_driver pmic_battery_driver_ldm = { + .driver = { + .name = "pmic_battery", + .bus = &platform_bus_type, + }, + .probe = pmic_battery_probe, + .remove = pmic_battery_remove, +}; + +static int __init pmic_battery_init(void) +{ + pr_debug("PMIC Battery driver loading...\n"); + return platform_driver_register(&pmic_battery_driver_ldm); +} + +static void __exit pmic_battery_exit(void) +{ + platform_driver_unregister(&pmic_battery_driver_ldm); + pr_debug("PMIC Battery driver successfully unloaded\n"); +} + +module_init(pmic_battery_init); +module_exit(pmic_battery_exit); + +MODULE_DESCRIPTION("pmic_battery driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/pmic/mc13892/pmic_light.c b/drivers/mxc/pmic/mc13892/pmic_light.c new file mode 100644 index 000000000000..caaa98d7d7d9 --- /dev/null +++ b/drivers/mxc/pmic/mc13892/pmic_light.c @@ -0,0 +1,685 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mc13892/pmic_light.c + * @brief This is the main file of PMIC(mc13783) Light and Backlight driver. + * + * @ingroup PMIC_LIGHT + */ + +/* + * Includes + */ +#define DEBUG +#include +#include +#include +#include +#include + +#define BIT_CL_MAIN_LSH 9 +#define BIT_CL_AUX_LSH 21 +#define BIT_CL_KEY_LSH 9 +#define BIT_CL_RED_LSH 9 +#define BIT_CL_GREEN_LSH 21 +#define BIT_CL_BLUE_LSH 9 + +#define BIT_CL_MAIN_WID 3 +#define BIT_CL_AUX_WID 3 +#define BIT_CL_KEY_WID 3 +#define BIT_CL_RED_WID 3 +#define BIT_CL_GREEN_WID 3 +#define BIT_CL_BLUE_WID 3 + +#define BIT_DC_MAIN_LSH 3 +#define BIT_DC_AUX_LSH 15 +#define BIT_DC_KEY_LSH 3 +#define BIT_DC_RED_LSH 3 +#define BIT_DC_GREEN_LSH 15 +#define BIT_DC_BLUE_LSH 3 + +#define BIT_DC_MAIN_WID 6 +#define BIT_DC_AUX_WID 6 +#define BIT_DC_KEY_WID 6 +#define BIT_DC_RED_WID 6 +#define BIT_DC_GREEN_WID 6 +#define BIT_DC_BLUE_WID 6 + +#define BIT_RP_MAIN_LSH 2 +#define BIT_RP_AUX_LSH 14 +#define BIT_RP_KEY_LSH 2 +#define BIT_RP_RED_LSH 2 +#define BIT_RP_GREEN_LSH 14 +#define BIT_RP_BLUE_LSH 2 + +#define BIT_RP_MAIN_WID 1 +#define BIT_RP_AUX_WID 1 +#define BIT_RP_KEY_WID 1 +#define BIT_RP_RED_WID 1 +#define BIT_RP_GREEN_WID 1 +#define BIT_RP_BLUE_WID 1 + +#define BIT_HC_MAIN_LSH 1 +#define BIT_HC_AUX_LSH 13 +#define BIT_HC_KEY_LSH 1 + +#define BIT_HC_MAIN_WID 1 +#define BIT_HC_AUX_WID 1 +#define BIT_HC_KEY_WID 1 + +#define BIT_BP_RED_LSH 0 +#define BIT_BP_GREEN_LSH 12 +#define BIT_BP_BLUE_LSH 0 + +#define BIT_BP_RED_WID 2 +#define BIT_BP_GREEN_WID 2 +#define BIT_BP_BLUE_WID 2 + +int pmic_light_init_reg(void) +{ + CHECK_ERROR(pmic_write_reg(REG_LED_CTL0, 0, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(REG_LED_CTL1, 0, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(REG_LED_CTL2, 0, PMIC_ALL_BITS)); + CHECK_ERROR(pmic_write_reg(REG_LED_CTL3, 0, PMIC_ALL_BITS)); + + return 0; +} + +static int pmic_light_suspend(struct platform_device *dev, pm_message_t state) +{ + return 0; +}; + +static int pmic_light_resume(struct platform_device *pdev) +{ + return 0; +}; + +PMIC_STATUS mc13892_bklit_set_hi_current(enum lit_channel channel, int mode) +{ + unsigned int mask; + unsigned int value; + int reg; + + switch (channel) { + case LIT_MAIN: + value = BITFVAL(BIT_HC_MAIN, mode); + mask = BITFMASK(BIT_HC_MAIN); + reg = REG_LED_CTL0; + break; + case LIT_AUX: + value = BITFVAL(BIT_HC_AUX, mode); + mask = BITFMASK(BIT_HC_AUX); + reg = REG_LED_CTL0; + break; + case LIT_KEY: + value = BITFVAL(BIT_HC_KEY, mode); + mask = BITFMASK(BIT_HC_KEY); + reg = REG_LED_CTL1; + break; + default: + return PMIC_PARAMETER_ERROR; + } + CHECK_ERROR(pmic_write_reg(reg, value, mask)); + return PMIC_SUCCESS; +} + +PMIC_STATUS mc13892_bklit_get_hi_current(enum lit_channel channel, int *mode) +{ + unsigned int mask; + int reg; + + switch (channel) { + case LIT_MAIN: + mask = BITFMASK(BIT_HC_MAIN); + reg = REG_LED_CTL0; + break; + case LIT_AUX: + mask = BITFMASK(BIT_HC_AUX); + reg = REG_LED_CTL0; + break; + case LIT_KEY: + mask = BITFMASK(BIT_HC_KEY); + reg = REG_LED_CTL1; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_read_reg(reg, mode, mask)); + return PMIC_SUCCESS; +} + +PMIC_STATUS mc13892_bklit_set_current(enum lit_channel channel, + unsigned char level) +{ + unsigned int mask; + unsigned int value; + int reg; + + if (level > LIT_CURR_HI_42) + return PMIC_PARAMETER_ERROR; + else if (level >= LIT_CURR_HI_0) { + CHECK_ERROR(mc13892_bklit_set_hi_current(channel, 1)); + level -= LIT_CURR_HI_0; + } + + switch (channel) { + case LIT_MAIN: + value = BITFVAL(BIT_CL_MAIN, level); + mask = BITFMASK(BIT_CL_MAIN); + reg = REG_LED_CTL0; + break; + case LIT_AUX: + value = BITFVAL(BIT_CL_AUX, level); + mask = BITFMASK(BIT_CL_AUX); + reg = REG_LED_CTL0; + break; + case LIT_KEY: + value = BITFVAL(BIT_CL_KEY, level); + mask = BITFMASK(BIT_CL_KEY); + reg = REG_LED_CTL1; + break; + case LIT_RED: + value = BITFVAL(BIT_CL_RED, level); + mask = BITFMASK(BIT_CL_RED); + reg = REG_LED_CTL2; + break; + case LIT_GREEN: + value = BITFVAL(BIT_CL_GREEN, level); + mask = BITFMASK(BIT_CL_GREEN); + reg = REG_LED_CTL2; + break; + case LIT_BLUE: + value = BITFVAL(BIT_CL_BLUE, level); + mask = BITFMASK(BIT_CL_BLUE); + reg = REG_LED_CTL3; + break; + default: + return PMIC_PARAMETER_ERROR; + } + CHECK_ERROR(pmic_write_reg(reg, value, mask)); + + return PMIC_SUCCESS; +} + +PMIC_STATUS mc13892_bklit_get_current(enum lit_channel channel, + unsigned char *level) +{ + unsigned int reg_value = 0; + unsigned int mask = 0; + int reg, mode; + + CHECK_ERROR(mc13892_bklit_get_hi_current(channel, &mode)); + + switch (channel) { + case LIT_MAIN: + mask = BITFMASK(BIT_CL_MAIN); + reg = REG_LED_CTL0; + break; + case LIT_AUX: + mask = BITFMASK(BIT_CL_AUX); + reg = REG_LED_CTL0; + break; + case LIT_KEY: + mask = BITFMASK(BIT_CL_KEY); + reg = REG_LED_CTL1; + break; + case LIT_RED: + mask = BITFMASK(BIT_CL_RED); + reg = REG_LED_CTL2; + break; + case LIT_GREEN: + mask = BITFMASK(BIT_CL_GREEN); + reg = REG_LED_CTL2; + break; + case LIT_BLUE: + mask = BITFMASK(BIT_CL_BLUE); + reg = REG_LED_CTL3; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_read_reg(reg, ®_value, mask)); + + switch (channel) { + case LIT_MAIN: + *level = BITFEXT(reg_value, BIT_CL_MAIN); + break; + case LIT_AUX: + *level = BITFEXT(reg_value, BIT_CL_AUX); + break; + case LIT_KEY: + *level = BITFEXT(reg_value, BIT_CL_KEY); + break; + case LIT_RED: + *level = BITFEXT(reg_value, BIT_CL_RED); + break; + case LIT_GREEN: + *level = BITFEXT(reg_value, BIT_CL_GREEN); + break; + case LIT_BLUE: + *level = BITFEXT(reg_value, BIT_CL_BLUE); + break; + default: + return PMIC_PARAMETER_ERROR; + } + + if (mode == 1) + *level += LIT_CURR_HI_0; + + return PMIC_SUCCESS; +} + +PMIC_STATUS mc13892_bklit_set_dutycycle(enum lit_channel channel, + unsigned char dc) +{ + unsigned int mask; + unsigned int value; + int reg; + + switch (channel) { + case LIT_MAIN: + value = BITFVAL(BIT_DC_MAIN, dc); + mask = BITFMASK(BIT_DC_MAIN); + reg = REG_LED_CTL0; + break; + case LIT_AUX: + value = BITFVAL(BIT_DC_AUX, dc); + mask = BITFMASK(BIT_DC_AUX); + reg = REG_LED_CTL0; + break; + case LIT_KEY: + value = BITFVAL(BIT_DC_KEY, dc); + mask = BITFMASK(BIT_DC_KEY); + reg = REG_LED_CTL1; + break; + case LIT_RED: + value = BITFVAL(BIT_DC_RED, dc); + mask = BITFMASK(BIT_DC_RED); + reg = REG_LED_CTL2; + break; + case LIT_GREEN: + value = BITFVAL(BIT_DC_GREEN, dc); + mask = BITFMASK(BIT_DC_GREEN); + reg = REG_LED_CTL2; + break; + case LIT_BLUE: + value = BITFVAL(BIT_DC_BLUE, dc); + mask = BITFMASK(BIT_DC_BLUE); + reg = REG_LED_CTL3; + break; + default: + return PMIC_PARAMETER_ERROR; + } + CHECK_ERROR(pmic_write_reg(reg, value, mask)); + return PMIC_SUCCESS; +} + +PMIC_STATUS mc13892_bklit_get_dutycycle(enum lit_channel channel, + unsigned char *dc) +{ + unsigned int mask; + int reg; + unsigned int reg_value = 0; + + switch (channel) { + case LIT_MAIN: + mask = BITFMASK(BIT_DC_MAIN); + reg = REG_LED_CTL0; + break; + case LIT_AUX: + mask = BITFMASK(BIT_DC_AUX); + reg = REG_LED_CTL0; + break; + case LIT_KEY: + mask = BITFMASK(BIT_DC_KEY); + reg = REG_LED_CTL1; + break; + case LIT_RED: + mask = BITFMASK(BIT_DC_RED); + reg = REG_LED_CTL2; + break; + case LIT_GREEN: + mask = BITFMASK(BIT_DC_GREEN); + reg = REG_LED_CTL2; + break; + case LIT_BLUE: + mask = BITFMASK(BIT_DC_BLUE); + reg = REG_LED_CTL3; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_read_reg(reg, ®_value, mask)); + return PMIC_SUCCESS; +} + +PMIC_STATUS mc13892_bklit_set_ramp(enum lit_channel channel, int flag) +{ + unsigned int mask; + unsigned int value; + int reg; + + switch (channel) { + case LIT_MAIN: + value = BITFVAL(BIT_RP_MAIN, flag); + mask = BITFMASK(BIT_RP_MAIN); + reg = REG_LED_CTL0; + break; + case LIT_AUX: + value = BITFVAL(BIT_RP_AUX, flag); + mask = BITFMASK(BIT_RP_AUX); + reg = REG_LED_CTL0; + break; + case LIT_KEY: + value = BITFVAL(BIT_RP_KEY, flag); + mask = BITFMASK(BIT_RP_KEY); + reg = REG_LED_CTL1; + break; + case LIT_RED: + value = BITFVAL(BIT_RP_RED, flag); + mask = BITFMASK(BIT_RP_RED); + reg = REG_LED_CTL2; + break; + case LIT_GREEN: + value = BITFVAL(BIT_RP_GREEN, flag); + mask = BITFMASK(BIT_RP_GREEN); + reg = REG_LED_CTL2; + break; + case LIT_BLUE: + value = BITFVAL(BIT_RP_BLUE, flag); + mask = BITFMASK(BIT_RP_BLUE); + reg = REG_LED_CTL3; + break; + default: + return PMIC_PARAMETER_ERROR; + } + CHECK_ERROR(pmic_write_reg(reg, value, mask)); + return PMIC_SUCCESS; +} + +PMIC_STATUS mc13892_bklit_get_ramp(enum lit_channel channel, int *flag) +{ + unsigned int mask; + int reg; + + switch (channel) { + case LIT_MAIN: + mask = BITFMASK(BIT_RP_MAIN); + reg = REG_LED_CTL0; + break; + case LIT_AUX: + mask = BITFMASK(BIT_RP_AUX); + reg = REG_LED_CTL0; + break; + case LIT_KEY: + mask = BITFMASK(BIT_RP_KEY); + reg = REG_LED_CTL1; + break; + case LIT_RED: + mask = BITFMASK(BIT_RP_RED); + reg = REG_LED_CTL2; + break; + case LIT_GREEN: + mask = BITFMASK(BIT_RP_GREEN); + reg = REG_LED_CTL2; + break; + case LIT_BLUE: + mask = BITFMASK(BIT_RP_BLUE); + reg = REG_LED_CTL3; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_read_reg(reg, flag, mask)); + return PMIC_SUCCESS; +} + +PMIC_STATUS mc13892_bklit_set_blink_p(enum lit_channel channel, int period) +{ + unsigned int mask; + unsigned int value; + int reg; + + switch (channel) { + case LIT_RED: + value = BITFVAL(BIT_BP_RED, period); + mask = BITFMASK(BIT_BP_RED); + reg = REG_LED_CTL2; + break; + case LIT_GREEN: + value = BITFVAL(BIT_BP_GREEN, period); + mask = BITFMASK(BIT_BP_GREEN); + reg = REG_LED_CTL2; + break; + case LIT_BLUE: + value = BITFVAL(BIT_BP_BLUE, period); + mask = BITFMASK(BIT_BP_BLUE); + reg = REG_LED_CTL3; + break; + default: + return PMIC_PARAMETER_ERROR; + } + CHECK_ERROR(pmic_write_reg(reg, value, mask)); + return PMIC_SUCCESS; +} + +PMIC_STATUS mc13892_bklit_get_blink_p(enum lit_channel channel, int *period) +{ + unsigned int mask; + int reg; + + switch (channel) { + case LIT_RED: + mask = BITFMASK(BIT_BP_RED); + reg = REG_LED_CTL2; + break; + case LIT_GREEN: + mask = BITFMASK(BIT_BP_GREEN); + reg = REG_LED_CTL2; + break; + case LIT_BLUE: + mask = BITFMASK(BIT_BP_BLUE); + reg = REG_LED_CTL3; + break; + default: + return PMIC_PARAMETER_ERROR; + } + + CHECK_ERROR(pmic_read_reg(reg, period, mask)); + return PMIC_SUCCESS; +} + +EXPORT_SYMBOL(mc13892_bklit_set_current); +EXPORT_SYMBOL(mc13892_bklit_get_current); +EXPORT_SYMBOL(mc13892_bklit_set_dutycycle); +EXPORT_SYMBOL(mc13892_bklit_get_dutycycle); +EXPORT_SYMBOL(mc13892_bklit_set_ramp); +EXPORT_SYMBOL(mc13892_bklit_get_ramp); +EXPORT_SYMBOL(mc13892_bklit_set_blink_p); +EXPORT_SYMBOL(mc13892_bklit_get_blink_p); + +static int pmic_light_remove(struct platform_device *pdev) +{ + return 0; +} + +#ifdef DEBUG +static ssize_t lit_info(struct device *dev, struct device_attribute *attr, + char *buf) +{ + return 0; +} + +enum { + SET_CURR = 0, + SET_DC, + SET_RAMP, + SET_BP, + SET_CH, + LIT_CMD_MAX +}; + +static const char *const lit_cmd[LIT_CMD_MAX] = { + [SET_CURR] = "cur", + [SET_DC] = "dc", + [SET_RAMP] = "ra", + [SET_BP] = "bp", + [SET_CH] = "ch" +}; + +static int cmd(unsigned int index, int value) +{ + static int ch = LIT_MAIN; + int ret = 0; + + switch (index) { + case SET_CH: + ch = value; + break; + case SET_CURR: + pr_debug("set %d cur %d\n", ch, value); + ret = mc13892_bklit_set_current(ch, value); + break; + case SET_DC: + pr_debug("set %d dc %d\n", ch, value); + ret = mc13892_bklit_set_dutycycle(ch, value); + break; + case SET_RAMP: + pr_debug("set %d ramp %d\n", ch, value); + ret = mc13892_bklit_set_ramp(ch, value); + break; + case SET_BP: + pr_debug("set %d bp %d\n", ch, value); + ret = mc13892_bklit_set_blink_p(ch, value); + break; + default: + pr_debug("error command\n"); + break; + } + + if (ret == PMIC_SUCCESS) + pr_debug("command exec successfully!\n"); + + return 0; +} + +static ssize_t lit_ctl(struct device *dev, struct device_attribute *attr, + const char *buf, size_t count) +{ + int state = 0; + const char *const *s; + char *p, *q; + int error; + int len, value = 0; + + pr_debug("lit_ctl\n"); + + q = NULL; + q = memchr(buf, ' ', count); + + if (q != NULL) { + len = q - buf; + q += 1; + value = simple_strtoul(q, NULL, 10); + } else { + p = memchr(buf, '\n', count); + len = p ? p - buf : count; + } + + for (s = &lit_cmd[state]; state < LIT_CMD_MAX; s++, state++) { + if (*s && !strncmp(buf, *s, len)) + break; + } + if (state < LIT_CMD_MAX && *s) + error = cmd(state, value); + else + error = -EINVAL; + + return count; +} + +#else +static ssize_t lit_info(struct device *dev, struct device_attribute *attr, + char *buf) +{ + return 0; +} + +static ssize_t lit_ctl(struct device *dev, struct device_attribute *attr, + const char *buf, size_t count) +{ + return count; +} + +#endif + +static DEVICE_ATTR(lit, 0644, lit_info, lit_ctl); + +static int pmic_light_probe(struct platform_device *pdev) +{ + int ret = 0; + + pr_debug("PMIC ADC start probe\n"); + ret = device_create_file(&(pdev->dev), &dev_attr_lit); + if (ret) { + pr_debug("Can't create device file!\n"); + return -ENODEV; + } + + pmic_light_init_reg(); + + pr_debug("PMIC Light successfully loaded\n"); + return 0; +} + +static struct platform_driver pmic_light_driver_ldm = { + .driver = { + .name = "pmic_light", + }, + .suspend = pmic_light_suspend, + .resume = pmic_light_resume, + .probe = pmic_light_probe, + .remove = pmic_light_remove, +}; + +/* + * Initialization and Exit + */ + +static int __init pmic_light_init(void) +{ + pr_debug("PMIC Light driver loading...\n"); + return platform_driver_register(&pmic_light_driver_ldm); +} +static void __exit pmic_light_exit(void) +{ + platform_driver_unregister(&pmic_light_driver_ldm); + pr_debug("PMIC Light driver successfully unloaded\n"); +} + +/* + * Module entry points + */ + +subsys_initcall(pmic_light_init); +module_exit(pmic_light_exit); + +MODULE_DESCRIPTION("PMIC_LIGHT"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/security/Kconfig b/drivers/mxc/security/Kconfig new file mode 100644 index 000000000000..9c829da21239 --- /dev/null +++ b/drivers/mxc/security/Kconfig @@ -0,0 +1,11 @@ +menu "MXC Security Drivers" + +config MXC_DRYICE + tristate "MXC DryIce Driver" + depends on ARCH_MX25 + default n + ---help--- + This module contains the core API's for accessing the DryIce module. + If you are unsure about this, say N here. + +endmenu diff --git a/drivers/mxc/security/Makefile b/drivers/mxc/security/Makefile new file mode 100644 index 000000000000..33fd5b86826e --- /dev/null +++ b/drivers/mxc/security/Makefile @@ -0,0 +1 @@ +obj-$(CONFIG_MXC_DRYICE) += dryice.o diff --git a/drivers/mxc/security/dryice-regs.h b/drivers/mxc/security/dryice-regs.h new file mode 100644 index 000000000000..bcf0aff4df08 --- /dev/null +++ b/drivers/mxc/security/dryice-regs.h @@ -0,0 +1,207 @@ +/* + * Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + + +#ifndef __DRYICE_REGS_H__ +#define __DRYICE_REGS_H__ + +/*********************************************************************** + * DryIce Register Definitions + ***********************************************************************/ + +/* DryIce Time Counter MSB Reg */ +#define DTCMR 0x00 + +/* DryIce Time Counter LSB Reg */ +#define DTCLR 0x04 + +/* DryIce Clock Alarm MSB Reg */ +#define DCAMR 0x08 + +/* DryIce Clock Alarm LSB Reg */ +#define DCALR 0x0c + +/* DryIce Control Reg */ +#define DCR 0x10 +#define DCR_TDCHL (1 << 30) /* Tamper Detect Config Hard Lock */ +#define DCR_TDCSL (1 << 29) /* Tamper Detect COnfig Soft Lock */ +#define DCR_KSHL (1 << 28) /* Key Select Hard Lock */ +#define DCR_KSSL (1 << 27) /* Key Select Soft Lock */ +#define DCR_RKHL (1 << 26) /* Random Key Hard Lock */ +#define DCR_RKSL (1 << 25) /* Random Key Soft Lock */ +#define DCR_PKRHL (1 << 24) /* Programmed Key Read Hard Lock */ +#define DCR_PKRSL (1 << 23) /* Programmed Key Read Soft Lock */ +#define DCR_PKWHL (1 << 22) /* Programmed Key Write Hard Lock */ +#define DCR_PKWSL (1 << 21) /* Programmed Key Write Soft Lock */ +#define DCR_MCHL (1 << 20) /* Monotonic Counter Hard Lock */ +#define DCR_MCSL (1 << 19) /* Monotonic Counter Soft Lock */ +#define DCR_TCHL (1 << 18) /* Time Counter Hard Lock */ +#define DCR_TCSL (1 << 17) /* Time Counter Soft Lock */ +#define DCR_FSHL (1 << 16) /* Failure State Hard Lock */ +#define DCR_NSA (1 << 15) /* Non-Secure Access */ +#define DCR_OSCB (1 << 14) /* Oscillator Bypass */ +#define DCR_APE (1 << 4) /* Alarm Pin Enable */ +#define DCR_TCE (1 << 3) /* Time Counter Enable */ +#define DCR_MCE (1 << 2) /* Monotonic Counter Enable */ +#define DCR_SWR (1 << 0) /* Software Reset (w/o) */ + +/* DryIce Status Reg */ +#define DSR 0x14 +#define DSR_WTD (1 << 23) /* Wire-mesh Tampering Detected */ +#define DSR_ETBD (1 << 22) /* External Tampering B Detected */ +#define DSR_ETAD (1 << 21) /* External Tampering A Detected */ +#define DSR_EBD (1 << 20) /* External Boot Detected */ +#define DSR_SAD (1 << 19) /* Security Alarm Detected */ +#define DSR_TTD (1 << 18) /* Temperature Tampering Detected */ +#define DSR_CTD (1 << 17) /* Clock Tampering Detected */ +#define DSR_VTD (1 << 16) /* Voltage Tampering Detected */ +#define DSR_KBF (1 << 11) /* Key Busy Flag */ +#define DSR_WBF (1 << 10) /* Write Busy Flag */ +#define DSR_WNF (1 << 9) /* Write Next Flag */ +#define DSR_WCF (1 << 8) /* Write Complete Flag */ +#define DSR_WEF (1 << 7) /* Write Error Flag */ +#define DSR_RKE (1 << 6) /* Random Key Error */ +#define DSR_RKV (1 << 5) /* Random Key Valid */ +#define DSR_CAF (1 << 4) /* Clock Alarm Flag */ +#define DSR_MCO (1 << 3) /* Monotonic Counter Overflow */ +#define DSR_TCO (1 << 2) /* Time Counter Overflow */ +#define DSR_NVF (1 << 1) /* Non-Valid Flag */ +#define DSR_SVF (1 << 0) /* Security Violation Flag */ + +#define DSR_TAMPER_BITS (DSR_WTD | DSR_ETBD | DSR_ETAD | DSR_EBD | DSR_SAD | \ + DSR_TTD | DSR_CTD | DSR_VTD | DSR_MCO | DSR_TCO) + +/* ensure that external tamper defs match register bits */ +#if DSR_WTD != DI_TAMPER_EVENT_WTD +#error "Mismatch between DSR_WTD and DI_TAMPER_EVENT_WTD" +#endif +#if DSR_ETBD != DI_TAMPER_EVENT_ETBD +#error "Mismatch between DSR_ETBD and DI_TAMPER_EVENT_ETBD" +#endif +#if DSR_ETAD != DI_TAMPER_EVENT_ETAD +#error "Mismatch between DSR_ETAD and DI_TAMPER_EVENT_ETAD" +#endif +#if DSR_EBD != DI_TAMPER_EVENT_EBD +#error "Mismatch between DSR_EBD and DI_TAMPER_EVENT_EBD" +#endif +#if DSR_SAD != DI_TAMPER_EVENT_SAD +#error "Mismatch between DSR_SAD and DI_TAMPER_EVENT_SAD" +#endif +#if DSR_TTD != DI_TAMPER_EVENT_TTD +#error "Mismatch between DSR_TTD and DI_TAMPER_EVENT_TTD" +#endif +#if DSR_CTD != DI_TAMPER_EVENT_CTD +#error "Mismatch between DSR_CTD and DI_TAMPER_EVENT_CTD" +#endif +#if DSR_VTD != DI_TAMPER_EVENT_VTD +#error "Mismatch between DSR_VTD and DI_TAMPER_EVENT_VTD" +#endif +#if DSR_MCO != DI_TAMPER_EVENT_MCO +#error "Mismatch between DSR_MCO and DI_TAMPER_EVENT_MCO" +#endif +#if DSR_TCO != DI_TAMPER_EVENT_TCO +#error "Mismatch between DSR_TCO and DI_TAMPER_EVENT_TCO" +#endif + +/* DryIce Interrupt Enable Reg */ +#define DIER 0x18 +#define DIER_WNIE (1 << 9) /* Write Next Interrupt Enable */ +#define DIER_WCIE (1 << 8) /* Write Complete Interrupt Enable */ +#define DIER_WEIE (1 << 7) /* Write Error Interrupt Enable */ +#define DIER_RKIE (1 << 5) /* Random Key Interrupt Enable */ +#define DIER_CAIE (1 << 4) /* Clock Alarm Interrupt Enable */ +#define DIER_MOIE (1 << 3) /* Monotonic Overflow Interrupt En */ +#define DIER_TOIE (1 << 2) /* Time Overflow Interrupt Enable */ +#define DIER_SVIE (1 << 0) /* Security Violation Interrupt En */ + +/* DryIce Monotonic Counter Reg */ +#define DMCR 0x1c + +/* DryIce Key Select Reg */ +#define DKSR 0x20 +#define DKSR_IIM_KEY 0x0 +#define DKSR_PROG_KEY 0x4 +#define DKSR_RAND_KEY 0x5 +#define DKSR_PROG_XOR_IIM_KEY 0x6 +#define DKSR_RAND_XOR_IIM_KEY 0x7 + +/* DryIce Key Control Reg */ +#define DKCR 0x24 +#define DKCR_LRK (1 << 0) /* Load Random Key */ + +/* DryIce Tamper Configuration Reg */ +#define DTCR 0x28 +#define DTCR_ETGFB_SHIFT 27 /* Ext Tamper Glitch Filter B */ +#define DTCR_ETGFB_MASK 0xf8000000 +#define DTCR_ETGFA_SHIFT 22 /* Ext Tamper Glitch Filter A */ +#define DTCR_ETGFA_MASK 0x07c00000 +#define DTCR_WTGF_SHIFT 17 /* Wire-mesh Tamper Glitch Filter */ +#define DTCR_WTGF_MASK 0x003e0000 +#define DTCR_WGFE (1 << 16) /* Wire-mesh Glitch Filter Enable */ +#define DTCR_SAOE (1 << 15) /* Security Alarm Output Enable */ +#define DTCR_MOE (1 << 9) /* Monotonic Overflow Enable */ +#define DTCR_TOE (1 << 8) /* Time Overflow Enable */ +#define DTCR_WTE (1 << 7) /* Wire-mesh Tampering Enable */ +#define DTCR_ETBE (1 << 6) /* External Tampering B Enable */ +#define DTCR_ETAE (1 << 5) /* External Tampering A Enable */ +#define DTCR_EBE (1 << 4) /* External Boot Enable */ +#define DTCR_SAIE (1 << 3) /* Security Alarm Input Enable */ +#define DTCR_TTE (1 << 2) /* Temperature Tamper Enable */ +#define DTCR_CTE (1 << 1) /* Clock Tamper Enable */ +#define DTCR_VTE (1 << 0) /* Voltage Tamper Enable */ + +/* DryIce Analog Configuration Reg */ +#define DACR 0x2c +#define DACR_VRC_SHIFT 6 /* Voltage Reference Configuration */ +#define DACR_VRC_MASK 0x000001c0 +#define DACR_HTDC_SHIFT 3 /* High Temperature Detect Configuration */ +#define DACR_HTDC_MASK 0x00000038 +#define DACR_LTDC_SHIFT 0 /* Low Temperature Detect Configuration */ +#define DACR_LTDC_MASK 0x00000007 + +/* DryIce General Purpose Reg */ +#define DGPR 0x3c + +/* DryIce Programmed Key0-7 Regs */ +#define DPKR0 0x40 +#define DPKR1 0x44 +#define DPKR2 0x48 +#define DPKR3 0x4c +#define DPKR4 0x50 +#define DPKR5 0x54 +#define DPKR6 0x58 +#define DPKR7 0x5c + +/* DryIce Random Key0-7 Regs */ +#define DRKR0 0x60 +#define DRKR1 0x64 +#define DRKR2 0x68 +#define DRKR3 0x6c +#define DRKR4 0x70 +#define DRKR5 0x74 +#define DRKR6 0x78 +#define DRKR7 0x7c + +#define DI_ADDRESS_RANGE (DRKR7 + 4) + +/* + * this doesn't really belong here but the + * portability layer doesn't include it + */ +#ifdef LINUX_KERNEL +#define EXTERN_SYMBOL(symbol) EXPORT_SYMBOL(symbol) +#else +#define EXTERN_SYMBOL(symbol) do {} while (0) +#endif + +#endif /* __DRYICE_REGS_H__ */ diff --git a/drivers/mxc/security/dryice.c b/drivers/mxc/security/dryice.c new file mode 100644 index 000000000000..bf048dadd5b2 --- /dev/null +++ b/drivers/mxc/security/dryice.c @@ -0,0 +1,1123 @@ +/* + * Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + + +#undef DI_DEBUG /* enable debug messages */ +#undef DI_DEBUG_REGIO /* show register read/write */ +#undef DI_TESTING /* include test code */ + +#ifdef DI_DEBUG +#define di_debug(fmt, arg...) os_printk(KERN_INFO fmt, ##arg) +#else +#define di_debug(fmt, arg...) do {} while (0) +#endif + +#define di_info(fmt, arg...) os_printk(KERN_INFO fmt, ##arg) +#define di_warn(fmt, arg...) os_printk(KERN_WARNING fmt, ##arg) + +#include "sahara2/include/portable_os.h" +#include "dryice.h" +#include "dryice-regs.h" + +/* mask of the lock-related function flags */ +#define DI_FUNC_LOCK_FLAGS (DI_FUNC_FLAG_READ_LOCK | \ + DI_FUNC_FLAG_WRITE_LOCK | \ + DI_FUNC_FLAG_HARD_LOCK) + +/* + * dryice hardware states + */ +enum di_states { + DI_STATE_VALID = 0, + DI_STATE_NON_VALID, + DI_STATE_FAILURE, +}; + +/* + * todo list actions + */ +enum todo_actions { + TODO_ACT_WRITE_VAL, + TODO_ACT_WRITE_PTR, + TODO_ACT_WRITE_PTR32, + TODO_ACT_ASSIGN, + TODO_ACT_WAIT_RKG, +}; + +/* + * todo list status + */ +enum todo_status { + TODO_ST_LOADING, + TODO_ST_READY, + TODO_ST_PEND_WCF, + TODO_ST_PEND_RKG, + TODO_ST_DONE, +}; + +OS_DEV_INIT_DCL(dryice_init) +OS_DEV_SHUTDOWN_DCL(dryice_exit) +OS_DEV_ISR_DCL(dryice_norm_irq) +OS_WAIT_OBJECT(done_queue); +OS_WAIT_OBJECT(exit_queue); + +struct dryice_data { + int busy; /* enforce exclusive access */ + os_lock_t busy_lock; + int exit_flag; /* don't start new operations */ + + uint32_t baseaddr; /* physical base address */ + void *ioaddr; /* virtual base address */ + + /* interrupt handling */ + struct irq_struct { + os_interrupt_id_t irq; + int set; + } irq_norm, irq_sec; + + struct clk *clk; /* clock control */ + + int key_programmed; /* key has been programmed */ + int key_selected; /* key has been selected */ + + /* callback function and cookie */ + void (*cb_func)(di_return_t rc, unsigned long cookie); + unsigned long cb_cookie; +} *di = NULL; + +#define TODO_LIST_LEN 12 +static struct { + struct td { + enum todo_actions action; + uint32_t src; + uint32_t dst; + int num; + } list[TODO_LIST_LEN]; + int cur; /* current todo pointer */ + int num; /* number of todo's on the list */ + int async; /* non-zero if list is async */ + int status; /* current status of the list */ + di_return_t rc; /* return code generated by the list */ +} todo; + +/* + * dryice register read/write functions + */ +#ifdef DI_DEBUG_REGIO +static uint32_t di_read(int reg) +{ + uint32_t val = os_read32(di->ioaddr + (reg)); + di_info("di_read(0x%02x) = 0x%08x\n", reg, val); + + return val; +} + +static void di_write(uint32_t val, int reg) +{ + di_info("dryice_write_reg(0x%08x, 0x%02x)\n", val, reg); + os_write32(di->ioaddr + (reg), val); +} +#else +#define di_read(reg) os_read32(di->ioaddr + (reg)) +#define di_write(val, reg) os_write32(di->ioaddr + (reg), val); +#endif + +/* + * set the dryice busy flag atomically, allowing + * for case where the driver is trying to exit. + */ +static int di_busy_set(void) +{ + os_lock_context_t context; + int rc = 0; + + os_lock_save_context(di->busy_lock, context); + if (di->exit_flag || di->busy) + rc = 1; + else + di->busy = 1; + os_unlock_restore_context(di->busy_lock, context); + + return rc; +} + +/* + * clear the dryice busy flag + */ +static inline void di_busy_clear(void) +{ + /* don't acquire the lock because the race is benign */ + di->busy = 0; + + if (di->exit_flag) + os_wake_sleepers(exit_queue); +} + +/* + * return the current state of dryice + * (valid, non-valid, or failure) + */ +static enum di_states di_state(void) +{ + enum di_states state = DI_STATE_VALID; + uint32_t dsr = di_read(DSR); + + if (dsr & DSR_NVF) + state = DI_STATE_NON_VALID; + else if (dsr & DSR_SVF) + state = DI_STATE_FAILURE; + + return state; +} + +#define DI_WRITE_LOOP_CNT 0x1000 +/* + * the write-error flag is something that shouldn't get set + * during normal operation. if it's set something is terribly + * wrong. the best we can do is try to clear the bit and hope + * that dryice will recover. this situation is similar to an + * unexpected bus fault in terms of severity. + */ +static void try_to_clear_wef(void) +{ + int cnt; + + while (1) { + di_write(DSR_WEF, DSR); + for (cnt = 0; cnt < DI_WRITE_LOOP_CNT; cnt++) { + if ((di_read(DSR) & DSR_WEF) == 0) + break; + } + di_warn("WARNING: DryIce cannot clear DSR_WEF " + "(Write Error Flag)!\n"); + } +} + +/* + * write a dryice register and loop, waiting for it + * to complete. use only during driver initialization. + * returns 0 on success or 1 on write failure. + */ +static int di_write_loop(uint32_t val, int reg) +{ + int rc = 0; + int cnt; + + di_debug("FUNC: %s\n", __func__); + di_write(val, reg); + + for (cnt = 0; cnt < DI_WRITE_LOOP_CNT; cnt++) { + uint32_t dsr = di_read(DSR); + if (dsr & DSR_WEF) { + try_to_clear_wef(); + rc = 1; + } + if (dsr & DSR_WCF) + break; + } + di_debug("wait_write_loop looped %d times\n", cnt); + if (cnt == DI_WRITE_LOOP_CNT) + rc = 1; + + if (rc) + di_warn("DryIce wait_write_done: WRITE ERROR!\n"); + return rc; +} + +/* + * initialize the todo list. must be called + * before adding items to the list. + */ +static void todo_init(int async_flag) +{ + di_debug("FUNC: %s\n", __func__); + todo.cur = 0; + todo.num = 0; + todo.async = async_flag; + todo.rc = 0; + todo.status = TODO_ST_LOADING; +} + +/* + * perform the current action on the todo list + */ +#define TC todo.list[todo.cur] +void todo_cur(void) +{ + di_debug("FUNC: %s[%d]\n", __func__, todo.cur); + switch (TC.action) { + case TODO_ACT_WRITE_VAL: + di_debug(" TODO_ACT_WRITE_VAL\n"); + /* enable the write-completion interrupt */ + todo.status = TODO_ST_PEND_WCF; + di_write(di_read(DIER) | DIER_WCIE, DIER); + + di_write(TC.src, TC.dst); + break; + + case TODO_ACT_WRITE_PTR32: + di_debug(" TODO_ACT_WRITE_PTR32\n"); + /* enable the write-completion interrupt */ + todo.status = TODO_ST_PEND_WCF; + di_write(di_read(DIER) | DIER_WCIE, DIER); + + di_write(*(uint32_t *)TC.src, TC.dst); + break; + + case TODO_ACT_WRITE_PTR: + { + uint8_t *p = (uint8_t *)TC.src; + uint32_t val = 0; + int num = TC.num; + + di_debug(" TODO_ACT_WRITE_PTR\n"); + while (num--) + val = (val << 8) | *p++; + + /* enable the write-completion interrupt */ + todo.status = TODO_ST_PEND_WCF; + di_write(di_read(DIER) | DIER_WCIE, DIER); + + di_write(val, TC.dst); + } + break; + + case TODO_ACT_ASSIGN: + di_debug(" TODO_ACT_ASSIGN\n"); + switch (TC.num) { + case 1: + *(uint8_t *)TC.dst = TC.src; + break; + case 2: + *(uint16_t *)TC.dst = TC.src; + break; + case 4: + *(uint32_t *)TC.dst = TC.src; + break; + default: + di_warn("Unexpected size in TODO_ACT_ASSIGN\n"); + break; + } + break; + + case TODO_ACT_WAIT_RKG: + di_debug(" TODO_ACT_WAIT_RKG\n"); + /* enable the random-key interrupt */ + todo.status = TODO_ST_PEND_RKG; + di_write(di_read(DIER) | DIER_RKIE, DIER); + break; + + default: + di_debug(" TODO_ACT_NOOP\n"); + break; + } +} + +/* + * called when done with the todo list. + * if async, it does the callback. + * if blocking, it wakes up the caller. + */ +static void todo_done(di_return_t rc) +{ + todo.rc = rc; + todo.status = TODO_ST_DONE; + if (todo.async) { + di_busy_clear(); + if (di->cb_func) + di->cb_func(rc, di->cb_cookie); + } else + os_wake_sleepers(done_queue); +} + +/* + * performs the actions sequentially from the todo list + * until it encounters an item that isn't ready. + */ +static void todo_run(void) +{ + di_debug("FUNC: %s\n", __func__); + while (todo.status == TODO_ST_READY) { + if (todo.cur == todo.num) { + todo_done(0); + break; + } + todo_cur(); + if (todo.status != TODO_ST_READY) + break; + todo.cur++; + } +} + +/* + * kick off the todo list by making it ready + */ +static void todo_start(void) +{ + di_debug("FUNC: %s\n", __func__); + todo.status = TODO_ST_READY; + todo_run(); +} + +/* + * blocking callers sleep here until the todo list is done + */ +static int todo_wait_done(void) +{ + di_debug("FUNC: %s\n", __func__); + os_sleep(done_queue, todo.status == TODO_ST_DONE, 0); + + return todo.rc; +} + +/* + * add a dryice register write to the todo list. + * the value to be written is supplied. + */ +#define todo_write_val(val, reg) \ + todo_add(TODO_ACT_WRITE_VAL, val, reg, 0) + +/* + * add a dryice register write to the todo list. + * "size" bytes pointed to by addr will be written. + */ +#define todo_write_ptr(addr, reg, size) \ + todo_add(TODO_ACT_WRITE_PTR, (uint32_t)addr, reg, size) + +/* + * add a dryice register write to the todo list. + * the word pointed to by addr will be written. + */ +#define todo_write_ptr32(addr, reg) \ + todo_add(TODO_ACT_WRITE_PTR32, (uint32_t)addr, reg, 0) + +/* + * add a dryice memory write to the todo list. + * object can only have a size of 1, 2, or 4 bytes. + */ +#define todo_assign(var, val) \ + todo_add(TODO_ACT_ASSIGN, val, (uint32_t)&(var), sizeof(var)) + +#define todo_wait_rkg() \ + todo_add(TODO_ACT_WAIT_RKG, 0, 0, 0) + +static void todo_add(int action, uint32_t src, uint32_t dst, int num) +{ + struct td *p = &todo.list[todo.num]; + + di_debug("FUNC: %s\n", __func__); + if (todo.num == TODO_LIST_LEN) { + di_warn("WARNING: DryIce todo-list overflow!\n"); + return; + } + p->action = action; + p->src = src; + p->dst = dst; + p->num = num; + todo.num++; +} + +#if defined(DI_DEBUG) || defined(DI_TESTING) +/* + * print out the contents of the dryice status register + * with all the bits decoded + */ +static void show_dsr(const char *heading) +{ + uint32_t dsr = di_read(DSR); + + di_info("%s\n", heading); + if (dsr & DSR_TAMPER_BITS) { + if (dsr & DSR_WTD) + di_info("Wire-mesh Tampering Detected\n"); + if (dsr & DSR_ETBD) + di_info("External Tampering B Detected\n"); + if (dsr & DSR_ETAD) + di_info("External Tampering A Detected\n"); + if (dsr & DSR_EBD) + di_info("External Boot Detected\n"); + if (dsr & DSR_SAD) + di_info("Security Alarm Detected\n"); + if (dsr & DSR_TTD) + di_info("Temperature Tampering Detected\n"); + if (dsr & DSR_CTD) + di_info("Clock Tampering Detected\n"); + if (dsr & DSR_VTD) + di_info("Voltage Tampering Detected\n"); + if (dsr & DSR_MCO) + di_info("Monotonic Counter Overflow\n"); + if (dsr & DSR_TCO) + di_info("Time Counter Overflow\n"); + } else + di_info("No Tamper Events Detected\n"); + + di_info("%d Key Busy Flag\n", !!(dsr & DSR_KBF)); + di_info("%d Write Busy Flag\n", !!(dsr & DSR_WBF)); + di_info("%d Write Next Flag\n", !!(dsr & DSR_WNF)); + di_info("%d Write Complete Flag\n", !!(dsr & DSR_WCF)); + di_info("%d Write Error Flag\n", !!(dsr & DSR_WEF)); + di_info("%d Random Key Error\n", !!(dsr & DSR_RKE)); + di_info("%d Random Key Valid\n", !!(dsr & DSR_RKV)); + di_info("%d Clock Alarm Flag\n", !!(dsr & DSR_CAF)); + di_info("%d Non-Valid Flag\n", !!(dsr & DSR_NVF)); + di_info("%d Security Violation Flag\n", !!(dsr & DSR_SVF)); +} + +/* + * print out a key in hex + */ +static void print_key(const char *tag, uint8_t *key, int bits) +{ + int bytes = (bits + 7) / 8; + + di_info("%s", tag); + while (bytes--) + os_printk("%02x", *key++); + os_printk("\n"); +} +#endif /* defined(DI_DEBUG) || defined(DI_TESTING) */ + +/* + * dryice normal interrupt service routine + */ +OS_DEV_ISR(dryice_norm_irq) +{ + /* save dryice status register */ + uint32_t dsr = di_read(DSR); + + if (dsr & DSR_WCF) { + /* disable the write-completion interrupt */ + di_write(di_read(DIER) & ~DIER_WCIE, DIER); + + if (todo.status == TODO_ST_PEND_WCF) { + if (dsr & DSR_WEF) { + try_to_clear_wef(); + todo_done(DI_ERR_WRITE); + } else { + todo.cur++; + todo.status = TODO_ST_READY; + todo_run(); + } + } + } else if (dsr & (DSR_RKV | DSR_RKE)) { + /* disable the random-key-gen interrupt */ + di_write(di_read(DIER) & ~DIER_RKIE, DIER); + + if (todo.status == TODO_ST_PEND_RKG) { + if (dsr & DSR_RKE) + todo_done(DI_ERR_FAIL); + else { + todo.cur++; + todo.status = TODO_ST_READY; + todo_run(); + } + } + } + + os_dev_isr_return(1); +} + +/* write loop with error handling -- for init only */ +#define di_write_loop_goto(val, reg, rc, label) \ + do {if (di_write_loop(val, reg)) \ + {rc = OS_ERROR_FAIL_S; goto label; } } while (0) + +/* + * dryice driver initialization + */ +OS_DEV_INIT(dryice_init) +{ + di_return_t rc = 0; + + di_info("MXC DryIce driver\n"); + + /* allocate memory */ + di = os_alloc_memory(sizeof(*di), GFP_KERNEL); + if (di == NULL) { + rc = OS_ERROR_NO_MEMORY_S; + goto err_alloc; + } + memset(di, 0, sizeof(*di)); + di->baseaddr = DRYICE_BASE_ADDR; + di->irq_norm.irq = MXC_INT_DRYICE_NORM; + di->irq_sec.irq = MXC_INT_DRYICE_SEC; + + /* map i/o registers */ + di->ioaddr = os_map_device(di->baseaddr, DI_ADDRESS_RANGE); + if (di->ioaddr == NULL) { + rc = OS_ERROR_FAIL_S; + goto err_iomap; + } + + /* allocate locks */ + di->busy_lock = os_lock_alloc_init(); + if (di->busy_lock == NULL) { + rc = OS_ERROR_NO_MEMORY_S; + goto err_locks; + } + + /* enable clocks (is there a portable way to do this?) */ + di->clk = clk_get(NULL, "dryice_clk"); + clk_enable(di->clk); + + /* register for interrupts */ + /* os_register_interrupt() dosen't support an option to make the + interrupt as shared. Replaced it with request_irq().*/ + rc = request_irq(di->irq_norm.irq, dryice_norm_irq, IRQF_SHARED, + "dry_ice", di); + if (rc) + goto err_irqs; + else + di->irq_norm.set = 1; + + /* + * DRYICE HARDWARE INIT + */ + +#ifdef DI_DEBUG + show_dsr("DSR Pre-Initialization State"); +#endif + + if (di_state() == DI_STATE_NON_VALID) { + uint32_t dsr = di_read(DSR); + + di_debug("initializing from non-valid state\n"); + + /* clear security violation flag */ + if (dsr & DSR_SVF) + di_write_loop_goto(DSR_SVF, DSR, rc, err_write); + + /* clear tamper detect flags */ + if (dsr & DSR_TAMPER_BITS) + di_write_loop_goto(DSR_TAMPER_BITS, DSR, rc, err_write); + + /* initialize timers */ + di_write_loop_goto(0, DTCLR, rc, err_write); + di_write_loop_goto(0, DTCMR, rc, err_write); + di_write_loop_goto(0, DMCR, rc, err_write); + + /* clear non-valid flag */ + di_write_loop_goto(DSR_NVF, DSR, rc, err_write); + } + + /* set tamper events we are interested in watching */ + di_write_loop_goto(DTCR_WTE | DTCR_ETBE | DTCR_ETAE, DTCR, rc, + err_write); +#ifdef DI_DEBUG + show_dsr("DSR Post-Initialization State"); +#endif + os_dev_init_return(OS_ERROR_OK_S); + +err_write: + /* unregister interrupts */ + if (di->irq_norm.set) + os_deregister_interrupt(di->irq_norm.irq); + if (di->irq_sec.set) + os_deregister_interrupt(di->irq_sec.irq); + + /* turn off clocks (is there a portable way to do this?) */ + clk_disable(di->clk); + clk_put(di->clk); + +err_irqs: + /* unallocate locks */ + os_lock_deallocate(di->busy_lock); + +err_locks: + /* unmap i/o registers */ + os_unmap_device(di->ioaddr, DI_ADDRESS_RANGE); + +err_iomap: + /* free the dryice struct */ + os_free_memory(di); + +err_alloc: + os_dev_init_return(rc); +} + +/* + * dryice driver exit routine + */ +OS_DEV_SHUTDOWN(dryice_exit) +{ + /* don't allow new operations */ + di->exit_flag = 1; + + /* wait for the current operation to complete */ + os_sleep(exit_queue, di->busy == 0, 0); + + /* unregister interrupts */ + if (di->irq_norm.set) + os_deregister_interrupt(di->irq_norm.irq); + if (di->irq_sec.set) + os_deregister_interrupt(di->irq_sec.irq); + + /* turn off clocks (is there a portable way to do this?) */ + clk_disable(di->clk); + clk_put(di->clk); + + /* unallocate locks */ + os_lock_deallocate(di->busy_lock); + + /* unmap i/o registers */ + os_unmap_device(di->ioaddr, DI_ADDRESS_RANGE); + + /* free the dryice struct */ + os_free_memory(di); + + os_dev_shutdown_return(OS_ERROR_OK_S); +} + +di_return_t dryice_set_programmed_key(const void *key_data, int key_bits, + int flags) +{ + uint32_t dcr; + int key_bytes, reg; + di_return_t rc = 0; + + if (di_busy_set()) + return DI_ERR_BUSY; + + if (key_data == NULL) { + rc = DI_ERR_INVAL; + goto err; + } + if (key_bits < 0 || key_bits > MAX_KEY_LEN || key_bits % 8) { + rc = DI_ERR_INVAL; + goto err; + } + if (flags & DI_FUNC_FLAG_WORD_KEY) { + if (key_bits % 32 || (uint32_t)key_data & 0x3) { + rc = DI_ERR_INVAL; + goto err; + } + } + if (di->key_programmed) { + rc = DI_ERR_INUSE; + goto err; + } + if (di_state() == DI_STATE_FAILURE) { + rc = DI_ERR_STATE; + goto err; + } + dcr = di_read(DCR); + if (dcr & DCR_PKWHL) { + rc = DI_ERR_HLOCK; + goto err; + } + if (dcr & DCR_PKWSL) { + rc = DI_ERR_SLOCK; + goto err; + } + key_bytes = key_bits / 8; + + todo_init((flags & DI_FUNC_FLAG_ASYNC) != 0); + + /* accomodate busses that can only do 32-bit transfers */ + if (flags & DI_FUNC_FLAG_WORD_KEY) { + uint32_t *keyp = (void *)key_data; + + for (reg = 0; reg < MAX_KEY_WORDS; reg++) { + if (reg < MAX_KEY_WORDS - key_bytes / 4) + todo_write_val(0, DPKR7 - reg * 4); + else { + todo_write_ptr32(keyp, DPKR7 - reg * 4); + keyp++; + } + } + } else { + uint8_t *keyp = (void *)key_data; + + for (reg = 0; reg < MAX_KEY_WORDS; reg++) { + int size = key_bytes - (MAX_KEY_WORDS - reg - 1) * 4; + if (size <= 0) + todo_write_val(0, DPKR7 - reg * 4); + else { + if (size > 4) + size = 4; + todo_write_ptr(keyp, DPKR7 - reg * 4, size); + keyp += size; + } + } + } + todo_assign(di->key_programmed, 1); + + if (flags & DI_FUNC_LOCK_FLAGS) { + dcr = di_read(DCR); + if (flags & DI_FUNC_FLAG_READ_LOCK) { + if (flags & DI_FUNC_FLAG_HARD_LOCK) + dcr |= DCR_PKRHL; + else + dcr |= DCR_PKRSL; + } + if (flags & DI_FUNC_FLAG_WRITE_LOCK) { + if (flags & DI_FUNC_FLAG_HARD_LOCK) + dcr |= DCR_PKWHL; + else + dcr |= DCR_PKWSL; + } + todo_write_val(dcr, DCR); + } + todo_start(); + + if (flags & DI_FUNC_FLAG_ASYNC) + return 0; + + rc = todo_wait_done(); +err: + di_busy_clear(); + return rc; +} +EXTERN_SYMBOL(dryice_set_programmed_key); + +di_return_t dryice_get_programmed_key(uint8_t *key_data, int key_bits) +{ + int reg, byte, key_bytes; + uint32_t dcr, dpkr; + di_return_t rc = 0; + + if (di_busy_set()) + return DI_ERR_BUSY; + + if (key_data == NULL) { + rc = DI_ERR_INVAL; + goto err; + } + if (key_bits < 0 || key_bits > MAX_KEY_LEN || key_bits % 8) { + rc = DI_ERR_INVAL; + goto err; + } + #if 0 + if (!di->key_programmed) { + rc = DI_ERR_UNSET; + goto err; + } + #endif + if (di_state() == DI_STATE_FAILURE) { + rc = DI_ERR_STATE; + goto err; + } + dcr = di_read(DCR); + if (dcr & DCR_PKRHL) { + rc = DI_ERR_HLOCK; + goto err; + } + if (dcr & DCR_PKRSL) { + rc = DI_ERR_SLOCK; + goto err; + } + key_bytes = key_bits / 8; + + /* read key */ + for (reg = 0; reg < MAX_KEY_WORDS; reg++) { + if (reg < (MAX_KEY_BYTES - key_bytes) / 4) + continue; + dpkr = di_read(DPKR7 - reg * 4); + + for (byte = 0; byte < 4; byte++) { + if (reg * 4 + byte >= MAX_KEY_BYTES - key_bytes) { + int shift = 24 - byte * 8; + *key_data++ = (dpkr >> shift) & 0xff; + } + } + dpkr = 0; /* cleared for security */ + } +err: + di_busy_clear(); + return rc; +} +EXTERN_SYMBOL(dryice_get_programmed_key); + +di_return_t dryice_release_programmed_key(void) +{ + uint32_t dcr; + di_return_t rc = 0; + + if (di_busy_set()) + return DI_ERR_BUSY; + + if (!di->key_programmed) { + rc = DI_ERR_UNSET; + goto err; + } + dcr = di_read(DCR); + if (dcr & DCR_PKWHL) { + rc = DI_ERR_HLOCK; + goto err; + } + if (dcr & DCR_PKWSL) { + rc = DI_ERR_SLOCK; + goto err; + } + di->key_programmed = 0; + +err: + di_busy_clear(); + return rc; +} +EXTERN_SYMBOL(dryice_release_programmed_key); + +di_return_t dryice_set_random_key(int flags) +{ + uint32_t dcr; + di_return_t rc = 0; + + if (di_busy_set()) + return DI_ERR_BUSY; + + if (di_state() == DI_STATE_FAILURE) { + rc = DI_ERR_STATE; + goto err; + } + dcr = di_read(DCR); + if (dcr & DCR_RKHL) { + rc = DI_ERR_HLOCK; + goto err; + } + if (dcr & DCR_RKSL) { + rc = DI_ERR_SLOCK; + goto err; + } + todo_init((flags & DI_FUNC_FLAG_ASYNC) != 0); + + /* clear Random Key Error bit, if set */ + if (di_read(DSR) & DSR_RKE) + todo_write_val(DSR_RKE, DCR); + + /* load random key */ + todo_write_val(DKCR_LRK, DKCR); + + /* wait for RKV (valid) or RKE (error) */ + todo_wait_rkg(); + + if (flags & DI_FUNC_LOCK_FLAGS) { + dcr = di_read(DCR); + if (flags & DI_FUNC_FLAG_WRITE_LOCK) { + if (flags & DI_FUNC_FLAG_HARD_LOCK) + dcr |= DCR_RKHL; + else + dcr |= DCR_RKSL; + } + todo_write_val(dcr, DCR); + } + todo_start(); + + if (flags & DI_FUNC_FLAG_ASYNC) + return 0; + + rc = todo_wait_done(); +err: + di_busy_clear(); + return rc; +} +EXTERN_SYMBOL(dryice_set_random_key); + +di_return_t dryice_select_key(di_key_t key, int flags) +{ + uint32_t dcr, dksr; + di_return_t rc = 0; + + if (di_busy_set()) + return DI_ERR_BUSY; + + switch (key) { + case DI_KEY_FK: + dksr = DKSR_IIM_KEY; + break; + case DI_KEY_PK: + dksr = DKSR_PROG_KEY; + break; + case DI_KEY_RK: + dksr = DKSR_RAND_KEY; + break; + case DI_KEY_FPK: + dksr = DKSR_PROG_XOR_IIM_KEY; + break; + case DI_KEY_FRK: + dksr = DKSR_RAND_XOR_IIM_KEY; + break; + default: + rc = DI_ERR_INVAL; + goto err; + } + if (di->key_selected) { + rc = DI_ERR_INUSE; + goto err; + } + if (di_state() != DI_STATE_VALID) { + rc = DI_ERR_STATE; + goto err; + } + dcr = di_read(DCR); + if (dcr & DCR_KSHL) { + rc = DI_ERR_HLOCK; + goto err; + } + if (dcr & DCR_KSSL) { + rc = DI_ERR_SLOCK; + goto err; + } + todo_init((flags & DI_FUNC_FLAG_ASYNC) != 0); + + /* select key */ + todo_write_val(dksr, DKSR); + + todo_assign(di->key_selected, 1); + + if (flags & DI_FUNC_LOCK_FLAGS) { + dcr = di_read(DCR); + if (flags & DI_FUNC_FLAG_WRITE_LOCK) { + if (flags & DI_FUNC_FLAG_HARD_LOCK) + dcr |= DCR_KSHL; + else + dcr |= DCR_KSSL; + } + todo_write_val(dcr, DCR); + } + todo_start(); + + if (flags & DI_FUNC_FLAG_ASYNC) + return 0; + + rc = todo_wait_done(); +err: + di_busy_clear(); + return rc; +} +EXTERN_SYMBOL(dryice_select_key); + +di_return_t dryice_check_key(di_key_t *key) +{ + uint32_t dksr; + di_return_t rc = 0; + + if (di_busy_set()) + return DI_ERR_BUSY; + + if (key == NULL) { + rc = DI_ERR_INVAL; + goto err; + } + + dksr = di_read(DKSR); + + if (di_state() != DI_STATE_VALID) { + dksr = DKSR_IIM_KEY; + rc = DI_ERR_STATE; + } else if (dksr == DI_KEY_RK || dksr == DI_KEY_FRK) { + if (!(di_read(DSR) & DSR_RKV)) { + dksr = DKSR_IIM_KEY; + rc = DI_ERR_UNSET; + } + } + switch (dksr) { + case DKSR_IIM_KEY: + *key = DI_KEY_FK; + break; + case DKSR_PROG_KEY: + *key = DI_KEY_PK; + break; + case DKSR_RAND_KEY: + *key = DI_KEY_RK; + break; + case DKSR_PROG_XOR_IIM_KEY: + *key = DI_KEY_FPK; + break; + case DKSR_RAND_XOR_IIM_KEY: + *key = DI_KEY_FRK; + break; + } +err: + di_busy_clear(); + return rc; +} +EXTERN_SYMBOL(dryice_check_key); + +di_return_t dryice_release_key_selection(void) +{ + uint32_t dcr; + di_return_t rc = 0; + + if (di_busy_set()) + return DI_ERR_BUSY; + + if (!di->key_selected) { + rc = DI_ERR_UNSET; + goto err; + } + dcr = di_read(DCR); + if (dcr & DCR_KSHL) { + rc = DI_ERR_HLOCK; + goto err; + } + if (dcr & DCR_KSSL) { + rc = DI_ERR_SLOCK; + goto err; + } + di->key_selected = 0; + +err: + di_busy_clear(); + return rc; +} +EXTERN_SYMBOL(dryice_release_key_selection); + +di_return_t dryice_get_tamper_event(uint32_t *events, uint32_t *timestamp, + int flags) +{ + di_return_t rc = 0; + + if (di_busy_set()) + return DI_ERR_BUSY; + + if (di_state() == DI_STATE_VALID) { + rc = DI_ERR_STATE; + goto err; + } + if (events == NULL) { + rc = DI_ERR_INVAL; + goto err; + } + *events = di_read(DSR) & DSR_TAMPER_BITS; + if (timestamp) { + if (di_state() == DI_STATE_NON_VALID) + *timestamp = di_read(DTCMR); + else + *timestamp = 0; + } +err: + di_busy_clear(); + return rc; +} +EXTERN_SYMBOL(dryice_get_tamper_event); + +di_return_t dryice_register_callback(void (*func)(di_return_t, + unsigned long cookie), + unsigned long cookie) +{ + di_return_t rc = 0; + + if (di_busy_set()) + return DI_ERR_BUSY; + + di->cb_func = func; + di->cb_cookie = cookie; + + di_busy_clear(); + return rc; +} +EXTERN_SYMBOL(dryice_register_callback); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("DryIce"); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/security/dryice.h b/drivers/mxc/security/dryice.h new file mode 100644 index 000000000000..b98b7cd03c90 --- /dev/null +++ b/drivers/mxc/security/dryice.h @@ -0,0 +1,287 @@ +/* + * Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + + +#ifndef __DRYICE_H__ +#define __DRYICE_H__ + + +/*! + * @file dryice.h + * @brief Definition of DryIce API. + */ + +/*! @page dryice_api DryIce API + * + * Definition of the DryIce API. + * + * The DryIce API implements a software interface to the DryIce hardware + * block. Methods are provided to store, retrieve, generate, and manage + * cryptographic keys and to monitor security tamper events. + * + * See @ref dryice_api for the DryIce API. + */ + +/*! + * This defines the SCC key length (in bits) + */ +#define SCC_KEY_LEN 168 + +/*! + * This defines the maximum key length (in bits) + */ +#define MAX_KEY_LEN 256 +#define MAX_KEY_BYTES ((MAX_KEY_LEN) / 8) +#define MAX_KEY_WORDS ((MAX_KEY_LEN) / 32) + +/*! + * @name DryIce Function Flags + */ +/*@{*/ +#define DI_FUNC_FLAG_ASYNC 0x01 /*!< do not block */ +#define DI_FUNC_FLAG_READ_LOCK 0x02 /*!< set read lock for this resource */ +#define DI_FUNC_FLAG_WRITE_LOCK 0x04 /*!< set write lock for resource */ +#define DI_FUNC_FLAG_HARD_LOCK 0x08 /*!< locks will be hard (default soft) */ +#define DI_FUNC_FLAG_WORD_KEY 0x10 /*!< key provided as 32-bit words */ +/*@}*/ + +/*! + * @name DryIce Tamper Events + */ +/*@{*/ +#define DI_TAMPER_EVENT_WTD (1 << 23) /*!< wire-mesh tampering det */ +#define DI_TAMPER_EVENT_ETBD (1 << 22) /*!< ext tampering det: input B */ +#define DI_TAMPER_EVENT_ETAD (1 << 21) /*!< ext tampering det: input A */ +#define DI_TAMPER_EVENT_EBD (1 << 20) /*!< external boot detected */ +#define DI_TAMPER_EVENT_SAD (1 << 19) /*!< security alarm detected */ +#define DI_TAMPER_EVENT_TTD (1 << 18) /*!< temperature tampering det */ +#define DI_TAMPER_EVENT_CTD (1 << 17) /*!< clock tampering det */ +#define DI_TAMPER_EVENT_VTD (1 << 16) /*!< voltage tampering det */ +#define DI_TAMPER_EVENT_MCO (1 << 3) /*!< monotonic counter overflow */ +#define DI_TAMPER_EVENT_TCO (1 << 2) /*!< time counter overflow */ +/*@}*/ + +/*! + * DryIce Key Sources + */ +typedef enum di_key { + DI_KEY_FK, /*!< the fused (IIM) key */ + DI_KEY_PK, /*!< the programmed key */ + DI_KEY_RK, /*!< the random key */ + DI_KEY_FPK, /*!< the programmed key XORed with the fused key */ + DI_KEY_FRK, /*!< the random key XORed with the fused key */ +} di_key_t; + +/*! + * DryIce Error Codes + */ +typedef enum dryice_return { + DI_SUCCESS = 0, /*!< operation was successful */ + DI_ERR_BUSY, /*!< device or resource busy */ + DI_ERR_STATE, /*!< dryice is in incompatible state */ + DI_ERR_INUSE, /*!< resource is already in use */ + DI_ERR_UNSET, /*!< resource has not been initialized */ + DI_ERR_WRITE, /*!< error occurred during register write */ + DI_ERR_INVAL, /*!< invalid argument */ + DI_ERR_FAIL, /*!< operation failed */ + DI_ERR_HLOCK, /*!< resource is hard locked */ + DI_ERR_SLOCK, /*!< resource is soft locked */ + DI_ERR_NOMEM, /*!< out of memory */ +} di_return_t; + +/*! + * These functions define the DryIce API. + */ + +/*! + * Write a given key to the Programmed Key registers in DryIce, and + * optionally lock the Programmed Key against either reading or further + * writing. The value is held until a call to the release_programmed_key + * interface is made, or until the appropriate HW reset if the write-lock + * flags are used. Unused key bits will be zeroed. + * + * @param[in] key_data A pointer to the key data to be programmed, with + * the most significant byte or word first. This + * will be interpreted as a byte pointer unless the + * WORD_KEY flag is set, in which case it will be + * treated as a word pointer and the key data will be + * read a word at a time, starting with the MSW. + * When called asynchronously, the data pointed to by + * key_data must persist until the operation completes. + * + * @param[in] key_bits The number of bits in the key to be stored. + * This must be a multiple of 8 and within the + * range of 0 and MAX_KEY_LEN. + * + * @param[in] flags This is a bit-wise OR of the flags to be passed + * to the function. Flags can include: + * ASYNC, READ_LOCK, WRITE_LOCK, HARD_LOCK, and + * WORD_KEY. + * + * @return Returns SUCCESS (0), BUSY if DryIce is busy, INVAL + * on invalid arguments, INUSE if key has already been + * programmed, STATE if DryIce is in the wrong state, + * HLOCK or SLOCK if the key registers are locked for + * writing, and WRITE if a write error occurs + * (See #di_return_t). + */ +extern di_return_t dryice_set_programmed_key(const void *key_data, int key_bits, + int flags); + +/*! + * Read the Programmed Key registers and write the contents into a buffer. + * + * @param[out] key_data A byte pointer to where the key data will be written, + * with the most significant byte being written first. + * + * @param[in] key_bits The number of bits of the key to be retrieved. + * This must be a multiple of 8 and within the + * range of 0 and MAX_KEY_LEN. + * + * @return Returns SUCCESS (0), BUSY if DryIce is busy, INVAL + * on invalid arguments, UNSET if key has not been + * programmed, STATE if DryIce is in the wrong state, + * and HLOCK or SLOCK if the key registers are locked for + * reading (See #di_return_t). + */ +extern di_return_t dryice_get_programmed_key(uint8_t *key_data, int key_bits); + +/*! + * Allow the set_programmed_key interface to be used to write a new + * Programmed Key to DryIce. Note that this interface does not overwrite + * the value in the Programmed Key registers. + * + * @return Returns SUCCESS (0), BUSY if DryIce is busy, + * UNSET if the key has not been previously set, and + * HLOCK or SLOCK if the key registers are locked for + * writing (See #di_return_t). + */ +extern di_return_t dryice_release_programmed_key(void); + +/*! + * Generate and load a new Random Key in DryIce, and optionally lock the + * Random Key against further change. + * + * @param[in] flags This is a bit-wise OR of the flags to be passed + * to the function. Flags can include: + * ASYNC, READ_LOCK, WRITE_LOCK, and HARD_LOCK. + * + * @return Returns SUCCESS (0), BUSY if DryIce is busy, STATE + * if DryIce is in the wrong state, FAIL if the key gen + * failed, HLOCK or SLOCK if the key registers are + * locked, and WRITE if a write error occurs + * (See #di_return_t). + */ +extern di_return_t dryice_set_random_key(int flags); + +/*! + * Set the key selection in DryIce to determine the key used by an + * encryption module such as SCC. The selection is held until a call to the + * Release Selected Key interface is made, or until the appropriate HW + * reset if the LOCK flags are used. + * + * @param[in] key The source of the key to be used by the SCC + * (See #di_key_t). + * + * @param[in] flags This is a bit-wise OR of the flags to be passed + * to the function. Flags can include: + * ASYNC, WRITE_LOCK, and HARD_LOCK. + * + * @return Returns SUCCESS (0), BUSY if DryIce is busy, INVAL + * on invalid arguments, INUSE if a selection has already + * been made, STATE if DryIce is in the wrong state, + * HLOCK or SLOCK if the selection register is locked, + * and WRITE if a write error occurs + */ +extern di_return_t dryice_select_key(di_key_t key, int flags); + +/*! + * Check which key will be used in the SCC. This is needed because in some + * DryIce states, the Key Select Register is overridden by a default value + * (the Fused/IIM key). + * + * @param[out] key The source of the key that is currently selected for + * use by the SCC. This may be different from the key + * specified by the dryice_select_key function + * (See #di_key_t). This value is set even if an error + * code (except for BUSY) is returned. + * + * @return Returns SUCCESS (0), BUSY if DryIce is busy, STATE if + * DryIce is in the wrong state, INVAL on invalid + * arguments, or UNSET if no key has been selected + * (See #di_return_t). + */ +extern di_return_t dryice_check_key(di_key_t *key); + +/*! + * Allow the dryice_select_key interface to be used to set a new key selection + * in DryIce. Note that this interface does not overwrite the value in DryIce. + * + * @return Returns SUCCESS (0), BUSY if DryIce is busy, UNSET + * if the no selection has been made previously, and + * HLOCK or SLOCK if the selection register is locked + * (See #di_return_t). + */ +extern di_return_t dryice_release_key_selection(void); + +/*! + * Returns tamper-detection status bits. Also an optional timestamp when + * DryIce is in the Non-valid state. If DryIce is not in Failure or Non-valid + * state, this interface returns a failure code. + * + * @param[out] events This is a bit-wise OR of the following events: + * WTD (Wire Mesh), ETBD (External Tamper B), + * ETAD (External Tamper A), EBD (External Boot), + * SAD (Security Alarm), TTD (Temperature Tamper), + * CTD (Clock Tamper), VTD (Voltage Tamper), + * MCO (Monolithic Counter Overflow), and + * TCO (Time Counter Overflow). + * + * @param[out] timestamp This is the value of the time counter in seconds + * when the tamper occurred. A timestamp will not be + * returned if a NULL pointer is specified. If DryIce + * is not in the Non-valid state the time cannot be + * read, so a timestamp of 0 will be returned. + * + * @param[in] flags This is a bit-wise OR of the flags to be passed + * to the function. Flags is ignored currently by + * this function. + * + * @return Returns SUCCESS (0), BUSY if DryIce is busy, and + * INVAL on invalid arguments (See #di_return_t). + */ +extern di_return_t +dryice_get_tamper_event(uint32_t *events, uint32_t *timestamp, int flags); + +/*! + * Provide a callback function to be called upon the completion of DryIce calls + * that are executed asynchronously. + * + * @param[in] func This is a pointer to a function of type: + * void callback(di_return_t rc, unsigned long cookie) + * The return code of the async function is passed + * back in "rc" along with the cookie provided when + * registering the callback. + * + * @param[in] cookie This is an "opaque" cookie of type unsigned long that + * is returned on subsequent callbacks. It may be of any + * value. + * + * @return Returns SUCCESS (0), or BUSY if DryIce is busy + * (See #di_return_t). + */ +extern di_return_t dryice_register_callback(void (*func)(di_return_t rc, + unsigned long cookie), + unsigned long cookie); + +#endif /* __DRYICE_H__ */ diff --git a/drivers/mxc/ssi/Kconfig b/drivers/mxc/ssi/Kconfig new file mode 100644 index 000000000000..4cb581c2f945 --- /dev/null +++ b/drivers/mxc/ssi/Kconfig @@ -0,0 +1,12 @@ +# +# SPI device configuration +# + +menu "MXC SSI support" + +config MXC_SSI + tristate "SSI support" + ---help--- + Say Y to get the SSI services API available on MXC platform. + +endmenu diff --git a/drivers/mxc/ssi/Makefile b/drivers/mxc/ssi/Makefile new file mode 100644 index 000000000000..f9bb4419fc19 --- /dev/null +++ b/drivers/mxc/ssi/Makefile @@ -0,0 +1,7 @@ +# +# Makefile for the kernel SSI device drivers. +# + +obj-$(CONFIG_MXC_SSI) += ssimod.o + +ssimod-objs := ssi.o diff --git a/drivers/mxc/ssi/registers.h b/drivers/mxc/ssi/registers.h new file mode 100644 index 000000000000..a9f4512596c6 --- /dev/null +++ b/drivers/mxc/ssi/registers.h @@ -0,0 +1,208 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + + /*! + * @file ../ssi/registers.h + * @brief This header file contains SSI driver low level definition to access module registers. + * + * @ingroup SSI + */ + +#ifndef __MXC_SSI_REGISTERS_H__ +#define __MXC_SSI_REGISTERS_H__ + +/*! + * This include to define bool type, false and true definitions. + */ +#include + +#define SPBA_CPU_SSI 0x07 + +#define MXC_SSISTX0 0x00 +#define MXC_SSISTX1 0x04 +#define MXC_SSISRX0 0x08 +#define MXC_SSISRX1 0x0C +#define MXC_SSISCR 0x10 +#define MXC_SSISISR 0x14 +#define MXC_SSISIER 0x18 +#define MXC_SSISTCR 0x1C +#define MXC_SSISRCR 0x20 +#define MXC_SSISTCCR 0x24 +#define MXC_SSISRCCR 0x28 +#define MXC_SSISFCSR 0x2C +#define MXC_SSISTR 0x30 +#define MXC_SSISOR 0x34 +#define MXC_SSISACNT 0x38 +#define MXC_SSISACADD 0x3C +#define MXC_SSISACDAT 0x40 +#define MXC_SSISATAG 0x44 +#define MXC_SSISTMSK 0x48 +#define MXC_SSISRMSK 0x4C + +/* MXC 91221 only */ +#define MXC_SSISACCST 0x50 +#define MXC_SSISACCEN 0x54 +#define MXC_SSISACCDIS 0x58 + +/*! SSI1 registers offset*/ +#define MXC_SSI1STX0 0x00 +#define MXC_SSI1STX1 0x04 +#define MXC_SSI1SRX0 0x08 +#define MXC_SSI1SRX1 0x0C +#define MXC_SSI1SCR 0x10 +#define MXC_SSI1SISR 0x14 +#define MXC_SSI1SIER 0x18 +#define MXC_SSI1STCR 0x1C +#define MXC_SSI1SRCR 0x20 +#define MXC_SSI1STCCR 0x24 +#define MXC_SSI1SRCCR 0x28 +#define MXC_SSI1SFCSR 0x2C +#define MXC_SSI1STR 0x30 +#define MXC_SSI1SOR 0x34 +#define MXC_SSI1SACNT 0x38 +#define MXC_SSI1SACADD 0x3C +#define MXC_SSI1SACDAT 0x40 +#define MXC_SSI1SATAG 0x44 +#define MXC_SSI1STMSK 0x48 +#define MXC_SSI1SRMSK 0x4C + +/* MXC91221 only */ + +#define MXC_SSISACCST 0x50 +#define MXC_SSISACCEN 0x54 +#define MXC_SSISACCDIS 0x58 + +/* Not on MXC91221 */ +/*! SSI2 registers offset*/ +#define MXC_SSI2STX0 0x00 +#define MXC_SSI2STX1 0x04 +#define MXC_SSI2SRX0 0x08 +#define MXC_SSI2SRX1 0x0C +#define MXC_SSI2SCR 0x10 +#define MXC_SSI2SISR 0x14 +#define MXC_SSI2SIER 0x18 +#define MXC_SSI2STCR 0x1C +#define MXC_SSI2SRCR 0x20 +#define MXC_SSI2STCCR 0x24 +#define MXC_SSI2SRCCR 0x28 +#define MXC_SSI2SFCSR 0x2C +#define MXC_SSI2STR 0x30 +#define MXC_SSI2SOR 0x34 +#define MXC_SSI2SACNT 0x38 +#define MXC_SSI2SACADD 0x3C +#define MXC_SSI2SACDAT 0x40 +#define MXC_SSI2SATAG 0x44 +#define MXC_SSI2STMSK 0x48 +#define MXC_SSI2SRMSK 0x4C + +/*! + * SCR Register bit shift definitions + */ +#define SSI_ENABLE_SHIFT 0 +#define SSI_TRANSMIT_ENABLE_SHIFT 1 +#define SSI_RECEIVE_ENABLE_SHIFT 2 +#define SSI_NETWORK_MODE_SHIFT 3 +#define SSI_SYNCHRONOUS_MODE_SHIFT 4 +#define SSI_I2S_MODE_SHIFT 5 +#define SSI_SYSTEM_CLOCK_SHIFT 7 +#define SSI_TWO_CHANNEL_SHIFT 8 +#define SSI_CLOCK_IDLE_SHIFT 9 + +/* MXC91221 only*/ +#define SSI_TX_FRAME_CLOCK_DISABLE_SHIFT 10 +#define SSI_RX_FRAME_CLOCK_DISABLE_SHIFT 11 + +/*! + * STCR & SRCR Registers bit shift definitions + */ +#define SSI_EARLY_FRAME_SYNC_SHIFT 0 +#define SSI_FRAME_SYNC_LENGTH_SHIFT 1 +#define SSI_FRAME_SYNC_INVERT_SHIFT 2 +#define SSI_CLOCK_POLARITY_SHIFT 3 +#define SSI_SHIFT_DIRECTION_SHIFT 4 +#define SSI_CLOCK_DIRECTION_SHIFT 5 +#define SSI_FRAME_DIRECTION_SHIFT 6 +#define SSI_FIFO_ENABLE_0_SHIFT 7 +#define SSI_FIFO_ENABLE_1_SHIFT 8 +#define SSI_BIT_0_SHIFT 9 + +/* MXC91221 only*/ +#define SSI_TX_FRAME_CLOCK_DISABLE_SHIFT 10 +#define SSI_RX_DATA_EXTENSION_SHIFT 10 /*SRCR only */ +/*! + * STCCR & SRCCR Registers bit shift definitions + */ +#define SSI_PRESCALER_MODULUS_SHIFT 0 +#define SSI_FRAME_RATE_DIVIDER_SHIFT 8 +#define SSI_WORD_LENGTH_SHIFT 13 +#define SSI_PRESCALER_RANGE_SHIFT 17 +#define SSI_DIVIDE_BY_TWO_SHIFT 18 +#define SSI_FRAME_DIVIDER_MASK 31 +#define SSI_MIN_FRAME_DIVIDER_RATIO 1 +#define SSI_MAX_FRAME_DIVIDER_RATIO 32 +#define SSI_PRESCALER_MODULUS_MASK 255 +#define SSI_MIN_PRESCALER_MODULUS_RATIO 1 +#define SSI_MAX_PRESCALER_MODULUS_RATIO 256 +#define SSI_WORD_LENGTH_MASK 15 + +#define SSI_IRQ_STATUS_NUMBER 25 + +/*! + * SFCSR Register bit shift definitions + */ +#define SSI_RX_FIFO_1_COUNT_SHIFT 28 +#define SSI_TX_FIFO_1_COUNT_SHIFT 24 +#define SSI_RX_FIFO_1_WATERMARK_SHIFT 20 +#define SSI_TX_FIFO_1_WATERMARK_SHIFT 16 +#define SSI_RX_FIFO_0_COUNT_SHIFT 12 +#define SSI_TX_FIFO_0_COUNT_SHIFT 8 +#define SSI_RX_FIFO_0_WATERMARK_SHIFT 4 +#define SSI_TX_FIFO_0_WATERMARK_SHIFT 0 +#define SSI_MIN_FIFO_WATERMARK 0 +#define SSI_MAX_FIFO_WATERMARK 8 + +/*! + * SSI Option Register (SOR) bit shift definitions + */ +#define SSI_FRAME_SYN_RESET_SHIFT 0 +#define SSI_WAIT_SHIFT 1 +#define SSI_INIT_SHIFT 3 +#define SSI_TRANSMITTER_CLEAR_SHIFT 4 +#define SSI_RECEIVER_CLEAR_SHIFT 5 +#define SSI_CLOCK_OFF_SHIFT 6 +#define SSI_WAIT_STATE_MASK 0x3 + +/*! + * SSI AC97 Control Register (SACNT) bit shift definitions + */ +#define AC97_MODE_ENABLE_SHIFT 0 +#define AC97_VARIABLE_OPERATION_SHIFT 1 +#define AC97_TAG_IN_FIFO_SHIFT 2 +#define AC97_READ_COMMAND_SHIFT 3 +#define AC97_WRITE_COMMAND_SHIFT 4 +#define AC97_FRAME_RATE_DIVIDER_SHIFT 5 +#define AC97_FRAME_RATE_MASK 0x3F + +/*! + * SSI Test Register (STR) bit shift definitions + */ +#define SSI_TEST_MODE_SHIFT 15 +#define SSI_RCK2TCK_SHIFT 14 +#define SSI_RFS2TFS_SHIFT 13 +#define SSI_RXSTATE_SHIFT 8 +#define SSI_TXD2RXD_SHIFT 7 +#define SSI_TCK2RCK_SHIFT 6 +#define SSI_TFS2RFS_SHIFT 5 +#define SSI_TXSTATE_SHIFT 0 + +#endif /* __MXC_SSI_REGISTERS_H__ */ diff --git a/drivers/mxc/ssi/ssi.c b/drivers/mxc/ssi/ssi.c new file mode 100644 index 000000000000..f849a3ec7072 --- /dev/null +++ b/drivers/mxc/ssi/ssi.c @@ -0,0 +1,1221 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file ssi.c + * @brief This file contains the implementation of the SSI driver main services + * + * + * @ingroup SSI + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "registers.h" +#include "ssi.h" + +static spinlock_t ssi_lock; +struct mxc_audio_platform_data *ssi_platform_data; + +EXPORT_SYMBOL(ssi_ac97_frame_rate_divider); +EXPORT_SYMBOL(ssi_ac97_get_command_address_register); +EXPORT_SYMBOL(ssi_ac97_get_command_data_register); +EXPORT_SYMBOL(ssi_ac97_get_tag_register); +EXPORT_SYMBOL(ssi_ac97_mode_enable); +EXPORT_SYMBOL(ssi_ac97_tag_in_fifo); +EXPORT_SYMBOL(ssi_ac97_read_command); +EXPORT_SYMBOL(ssi_ac97_set_command_address_register); +EXPORT_SYMBOL(ssi_ac97_set_command_data_register); +EXPORT_SYMBOL(ssi_ac97_set_tag_register); +EXPORT_SYMBOL(ssi_ac97_variable_mode); +EXPORT_SYMBOL(ssi_ac97_write_command); +EXPORT_SYMBOL(ssi_clock_idle_state); +EXPORT_SYMBOL(ssi_clock_off); +EXPORT_SYMBOL(ssi_enable); +EXPORT_SYMBOL(ssi_get_data); +EXPORT_SYMBOL(ssi_get_status); +EXPORT_SYMBOL(ssi_i2s_mode); +EXPORT_SYMBOL(ssi_interrupt_disable); +EXPORT_SYMBOL(ssi_interrupt_enable); +EXPORT_SYMBOL(ssi_network_mode); +EXPORT_SYMBOL(ssi_receive_enable); +EXPORT_SYMBOL(ssi_rx_bit0); +EXPORT_SYMBOL(ssi_rx_clock_direction); +EXPORT_SYMBOL(ssi_rx_clock_divide_by_two); +EXPORT_SYMBOL(ssi_rx_clock_polarity); +EXPORT_SYMBOL(ssi_rx_clock_prescaler); +EXPORT_SYMBOL(ssi_rx_early_frame_sync); +EXPORT_SYMBOL(ssi_rx_fifo_counter); +EXPORT_SYMBOL(ssi_rx_fifo_enable); +EXPORT_SYMBOL(ssi_rx_fifo_full_watermark); +EXPORT_SYMBOL(ssi_rx_flush_fifo); +EXPORT_SYMBOL(ssi_rx_frame_direction); +EXPORT_SYMBOL(ssi_rx_frame_rate); +EXPORT_SYMBOL(ssi_rx_frame_sync_active); +EXPORT_SYMBOL(ssi_rx_frame_sync_length); +EXPORT_SYMBOL(ssi_rx_mask_time_slot); +EXPORT_SYMBOL(ssi_rx_prescaler_modulus); +EXPORT_SYMBOL(ssi_rx_shift_direction); +EXPORT_SYMBOL(ssi_rx_word_length); +EXPORT_SYMBOL(ssi_set_data); +EXPORT_SYMBOL(ssi_set_wait_states); +EXPORT_SYMBOL(ssi_synchronous_mode); +EXPORT_SYMBOL(ssi_system_clock); +EXPORT_SYMBOL(ssi_transmit_enable); +EXPORT_SYMBOL(ssi_two_channel_mode); +EXPORT_SYMBOL(ssi_tx_bit0); +EXPORT_SYMBOL(ssi_tx_clock_direction); +EXPORT_SYMBOL(ssi_tx_clock_divide_by_two); +EXPORT_SYMBOL(ssi_tx_clock_polarity); +EXPORT_SYMBOL(ssi_tx_clock_prescaler); +EXPORT_SYMBOL(ssi_tx_early_frame_sync); +EXPORT_SYMBOL(ssi_tx_fifo_counter); +EXPORT_SYMBOL(ssi_tx_fifo_empty_watermark); +EXPORT_SYMBOL(ssi_tx_fifo_enable); +EXPORT_SYMBOL(ssi_tx_flush_fifo); +EXPORT_SYMBOL(ssi_tx_frame_direction); +EXPORT_SYMBOL(ssi_tx_frame_rate); +EXPORT_SYMBOL(ssi_tx_frame_sync_active); +EXPORT_SYMBOL(ssi_tx_frame_sync_length); +EXPORT_SYMBOL(ssi_tx_mask_time_slot); +EXPORT_SYMBOL(ssi_tx_prescaler_modulus); +EXPORT_SYMBOL(ssi_tx_shift_direction); +EXPORT_SYMBOL(ssi_tx_word_length); +EXPORT_SYMBOL(get_ssi_fifo_addr); + +struct resource *res; +unsigned long base_addr_1; +unsigned long base_addr_2; + +unsigned int get_ssi_fifo_addr(unsigned int ssi, int direction) +{ + unsigned int fifo_addr; + if (direction == 1) { + if (ssi_platform_data->ssi_num == 2) { + fifo_addr = + (ssi == + SSI1) ? (int)(base_addr_1 + + MXC_SSI1STX0) : (int)(base_addr_2 + + MXC_SSI2STX0); + } else { + fifo_addr = (int)(base_addr_1 + MXC_SSI1STX0); + } + } else { + fifo_addr = (int)(base_addr_1 + MXC_SSI1SRX0); + } + return fifo_addr; +} + +void *get_ssi_base_addr(unsigned int ssi) +{ + if (ssi_platform_data->ssi_num == 2) { + if (ssi == SSI1) + return IO_ADDRESS(base_addr_1); + else + return IO_ADDRESS(base_addr_2); + } + return IO_ADDRESS(base_addr_1); +} + +void set_register_bits(unsigned int mask, unsigned int data, + unsigned int offset, unsigned int ssi) +{ + volatile unsigned long reg = 0; + void *base_addr = get_ssi_base_addr(ssi); + unsigned long flags = 0; + + spin_lock_irqsave(&ssi_lock, flags); + reg = __raw_readl(base_addr + offset); + reg = (reg & (~mask)) | data; + __raw_writel(reg, base_addr + offset); + spin_unlock_irqrestore(&ssi_lock, flags); +} + +unsigned long getreg_value(unsigned int offset, unsigned int ssi) +{ + void *base_addr = get_ssi_base_addr(ssi); + return __raw_readl(base_addr + offset); +} + +void set_register(unsigned int data, unsigned int offset, unsigned int ssi) +{ + void *base_addr = get_ssi_base_addr(ssi); + __raw_writel(data, base_addr + offset); +} + +/*! + * This function controls the AC97 frame rate divider. + * + * @param module the module number + * @param frame_rate_divider the AC97 frame rate divider + */ +void ssi_ac97_frame_rate_divider(ssi_mod module, + unsigned char frame_rate_divider) +{ + unsigned int reg = 0; + + reg = getreg_value(MXC_SSISACNT, module); + reg |= ((frame_rate_divider & AC97_FRAME_RATE_MASK) + << AC97_FRAME_RATE_DIVIDER_SHIFT); + set_register(reg, MXC_SSISACNT, module); +} + +/*! + * This function gets the AC97 command address register. + * + * @param module the module number + * @return This function returns the command address slot information. + */ +unsigned int ssi_ac97_get_command_address_register(ssi_mod module) +{ + return getreg_value(MXC_SSISACADD, module); +} + +/*! + * This function gets the AC97 command data register. + * + * @param module the module number + * @return This function returns the command data slot information. + */ +unsigned int ssi_ac97_get_command_data_register(ssi_mod module) +{ + return getreg_value(MXC_SSISACDAT, module); +} + +/*! + * This function gets the AC97 tag register. + * + * @param module the module number + * @return This function returns the tag information. + */ +unsigned int ssi_ac97_get_tag_register(ssi_mod module) +{ + return getreg_value(MXC_SSISATAG, module); +} + +/*! + * This function controls the AC97 mode. + * + * @param module the module number + * @param state the AC97 mode state (enabled or disabled) + */ +void ssi_ac97_mode_enable(ssi_mod module, bool state) +{ + unsigned int reg = 0; + + reg = getreg_value(MXC_SSISACNT, module); + if (state == true) { + reg |= (1 << AC97_MODE_ENABLE_SHIFT); + } else { + reg &= ~(1 << AC97_MODE_ENABLE_SHIFT); + } + + set_register(reg, MXC_SSISACNT, module); +} + +/*! + * This function controls the AC97 tag in FIFO behavior. + * + * @param module the module number + * @param state the tag in fifo behavior (Tag info stored in Rx FIFO 0 if true, + * Tag info stored in SATAG register otherwise) + */ +void ssi_ac97_tag_in_fifo(ssi_mod module, bool state) +{ + unsigned int reg = 0; + + reg = getreg_value(MXC_SSISACNT, module); + if (state == true) { + reg |= (1 << AC97_TAG_IN_FIFO_SHIFT); + } else { + reg &= ~(1 << AC97_TAG_IN_FIFO_SHIFT); + } + + set_register(reg, MXC_SSISACNT, module); +} + +/*! + * This function controls the AC97 read command. + * + * @param module the module number + * @param state the next AC97 command is a read command or not + */ +void ssi_ac97_read_command(ssi_mod module, bool state) +{ + unsigned int reg = 0; + + reg = getreg_value(MXC_SSISACNT, module); + if (state == true) { + reg |= (1 << AC97_READ_COMMAND_SHIFT); + } else { + reg &= ~(1 << AC97_READ_COMMAND_SHIFT); + } + + set_register(reg, MXC_SSISACNT, module); +} + +/*! + * This function sets the AC97 command address register. + * + * @param module the module number + * @param address the command address slot information + */ +void ssi_ac97_set_command_address_register(ssi_mod module, unsigned int address) +{ + set_register(address, MXC_SSISACADD, module); +} + +/*! + * This function sets the AC97 command data register. + * + * @param module the module number + * @param data the command data slot information + */ +void ssi_ac97_set_command_data_register(ssi_mod module, unsigned int data) +{ + set_register(data, MXC_SSISACDAT, module); +} + +/*! + * This function sets the AC97 tag register. + * + * @param module the module number + * @param tag the tag information + */ +void ssi_ac97_set_tag_register(ssi_mod module, unsigned int tag) +{ + set_register(tag, MXC_SSISATAG, module); +} + +/*! + * This function controls the AC97 variable mode. + * + * @param module the module number + * @param state the AC97 variable mode state (enabled or disabled) + */ void ssi_ac97_variable_mode(ssi_mod module, bool state) +{ + unsigned int reg = 0; + + reg = getreg_value(MXC_SSISACNT, module); + if (state == true) { + reg |= (1 << AC97_VARIABLE_OPERATION_SHIFT); + } else { + reg &= ~(1 << AC97_VARIABLE_OPERATION_SHIFT); + } + + set_register(reg, MXC_SSISACNT, module); +} + +/*! + * This function controls the AC97 write command. + * + * @param module the module number + * @param state the next AC97 command is a write command or not + */ +void ssi_ac97_write_command(ssi_mod module, bool state) +{ + unsigned int reg = 0; + + reg = getreg_value(MXC_SSISACNT, module); + if (state == true) { + reg |= (1 << AC97_WRITE_COMMAND_SHIFT); + } else { + reg &= ~(1 << AC97_WRITE_COMMAND_SHIFT); + } + + set_register(reg, MXC_SSISACNT, module); +} + +/*! + * This function controls the idle state of the transmit clock port during SSI internal gated mode. + * + * @param module the module number + * @param state the clock idle state + */ +void ssi_clock_idle_state(ssi_mod module, idle_state state) +{ + set_register_bits(1 << SSI_CLOCK_IDLE_SHIFT, + state << SSI_CLOCK_IDLE_SHIFT, MXC_SSISCR, module); +} + +/*! + * This function turns off/on the ccm_ssi_clk to reduce power consumption. + * + * @param module the module number + * @param state the state for ccm_ssi_clk (true: turn off, else:turn on) + */ +void ssi_clock_off(ssi_mod module, bool state) +{ + set_register_bits(1 << SSI_CLOCK_OFF_SHIFT, + state << SSI_CLOCK_OFF_SHIFT, MXC_SSISOR, module); +} + +/*! + * This function enables/disables the SSI module. + * + * @param module the module number + * @param state the state for SSI module + */ +void ssi_enable(ssi_mod module, bool state) +{ + set_register_bits(1 << SSI_ENABLE_SHIFT, state << SSI_ENABLE_SHIFT, + MXC_SSISCR, module); +} + +/*! + * This function gets the data word in the Receive FIFO of the SSI module. + * + * @param module the module number + * @param fifo the Receive FIFO to read + * @return This function returns the read data. + */ +unsigned int ssi_get_data(ssi_mod module, fifo_nb fifo) +{ + unsigned int result = 0; + + if (ssi_fifo_0 == fifo) { + result = getreg_value(MXC_SSISRX0, module); + } else { + result = getreg_value(MXC_SSISRX1, module); + } + + return result; +} + +/*! + * This function returns the status of the SSI module (SISR register) as a combination of status. + * + * @param module the module number + * @return This function returns the status of the SSI module + */ +ssi_status_enable_mask ssi_get_status(ssi_mod module) +{ + unsigned int result; + + result = getreg_value(MXC_SSISISR, module); + result &= ((1 << SSI_IRQ_STATUS_NUMBER) - 1); + + return (ssi_status_enable_mask) result; +} + +/*! + * This function selects the I2S mode of the SSI module. + * + * @param module the module number + * @param mode the I2S mode + */ +void ssi_i2s_mode(ssi_mod module, mode_i2s mode) +{ + set_register_bits(3 << SSI_I2S_MODE_SHIFT, mode << SSI_I2S_MODE_SHIFT, + MXC_SSISCR, module); +} + +/*! + * This function disables the interrupts of the SSI module. + * + * @param module the module number + * @param mask the mask of the interrupts to disable + */ +void ssi_interrupt_disable(ssi_mod module, ssi_status_enable_mask mask) +{ + set_register_bits(mask, 0, MXC_SSISIER, module); +} + +/*! + * This function enables the interrupts of the SSI module. + * + * @param module the module number + * @param mask the mask of the interrupts to enable + */ +void ssi_interrupt_enable(ssi_mod module, ssi_status_enable_mask mask) +{ + set_register_bits(0, mask, MXC_SSISIER, module); +} + +/*! + * This function enables/disables the network mode of the SSI module. + * + * @param module the module number + * @param state the network mode state + */ +void ssi_network_mode(ssi_mod module, bool state) +{ + set_register_bits(1 << SSI_NETWORK_MODE_SHIFT, + state << SSI_NETWORK_MODE_SHIFT, MXC_SSISCR, module); +} + +/*! + * This function enables/disables the receive section of the SSI module. + * + * @param module the module number + * @param state the receive section state + */ +void ssi_receive_enable(ssi_mod module, bool state) +{ + set_register_bits(1 << SSI_RECEIVE_ENABLE_SHIFT, + state << SSI_RECEIVE_ENABLE_SHIFT, MXC_SSISCR, + module); +} + +/*! + * This function configures the SSI module to receive data word at bit position 0 or 23 in the Receive shift register. + * + * @param module the module number + * @param state the state to receive at bit 0 + */ +void ssi_rx_bit0(ssi_mod module, bool state) +{ + set_register_bits(1 << SSI_BIT_0_SHIFT, state << SSI_BIT_0_SHIFT, + MXC_SSISRCR, module); +} + +/*! + * This function controls the source of the clock signal used to clock the Receive shift register. + * + * @param module the module number + * @param direction the clock signal direction + */ +void ssi_rx_clock_direction(ssi_mod module, ssi_tx_rx_direction direction) +{ + set_register_bits(1 << SSI_CLOCK_DIRECTION_SHIFT, + direction << SSI_CLOCK_DIRECTION_SHIFT, MXC_SSISRCR, + module); +} + +/*! + * This function configures the divide-by-two divider of the SSI module for the receive section. + * + * @param module the module number + * @param state the divider state + */ +void ssi_rx_clock_divide_by_two(ssi_mod module, bool state) +{ + set_register_bits(1 << SSI_DIVIDE_BY_TWO_SHIFT, + state << SSI_DIVIDE_BY_TWO_SHIFT, MXC_SSISRCCR, + module); +} + +/*! + * This function controls which bit clock edge is used to clock in data. + * + * @param module the module number + * @param polarity the clock polarity + */ +void ssi_rx_clock_polarity(ssi_mod module, ssi_tx_rx_clock_polarity polarity) +{ + set_register_bits(1 << SSI_CLOCK_POLARITY_SHIFT, + polarity << SSI_CLOCK_POLARITY_SHIFT, MXC_SSISRCR, + module); +} + +/*! + * This function configures a fixed divide-by-eight clock prescaler divider of the SSI module in series with the variable prescaler for the receive section. + * + * @param module the module number + * @param state the prescaler state + */ +void ssi_rx_clock_prescaler(ssi_mod module, bool state) +{ + set_register_bits(1 << SSI_PRESCALER_RANGE_SHIFT, + state << SSI_PRESCALER_RANGE_SHIFT, + MXC_SSISRCCR, module); +} + +/*! + * This function controls the early frame sync configuration. + * + * @param module the module number + * @param early the early frame sync configuration + */ +void ssi_rx_early_frame_sync(ssi_mod module, ssi_tx_rx_early_frame_sync early) +{ + set_register_bits(1 << SSI_EARLY_FRAME_SYNC_SHIFT, + early << SSI_EARLY_FRAME_SYNC_SHIFT, + MXC_SSISRCR, module); +} + +/*! + * This function gets the number of data words in the Receive FIFO. + * + * @param module the module number + * @param fifo the fifo + * @return This function returns the number of words in the Rx FIFO. + */ +unsigned char ssi_rx_fifo_counter(ssi_mod module, fifo_nb fifo) +{ + unsigned char result; + result = 0; + + if (ssi_fifo_0 == fifo) { + result = getreg_value(MXC_SSISFCSR, module); + result &= (0xF << SSI_RX_FIFO_0_COUNT_SHIFT); + result = result >> SSI_RX_FIFO_0_COUNT_SHIFT; + } else { + result = getreg_value(MXC_SSISFCSR, module); + result &= (0xF << SSI_RX_FIFO_1_COUNT_SHIFT); + result = result >> SSI_RX_FIFO_1_COUNT_SHIFT; + } + + return result; +} + +/*! + * This function enables the Receive FIFO. + * + * @param module the module number + * @param fifo the fifo to enable + * @param enable the state of the fifo, enabled or disabled + */ + +void ssi_rx_fifo_enable(ssi_mod module, fifo_nb fifo, bool enable) +{ + volatile unsigned int reg; + + reg = getreg_value(MXC_SSISRCR, module); + if (enable == true) { + reg |= ((1 + fifo) << SSI_FIFO_ENABLE_0_SHIFT); + } else { + reg &= ~((1 + fifo) << SSI_FIFO_ENABLE_0_SHIFT); + } + + set_register(reg, MXC_SSISRCR, module); +} + +/*! + * This function controls the threshold at which the RFFx flag will be set. + * + * @param module the module number + * @param fifo the fifo to enable + * @param watermark the watermark + * @return This function returns the result of the operation (0 if successful, -1 otherwise). + */ +int ssi_rx_fifo_full_watermark(ssi_mod module, + fifo_nb fifo, unsigned char watermark) +{ + int result = -1; + result = -1; + + if ((watermark > SSI_MIN_FIFO_WATERMARK) && + (watermark <= SSI_MAX_FIFO_WATERMARK)) { + if (ssi_fifo_0 == fifo) { + set_register_bits(0xf << SSI_RX_FIFO_0_WATERMARK_SHIFT, + watermark << + SSI_RX_FIFO_0_WATERMARK_SHIFT, + MXC_SSISFCSR, module); + } else { + set_register_bits(0xf << SSI_RX_FIFO_1_WATERMARK_SHIFT, + watermark << + SSI_RX_FIFO_1_WATERMARK_SHIFT, + MXC_SSISFCSR, module); + } + + result = 0; + } + + return result; +} + +/*! + * This function flushes the Receive FIFOs. + * + * @param module the module number + */ +void ssi_rx_flush_fifo(ssi_mod module) +{ + set_register_bits(0, 1 << SSI_RECEIVER_CLEAR_SHIFT, MXC_SSISOR, module); +} + +/*! + * This function controls the direction of the Frame Sync signal for the receive section. + * + * @param module the module number + * @param direction the Frame Sync signal direction + */ +void ssi_rx_frame_direction(ssi_mod module, ssi_tx_rx_direction direction) +{ + set_register_bits(1 << SSI_FRAME_DIRECTION_SHIFT, + direction << SSI_FRAME_DIRECTION_SHIFT, + MXC_SSISRCR, module); +} + +/*! + * This function configures the Receive frame rate divider for the receive section. + * + * @param module the module number + * @param ratio the divide ratio from 1 to 32 + * @return This function returns the result of the operation (0 if successful, -1 otherwise). + */ +int ssi_rx_frame_rate(ssi_mod module, unsigned char ratio) +{ + int result = -1; + + if ((ratio >= SSI_MIN_FRAME_DIVIDER_RATIO) && + (ratio <= SSI_MAX_FRAME_DIVIDER_RATIO)) { + set_register_bits(SSI_FRAME_DIVIDER_MASK << + SSI_FRAME_RATE_DIVIDER_SHIFT, + (ratio - 1) << SSI_FRAME_RATE_DIVIDER_SHIFT, + MXC_SSISRCCR, module); + result = 0; + } + + return result; +} + +/*! + * This function controls the Frame Sync active polarity for the receive section. + * + * @param module the module number + * @param active the Frame Sync active polarity + */ +void ssi_rx_frame_sync_active(ssi_mod module, + ssi_tx_rx_frame_sync_active active) +{ + set_register_bits(1 << SSI_FRAME_SYNC_INVERT_SHIFT, + active << SSI_FRAME_SYNC_INVERT_SHIFT, + MXC_SSISRCR, module); +} + +/*! + * This function controls the Frame Sync length (one word or one bit long) for the receive section. + * + * @param module the module number + * @param length the Frame Sync length + */ +void ssi_rx_frame_sync_length(ssi_mod module, + ssi_tx_rx_frame_sync_length length) +{ + set_register_bits(1 << SSI_FRAME_SYNC_LENGTH_SHIFT, + length << SSI_FRAME_SYNC_LENGTH_SHIFT, + MXC_SSISRCR, module); +} + +/*! + * This function configures the time slot(s) to mask for the receive section. + * + * @param module the module number + * @param mask the mask to indicate the time slot(s) masked + */ +void ssi_rx_mask_time_slot(ssi_mod module, unsigned int mask) +{ + set_register_bits(0xFFFFFFFF, mask, MXC_SSISRMSK, module); +} + +/*! + * This function configures the Prescale divider for the receive section. + * + * @param module the module number + * @param divider the divide ratio from 1 to 256 + * @return This function returns the result of the operation (0 if successful, -1 otherwise). + */ +int ssi_rx_prescaler_modulus(ssi_mod module, unsigned int divider) +{ + int result = -1; + + if ((divider >= SSI_MIN_PRESCALER_MODULUS_RATIO) && + (divider <= SSI_MAX_PRESCALER_MODULUS_RATIO)) { + + set_register_bits(SSI_PRESCALER_MODULUS_MASK << + SSI_PRESCALER_MODULUS_SHIFT, + (divider - 1) << SSI_PRESCALER_MODULUS_SHIFT, + MXC_SSISRCCR, module); + result = 0; + } + + return result; +} + +/*! + * This function controls whether the MSB or LSB will be received first in a sample. + * + * @param module the module number + * @param direction the shift direction + */ +void ssi_rx_shift_direction(ssi_mod module, ssi_tx_rx_shift_direction direction) +{ + set_register_bits(1 << SSI_SHIFT_DIRECTION_SHIFT, + direction << SSI_SHIFT_DIRECTION_SHIFT, + MXC_SSISRCR, module); +} + +/*! + * This function configures the Receive word length. + * + * @param module the module number + * @param length the word length + */ +void ssi_rx_word_length(ssi_mod module, ssi_word_length length) +{ + set_register_bits(SSI_WORD_LENGTH_MASK << SSI_WORD_LENGTH_SHIFT, + length << SSI_WORD_LENGTH_SHIFT, + MXC_SSISRCCR, module); +} + +/*! + * This function sets the data word in the Transmit FIFO of the SSI module. + * + * @param module the module number + * @param fifo the FIFO number + * @param data the data to load in the FIFO + */ + +void ssi_set_data(ssi_mod module, fifo_nb fifo, unsigned int data) +{ + if (ssi_fifo_0 == fifo) { + set_register(data, MXC_SSISTX0, module); + } else { + set_register(data, MXC_SSISTX1, module); + } +} + +/*! + * This function controls the number of wait states between the core and SSI. + * + * @param module the module number + * @param wait the number of wait state(s) + */ +void ssi_set_wait_states(ssi_mod module, ssi_wait_states wait) +{ + set_register_bits(SSI_WAIT_STATE_MASK << SSI_WAIT_SHIFT, + wait << SSI_WAIT_SHIFT, MXC_SSISOR, module); +} + +/*! + * This function enables/disables the synchronous mode of the SSI module. + * + * @param module the module number + * @param state the synchronous mode state + */ +void ssi_synchronous_mode(ssi_mod module, bool state) +{ + set_register_bits(1 << SSI_SYNCHRONOUS_MODE_SHIFT, + state << SSI_SYNCHRONOUS_MODE_SHIFT, + MXC_SSISCR, module); +} + +/*! + * This function allows the SSI module to output the SYS_CLK at the SRCK port. + * + * @param module the module number + * @param state the system clock state + */ +void ssi_system_clock(ssi_mod module, bool state) +{ + set_register_bits(1 << SSI_SYSTEM_CLOCK_SHIFT, + state << SSI_SYSTEM_CLOCK_SHIFT, MXC_SSISCR, module); +} + +/*! + * This function enables/disables the transmit section of the SSI module. + * + * @param module the module number + * @param state the transmit section state + */ +void ssi_transmit_enable(ssi_mod module, bool state) +{ + set_register_bits(1 << SSI_TRANSMIT_ENABLE_SHIFT, + state << SSI_TRANSMIT_ENABLE_SHIFT, + MXC_SSISCR, module); +} + +/*! + * This function allows the SSI module to operate in the two channel mode. + * + * @param module the module number + * @param state the two channel mode state + */ +void ssi_two_channel_mode(ssi_mod module, bool state) +{ + set_register_bits(1 << SSI_TWO_CHANNEL_SHIFT, + state << SSI_TWO_CHANNEL_SHIFT, MXC_SSISCR, module); +} + +/*! + * This function configures the SSI module to transmit data word from bit position 0 or 23 in the Transmit shift register. + * + * @param module the module number + * @param state the transmit from bit 0 state + */ +void ssi_tx_bit0(ssi_mod module, bool state) +{ + set_register_bits(1 << SSI_BIT_0_SHIFT, + state << SSI_BIT_0_SHIFT, MXC_SSISTCR, module); +} + +/*! + * This function controls the direction of the clock signal used to clock the Transmit shift register. + * + * @param module the module number + * @param direction the clock signal direction + */ +void ssi_tx_clock_direction(ssi_mod module, ssi_tx_rx_direction direction) +{ + set_register_bits(1 << SSI_CLOCK_DIRECTION_SHIFT, + direction << SSI_CLOCK_DIRECTION_SHIFT, + MXC_SSISTCR, module); +} + +/*! + * This function configures the divide-by-two divider of the SSI module for the transmit section. + * + * @param module the module number + * @param state the divider state + */ +void ssi_tx_clock_divide_by_two(ssi_mod module, bool state) +{ + set_register_bits(1 << SSI_DIVIDE_BY_TWO_SHIFT, + state << SSI_DIVIDE_BY_TWO_SHIFT, + MXC_SSISTCCR, module); +} + +/*! + * This function controls which bit clock edge is used to clock out data. + * + * @param module the module number + * @param polarity the clock polarity + */ +void ssi_tx_clock_polarity(ssi_mod module, ssi_tx_rx_clock_polarity polarity) +{ + set_register_bits(1 << SSI_CLOCK_POLARITY_SHIFT, + polarity << SSI_CLOCK_POLARITY_SHIFT, + MXC_SSISTCR, module); +} + +/*! + * This function configures a fixed divide-by-eight clock prescaler divider of the SSI module in series with the variable prescaler for the transmit section. + * + * @param module the module number + * @param state the prescaler state + */ +void ssi_tx_clock_prescaler(ssi_mod module, bool state) +{ + set_register_bits(1 << SSI_PRESCALER_RANGE_SHIFT, + state << SSI_PRESCALER_RANGE_SHIFT, + MXC_SSISTCCR, module); +} + +/*! + * This function controls the early frame sync configuration for the transmit section. + * + * @param module the module number + * @param early the early frame sync configuration + */ +void ssi_tx_early_frame_sync(ssi_mod module, ssi_tx_rx_early_frame_sync early) +{ + set_register_bits(1 << SSI_EARLY_FRAME_SYNC_SHIFT, + early << SSI_EARLY_FRAME_SYNC_SHIFT, + MXC_SSISTCR, module); +} + +/*! + * This function gets the number of data words in the Transmit FIFO. + * + * @param module the module number + * @param fifo the fifo + * @return This function returns the number of words in the Tx FIFO. + */ +unsigned char ssi_tx_fifo_counter(ssi_mod module, fifo_nb fifo) +{ + unsigned char result = 0; + + if (ssi_fifo_0 == fifo) { + result = getreg_value(MXC_SSISFCSR, module); + result &= (0xF << SSI_TX_FIFO_0_COUNT_SHIFT); + result >>= SSI_TX_FIFO_0_COUNT_SHIFT; + } else { + result = getreg_value(MXC_SSISFCSR, module); + result &= (0xF << SSI_TX_FIFO_1_COUNT_SHIFT); + result >>= SSI_TX_FIFO_1_COUNT_SHIFT; + } + + return result; +} + +/*! + * This function controls the threshold at which the TFEx flag will be set. + * + * @param module the module number + * @param fifo the fifo to enable + * @param watermark the watermark + * @return This function returns the result of the operation (0 if successful, -1 otherwise). + */ +int ssi_tx_fifo_empty_watermark(ssi_mod module, + fifo_nb fifo, unsigned char watermark) +{ + int result = -1; + + if ((watermark > SSI_MIN_FIFO_WATERMARK) && + (watermark <= SSI_MAX_FIFO_WATERMARK)) { + if (ssi_fifo_0 == fifo) { + set_register_bits(0xf << SSI_TX_FIFO_0_WATERMARK_SHIFT, + watermark << + SSI_TX_FIFO_0_WATERMARK_SHIFT, + MXC_SSISFCSR, module); + } else { + set_register_bits(0xf << SSI_TX_FIFO_1_WATERMARK_SHIFT, + watermark << + SSI_TX_FIFO_1_WATERMARK_SHIFT, + MXC_SSISFCSR, module); + } + + result = 0; + } + + return result; +} + +/*! + * This function enables the Transmit FIFO. + * + * @param module the module number + * @param fifo the fifo to enable + * @param enable the state of the fifo, enabled or disabled + */ + +void ssi_tx_fifo_enable(ssi_mod module, fifo_nb fifo, bool enable) +{ + unsigned int reg; + + reg = getreg_value(MXC_SSISTCR, module); + if (enable == true) { + reg |= ((1 + fifo) << SSI_FIFO_ENABLE_0_SHIFT); + } else { + reg &= ~((1 + fifo) << SSI_FIFO_ENABLE_0_SHIFT); + } + + set_register(reg, MXC_SSISTCR, module); +} + +/*! + * This function flushes the Transmit FIFOs. + * + * @param module the module number + */ +void ssi_tx_flush_fifo(ssi_mod module) +{ + set_register_bits(0, 1 << SSI_TRANSMITTER_CLEAR_SHIFT, + MXC_SSISOR, module); +} + +/*! + * This function controls the direction of the Frame Sync signal for the transmit section. + * + * @param module the module number + * @param direction the Frame Sync signal direction + */ +void ssi_tx_frame_direction(ssi_mod module, ssi_tx_rx_direction direction) +{ + set_register_bits(1 << SSI_FRAME_DIRECTION_SHIFT, + direction << SSI_FRAME_DIRECTION_SHIFT, + MXC_SSISTCR, module); +} + +/*! + * This function configures the Transmit frame rate divider. + * + * @param module the module number + * @param ratio the divide ratio from 1 to 32 + * @return This function returns the result of the operation (0 if successful, -1 otherwise). + */ +int ssi_tx_frame_rate(ssi_mod module, unsigned char ratio) +{ + int result = -1; + + if ((ratio >= SSI_MIN_FRAME_DIVIDER_RATIO) && + (ratio <= SSI_MAX_FRAME_DIVIDER_RATIO)) { + + set_register_bits(SSI_FRAME_DIVIDER_MASK << + SSI_FRAME_RATE_DIVIDER_SHIFT, + (ratio - 1) << SSI_FRAME_RATE_DIVIDER_SHIFT, + MXC_SSISTCCR, module); + result = 0; + } + + return result; +} + +/*! + * This function controls the Frame Sync active polarity for the transmit section. + * + * @param module the module number + * @param active the Frame Sync active polarity + */ +void ssi_tx_frame_sync_active(ssi_mod module, + ssi_tx_rx_frame_sync_active active) +{ + set_register_bits(1 << SSI_FRAME_SYNC_INVERT_SHIFT, + active << SSI_FRAME_SYNC_INVERT_SHIFT, + MXC_SSISTCR, module); +} + +/*! + * This function controls the Frame Sync length (one word or one bit long) for the transmit section. + * + * @param module the module number + * @param length the Frame Sync length + */ +void ssi_tx_frame_sync_length(ssi_mod module, + ssi_tx_rx_frame_sync_length length) +{ + set_register_bits(1 << SSI_FRAME_SYNC_LENGTH_SHIFT, + length << SSI_FRAME_SYNC_LENGTH_SHIFT, + MXC_SSISTCR, module); +} + +/*! + * This function configures the time slot(s) to mask for the transmit section. + * + * @param module the module number + * @param mask the mask to indicate the time slot(s) masked + */ +void ssi_tx_mask_time_slot(ssi_mod module, unsigned int mask) +{ + set_register_bits(0xFFFFFFFF, mask, MXC_SSISTMSK, module); +} + +/*! + * This function configures the Prescale divider for the transmit section. + * + * @param module the module number + * @param divider the divide ratio from 1 to 256 + * @return This function returns the result of the operation (0 if successful, -1 otherwise). + */ +int ssi_tx_prescaler_modulus(ssi_mod module, unsigned int divider) +{ + int result = -1; + + if ((divider >= SSI_MIN_PRESCALER_MODULUS_RATIO) && + (divider <= SSI_MAX_PRESCALER_MODULUS_RATIO)) { + + set_register_bits(SSI_PRESCALER_MODULUS_MASK << + SSI_PRESCALER_MODULUS_SHIFT, + (divider - 1) << SSI_PRESCALER_MODULUS_SHIFT, + MXC_SSISTCCR, module); + result = 0; + } + + return result; +} + +/*! + * This function controls whether the MSB or LSB will be transmitted first in a sample. + * + * @param module the module number + * @param direction the shift direction + */ +void ssi_tx_shift_direction(ssi_mod module, ssi_tx_rx_shift_direction direction) +{ + set_register_bits(1 << SSI_SHIFT_DIRECTION_SHIFT, + direction << SSI_SHIFT_DIRECTION_SHIFT, + MXC_SSISTCR, module); +} + +/*! + * This function configures the Transmit word length. + * + * @param module the module number + * @param length the word length + */ +void ssi_tx_word_length(ssi_mod module, ssi_word_length length) +{ + set_register_bits(SSI_WORD_LENGTH_MASK << SSI_WORD_LENGTH_SHIFT, + length << SSI_WORD_LENGTH_SHIFT, + MXC_SSISTCCR, module); +} + +/*! + * This function initializes the driver in terms of memory of the soundcard + * and some basic HW clock settings. + * + * @return 0 on success, -1 otherwise. + */ +static int __init ssi_probe(struct platform_device *pdev) +{ + int ret = -1; + ssi_platform_data = + (struct mxc_audio_platform_data *)pdev->dev.platform_data; + if (!ssi_platform_data) { + dev_err(&pdev->dev, "can't get the platform data for SSI\n"); + return -EINVAL; + } + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + + if (!res) { + dev_err(&pdev->dev, "can't get platform resource - SSI\n"); + ret = -ENOMEM; + goto err; + } + + if (pdev->id == 0) { + base_addr_1 = res->start; + } else if (pdev->id == 1) { + base_addr_2 = res->start; + } + + printk(KERN_INFO "SSI %d module loaded successfully \n", pdev->id + 1); + + return 0; + err: + return -1; + +} + +static int ssi_remove(struct platform_device *dev) +{ + return 0; +} + +static struct platform_driver mxc_ssi_driver = { + .probe = ssi_probe, + .remove = ssi_remove, + .driver = { + .name = "mxc_ssi", + }, +}; + +/*! + * This function implements the init function of the SSI device. + * This function is called when the module is loaded. + * + * @return This function returns 0. + */ +static int __init ssi_init(void) +{ + spin_lock_init(&ssi_lock); + return platform_driver_register(&mxc_ssi_driver); + +} + +/*! + * This function implements the exit function of the SPI device. + * This function is called when the module is unloaded. + * + */ +static void __exit ssi_exit(void) +{ + platform_driver_unregister(&mxc_ssi_driver); + printk(KERN_INFO "SSI module unloaded successfully\n"); +} + +module_init(ssi_init); +module_exit(ssi_exit); + +MODULE_DESCRIPTION("SSI char device driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/mxc/ssi/ssi.h b/drivers/mxc/ssi/ssi.h new file mode 100644 index 000000000000..6edd3a3b3110 --- /dev/null +++ b/drivers/mxc/ssi/ssi.h @@ -0,0 +1,574 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + + /*! + * @defgroup SSI Synchronous Serial Interface (SSI) Driver + */ + + /*! + * @file ssi.h + * @brief This header file contains SSI driver functions prototypes. + * + * @ingroup SSI + */ + +#ifndef __MXC_SSI_H__ +#define __MXC_SSI_H__ + +#include "ssi_types.h" + +/*! + * This function gets the SSI fifo address. + * + * @param ssi ssi number + * @param direction To indicate playback / recording + * @return This function returns the SSI fifo address. + */ +unsigned int get_ssi_fifo_addr(unsigned int ssi, int direction); + +/*! + * This function controls the AC97 frame rate divider. + * + * @param module the module number + * @param frame_rate_divider the AC97 frame rate divider + */ +void ssi_ac97_frame_rate_divider(ssi_mod module, + unsigned char frame_rate_divider); + +/*! + * This function gets the AC97 command address register. + * + * @param module the module number + * @return This function returns the command address slot information. + */ +unsigned int ssi_ac97_get_command_address_register(ssi_mod module); + +/*! + * This function gets the AC97 command data register. + * + * @param module the module number + * @return This function returns the command data slot information. + */ +unsigned int ssi_ac97_get_command_data_register(ssi_mod module); + +/*! + * This function gets the AC97 tag register. + * + * @param module the module number + * @return This function returns the tag information. + */ +unsigned int ssi_ac97_get_tag_register(ssi_mod module); + +/*! + * This function controls the AC97 mode. + * + * @param module the module number + * @param state the AC97 mode state (enabled or disabled) + */ +void ssi_ac97_mode_enable(ssi_mod module, bool state); + +/*! + * This function controls the AC97 tag in FIFO behavior. + * + * @param module the module number + * @param state the tag in fifo behavior (Tag info stored in Rx FIFO 0 if TRUE, + * Tag info stored in SATAG register otherwise) + */ +void ssi_ac97_tag_in_fifo(ssi_mod module, bool state); + +/*! + * This function controls the AC97 read command. + * + * @param module the module number + * @param state the next AC97 command is a read command or not + */ +void ssi_ac97_read_command(ssi_mod module, bool state); + +/*! + * This function sets the AC97 command address register. + * + * @param module the module number + * @param address the command address slot information + */ +void ssi_ac97_set_command_address_register(ssi_mod module, + unsigned int address); + +/*! + * This function sets the AC97 command data register. + * + * @param module the module number + * @param data the command data slot information + */ +void ssi_ac97_set_command_data_register(ssi_mod module, unsigned int data); + +/*! + * This function sets the AC97 tag register. + * + * @param module the module number + * @param tag the tag information + */ +void ssi_ac97_set_tag_register(ssi_mod module, unsigned int tag); + +/*! + * This function controls the AC97 variable mode. + * + * @param module the module number + * @param state the AC97 variable mode state (enabled or disabled) + */ +void ssi_ac97_variable_mode(ssi_mod module, bool state); + +/*! + * This function controls the AC97 write command. + * + * @param module the module number + * @param state the next AC97 command is a write command or not + */ +void ssi_ac97_write_command(ssi_mod module, bool state); + +/*! + * This function controls the idle state of the transmit clock port during SSI internal gated mode. + * + * @param module the module number + * @param state the clock idle state + */ +void ssi_clock_idle_state(ssi_mod module, idle_state state); + +/*! + * This function turns off/on the ccm_ssi_clk to reduce power consumption. + * + * @param module the module number + * @param state the state for ccm_ssi_clk (true: turn off, else:turn on) + */ +void ssi_clock_off(ssi_mod module, bool state); + +/*! + * This function enables/disables the SSI module. + * + * @param module the module number + * @param state the state for SSI module + */ +void ssi_enable(ssi_mod module, bool state); + +/*! + * This function gets the data word in the Receive FIFO of the SSI module. + * + * @param module the module number + * @param fifo the Receive FIFO to read + * @return This function returns the read data. + */ +unsigned int ssi_get_data(ssi_mod module, fifo_nb fifo); + +/*! + * This function returns the status of the SSI module (SISR register) as a combination of status. + * + * @param module the module number + * @return This function returns the status of the SSI module. + */ +ssi_status_enable_mask ssi_get_status(ssi_mod module); + +/*! + * This function selects the I2S mode of the SSI module. + * + * @param module the module number + * @param mode the I2S mode + */ +void ssi_i2s_mode(ssi_mod module, mode_i2s mode); + +/*! + * This function disables the interrupts of the SSI module. + * + * @param module the module number + * @param mask the mask of the interrupts to disable + */ +void ssi_interrupt_disable(ssi_mod module, ssi_status_enable_mask mask); + +/*! + * This function enables the interrupts of the SSI module. + * + * @param module the module number + * @param mask the mask of the interrupts to enable + */ +void ssi_interrupt_enable(ssi_mod module, ssi_status_enable_mask mask); + +/*! + * This function enables/disables the network mode of the SSI module. + * + * @param module the module number + * @param state the network mode state + */ +void ssi_network_mode(ssi_mod module, bool state); + +/*! + * This function enables/disables the receive section of the SSI module. + * + * @param module the module number + * @param state the receive section state + */ +void ssi_receive_enable(ssi_mod module, bool state); + +/*! + * This function configures the SSI module to receive data word at bit position 0 or 23 in the Receive shift register. + * + * @param module the module number + * @param state the state to receive at bit 0 + */ +void ssi_rx_bit0(ssi_mod module, bool state); + +/*! + * This function controls the source of the clock signal used to clock the Receive shift register. + * + * @param module the module number + * @param direction the clock signal direction + */ +void ssi_rx_clock_direction(ssi_mod module, ssi_tx_rx_direction direction); + +/*! + * This function configures the divide-by-two divider of the SSI module for the receive section. + * + * @param module the module number + * @param state the divider state + */ +void ssi_rx_clock_divide_by_two(ssi_mod module, bool state); + +/*! + * This function controls which bit clock edge is used to clock in data. + * + * @param module the module number + * @param polarity the clock polarity + */ +void ssi_rx_clock_polarity(ssi_mod module, ssi_tx_rx_clock_polarity polarity); + +/*! + * This function configures a fixed divide-by-eight clock prescaler divider of the SSI module in series with the variable prescaler for the receive section. + * + * @param module the module number + * @param state the prescaler state + */ +void ssi_rx_clock_prescaler(ssi_mod module, bool state); + +/*! + * This function controls the early frame sync configuration. + * + * @param module the module number + * @param early the early frame sync configuration + */ +void ssi_rx_early_frame_sync(ssi_mod module, ssi_tx_rx_early_frame_sync early); + +/*! + * This function gets the number of data words in the Receive FIFO. + * + * @param module the module number + * @param fifo the fifo + * @return This function returns the number of words in the Rx FIFO. + */ +unsigned char ssi_rx_fifo_counter(ssi_mod module, fifo_nb fifo); + +/*! + * This function enables the Receive FIFO. + * + * @param module the module number + * @param fifo the fifo to enable + * @param enabled the state of the fifo, enabled or disabled + */ +void ssi_rx_fifo_enable(ssi_mod module, fifo_nb fifo, bool enabled); + +/*! + * This function controls the threshold at which the RFFx flag will be set. + * + * @param module the module number + * @param fifo the fifo to enable + * @param watermark the watermark + * @return This function returns the result of the operation (0 if successful, -1 otherwise). + */ +int ssi_rx_fifo_full_watermark(ssi_mod module, + fifo_nb fifo, unsigned char watermark); + +/*! + * This function flushes the Receive FIFOs. + * + * @param module the module number + */ +void ssi_rx_flush_fifo(ssi_mod module); + +/*! + * This function controls the direction of the Frame Sync signal for the receive section. + * + * @param module the module number + * @param direction the Frame Sync signal direction + */ +void ssi_rx_frame_direction(ssi_mod module, ssi_tx_rx_direction direction); + +/*! + * This function configures the Receive frame rate divider for the receive section. + * + * @param module the module number + * @param ratio the divide ratio from 1 to 32 + * @return This function returns the result of the operation (0 if successful, -1 otherwise). + */ +int ssi_rx_frame_rate(ssi_mod module, unsigned char ratio); + +/*! + * This function controls the Frame Sync active polarity for the receive section. + * + * @param module the module number + * @param active the Frame Sync active polarity + */ +void ssi_rx_frame_sync_active(ssi_mod module, + ssi_tx_rx_frame_sync_active active); + +/*! + * This function controls the Frame Sync length (one word or one bit long) for the receive section. + * + * @param module the module number + * @param length the Frame Sync length + */ +void ssi_rx_frame_sync_length(ssi_mod module, + ssi_tx_rx_frame_sync_length length); + +/*! + * This function configures the time slot(s) to mask for the receive section. + * + * @param module the module number + * @param mask the mask to indicate the time slot(s) masked + */ +void ssi_rx_mask_time_slot(ssi_mod module, unsigned int mask); + +/*! + * This function configures the Prescale divider for the receive section. + * + * @param module the module number + * @param divider the divide ratio from 1 to 256 + * @return This function returns the result of the operation (0 if successful, -1 otherwise). + */ +int ssi_rx_prescaler_modulus(ssi_mod module, unsigned int divider); + +/*! + * This function controls whether the MSB or LSB will be received first in a sample. + * + * @param module the module number + * @param direction the shift direction + */ +void ssi_rx_shift_direction(ssi_mod module, + ssi_tx_rx_shift_direction direction); + +/*! + * This function configures the Receive word length. + * + * @param module the module number + * @param length the word length + */ +void ssi_rx_word_length(ssi_mod module, ssi_word_length length); + +/*! + * This function sets the data word in the Transmit FIFO of the SSI module. + * + * @param module the module number + * @param fifo the FIFO number + * @param data the data to load in the FIFO + */ +void ssi_set_data(ssi_mod module, fifo_nb fifo, unsigned int data); + +/*! + * This function controls the number of wait states between the core and SSI. + * + * @param module the module number + * @param wait the number of wait state(s) + */ +void ssi_set_wait_states(ssi_mod module, ssi_wait_states wait); + +/*! + * This function enables/disables the synchronous mode of the SSI module. + * + * @param module the module number + * @param state the synchronous mode state + */ +void ssi_synchronous_mode(ssi_mod module, bool state); + +/*! + * This function allows the SSI module to output the SYS_CLK at the SRCK port. + * + * @param module the module number + * @param state the system clock state + */ +void ssi_system_clock(ssi_mod module, bool state); + +/*! + * This function enables/disables the transmit section of the SSI module. + * + * @param module the module number + * @param state the transmit section state + */ +void ssi_transmit_enable(ssi_mod module, bool state); + +/*! + * This function allows the SSI module to operate in the two channel mode. + * + * @param module the module number + * @param state the two channel mode state + */ +void ssi_two_channel_mode(ssi_mod module, bool state); + +/*! + * This function configures the SSI module to transmit data word from bit position 0 or 23 in the Transmit shift register. + * + * @param module the module number + * @param state the transmit from bit 0 state + */ +void ssi_tx_bit0(ssi_mod module, bool state); + +/*! + * This function controls the direction of the clock signal used to clock the Transmit shift register. + * + * @param module the module number + * @param direction the clock signal direction + */ +void ssi_tx_clock_direction(ssi_mod module, ssi_tx_rx_direction direction); + +/*! + * This function configures the divide-by-two divider of the SSI module for the transmit section. + * + * @param module the module number + * @param state the divider state + */ +void ssi_tx_clock_divide_by_two(ssi_mod module, bool state); + +/*! + * This function controls which bit clock edge is used to clock out data. + * + * @param module the module number + * @param polarity the clock polarity + */ +void ssi_tx_clock_polarity(ssi_mod module, ssi_tx_rx_clock_polarity polarity); + +/*! + * This function configures a fixed divide-by-eight clock prescaler divider of the SSI module in series with the variable prescaler for the transmit section. + * + * @param module the module number + * @param state the prescaler state + */ +void ssi_tx_clock_prescaler(ssi_mod module, bool state); + +/*! + * This function controls the early frame sync configuration for the transmit section. + * + * @param module the module number + * @param early the early frame sync configuration + */ +void ssi_tx_early_frame_sync(ssi_mod module, ssi_tx_rx_early_frame_sync early); + +/*! + * This function gets the number of data words in the Transmit FIFO. + * + * @param module the module number + * @param fifo the fifo + * @return This function returns the number of words in the Tx FIFO. + */ +unsigned char ssi_tx_fifo_counter(ssi_mod module, fifo_nb fifo); + +/*! + * This function controls the threshold at which the TFEx flag will be set. + * + * @param module the module number + * @param fifo the fifo to enable + * @param watermark the watermark + * @return This function returns the result of the operation (0 if successful, -1 otherwise). + */ +int ssi_tx_fifo_empty_watermark(ssi_mod module, fifo_nb fifo, + unsigned char watermark); + +/*! + * This function enables the Transmit FIFO. + * + * @param module the module number + * @param fifo the fifo to enable + * @param enable the state of the FIFO, enabled or disabled + */ +void ssi_tx_fifo_enable(ssi_mod module, fifo_nb fifo, bool enable); + +/*! + * This function flushes the Transmit FIFOs. + * + * @param module the module number + */ +void ssi_tx_flush_fifo(ssi_mod module); + +/*! + * This function controls the direction of the Frame Sync signal for the transmit section. + * + * @param module the module number + * @param direction the Frame Sync signal direction + */ +void ssi_tx_frame_direction(ssi_mod module, ssi_tx_rx_direction direction); + +/*! + * This function configures the Transmit frame rate divider. + * + * @param module the module number + * @param ratio the divide ratio from 1 to 32 + * @return This function returns the result of the operation (0 if successful, -1 otherwise). + */ +int ssi_tx_frame_rate(ssi_mod module, unsigned char ratio); + +/*! + * This function controls the Frame Sync active polarity for the transmit section. + * + * @param module the module number + * @param active the Frame Sync active polarity + */ +void ssi_tx_frame_sync_active(ssi_mod module, + ssi_tx_rx_frame_sync_active active); + +/*! + * This function controls the Frame Sync length (one word or one bit long) for the transmit section. + * + * @param module the module number + * @param length the Frame Sync length + */ +void ssi_tx_frame_sync_length(ssi_mod module, + ssi_tx_rx_frame_sync_length length); + +/*! + * This function configures the time slot(s) to mask for the transmit section. + * + * @param module the module number + * @param mask the mask to indicate the time slot(s) masked + */ +void ssi_tx_mask_time_slot(ssi_mod module, unsigned int mask); + +/*! + * This function configures the Prescale divider for the transmit section. + * + * @param module the module number + * @param divider the divide ratio from 1 to 256 + * @return This function returns the result of the operation (0 if successful, -1 otherwise). + */ +int ssi_tx_prescaler_modulus(ssi_mod module, unsigned int divider); + +/*! + * This function controls whether the MSB or LSB will be transmited first in a sample. + * + * @param module the module number + * @param direction the shift direction + */ +void ssi_tx_shift_direction(ssi_mod module, + ssi_tx_rx_shift_direction direction); + +/*! + * This function configures the Transmit word length. + * + * @param module the module number + * @param length the word length + */ +void ssi_tx_word_length(ssi_mod module, ssi_word_length length); + +#endif /* __MXC_SSI_H__ */ diff --git a/drivers/mxc/ssi/ssi_types.h b/drivers/mxc/ssi/ssi_types.h new file mode 100644 index 000000000000..5d8a6b845b6f --- /dev/null +++ b/drivers/mxc/ssi/ssi_types.h @@ -0,0 +1,367 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + + /*! + * @file ssi_types.h + * @brief This header file contains SSI types. + * + * @ingroup SSI + */ + +#ifndef __MXC_SSI_TYPES_H__ +#define __MXC_SSI_TYPES_H__ + +/*! + * This enumeration describes the FIFO number. + */ +typedef enum { + /*! + * FIFO 0 + */ + ssi_fifo_0 = 0, + /*! + * FIFO 1 + */ + ssi_fifo_1 = 1 +} fifo_nb; + +/*! + * This enumeration describes the clock idle state. + */ +typedef enum { + /*! + * Clock idle state is 1 + */ + clock_idle_state_1 = 0, + /*! + * Clock idle state is 0 + */ + clock_idle_state_0 = 1 +} idle_state; + +/*! + * This enumeration describes I2S mode. + */ +typedef enum { + /*! + * Normal mode + */ + i2s_normal = 0, + /*! + * Master mode + */ + i2s_master = 1, + /*! + * Slave mode + */ + i2s_slave = 2 +} mode_i2s; + +/*! + * This enumeration describes index for both SSI1 and SSI2 modules. + */ +typedef enum { + /*! + * SSI1 index + */ + SSI1 = 0, + /*! + * SSI2 index not present on MXC 91221 and MXC91311 + */ + SSI2 = 1 +} ssi_mod; + +/*! + * This enumeration describes the status/enable bits for interrupt source of the SSI module. + */ +typedef enum { + /*! + * SSI Transmit FIFO 0 empty bit + */ + ssi_tx_fifo_0_empty = 0x00000001, + /*! + * SSI Transmit FIFO 1 empty bit + */ + ssi_tx_fifo_1_empty = 0x00000002, + /*! + * SSI Receive FIFO 0 full bit + */ + ssi_rx_fifo_0_full = 0x00000004, + /*! + * SSI Receive FIFO 1 full bit + */ + ssi_rx_fifo_1_full = 0x00000008, + /*! + * SSI Receive Last Time Slot bit + */ + ssi_rls = 0x00000010, + /*! + * SSI Transmit Last Time Slot bit + */ + ssi_tls = 0x00000020, + /*! + * SSI Receive Frame Sync bit + */ + ssi_rfs = 0x00000040, + /*! + * SSI Transmit Frame Sync bit + */ + ssi_tfs = 0x00000080, + /*! + * SSI Transmitter underrun 0 bit + */ + ssi_transmitter_underrun_0 = 0x00000100, + /*! + * SSI Transmitter underrun 1 bit + */ + ssi_transmitter_underrun_1 = 0x00000200, + /*! + * SSI Receiver overrun 0 bit + */ + ssi_receiver_overrun_0 = 0x00000400, + /*! + * SSI Receiver overrun 1 bit + */ + ssi_receiver_overrun_1 = 0x00000800, + /*! + * SSI Transmit Data register empty 0 bit + */ + ssi_tx_data_reg_empty_0 = 0x00001000, + /*! + * SSI Transmit Data register empty 1 bit + */ + ssi_tx_data_reg_empty_1 = 0x00002000, + + /*! + * SSI Receive Data Ready 0 bit + */ + ssi_rx_data_ready_0 = 0x00004000, + /*! + * SSI Receive Data Ready 1 bit + */ + ssi_rx_data_ready_1 = 0x00008000, + /*! + * SSI Receive tag updated bit + */ + ssi_rx_tag_updated = 0x00010000, + /*! + * SSI Command data register updated bit + */ + ssi_cmd_data_reg_updated = 0x00020000, + /*! + * SSI Command address register updated bit + */ + ssi_cmd_address_reg_updated = 0x00040000, + /*! + * SSI Transmit interrupt enable bit + */ + ssi_tx_interrupt_enable = 0x00080000, + /*! + * SSI Transmit DMA enable bit + */ + ssi_tx_dma_interrupt_enable = 0x00100000, + /*! + * SSI Receive interrupt enable bit + */ + ssi_rx_interrupt_enable = 0x00200000, + /*! + * SSI Receive DMA enable bit + */ + ssi_rx_dma_interrupt_enable = 0x00400000, + /*! + * SSI Tx frame complete enable bit on MXC91221 & MXC91311 only + */ + ssi_tx_frame_complete = 0x00800000, + /*! + * SSI Rx frame complete on MXC91221 & MXC91311 only + */ + ssi_rx_frame_complete = 0x001000000 +} ssi_status_enable_mask; + +/*! + * This enumeration describes the clock edge to clock in or clock out data. + */ +typedef enum { + /*! + * Clock on rising edge + */ + ssi_clock_on_rising_edge = 0, + /*! + * Clock on falling edge + */ + ssi_clock_on_falling_edge = 1 +} ssi_tx_rx_clock_polarity; + +/*! + * This enumeration describes the clock direction. + */ +typedef enum { + /*! + * Clock is external + */ + ssi_tx_rx_externally = 0, + /*! + * Clock is generated internally + */ + ssi_tx_rx_internally = 1 +} ssi_tx_rx_direction; + +/*! + * This enumeration describes the early frame sync behavior. + */ +typedef enum { + /*! + * Frame Sync starts on the first data bit + */ + ssi_frame_sync_first_bit = 0, + /*! + * Frame Sync starts one bit before the first data bit + */ + ssi_frame_sync_one_bit_before = 1 +} ssi_tx_rx_early_frame_sync; + +/*! + * This enumeration describes the Frame Sync active value. + */ +typedef enum { + /*! + * Frame Sync is active when high + */ + ssi_frame_sync_active_high = 0, + /*! + * Frame Sync is active when low + */ + ssi_frame_sync_active_low = 1 +} ssi_tx_rx_frame_sync_active; + +/*! + * This enumeration describes the Frame Sync active length. + */ +typedef enum { + /*! + * Frame Sync is active when high + */ + ssi_frame_sync_one_word = 0, + /*! + * Frame Sync is active when low + */ + ssi_frame_sync_one_bit = 1 +} ssi_tx_rx_frame_sync_length; + +/*! + * This enumeration describes the Tx/Rx frame shift direction. + */ +typedef enum { + /*! + * MSB first + */ + ssi_msb_first = 0, + /*! + * LSB first + */ + ssi_lsb_first = 1 +} ssi_tx_rx_shift_direction; + +/*! + * This enumeration describes the wait state number. + */ +typedef enum { + /*! + * 0 wait state + */ + ssi_waitstates0 = 0x0, + /*! + * 1 wait state + */ + ssi_waitstates1 = 0x1, + /*! + * 2 wait states + */ + ssi_waitstates2 = 0x2, + /*! + * 3 wait states + */ + ssi_waitstates3 = 0x3 +} ssi_wait_states; + +/*! + * This enumeration describes the word length. + */ +typedef enum { + /*! + * 2 bits long + */ + ssi_2_bits = 0x0, + /*! + * 4 bits long + */ + ssi_4_bits = 0x1, + /*! + * 6 bits long + */ + ssi_6_bits = 0x2, + /*! + * 8 bits long + */ + ssi_8_bits = 0x3, + /*! + * 10 bits long + */ + ssi_10_bits = 0x4, + /*! + * 12 bits long + */ + ssi_12_bits = 0x5, + /*! + * 14 bits long + */ + ssi_14_bits = 0x6, + /*! + * 16 bits long + */ + ssi_16_bits = 0x7, + /*! + * 18 bits long + */ + ssi_18_bits = 0x8, + /*! + * 20 bits long + */ + ssi_20_bits = 0x9, + /*! + * 22 bits long + */ + ssi_22_bits = 0xA, + /*! + * 24 bits long + */ + ssi_24_bits = 0xB, + /*! + * 26 bits long + */ + ssi_26_bits = 0xC, + /*! + * 28 bits long + */ + ssi_28_bits = 0xD, + /*! + * 30 bits long + */ + ssi_30_bits = 0xE, + /*! + * 32 bits long + */ + ssi_32_bits = 0xF +} ssi_word_length; + +#endif /* __MXC_SSI_TYPES_H__ */ diff --git a/drivers/mxc/vpu/Kconfig b/drivers/mxc/vpu/Kconfig new file mode 100644 index 000000000000..37e55e03d2f2 --- /dev/null +++ b/drivers/mxc/vpu/Kconfig @@ -0,0 +1,30 @@ +# +# Codec configuration +# + +menu "MXC VPU(Video Processing Unit) support" + +config MXC_VPU + tristate "Support for MXC VPU(Video Processing Unit)" + depends on (ARCH_MX3 || ARCH_MX27 || ARCH_MX37 || ARCH_MX5) + default y + ---help--- + The VPU codec device provides codec function for H.264/MPEG4/H.263, + as well as MPEG2/VC-1/DivX on some platforms. + +config MXC_VPU_IRAM + tristate "Use IRAM as temporary buffer for VPU to enhance performace" + depends on (ARCH_MX37 || ARCH_MX5) + default y + ---help--- + The VPU can use internal RAM as temporary buffer to save external + memroy bandwith, thus to enhance video performance. + +config MXC_VPU_DEBUG + bool "MXC VPU debugging" + depends on MXC_VPU != n + help + This is an option for the developers; most people should + say N here. This enables MXC VPU driver debugging. + +endmenu diff --git a/drivers/mxc/vpu/Makefile b/drivers/mxc/vpu/Makefile new file mode 100644 index 000000000000..88e8f2c084a0 --- /dev/null +++ b/drivers/mxc/vpu/Makefile @@ -0,0 +1,10 @@ +# +# Makefile for the VPU drivers. +# + +obj-$(CONFIG_MXC_VPU) += vpu.o +vpu-objs := mxc_vpu.o mxc_vl2cc.o + +ifeq ($(CONFIG_MXC_VPU_DEBUG),y) +EXTRA_CFLAGS += -DDEBUG +endif diff --git a/drivers/mxc/vpu/mxc_vl2cc.c b/drivers/mxc/vpu/mxc_vl2cc.c new file mode 100644 index 000000000000..c077ac1c2639 --- /dev/null +++ b/drivers/mxc/vpu/mxc_vl2cc.c @@ -0,0 +1,124 @@ +/* + * Copyright 2007-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mxc_vl2cc.c + * + * @brief VL2CC initialization and flush operation implementation + * + * @ingroup VL2CC + */ + +#include +#include +#include +#include +#include +#include + +#define VL2CC_CTRL_OFFSET (0x100) +#define VL2CC_AUXCTRL_OFFSET (0x104) +#define VL2CC_INVWAY_OFFSET (0x77C) +#define VL2CC_CLEANWAY_OFFSET (0x7BC) + +/*! VL2CC clock handle. */ +static struct clk *vl2cc_clk; +static u32 *vl2cc_base; + +/*! + * Initialization function of VL2CC. Remap the VL2CC base address. + * + * @return status 0 success. + */ +int vl2cc_init(u32 vl2cc_hw_base) +{ + vl2cc_base = ioremap(vl2cc_hw_base, SZ_8K - 1); + if (vl2cc_base == NULL) { + printk(KERN_INFO "vl2cc: Unable to ioremap\n"); + return -ENOMEM; + } + + vl2cc_clk = clk_get(NULL, "vl2cc_clk"); + if (IS_ERR(vl2cc_clk)) { + printk(KERN_INFO "vl2cc: Unable to get clock\n"); + iounmap(vl2cc_base); + return -EIO; + } + + printk(KERN_INFO "VL2CC initialized\n"); + return 0; +} + +/*! + * Enable VL2CC hardware + */ +void vl2cc_enable(void) +{ + volatile u32 reg; + + clk_enable(vl2cc_clk); + + /* Disable VL2CC */ + reg = __raw_readl(vl2cc_base + VL2CC_CTRL_OFFSET); + reg &= 0xFFFFFFFE; + __raw_writel(reg, vl2cc_base + VL2CC_CTRL_OFFSET); + + /* Set the latency for data RAM reads, data RAM writes, tag RAM and + * dirty RAM to 1 cycle - write 0x0 to AUX CTRL [11:0] and also + * configure the number of ways to 8 - write 8 to AUX CTRL [16:13] + */ + reg = __raw_readl(vl2cc_base + VL2CC_AUXCTRL_OFFSET); + reg &= 0xFFFE1000; /* Clear [16:13] too */ + reg |= (0x8 << 13); /* [16:13] = 8; */ + __raw_writel(reg, vl2cc_base + VL2CC_AUXCTRL_OFFSET); + + /* Invalidate the VL2CC ways - write 0xff to INV BY WAY and poll the + * register until its value is 0x0 + */ + __raw_writel(0xff, vl2cc_base + VL2CC_INVWAY_OFFSET); + while (__raw_readl(vl2cc_base + VL2CC_INVWAY_OFFSET) != 0x0) + ; + + /* Enable VL2CC */ + reg = __raw_readl(vl2cc_base + VL2CC_CTRL_OFFSET); + reg |= 0x1; + __raw_writel(reg, vl2cc_base + VL2CC_CTRL_OFFSET); +} + +/*! + * Flush VL2CC + */ +void vl2cc_flush(void) +{ + __raw_writel(0xff, vl2cc_base + VL2CC_CLEANWAY_OFFSET); + while (__raw_readl(vl2cc_base + VL2CC_CLEANWAY_OFFSET) != 0x0) + ; +} + +/*! + * Disable VL2CC + */ +void vl2cc_disable(void) +{ + __raw_writel(0, vl2cc_base + VL2CC_CTRL_OFFSET); + clk_disable(vl2cc_clk); +} + +/*! + * Cleanup VL2CC + */ +void vl2cc_cleanup(void) +{ + clk_put(vl2cc_clk); + iounmap(vl2cc_base); +} diff --git a/drivers/mxc/vpu/mxc_vpu.c b/drivers/mxc/vpu/mxc_vpu.c new file mode 100644 index 000000000000..d51f3f09f1b9 --- /dev/null +++ b/drivers/mxc/vpu/mxc_vpu.c @@ -0,0 +1,862 @@ +/* + * Copyright 2006-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mxc_vpu.c + * + * @brief VPU system initialization and file operation implementation + * + * @ingroup VPU + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include + +struct vpu_priv { + struct fasync_struct *async_queue; +}; + +/* To track the allocated memory buffer */ +typedef struct memalloc_record { + struct list_head list; + struct vpu_mem_desc mem; +} memalloc_record; + +struct iram_setting { + u32 start; + u32 end; +}; + +static DEFINE_SPINLOCK(vpu_lock); +static LIST_HEAD(head); + +static int vpu_major; +static int vpu_clk_usercount; +static struct class *vpu_class; +static struct vpu_priv vpu_data; +static u8 open_count; +static struct clk *vpu_clk; +static struct vpu_mem_desc bitwork_mem = { 0 }; +static struct vpu_mem_desc pic_para_mem = { 0 }; +static struct vpu_mem_desc user_data_mem = { 0 }; +static struct vpu_mem_desc share_mem = { 0 }; + +static void __iomem *vpu_base; +static int vpu_irq; +static u32 phy_vpu_base_addr; +static struct mxc_vpu_platform_data *vpu_plat; + +/* IRAM setting */ +static struct iram_setting iram; + +/* implement the blocking ioctl */ +static int codec_done; +static wait_queue_head_t vpu_queue; + +static u32 workctrl_regsave[6]; +static u32 rd_ptr_regsave[4]; +static u32 wr_ptr_regsave[4]; +static u32 dis_flag_regsave[4]; + +#define READ_REG(x) __raw_readl(vpu_base + x) +#define WRITE_REG(val, x) __raw_writel(val, vpu_base + x) +#define SAVE_WORK_REGS do { \ + int i; \ + for (i = 0; i < ARRAY_SIZE(workctrl_regsave)/2; i++) \ + workctrl_regsave[i] = READ_REG(BIT_WORK_CTRL_BUF_REG(i));\ +} while (0) +#define RESTORE_WORK_REGS do { \ + int i; \ + for (i = 0; i < ARRAY_SIZE(workctrl_regsave)/2; i++) \ + WRITE_REG(workctrl_regsave[i], BIT_WORK_CTRL_BUF_REG(i));\ +} while (0) +#define SAVE_CTRL_REGS do { \ + int i; \ + for (i = ARRAY_SIZE(workctrl_regsave)/2; \ + i < ARRAY_SIZE(workctrl_regsave); i++) \ + workctrl_regsave[i] = READ_REG(BIT_WORK_CTRL_BUF_REG(i));\ +} while (0) +#define RESTORE_CTRL_REGS do { \ + int i; \ + for (i = ARRAY_SIZE(workctrl_regsave)/2; \ + i < ARRAY_SIZE(workctrl_regsave); i++) \ + WRITE_REG(workctrl_regsave[i], BIT_WORK_CTRL_BUF_REG(i));\ +} while (0) +#define SAVE_RDWR_PTR_REGS do { \ + int i; \ + for (i = 0; i < ARRAY_SIZE(rd_ptr_regsave); i++) \ + rd_ptr_regsave[i] = READ_REG(BIT_RD_PTR_REG(i)); \ + for (i = 0; i < ARRAY_SIZE(wr_ptr_regsave); i++) \ + wr_ptr_regsave[i] = READ_REG(BIT_WR_PTR_REG(i)); \ +} while (0) +#define RESTORE_RDWR_PTR_REGS do { \ + int i; \ + for (i = 0; i < ARRAY_SIZE(rd_ptr_regsave); i++) \ + WRITE_REG(rd_ptr_regsave[i], BIT_RD_PTR_REG(i)); \ + for (i = 0; i < ARRAY_SIZE(wr_ptr_regsave); i++) \ + WRITE_REG(wr_ptr_regsave[i], BIT_WR_PTR_REG(i)); \ +} while (0) +#define SAVE_DIS_FLAG_REGS do { \ + int i; \ + for (i = 0; i < ARRAY_SIZE(dis_flag_regsave); i++) \ + dis_flag_regsave[i] = READ_REG(BIT_FRM_DIS_FLG_REG(i)); \ +} while (0) +#define RESTORE_DIS_FLAG_REGS do { \ + int i; \ + for (i = 0; i < ARRAY_SIZE(dis_flag_regsave); i++) \ + WRITE_REG(dis_flag_regsave[i], BIT_FRM_DIS_FLG_REG(i)); \ +} while (0) + +/*! + * Private function to alloc dma buffer + * @return status 0 success. + */ +static int vpu_alloc_dma_buffer(struct vpu_mem_desc *mem) +{ + mem->cpu_addr = (unsigned long) + dma_alloc_coherent(NULL, PAGE_ALIGN(mem->size), + (dma_addr_t *) (&mem->phy_addr), + GFP_DMA | GFP_KERNEL); + pr_debug("[ALLOC] mem alloc cpu_addr = 0x%x\n", mem->cpu_addr); + if ((void *)(mem->cpu_addr) == NULL) { + printk(KERN_ERR "Physical memory allocation error!\n"); + return -1; + } + return 0; +} + +/*! + * Private function to free dma buffer + */ +static void vpu_free_dma_buffer(struct vpu_mem_desc *mem) +{ + if (mem->cpu_addr != 0) { + dma_free_coherent(0, PAGE_ALIGN(mem->size), + (void *)mem->cpu_addr, mem->phy_addr); + } +} + +/*! + * Private function to free buffers + * @return status 0 success. + */ +static int vpu_free_buffers(void) +{ + struct memalloc_record *rec, *n; + struct vpu_mem_desc mem; + + list_for_each_entry_safe(rec, n, &head, list) { + mem = rec->mem; + if (mem.cpu_addr != 0) { + vpu_free_dma_buffer(&mem); + pr_debug("[FREE] freed paddr=0x%08X\n", mem.phy_addr); + /* delete from list */ + list_del(&rec->list); + kfree(rec); + } + } + + return 0; +} + +/*! + * @brief vpu interrupt handler + */ +static irqreturn_t vpu_irq_handler(int irq, void *dev_id) +{ + struct vpu_priv *dev = dev_id; + + READ_REG(BIT_INT_STATUS); + WRITE_REG(0x1, BIT_INT_CLEAR); + + if (dev->async_queue) + kill_fasync(&dev->async_queue, SIGIO, POLL_IN); + + /* + * Clock is gated on when dec/enc started, gate it off when + * interrupt is received. + */ + clk_disable(vpu_clk); + + codec_done = 1; + wake_up_interruptible(&vpu_queue); + + return IRQ_HANDLED; +} + +/*! + * @brief open function for vpu file operation + * + * @return 0 on success or negative error code on error + */ +static int vpu_open(struct inode *inode, struct file *filp) +{ + spin_lock(&vpu_lock); + if ((open_count++ == 0) && cpu_is_mx32()) + vl2cc_enable(); + filp->private_data = (void *)(&vpu_data); + spin_unlock(&vpu_lock); + return 0; +} + +/*! + * @brief IO ctrl function for vpu file operation + * @param cmd IO ctrl command + * @return 0 on success or negative error code on error + */ +static int vpu_ioctl(struct inode *inode, struct file *filp, u_int cmd, + u_long arg) +{ + int ret = 0; + + switch (cmd) { + case VPU_IOC_PHYMEM_ALLOC: + { + struct memalloc_record *rec; + + rec = kzalloc(sizeof(*rec), GFP_KERNEL); + if (!rec) + return -ENOMEM; + + ret = copy_from_user(&(rec->mem), + (struct vpu_mem_desc *)arg, + sizeof(struct vpu_mem_desc)); + if (ret) { + kfree(rec); + return -EFAULT; + } + + pr_debug("[ALLOC] mem alloc size = 0x%x\n", + rec->mem.size); + + ret = vpu_alloc_dma_buffer(&(rec->mem)); + if (ret == -1) { + kfree(rec); + printk(KERN_ERR + "Physical memory allocation error!\n"); + break; + } + ret = copy_to_user((void __user *)arg, &(rec->mem), + sizeof(struct vpu_mem_desc)); + if (ret) { + kfree(rec); + ret = -EFAULT; + break; + } + + spin_lock(&vpu_lock); + list_add(&rec->list, &head); + spin_unlock(&vpu_lock); + + break; + } + case VPU_IOC_PHYMEM_FREE: + { + struct memalloc_record *rec, *n; + struct vpu_mem_desc vpu_mem; + + ret = copy_from_user(&vpu_mem, + (struct vpu_mem_desc *)arg, + sizeof(struct vpu_mem_desc)); + if (ret) + return -EACCES; + + pr_debug("[FREE] mem freed cpu_addr = 0x%x\n", + vpu_mem.cpu_addr); + if ((void *)vpu_mem.cpu_addr != NULL) { + vpu_free_dma_buffer(&vpu_mem); + } + + spin_lock(&vpu_lock); + list_for_each_entry_safe(rec, n, &head, list) { + if (rec->mem.cpu_addr == vpu_mem.cpu_addr) { + /* delete from list */ + list_del(&rec->list); + kfree(rec); + break; + } + } + spin_unlock(&vpu_lock); + + break; + } + case VPU_IOC_WAIT4INT: + { + u_long timeout = (u_long) arg; + if (!wait_event_interruptible_timeout + (vpu_queue, codec_done != 0, + msecs_to_jiffies(timeout))) { + printk(KERN_WARNING "VPU blocking: timeout.\n"); + ret = -ETIME; + } else if (signal_pending(current)) { + printk(KERN_WARNING + "VPU interrupt received.\n"); + ret = -ERESTARTSYS; + } else + codec_done = 0; + break; + } + case VPU_IOC_VL2CC_FLUSH: + if (cpu_is_mx32()) { + vl2cc_flush(); + } + break; + case VPU_IOC_IRAM_SETTING: + { + ret = copy_to_user((void __user *)arg, &iram, + sizeof(struct iram_setting)); + if (ret) + ret = -EFAULT; + + break; + } + case VPU_IOC_CLKGATE_SETTING: + { + u32 clkgate_en; + + if (get_user(clkgate_en, (u32 __user *) arg)) + return -EFAULT; + + if (clkgate_en) { + clk_enable(vpu_clk); + } else { + clk_disable(vpu_clk); + } + + break; + } + case VPU_IOC_GET_SHARE_MEM: + { + spin_lock(&vpu_lock); + if (share_mem.cpu_addr != 0) { + ret = copy_to_user((void __user *)arg, + &share_mem, + sizeof(struct vpu_mem_desc)); + spin_unlock(&vpu_lock); + break; + } else { + if (copy_from_user(&share_mem, + (struct vpu_mem_desc *)arg, + sizeof(struct vpu_mem_desc))) { + spin_unlock(&vpu_lock); + return -EFAULT; + } + if (vpu_alloc_dma_buffer(&share_mem) == -1) + ret = -EFAULT; + else { + if (copy_to_user((void __user *)arg, + &share_mem, + sizeof(struct + vpu_mem_desc))) + ret = -EFAULT; + } + } + spin_unlock(&vpu_lock); + break; + } + case VPU_IOC_GET_WORK_ADDR: + { + if (bitwork_mem.cpu_addr != 0) { + ret = + copy_to_user((void __user *)arg, + &bitwork_mem, + sizeof(struct vpu_mem_desc)); + break; + } else { + if (copy_from_user(&bitwork_mem, + (struct vpu_mem_desc *)arg, + sizeof(struct vpu_mem_desc))) + return -EFAULT; + + if (vpu_alloc_dma_buffer(&bitwork_mem) == -1) + ret = -EFAULT; + else if (copy_to_user((void __user *)arg, + &bitwork_mem, + sizeof(struct + vpu_mem_desc))) + ret = -EFAULT; + } + break; + } + case VPU_IOC_GET_PIC_PARA_ADDR: + { + if (pic_para_mem.cpu_addr != 0) { + ret = + copy_to_user((void __user *)arg, + &pic_para_mem, + sizeof(struct vpu_mem_desc)); + break; + } else { + if (copy_from_user(&pic_para_mem, + (struct vpu_mem_desc *)arg, + sizeof(struct vpu_mem_desc))) + return -EFAULT; + + if (vpu_alloc_dma_buffer(&pic_para_mem) == -1) + ret = -EFAULT; + else if (copy_to_user((void __user *)arg, + &pic_para_mem, + sizeof(struct + vpu_mem_desc))) + ret = -EFAULT; + } + break; + } + case VPU_IOC_GET_USER_DATA_ADDR: + { + if (user_data_mem.cpu_addr != 0) { + ret = + copy_to_user((void __user *)arg, + &user_data_mem, + sizeof(struct vpu_mem_desc)); + break; + } else { + if (copy_from_user(&user_data_mem, + (struct vpu_mem_desc *)arg, + sizeof(struct vpu_mem_desc))) + return -EFAULT; + + if (vpu_alloc_dma_buffer(&user_data_mem) == -1) + ret = -EFAULT; + else if (copy_to_user((void __user *)arg, + &user_data_mem, + sizeof(struct + vpu_mem_desc))) + ret = -EFAULT; + } + break; + } + case VPU_IOC_SYS_SW_RESET: + { + if (vpu_plat->reset) + vpu_plat->reset(); + + break; + } + case VPU_IOC_REG_DUMP: + break; + case VPU_IOC_PHYMEM_DUMP: + break; + default: + { + printk(KERN_ERR "No such IOCTL, cmd is %d\n", cmd); + break; + } + } + return ret; +} + +/*! + * @brief Release function for vpu file operation + * @return 0 on success or negative error code on error + */ +static int vpu_release(struct inode *inode, struct file *filp) +{ + spin_lock(&vpu_lock); + if (open_count > 0 && !(--open_count)) { + vpu_free_buffers(); + + if (cpu_is_mx32()) + vl2cc_disable(); + + /* Free shared memory when vpu device is idle */ + vpu_free_dma_buffer(&share_mem); + share_mem.cpu_addr = 0; + } + spin_unlock(&vpu_lock); + + return 0; +} + +/*! + * @brief fasync function for vpu file operation + * @return 0 on success or negative error code on error + */ +static int vpu_fasync(int fd, struct file *filp, int mode) +{ + struct vpu_priv *dev = (struct vpu_priv *)filp->private_data; + return fasync_helper(fd, filp, mode, &dev->async_queue); +} + +/*! + * @brief memory map function of harware registers for vpu file operation + * @return 0 on success or negative error code on error + */ +static int vpu_map_hwregs(struct file *fp, struct vm_area_struct *vm) +{ + unsigned long pfn; + + vm->vm_flags |= VM_IO | VM_RESERVED; + vm->vm_page_prot = pgprot_noncached(vm->vm_page_prot); + pfn = phy_vpu_base_addr >> PAGE_SHIFT; + pr_debug("size=0x%x, page no.=0x%x\n", + (int)(vm->vm_end - vm->vm_start), (int)pfn); + return remap_pfn_range(vm, vm->vm_start, pfn, vm->vm_end - vm->vm_start, + vm->vm_page_prot) ? -EAGAIN : 0; +} + +/*! + * @brief memory map function of memory for vpu file operation + * @return 0 on success or negative error code on error + */ +static int vpu_map_mem(struct file *fp, struct vm_area_struct *vm) +{ + int request_size; + request_size = vm->vm_end - vm->vm_start; + + pr_debug(" start=0x%x, pgoff=0x%x, size=0x%x\n", + (unsigned int)(vm->vm_start), (unsigned int)(vm->vm_pgoff), + request_size); + + vm->vm_flags |= VM_IO | VM_RESERVED; + vm->vm_page_prot = pgprot_noncached(vm->vm_page_prot); + + return remap_pfn_range(vm, vm->vm_start, vm->vm_pgoff, + request_size, vm->vm_page_prot) ? -EAGAIN : 0; + +} + +/*! + * @brief memory map interface for vpu file operation + * @return 0 on success or negative error code on error + */ +static int vpu_mmap(struct file *fp, struct vm_area_struct *vm) +{ + if (vm->vm_pgoff) + return vpu_map_mem(fp, vm); + else + return vpu_map_hwregs(fp, vm); +} + +struct file_operations vpu_fops = { + .owner = THIS_MODULE, + .open = vpu_open, + .ioctl = vpu_ioctl, + .release = vpu_release, + .fasync = vpu_fasync, + .mmap = vpu_mmap, +}; + +/*! + * This function is called by the driver framework to initialize the vpu device. + * @param dev The device structure for the vpu passed in by the framework. + * @return 0 on success or negative error code on error + */ +static int vpu_dev_probe(struct platform_device *pdev) +{ + int err = 0; + struct device *temp_class; + struct resource *res; + unsigned long addr = 0; + + vpu_plat = pdev->dev.platform_data; + + iram_alloc(VPU_IRAM_SIZE, &addr); + if (addr == 0) + iram.start = iram.end = 0; + else { + iram.start = addr; + iram.end = addr + VPU_IRAM_SIZE - 1; + } + + if (cpu_is_mx32()) { + err = vl2cc_init(iram.start); + if (err != 0) + return err; + } + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!res) { + printk(KERN_ERR "vpu: unable to get vpu base addr\n"); + return -ENODEV; + } + phy_vpu_base_addr = res->start; + vpu_base = ioremap(res->start, res->end - res->start); + + vpu_major = register_chrdev(vpu_major, "mxc_vpu", &vpu_fops); + if (vpu_major < 0) { + printk(KERN_ERR "vpu: unable to get a major for VPU\n"); + err = -EBUSY; + goto error; + } + + vpu_class = class_create(THIS_MODULE, "mxc_vpu"); + if (IS_ERR(vpu_class)) { + err = PTR_ERR(vpu_class); + goto err_out_chrdev; + } + + temp_class = device_create(vpu_class, NULL, MKDEV(vpu_major, 0), + NULL, "mxc_vpu"); + if (IS_ERR(temp_class)) { + err = PTR_ERR(temp_class); + goto err_out_class; + } + + vpu_clk = clk_get(&pdev->dev, "vpu_clk"); + if (IS_ERR(vpu_clk)) { + err = -ENOENT; + goto err_out_class; + } + + res = platform_get_resource(pdev, IORESOURCE_IRQ, 0); + if (!res) { + printk(KERN_ERR "vpu: unable to get vpu interrupt\n"); + err = -ENXIO; + goto err_out_class; + } + vpu_irq = res->start; + + err = request_irq(vpu_irq, vpu_irq_handler, 0, "VPU_CODEC_IRQ", + (void *)(&vpu_data)); + if (err) + goto err_out_class; + + printk(KERN_INFO "VPU initialized\n"); + goto out; + + err_out_class: + device_destroy(vpu_class, MKDEV(vpu_major, 0)); + class_destroy(vpu_class); + err_out_chrdev: + unregister_chrdev(vpu_major, "mxc_vpu"); + error: + iounmap(vpu_base); + if (cpu_is_mx32()) { + vl2cc_cleanup(); + } + out: + return err; +} + +static int vpu_dev_remove(struct platform_device *pdev) +{ + free_irq(vpu_irq, &vpu_data); + iounmap(vpu_base); + iram_free(iram.start, VPU_IRAM_SIZE); + + return 0; +} + +#ifdef CONFIG_PM +static int vpu_suspend(struct platform_device *pdev, pm_message_t state) +{ + int i; + unsigned long timeout; + + /* Wait for vpu go to idle state, suspect vpu cannot be changed + to idle state after about 1 sec */ + if (open_count > 0) { + timeout = jiffies + HZ; + clk_enable(vpu_clk); + while (READ_REG(BIT_BUSY_FLAG)) { + msleep(1); + if (time_after(jiffies, timeout)) + goto out; + } + clk_disable(vpu_clk); + } + + /* Make sure clock is disabled before suspend */ + vpu_clk_usercount = clk_get_usecount(vpu_clk); + for (i = 0; i < vpu_clk_usercount; i++) + clk_disable(vpu_clk); + + if (!cpu_is_mx53()) { + clk_enable(vpu_clk); + if (bitwork_mem.cpu_addr != 0) { + SAVE_WORK_REGS; + SAVE_CTRL_REGS; + SAVE_RDWR_PTR_REGS; + SAVE_DIS_FLAG_REGS; + + WRITE_REG(0x1, BIT_BUSY_FLAG); + WRITE_REG(VPU_SLEEP_REG_VALUE, BIT_RUN_COMMAND); + while (READ_REG(BIT_BUSY_FLAG)) + ; + } + clk_disable(vpu_clk); + } + + if (cpu_is_mx37() || cpu_is_mx51()) + mxc_pg_enable(pdev); + + return 0; + +out: + clk_disable(vpu_clk); + return -EAGAIN; + +} + +static int vpu_resume(struct platform_device *pdev) +{ + int i; + + if (cpu_is_mx37() || cpu_is_mx51()) + mxc_pg_disable(pdev); + + if (cpu_is_mx53()) + goto recover_clk; + + clk_enable(vpu_clk); + if (bitwork_mem.cpu_addr != 0) { + u32 *p = (u32 *) bitwork_mem.cpu_addr; + u32 data; + u16 data_hi; + u16 data_lo; + + RESTORE_WORK_REGS; + + WRITE_REG(0x0, BIT_RESET_CTRL); + WRITE_REG(0x0, BIT_CODE_RUN); + + /* + * Re-load boot code, from the codebuffer in external RAM. + * Thankfully, we only need 4096 bytes, same for all platforms. + */ + if (cpu_is_mx51()) { + for (i = 0; i < 2048; i += 4) { + data = p[(i / 2) + 1]; + data_hi = (data >> 16) & 0xFFFF; + data_lo = data & 0xFFFF; + WRITE_REG((i << 16) | data_hi, BIT_CODE_DOWN); + WRITE_REG(((i + 1) << 16) | data_lo, + BIT_CODE_DOWN); + + data = p[i / 2]; + data_hi = (data >> 16) & 0xFFFF; + data_lo = data & 0xFFFF; + WRITE_REG(((i + 2) << 16) | data_hi, + BIT_CODE_DOWN); + WRITE_REG(((i + 3) << 16) | data_lo, + BIT_CODE_DOWN); + } + } else { + for (i = 0; i < 2048; i += 2) { + if (cpu_is_mx37()) + data = swab32(p[i / 2]); + else + data = p[i / 2]; + data_hi = (data >> 16) & 0xFFFF; + data_lo = data & 0xFFFF; + + WRITE_REG((i << 16) | data_hi, BIT_CODE_DOWN); + WRITE_REG(((i + 1) << 16) | data_lo, + BIT_CODE_DOWN); + } + } + + RESTORE_CTRL_REGS; + + WRITE_REG(BITVAL_PIC_RUN, BIT_INT_ENABLE); + + WRITE_REG(0x1, BIT_BUSY_FLAG); + WRITE_REG(0x1, BIT_CODE_RUN); + while (READ_REG(BIT_BUSY_FLAG)) + ; + + RESTORE_RDWR_PTR_REGS; + RESTORE_DIS_FLAG_REGS; + + WRITE_REG(0x1, BIT_BUSY_FLAG); + WRITE_REG(VPU_WAKE_REG_VALUE, BIT_RUN_COMMAND); + while (READ_REG(BIT_BUSY_FLAG)) + ; + } + clk_disable(vpu_clk); + +recover_clk: + /* Recover vpu clock */ + for (i = 0; i < vpu_clk_usercount; i++) + clk_enable(vpu_clk); + + return 0; +} +#else +#define vpu_suspend NULL +#define vpu_resume NULL +#endif /* !CONFIG_PM */ + +/*! Driver definition + * + */ +static struct platform_driver mxcvpu_driver = { + .driver = { + .name = "mxc_vpu", + }, + .probe = vpu_dev_probe, + .remove = vpu_dev_remove, + .suspend = vpu_suspend, + .resume = vpu_resume, +}; + +static int __init vpu_init(void) +{ + int ret = platform_driver_register(&mxcvpu_driver); + + init_waitqueue_head(&vpu_queue); + + return ret; +} + +static void __exit vpu_exit(void) +{ + if (vpu_major > 0) { + device_destroy(vpu_class, MKDEV(vpu_major, 0)); + class_destroy(vpu_class); + unregister_chrdev(vpu_major, "mxc_vpu"); + vpu_major = 0; + } + + if (cpu_is_mx32()) { + vl2cc_cleanup(); + } + + vpu_free_dma_buffer(&bitwork_mem); + vpu_free_dma_buffer(&pic_para_mem); + vpu_free_dma_buffer(&user_data_mem); + + clk_put(vpu_clk); + + platform_driver_unregister(&mxcvpu_driver); + return; +} + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("Linux VPU driver for Freescale i.MX/MXC"); +MODULE_LICENSE("GPL"); + +module_init(vpu_init); +module_exit(vpu_exit); diff --git a/drivers/net/Kconfig b/drivers/net/Kconfig index ce2fcdd4ab90..1d1a0b156898 100644 --- a/drivers/net/Kconfig +++ b/drivers/net/Kconfig @@ -1908,7 +1908,7 @@ config 68360_ENET config FEC bool "FEC ethernet controller (of ColdFire and some i.MX CPUs)" depends on M523x || M527x || M5272 || M528x || M520x || M532x || \ - MACH_MX27 || ARCH_MX35 || ARCH_MX25 || ARCH_MX5 + MACH_MX27 || ARCH_MX35 || ARCH_MX25 || ARCH_MX5 || ARCH_MX28 select PHYLIB help Say Y here if you want to use the built-in 10/100 Fast ethernet diff --git a/drivers/net/can/Kconfig b/drivers/net/can/Kconfig index 2c5227c02fa0..75dba17f107d 100644 --- a/drivers/net/can/Kconfig +++ b/drivers/net/can/Kconfig @@ -89,4 +89,13 @@ config CAN_DEBUG_DEVICES a problem with CAN support and want to see more of what is going on. +config CAN_FLEXCAN + tristate "Freescale FlexCAN" + depends on CAN && (ARCH_MX25 || ARCH_MX35 || ARCH_MX28 || ARCH_MX53) + default y + ---help--- + This select the support of Freescale CAN(FlexCAN). + This driver can also be built as a module. + If unsure, say N. + endmenu diff --git a/drivers/net/can/Makefile b/drivers/net/can/Makefile index 9047cd066fea..3d7b76ab3147 100644 --- a/drivers/net/can/Makefile +++ b/drivers/net/can/Makefile @@ -3,6 +3,7 @@ # obj-$(CONFIG_CAN_VCAN) += vcan.o +obj-$(CONFIG_CAN_FLEXCAN) += flexcan/ obj-$(CONFIG_CAN_DEV) += can-dev.o can-dev-y := dev.o diff --git a/drivers/net/can/flexcan/Makefile b/drivers/net/can/flexcan/Makefile new file mode 100644 index 000000000000..b2dbb4fb2793 --- /dev/null +++ b/drivers/net/can/flexcan/Makefile @@ -0,0 +1,3 @@ +obj-$(CONFIG_CAN_FLEXCAN) += flexcan.o + +flexcan-y := dev.o drv.o mbm.o diff --git a/drivers/net/can/flexcan/dev.c b/drivers/net/can/flexcan/dev.c new file mode 100644 index 000000000000..27ab701ad6ba --- /dev/null +++ b/drivers/net/can/flexcan/dev.c @@ -0,0 +1,732 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file dev.c + * + * @brief Driver for Freescale CAN Controller FlexCAN. + * + * @ingroup can + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#ifdef CONFIG_ARCH_MXS +#include +#endif +#include "flexcan.h" + +#define DEFAULT_BITRATE 500000 +#define TIME_SEGMENT_MIN 8 +#define TIME_SEGMENT_MAX 25 +#define TIME_SEGMENT_MID ((TIME_SEGMENT_MIN + TIME_SEGMENT_MAX)/2) + +struct time_segment { + char propseg; + char pseg1; + char pseg2; +}; + +struct time_segment time_segments[] = { + { /* total 8 timequanta */ + 1, 2, 1 + }, + { /* total 9 timequanta */ + 1, 2, 2 + }, + { /* total 10 timequanta */ + 2, 2, 2 + }, + { /* total 11 timequanta */ + 2, 2, 3 + }, + { /* total 12 timequanta */ + 2, 3, 3 + }, + { /* total 13 timequanta */ + 3, 3, 3 + }, + { /* total 14 timequanta */ + 3, 3, 4 + }, + { /* total 15 timequanta */ + 3, 4, 4 + }, + { /* total 16 timequanta */ + 4, 4, 4 + }, + { /* total 17 timequanta */ + 4, 4, 5 + }, + { /* total 18 timequanta */ + 4, 5, 5 + }, + { /* total 19 timequanta */ + 5, 5, 5 + }, + { /* total 20 timequanta */ + 5, 5, 6 + }, + { /* total 21 timequanta */ + 5, 6, 6 + }, + { /* total 22 timequanta */ + 6, 6, 6 + }, + { /* total 23 timequanta */ + 6, 6, 7 + }, + { /* total 24 timequanta */ + 6, 7, 7 + }, + { /* total 25 timequanta */ + 7, 7, 7 + }, +}; + +enum { + FLEXCAN_ATTR_STATE = 0, + FLEXCAN_ATTR_BITRATE, + FLEXCAN_ATTR_BR_PRESDIV, + FLEXCAN_ATTR_BR_RJW, + FLEXCAN_ATTR_BR_PROPSEG, + FLEXCAN_ATTR_BR_PSEG1, + FLEXCAN_ATTR_BR_PSEG2, + FLEXCAN_ATTR_BR_CLKSRC, + FLEXCAN_ATTR_MAXMB, + FLEXCAN_ATTR_XMIT_MAXMB, + FLEXCAN_ATTR_FIFO, + FLEXCAN_ATTR_WAKEUP, + FLEXCAN_ATTR_SRX_DIS, + FLEXCAN_ATTR_WAK_SRC, + FLEXCAN_ATTR_BCC, + FLEXCAN_ATTR_LOCAL_PRIORITY, + FLEXCAN_ATTR_ABORT, + FLEXCAN_ATTR_LOOPBACK, + FLEXCAN_ATTR_SMP, + FLEXCAN_ATTR_BOFF_REC, + FLEXCAN_ATTR_TSYN, + FLEXCAN_ATTR_LISTEN, + FLEXCAN_ATTR_EXTEND_MSG, + FLEXCAN_ATTR_STANDARD_MSG, +#ifdef CONFIG_CAN_DEBUG_DEVICES + FLEXCAN_ATTR_DUMP_REG, + FLEXCAN_ATTR_DUMP_XMIT_MB, + FLEXCAN_ATTR_DUMP_RX_MB, +#endif + FLEXCAN_ATTR_MAX +}; + +static ssize_t flexcan_show_attr(struct device *dev, + struct device_attribute *attr, char *buf); +static ssize_t flexcan_set_attr(struct device *dev, + struct device_attribute *attr, const char *buf, + size_t count); + +static struct device_attribute flexcan_dev_attr[FLEXCAN_ATTR_MAX] = { + [FLEXCAN_ATTR_STATE] = __ATTR(state, 0444, flexcan_show_attr, NULL), + [FLEXCAN_ATTR_BITRATE] = + __ATTR(bitrate, 0644, flexcan_show_attr, flexcan_set_attr), + [FLEXCAN_ATTR_BR_PRESDIV] = + __ATTR(br_presdiv, 0644, flexcan_show_attr, flexcan_set_attr), + [FLEXCAN_ATTR_BR_RJW] = + __ATTR(br_rjw, 0644, flexcan_show_attr, flexcan_set_attr), + [FLEXCAN_ATTR_BR_PROPSEG] = + __ATTR(br_propseg, 0644, flexcan_show_attr, flexcan_set_attr), + [FLEXCAN_ATTR_BR_PSEG1] = + __ATTR(br_pseg1, 0644, flexcan_show_attr, flexcan_set_attr), + [FLEXCAN_ATTR_BR_PSEG2] = + __ATTR(br_pseg2, 0644, flexcan_show_attr, flexcan_set_attr), + [FLEXCAN_ATTR_BR_CLKSRC] = + __ATTR(br_clksrc, 0644, flexcan_show_attr, flexcan_set_attr), + [FLEXCAN_ATTR_MAXMB] = + __ATTR(maxmb, 0644, flexcan_show_attr, flexcan_set_attr), + [FLEXCAN_ATTR_XMIT_MAXMB] = + __ATTR(xmit_maxmb, 0644, flexcan_show_attr, flexcan_set_attr), + [FLEXCAN_ATTR_FIFO] = + __ATTR(fifo, 0644, flexcan_show_attr, flexcan_set_attr), + [FLEXCAN_ATTR_WAKEUP] = + __ATTR(wakeup, 0644, flexcan_show_attr, flexcan_set_attr), + [FLEXCAN_ATTR_SRX_DIS] = + __ATTR(srx_dis, 0644, flexcan_show_attr, flexcan_set_attr), + [FLEXCAN_ATTR_WAK_SRC] = + __ATTR(wak_src, 0644, flexcan_show_attr, flexcan_set_attr), + [FLEXCAN_ATTR_BCC] = + __ATTR(bcc, 0644, flexcan_show_attr, flexcan_set_attr), + [FLEXCAN_ATTR_LOCAL_PRIORITY] = + __ATTR(local_priority, 0644, flexcan_show_attr, flexcan_set_attr), + [FLEXCAN_ATTR_ABORT] = + __ATTR(abort, 0644, flexcan_show_attr, flexcan_set_attr), + [FLEXCAN_ATTR_LOOPBACK] = + __ATTR(loopback, 0644, flexcan_show_attr, flexcan_set_attr), + [FLEXCAN_ATTR_SMP] = + __ATTR(smp, 0644, flexcan_show_attr, flexcan_set_attr), + [FLEXCAN_ATTR_BOFF_REC] = + __ATTR(boff_rec, 0644, flexcan_show_attr, flexcan_set_attr), + [FLEXCAN_ATTR_TSYN] = + __ATTR(tsyn, 0644, flexcan_show_attr, flexcan_set_attr), + [FLEXCAN_ATTR_LISTEN] = + __ATTR(listen, 0644, flexcan_show_attr, flexcan_set_attr), + [FLEXCAN_ATTR_EXTEND_MSG] = + __ATTR(ext_msg, 0644, flexcan_show_attr, flexcan_set_attr), + [FLEXCAN_ATTR_STANDARD_MSG] = + __ATTR(std_msg, 0644, flexcan_show_attr, flexcan_set_attr), +#ifdef CONFIG_CAN_DEBUG_DEVICES + [FLEXCAN_ATTR_DUMP_REG] = + __ATTR(dump_reg, 0444, flexcan_show_attr, NULL), + [FLEXCAN_ATTR_DUMP_XMIT_MB] = + __ATTR(dump_xmit_mb, 0444, flexcan_show_attr, NULL), + [FLEXCAN_ATTR_DUMP_RX_MB] = + __ATTR(dump_rx_mb, 0444, flexcan_show_attr, NULL), +#endif +}; + +static void flexcan_set_bitrate(struct flexcan_device *flexcan, int bitrate) +{ + /* TODO:: implement in future + * based on the bitrate to get the timing of + * presdiv, pseg1, pseg2, propseg + */ + int i, rate, div; + bool found = false; + struct time_segment *segment; + rate = clk_get_rate(flexcan->clk); + + if (!bitrate) + bitrate = DEFAULT_BITRATE; + + if (rate % bitrate == 0) { + div = rate / bitrate; + for (i = TIME_SEGMENT_MID; i <= TIME_SEGMENT_MAX; i++) { + if (div % i == 0) { + found = true; + break; + } + } + if (!found) { + for (i = TIME_SEGMENT_MID - 1; + i >= TIME_SEGMENT_MIN; i--) { + if (div % i == 0) { + found = true; + break; + } + } + + } + } + + if (found) { + segment = &time_segments[i - TIME_SEGMENT_MIN]; + flexcan->br_presdiv = div/i - 1; + flexcan->br_propseg = segment->propseg; + flexcan->br_pseg1 = segment->pseg1; + flexcan->br_pseg2 = segment->pseg2; + flexcan->bitrate = bitrate; + } else { + pr_info("The bitrate %d can't supported with clock \ + rate of %d \n", bitrate, rate); + } +} + +static void flexcan_update_bitrate(struct flexcan_device *flexcan) +{ + int rate, div; + + if (flexcan->br_clksrc) + rate = clk_get_rate(flexcan->clk); + else { + struct clk *clk; + clk = clk_get(NULL, "ckih"); + if (!clk) + return; + rate = clk_get_rate(clk); + clk_put(clk); + } + if (!rate) + return; + + div = (flexcan->br_presdiv + 1); + div *= + (flexcan->br_propseg + flexcan->br_pseg1 + flexcan->br_pseg2 + 4); + flexcan->bitrate = (rate + div - 1) / div; +} + +#ifdef CONFIG_CAN_DEBUG_DEVICES +static int flexcan_dump_reg(struct flexcan_device *flexcan, char *buf) +{ + int ret = 0; + unsigned int reg; + reg = __raw_readl(flexcan->io_base + CAN_HW_REG_MCR); + ret += sprintf(buf + ret, "MCR::0x%x\n", reg); + reg = __raw_readl(flexcan->io_base + CAN_HW_REG_CTRL); + ret += sprintf(buf + ret, "CTRL::0x%x\n", reg); + reg = __raw_readl(flexcan->io_base + CAN_HW_REG_RXGMASK); + ret += sprintf(buf + ret, "RXGMASK::0x%x\n", reg); + reg = __raw_readl(flexcan->io_base + CAN_HW_REG_RX14MASK); + ret += sprintf(buf + ret, "RX14MASK::0x%x\n", reg); + reg = __raw_readl(flexcan->io_base + CAN_HW_REG_RX15MASK); + ret += sprintf(buf + ret, "RX15MASK::0x%x\n", reg); + reg = __raw_readl(flexcan->io_base + CAN_HW_REG_ECR); + ret += sprintf(buf + ret, "ECR::0x%x\n", reg); + reg = __raw_readl(flexcan->io_base + CAN_HW_REG_ESR); + ret += sprintf(buf + ret, "ESR::0x%x\n", reg); + reg = __raw_readl(flexcan->io_base + CAN_HW_REG_IMASK2); + ret += sprintf(buf + ret, "IMASK2::0x%x\n", reg); + reg = __raw_readl(flexcan->io_base + CAN_HW_REG_IMASK1); + ret += sprintf(buf + ret, "IMASK1::0x%x\n", reg); + reg = __raw_readl(flexcan->io_base + CAN_HW_REG_IFLAG2); + ret += sprintf(buf + ret, "IFLAG2::0x%x\n", reg); + reg = __raw_readl(flexcan->io_base + CAN_HW_REG_IFLAG1); + ret += sprintf(buf + ret, "IFLAG1::0x%x\n", reg); + return ret; +} + +static int flexcan_dump_xmit_mb(struct flexcan_device *flexcan, char *buf) +{ + int ret = 0, i; + i = flexcan->xmit_maxmb + 1; + for (; i <= flexcan->maxmb; i++) + ret += + sprintf(buf + ret, + "mb[%d]::CS:0x%x ID:0x%x DATA[1~2]:0x%02x,0x%02x\n", + i, flexcan->hwmb[i].mb_cs, + flexcan->hwmb[i].mb_id, flexcan->hwmb[i].mb_data[1], + flexcan->hwmb[i].mb_data[2]); + return ret; +} + +static int flexcan_dump_rx_mb(struct flexcan_device *flexcan, char *buf) +{ + int ret = 0, i; + for (i = 0; i <= flexcan->xmit_maxmb; i++) + ret += + sprintf(buf + ret, + "mb[%d]::CS:0x%x ID:0x%x DATA[1~2]:0x%02x,0x%02x\n", + i, flexcan->hwmb[i].mb_cs, + flexcan->hwmb[i].mb_id, flexcan->hwmb[i].mb_data[1], + flexcan->hwmb[i].mb_data[2]); + return ret; +} +#endif + +static ssize_t flexcan_show_state(struct net_device *net, char *buf) +{ + int ret, esr; + struct flexcan_device *flexcan = netdev_priv(net); + ret = sprintf(buf, "%s::", netif_running(net) ? "Start" : "Stop"); + if (netif_carrier_ok(net)) { + esr = __raw_readl(flexcan->io_base + CAN_HW_REG_ESR); + switch ((esr & __ESR_FLT_CONF_MASK) >> __ESR_FLT_CONF_OFF) { + case 0: + ret += sprintf(buf + ret, "normal\n"); + break; + case 1: + ret += sprintf(buf + ret, "error passive\n"); + break; + default: + ret += sprintf(buf + ret, "bus off\n"); + } + } else + ret += sprintf(buf + ret, "bus off\n"); + return ret; +} + +static ssize_t flexcan_show_attr(struct device *dev, + struct device_attribute *attr, char *buf) +{ + int attr_id; + struct net_device *net; + struct flexcan_device *flexcan; + + net = dev_get_drvdata(dev); + BUG_ON(!net); + flexcan = netdev_priv(net); + BUG_ON(!flexcan); + + attr_id = attr - flexcan_dev_attr; + switch (attr_id) { + case FLEXCAN_ATTR_STATE: + return flexcan_show_state(net, buf); + case FLEXCAN_ATTR_BITRATE: + return sprintf(buf, "%d\n", flexcan->bitrate); + case FLEXCAN_ATTR_BR_PRESDIV: + return sprintf(buf, "%d\n", flexcan->br_presdiv + 1); + case FLEXCAN_ATTR_BR_RJW: + return sprintf(buf, "%d\n", flexcan->br_rjw); + case FLEXCAN_ATTR_BR_PROPSEG: + return sprintf(buf, "%d\n", flexcan->br_propseg + 1); + case FLEXCAN_ATTR_BR_PSEG1: + return sprintf(buf, "%d\n", flexcan->br_pseg1 + 1); + case FLEXCAN_ATTR_BR_PSEG2: + return sprintf(buf, "%d\n", flexcan->br_pseg2 + 1); + case FLEXCAN_ATTR_BR_CLKSRC: + return sprintf(buf, "%s\n", flexcan->br_clksrc ? "bus" : "osc"); + case FLEXCAN_ATTR_MAXMB: + return sprintf(buf, "%d\n", flexcan->maxmb + 1); + case FLEXCAN_ATTR_XMIT_MAXMB: + return sprintf(buf, "%d\n", flexcan->xmit_maxmb + 1); + case FLEXCAN_ATTR_FIFO: + return sprintf(buf, "%d\n", flexcan->fifo); + case FLEXCAN_ATTR_WAKEUP: + return sprintf(buf, "%d\n", flexcan->wakeup); + case FLEXCAN_ATTR_SRX_DIS: + return sprintf(buf, "%d\n", flexcan->srx_dis); + case FLEXCAN_ATTR_WAK_SRC: + return sprintf(buf, "%d\n", flexcan->wak_src); + case FLEXCAN_ATTR_BCC: + return sprintf(buf, "%d\n", flexcan->bcc); + case FLEXCAN_ATTR_LOCAL_PRIORITY: + return sprintf(buf, "%d\n", flexcan->lprio); + case FLEXCAN_ATTR_ABORT: + return sprintf(buf, "%d\n", flexcan->abort); + case FLEXCAN_ATTR_LOOPBACK: + return sprintf(buf, "%d\n", flexcan->loopback); + case FLEXCAN_ATTR_SMP: + return sprintf(buf, "%d\n", flexcan->smp); + case FLEXCAN_ATTR_BOFF_REC: + return sprintf(buf, "%d\n", flexcan->boff_rec); + case FLEXCAN_ATTR_TSYN: + return sprintf(buf, "%d\n", flexcan->tsyn); + case FLEXCAN_ATTR_LISTEN: + return sprintf(buf, "%d\n", flexcan->listen); + case FLEXCAN_ATTR_EXTEND_MSG: + return sprintf(buf, "%d\n", flexcan->ext_msg); + case FLEXCAN_ATTR_STANDARD_MSG: + return sprintf(buf, "%d\n", flexcan->std_msg); +#ifdef CONFIG_CAN_DEBUG_DEVICES + case FLEXCAN_ATTR_DUMP_REG: + return flexcan_dump_reg(flexcan, buf); + case FLEXCAN_ATTR_DUMP_XMIT_MB: + return flexcan_dump_xmit_mb(flexcan, buf); + case FLEXCAN_ATTR_DUMP_RX_MB: + return flexcan_dump_rx_mb(flexcan, buf); +#endif + default: + return sprintf(buf, "%s:%p->%p\n", __func__, flexcan_dev_attr, + attr); + } +} + +static ssize_t flexcan_set_attr(struct device *dev, + struct device_attribute *attr, const char *buf, + size_t count) +{ + int attr_id, tmp; + struct net_device *net; + struct flexcan_device *flexcan; + + net = dev_get_drvdata(dev); + BUG_ON(!net); + flexcan = netdev_priv(net); + BUG_ON(!flexcan); + + attr_id = attr - flexcan_dev_attr; + + if (mutex_lock_interruptible(&flexcan->mutex)) + return count; + + if (netif_running(net)) + goto set_finish; + + if (attr_id == FLEXCAN_ATTR_BR_CLKSRC) { + if (!strncasecmp(buf, "bus", 3)) + flexcan->br_clksrc = 1; + else if (!strncasecmp(buf, "osc", 3)) + flexcan->br_clksrc = 0; + goto set_finish; + } + + tmp = simple_strtoul(buf, NULL, 0); + switch (attr_id) { + case FLEXCAN_ATTR_BITRATE: + flexcan_set_bitrate(flexcan, tmp); + break; + case FLEXCAN_ATTR_BR_PRESDIV: + if ((tmp > 0) && (tmp <= FLEXCAN_MAX_PRESDIV)) { + flexcan->br_presdiv = tmp - 1; + flexcan_update_bitrate(flexcan); + } + break; + case FLEXCAN_ATTR_BR_RJW: + if ((tmp > 0) && (tmp <= FLEXCAN_MAX_RJW)) + flexcan->br_rjw = tmp - 1; + break; + case FLEXCAN_ATTR_BR_PROPSEG: + if ((tmp > 0) && (tmp <= FLEXCAN_MAX_PROPSEG)) { + flexcan->br_propseg = tmp - 1; + flexcan_update_bitrate(flexcan); + } + break; + case FLEXCAN_ATTR_BR_PSEG1: + if ((tmp > 0) && (tmp <= FLEXCAN_MAX_PSEG1)) { + flexcan->br_pseg1 = tmp - 1; + flexcan_update_bitrate(flexcan); + } + break; + case FLEXCAN_ATTR_BR_PSEG2: + if ((tmp > 0) && (tmp <= FLEXCAN_MAX_PSEG2)) { + flexcan->br_pseg2 = tmp - 1; + flexcan_update_bitrate(flexcan); + } + break; + case FLEXCAN_ATTR_MAXMB: + if ((tmp > 0) && (tmp <= FLEXCAN_MAX_MB)) { + if (flexcan->maxmb != (tmp - 1)) { + flexcan->maxmb = tmp - 1; + if (flexcan->xmit_maxmb < flexcan->maxmb) + flexcan->xmit_maxmb = flexcan->maxmb; + } + } + break; + case FLEXCAN_ATTR_XMIT_MAXMB: + if ((tmp > 0) && (tmp <= (flexcan->maxmb + 1))) { + if (flexcan->xmit_maxmb != (tmp - 1)) + flexcan->xmit_maxmb = tmp - 1; + } + break; + case FLEXCAN_ATTR_FIFO: + flexcan->fifo = tmp ? 1 : 0; + break; + case FLEXCAN_ATTR_WAKEUP: + flexcan->wakeup = tmp ? 1 : 0; + break; + case FLEXCAN_ATTR_SRX_DIS: + flexcan->srx_dis = tmp ? 1 : 0; + break; + case FLEXCAN_ATTR_WAK_SRC: + flexcan->wak_src = tmp ? 1 : 0; + break; + case FLEXCAN_ATTR_BCC: + flexcan->bcc = tmp ? 1 : 0; + break; + case FLEXCAN_ATTR_LOCAL_PRIORITY: + flexcan->lprio = tmp ? 1 : 0; + break; + case FLEXCAN_ATTR_ABORT: + flexcan->abort = tmp ? 1 : 0; + break; + case FLEXCAN_ATTR_LOOPBACK: + flexcan->loopback = tmp ? 1 : 0; + break; + case FLEXCAN_ATTR_SMP: + flexcan->smp = tmp ? 1 : 0; + break; + case FLEXCAN_ATTR_BOFF_REC: + flexcan->boff_rec = tmp ? 1 : 0; + break; + case FLEXCAN_ATTR_TSYN: + flexcan->tsyn = tmp ? 1 : 0; + break; + case FLEXCAN_ATTR_LISTEN: + flexcan->listen = tmp ? 1 : 0; + break; + case FLEXCAN_ATTR_EXTEND_MSG: + flexcan->ext_msg = tmp ? 1 : 0; + break; + case FLEXCAN_ATTR_STANDARD_MSG: + flexcan->std_msg = tmp ? 1 : 0; + break; + } + set_finish: + mutex_unlock(&flexcan->mutex); + return count; +} + +static void flexcan_device_default(struct flexcan_device *dev) +{ + struct platform_device *pdev = dev->dev; + struct flexcan_platform_data *plat_data = (pdev->dev).platform_data; + dev->br_clksrc = plat_data->br_clksrc; + dev->br_rjw = plat_data->br_rjw; + dev->br_presdiv = plat_data->br_presdiv; + dev->br_propseg = plat_data->br_propseg; + dev->br_pseg1 = plat_data->br_pseg1; + dev->br_pseg2 = plat_data->br_pseg2; + + dev->bcc = plat_data->bcc; + dev->srx_dis = plat_data->srx_dis; + dev->smp = plat_data->smp; + dev->boff_rec = plat_data->boff_rec; + + dev->maxmb = FLEXCAN_MAX_MB - 1; + dev->xmit_maxmb = (FLEXCAN_MAX_MB >> 1) - 1; + dev->xmit_mb = dev->maxmb - dev->xmit_maxmb; + + dev->ext_msg = plat_data->ext_msg; + dev->std_msg = plat_data->std_msg; +} + +static int flexcan_device_attach(struct flexcan_device *flexcan) +{ + int ret; + struct resource *res; + struct platform_device *pdev = flexcan->dev; + struct flexcan_platform_data *plat_data = (pdev->dev).platform_data; + + res = platform_get_resource(flexcan->dev, IORESOURCE_MEM, 0); + if (!res) + return -ENODEV; + + flexcan->io_base = ioremap(res->start, res->end - res->start + 1); + if (!flexcan->io_base) + return -ENOMEM; + + flexcan->irq = platform_get_irq(flexcan->dev, 0); + if (!flexcan->irq) { + ret = -ENODEV; + goto no_irq_err; + } + + ret = -EINVAL; + if (plat_data) { + if (plat_data->core_reg) { + flexcan->core_reg = regulator_get(&pdev->dev, + plat_data->core_reg); + if (!flexcan->core_reg) + goto plat_err; + } + + if (plat_data->io_reg) { + flexcan->io_reg = regulator_get(&pdev->dev, + plat_data->io_reg); + if (!flexcan->io_reg) + goto plat_err; + } + } + flexcan->clk = clk_get(&(flexcan->dev)->dev, "can_clk"); + flexcan->hwmb = (struct can_hw_mb *)(flexcan->io_base + CAN_MB_BASE); + flexcan->rx_mask = (unsigned int *)(flexcan->io_base + CAN_RXMASK_BASE); + + return 0; + plat_err: + if (flexcan->core_reg) { + regulator_put(flexcan->core_reg); + flexcan->core_reg = NULL; + } + no_irq_err: + if (flexcan->io_base) + iounmap(flexcan->io_base); + return ret; +} + +static void flexcan_device_detach(struct flexcan_device *flexcan) +{ + if (flexcan->clk) { + clk_put(flexcan->clk); + flexcan->clk = NULL; + } + + if (flexcan->io_reg) { + regulator_put(flexcan->io_reg); + flexcan->io_reg = NULL; + } + + if (flexcan->core_reg) { + regulator_put(flexcan->core_reg); + flexcan->core_reg = NULL; + } + + if (flexcan->io_base) + iounmap(flexcan->io_base); +} + +/*! + * @brief The function allocates can device. + * + * @param pdev the pointer of platform device. + * @param setup the initial function pointer of network device. + * + * @return none + */ +struct net_device *flexcan_device_alloc(struct platform_device *pdev, + void (*setup) (struct net_device *dev)) +{ + struct flexcan_device *flexcan; + struct net_device *net; + int i, num; + + net = alloc_netdev(sizeof(*flexcan), "can%d", setup); + if (net == NULL) { + printk(KERN_ERR "Allocate netdevice for FlexCAN fail!\n"); + return NULL; + } + flexcan = netdev_priv(net); + memset(flexcan, 0, sizeof(*flexcan)); + + mutex_init(&flexcan->mutex); + init_timer(&flexcan->timer); + + flexcan->dev = pdev; + if (flexcan_device_attach(flexcan)) { + printk(KERN_ERR "Attach FlexCAN fail!\n"); + free_netdev(net); + return NULL; + } + flexcan_device_default(flexcan); + flexcan_set_bitrate(flexcan, flexcan->bitrate); + flexcan_update_bitrate(flexcan); + + num = ARRAY_SIZE(flexcan_dev_attr); + + for (i = 0; i < num; i++) { + if (device_create_file(&pdev->dev, flexcan_dev_attr + i)) { + printk(KERN_ERR "Create attribute file fail!\n"); + break; + } + } + + if (i != num) { + for (; i >= 0; i--) + device_remove_file(&pdev->dev, flexcan_dev_attr + i); + free_netdev(net); + return NULL; + } + dev_set_drvdata(&pdev->dev, net); + return net; +} + +/*! + * @brief The function frees can device. + * + * @param pdev the pointer of platform device. + * + * @return none + */ +void flexcan_device_free(struct platform_device *pdev) +{ + struct net_device *net; + struct flexcan_device *flexcan; + int i, num; + net = (struct net_device *)dev_get_drvdata(&pdev->dev); + + unregister_netdev(net); + flexcan = netdev_priv(net); + del_timer(&flexcan->timer); + + num = ARRAY_SIZE(flexcan_dev_attr); + + for (i = 0; i < num; i++) + device_remove_file(&pdev->dev, flexcan_dev_attr + i); + + flexcan_device_detach(netdev_priv(net)); + free_netdev(net); +} diff --git a/drivers/net/can/flexcan/drv.c b/drivers/net/can/flexcan/drv.c new file mode 100644 index 000000000000..f0a408d5640f --- /dev/null +++ b/drivers/net/can/flexcan/drv.c @@ -0,0 +1,628 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file drv.c + * + * @brief Driver for Freescale CAN Controller FlexCAN. + * + * @ingroup can + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "flexcan.h" + +static void flexcan_hw_start(struct flexcan_device *flexcan) +{ + unsigned int reg; + if ((flexcan->maxmb + 1) > 32) { + __raw_writel(0xFFFFFFFF, flexcan->io_base + CAN_HW_REG_IMASK1); + reg = (1 << (flexcan->maxmb - 31)) - 1; + __raw_writel(reg, flexcan->io_base + CAN_HW_REG_IMASK2); + } else { + reg = (1 << (flexcan->maxmb + 1)) - 1; + __raw_writel(reg, flexcan->io_base + CAN_HW_REG_IMASK1); + __raw_writel(0, flexcan->io_base + CAN_HW_REG_IMASK2); + } + + reg = __raw_readl(flexcan->io_base + CAN_HW_REG_MCR) & (~__MCR_HALT); + __raw_writel(reg, flexcan->io_base + CAN_HW_REG_MCR); +} + +static void flexcan_hw_stop(struct flexcan_device *flexcan) +{ + unsigned int reg; + reg = __raw_readl(flexcan->io_base + CAN_HW_REG_MCR); + __raw_writel(reg | __MCR_HALT, flexcan->io_base + CAN_HW_REG_MCR); +} + +static int flexcan_hw_reset(struct flexcan_device *flexcan) +{ + unsigned int reg; + int timeout = 100000; + + reg = __raw_readl(flexcan->io_base + CAN_HW_REG_MCR); + __raw_writel(reg | __MCR_MDIS, flexcan->io_base + CAN_HW_REG_MCR); + + reg = __raw_readl(flexcan->io_base + CAN_HW_REG_CTRL); + if (flexcan->br_clksrc) + reg |= __CTRL_CLK_SRC; + else + reg &= ~__CTRL_CLK_SRC; + __raw_writel(reg, flexcan->io_base + CAN_HW_REG_CTRL); + + reg = __raw_readl(flexcan->io_base + CAN_HW_REG_MCR) & (~__MCR_MDIS); + __raw_writel(reg, flexcan->io_base + CAN_HW_REG_MCR); + reg |= __MCR_SOFT_RST; + __raw_writel(reg, flexcan->io_base + CAN_HW_REG_MCR); + + reg = __raw_readl(flexcan->io_base + CAN_HW_REG_MCR); + while (reg & __MCR_SOFT_RST) { + if (--timeout <= 0) { + printk(KERN_ERR "Flexcan software Reset Timeouted\n"); + return -1; + } + udelay(10); + reg = __raw_readl(flexcan->io_base + CAN_HW_REG_MCR); + } + return 0; +} + +static inline void flexcan_mcr_setup(struct flexcan_device *flexcan) +{ + unsigned int reg; + + reg = __raw_readl(flexcan->io_base + CAN_HW_REG_MCR); + reg &= ~(__MCR_MAX_MB_MASK | __MCR_WAK_MSK | __MCR_MAX_IDAM_MASK); + + if (flexcan->fifo) + reg |= __MCR_FEN; + else + reg &= ~__MCR_FEN; + + if (flexcan->wakeup) + reg |= __MCR_SLF_WAK | __MCR_WAK_MSK; + else + reg &= ~(__MCR_SLF_WAK | __MCR_WAK_MSK); + + if (flexcan->wak_src) + reg |= __MCR_WAK_SRC; + else + reg &= ~__MCR_WAK_SRC; + + if (flexcan->srx_dis) + reg |= __MCR_SRX_DIS; + else + reg &= ~__MCR_SRX_DIS; + + if (flexcan->bcc) + reg |= __MCR_BCC; + else + reg &= ~__MCR_BCC; + + if (flexcan->lprio) + reg |= __MCR_LPRIO_EN; + else + reg &= ~__MCR_LPRIO_EN; + + if (flexcan->abort) + reg |= __MCR_AEN; + else + reg &= ~__MCR_AEN; + + reg |= (flexcan->maxmb << __MCR_MAX_MB_OFFSET); + reg |= __MCR_DOZE | __MCR_MAX_IDAM_C; + __raw_writel(reg, flexcan->io_base + CAN_HW_REG_MCR); +} + +static inline void flexcan_ctrl_setup(struct flexcan_device *flexcan) +{ + unsigned int reg; + + reg = __raw_readl(flexcan->io_base + CAN_HW_REG_CTRL); + reg &= ~(__CTRL_PRESDIV_MASK | __CTRL_RJW_MASK | __CTRL_PSEG1_MASK | + __CTRL_PSEG2_MASK | __CTRL_PROPSEG_MASK); + + if (flexcan->loopback) + reg |= __CTRL_LPB; + else + reg &= ~__CTRL_LPB; + + if (flexcan->smp) + reg |= __CTRL_SMP; + else + reg &= ~__CTRL_SMP; + + if (flexcan->boff_rec) + reg |= __CTRL_BOFF_REC; + else + reg &= ~__CTRL_BOFF_REC; + + if (flexcan->tsyn) + reg |= __CTRL_TSYN; + else + reg &= ~__CTRL_TSYN; + + if (flexcan->listen) + reg |= __CTRL_LOM; + else + reg &= ~__CTRL_LOM; + + reg |= (flexcan->br_presdiv << __CTRL_PRESDIV_OFFSET) | + (flexcan->br_rjw << __CTRL_RJW_OFFSET) | + (flexcan->br_pseg1 << __CTRL_PSEG1_OFFSET) | + (flexcan->br_pseg2 << __CTRL_PSEG2_OFFSET) | + (flexcan->br_propseg << __CTRL_PROPSEG_OFFSET); + + reg &= ~__CTRL_LBUF; + + reg |= __CTRL_TWRN_MSK | __CTRL_RWRN_MSK | __CTRL_BOFF_MSK | + __CTRL_ERR_MSK; + + __raw_writel(reg, flexcan->io_base + CAN_HW_REG_CTRL); +} + +static int flexcan_hw_restart(struct net_device *dev) +{ + unsigned int reg; + struct flexcan_device *flexcan = netdev_priv(dev); + + reg = __raw_readl(flexcan->io_base + CAN_HW_REG_MCR); + if (reg & __MCR_SOFT_RST) + return 1; + + flexcan_mcr_setup(flexcan); + + __raw_writel(0, flexcan->io_base + CAN_HW_REG_IMASK2); + __raw_writel(0, flexcan->io_base + CAN_HW_REG_IMASK1); + + __raw_writel(0xFFFFFFFF, flexcan->io_base + CAN_HW_REG_IFLAG2); + __raw_writel(0xFFFFFFFF, flexcan->io_base + CAN_HW_REG_IFLAG1); + + __raw_writel(0, flexcan->io_base + CAN_HW_REG_ECR); + + flexcan_mbm_init(flexcan); + netif_carrier_on(dev); + flexcan_hw_start(flexcan); + + if (netif_queue_stopped(dev)) + netif_start_queue(dev); + + return 0; +} + +static void flexcan_hw_watch(unsigned long data) +{ + unsigned int reg, ecr; + struct net_device *dev = (struct net_device *)data; + struct flexcan_device *flexcan = dev ? netdev_priv(dev) : NULL; + + BUG_ON(!flexcan); + + reg = __raw_readl(flexcan->io_base + CAN_HW_REG_MCR); + if (reg & __MCR_MDIS) { + if (flexcan_hw_restart(dev)) + mod_timer(&flexcan->timer, HZ / 20); + return; + } + ecr = __raw_readl(flexcan->io_base + CAN_HW_REG_ECR); + if (flexcan->boff_rec) { + if (((reg & __ESR_FLT_CONF_MASK) >> __ESR_FLT_CONF_OFF) > 1) { + reg |= __MCR_SOFT_RST; + __raw_writel(reg, flexcan->io_base + CAN_HW_REG_MCR); + mod_timer(&flexcan->timer, HZ / 20); + return; + } + netif_carrier_on(dev); + } +} + +static void flexcan_hw_busoff(struct net_device *dev) +{ + struct flexcan_device *flexcan = netdev_priv(dev); + unsigned int reg; + + netif_carrier_off(dev); + + flexcan->timer.function = flexcan_hw_watch; + flexcan->timer.data = (unsigned long)dev; + + if (flexcan->boff_rec) { + mod_timer(&flexcan->timer, HZ / 10); + return; + } + reg = __raw_readl(flexcan->io_base + CAN_HW_REG_MCR); + __raw_writel(reg | __MCR_SOFT_RST, flexcan->io_base + CAN_HW_REG_MCR); + mod_timer(&flexcan->timer, HZ / 20); +} + +static int flexcan_hw_open(struct flexcan_device *flexcan) +{ + if (flexcan_hw_reset(flexcan)) + return -EFAULT; + + flexcan_mcr_setup(flexcan); + flexcan_ctrl_setup(flexcan); + + __raw_writel(0, flexcan->io_base + CAN_HW_REG_IMASK2); + __raw_writel(0, flexcan->io_base + CAN_HW_REG_IMASK1); + + __raw_writel(0xFFFFFFFF, flexcan->io_base + CAN_HW_REG_IFLAG2); + __raw_writel(0xFFFFFFFF, flexcan->io_base + CAN_HW_REG_IFLAG1); + + __raw_writel(0, flexcan->io_base + CAN_HW_REG_ECR); + return 0; +} + +static void flexcan_err_handler(struct net_device *dev) +{ + struct flexcan_device *flexcan = netdev_priv(dev); + struct sk_buff *skb; + struct can_frame *frame; + unsigned int esr, ecr; + + esr = __raw_readl(flexcan->io_base + CAN_HW_REG_ESR); + __raw_writel(esr & __ESR_INTERRUPTS, flexcan->io_base + CAN_HW_REG_ESR); + + if (esr & __ESR_WAK_INT) + return; + + skb = dev_alloc_skb(sizeof(struct can_frame)); + if (!skb) { + printk(KERN_ERR "%s: allocates skb fail in\n", __func__); + return; + } + frame = (struct can_frame *)skb_put(skb, sizeof(*frame)); + memset(frame, 0, sizeof(*frame)); + frame->can_id = CAN_ERR_FLAG | CAN_ERR_CRTL; + frame->can_dlc = CAN_ERR_DLC; + + if (esr & __ESR_TWRN_INT) + frame->data[1] |= CAN_ERR_CRTL_TX_WARNING; + + if (esr & __ESR_RWRN_INT) + frame->data[1] |= CAN_ERR_CRTL_RX_WARNING; + + if (esr & __ESR_BOFF_INT) + frame->can_id |= CAN_ERR_BUSOFF; + + if (esr & __ESR_ERR_INT) { + if (esr & __ESR_BIT1_ERR) + frame->data[2] |= CAN_ERR_PROT_BIT1; + + if (esr & __ESR_BIT0_ERR) + frame->data[2] |= CAN_ERR_PROT_BIT0; + + if (esr & __ESR_ACK_ERR) + frame->can_id |= CAN_ERR_ACK; + + /*TODO:// if (esr & __ESR_CRC_ERR) */ + + if (esr & __ESR_FRM_ERR) + frame->data[2] |= CAN_ERR_PROT_FORM; + + if (esr & __ESR_STF_ERR) + frame->data[2] |= CAN_ERR_PROT_STUFF; + + ecr = __raw_readl(flexcan->io_base + CAN_HW_REG_ECR); + switch ((esr & __ESR_FLT_CONF_MASK) >> __ESR_FLT_CONF_OFF) { + case 0: + if (__ECR_TX_ERR_COUNTER(ecr) >= __ECR_ACTIVE_THRESHOLD) + frame->data[1] |= CAN_ERR_CRTL_TX_WARNING; + if (__ECR_RX_ERR_COUNTER(ecr) >= __ECR_ACTIVE_THRESHOLD) + frame->data[1] |= CAN_ERR_CRTL_RX_WARNING; + break; + case 1: + if (__ECR_TX_ERR_COUNTER(ecr) >= + __ECR_PASSIVE_THRESHOLD) + frame->data[1] |= CAN_ERR_CRTL_TX_PASSIVE; + + if (__ECR_RX_ERR_COUNTER(ecr) >= + __ECR_PASSIVE_THRESHOLD) + frame->data[1] |= CAN_ERR_CRTL_RX_PASSIVE; + break; + default: + frame->can_id |= CAN_ERR_BUSOFF; + } + } + + if (frame->can_id & CAN_ERR_BUSOFF) + flexcan_hw_busoff(dev); + + skb->dev = dev; + skb->ip_summed = CHECKSUM_UNNECESSARY; + netif_receive_skb(skb); +} + +static irqreturn_t flexcan_irq_handler(int irq, void *data) +{ + struct net_device *dev = (struct net_device *)data; + struct flexcan_device *flexcan = dev ? netdev_priv(dev) : NULL; + unsigned int reg; + + BUG_ON(!flexcan); + + reg = __raw_readl(flexcan->io_base + CAN_HW_REG_ESR); + if (reg & __ESR_INTERRUPTS) { + flexcan_err_handler(dev); + return IRQ_HANDLED; + } + + flexcan_mbm_isr(dev); + return IRQ_HANDLED; +} + +static int flexcan_start_xmit(struct sk_buff *skb, struct net_device *dev) +{ + struct can_frame *frame = (struct can_frame *)skb->data; + struct flexcan_device *flexcan = netdev_priv(dev); + struct net_device_stats *stats = &dev->stats; + + BUG_ON(!flexcan); + + if (frame->can_dlc > 8) + return -EINVAL; + + if (!flexcan_mbm_xmit(flexcan, frame)) { + dev_kfree_skb(skb); + stats->tx_bytes += frame->can_dlc; + stats->tx_packets++; + dev->trans_start = jiffies; + return NETDEV_TX_OK; + } + netif_stop_queue(dev); + return NETDEV_TX_BUSY; +} + +static int flexcan_open(struct net_device *dev) +{ + struct flexcan_device *flexcan; + struct platform_device *pdev; + struct flexcan_platform_data *plat_data; + + flexcan = netdev_priv(dev); + BUG_ON(!flexcan); + + pdev = flexcan->dev; + plat_data = (pdev->dev).platform_data; + if (plat_data && plat_data->active) + plat_data->active(pdev->id); + + if (flexcan->clk) + if (clk_enable(flexcan->clk)) + goto clk_err; + + if (flexcan->core_reg) + if (regulator_enable(flexcan->core_reg)) + goto core_reg_err; + + if (flexcan->io_reg) + if (regulator_enable(flexcan->io_reg)) + goto io_reg_err; + + if (plat_data && plat_data->xcvr_enable) + plat_data->xcvr_enable(pdev->id, 1); + + if (request_irq(flexcan->irq, flexcan_irq_handler, IRQF_SHARED, + dev->name, dev)) + goto irq_err; + add_interrupt_randomness(flexcan->irq); + + if (flexcan_hw_open(flexcan)) + goto open_err; + + flexcan_mbm_init(flexcan); + netif_carrier_on(dev); + flexcan_hw_start(flexcan); + return 0; + open_err: + free_irq(flexcan->irq, dev); + irq_err: + if (plat_data && plat_data->xcvr_enable) + plat_data->xcvr_enable(pdev->id, 0); + + if (flexcan->io_reg) + regulator_disable(flexcan->io_reg); + io_reg_err: + if (flexcan->core_reg) + regulator_disable(flexcan->core_reg); + core_reg_err: + if (flexcan->clk) + clk_disable(flexcan->clk); + clk_err: + if (plat_data && plat_data->inactive) + plat_data->inactive(pdev->id); + return -ENODEV; +} + +static int flexcan_stop(struct net_device *dev) +{ + struct flexcan_device *flexcan; + struct platform_device *pdev; + struct flexcan_platform_data *plat_data; + + flexcan = netdev_priv(dev); + + BUG_ON(!flexcan); + + pdev = flexcan->dev; + plat_data = (pdev->dev).platform_data; + + flexcan_hw_stop(flexcan); + + free_irq(flexcan->irq, dev); + + if (plat_data && plat_data->xcvr_enable) + plat_data->xcvr_enable(pdev->id, 0); + + if (flexcan->io_reg) + regulator_disable(flexcan->io_reg); + if (flexcan->core_reg) + regulator_disable(flexcan->core_reg); + if (flexcan->clk) + clk_disable(flexcan->clk); + if (plat_data && plat_data->inactive) + plat_data->inactive(pdev->id); + return 0; +} + +static struct net_device_ops flexcan_netdev_ops = { + .ndo_open = flexcan_open, + .ndo_stop = flexcan_stop, + .ndo_start_xmit = flexcan_start_xmit, +}; + +static void flexcan_setup(struct net_device *dev) +{ + dev->type = ARPHRD_CAN; + dev->mtu = sizeof(struct can_frame); + dev->hard_header_len = 0; + dev->addr_len = 0; + dev->tx_queue_len = FLEXCAN_MAX_MB; + dev->flags = IFF_NOARP; + dev->features = NETIF_F_NO_CSUM; + + dev->netdev_ops = &flexcan_netdev_ops; +} + +static int flexcan_probe(struct platform_device *pdev) +{ + struct net_device *net; + net = flexcan_device_alloc(pdev, flexcan_setup); + if (!net) + return -ENOMEM; + + if (register_netdev(net)) { + flexcan_device_free(pdev); + return -ENODEV; + } + return 0; +} + +static int flexcan_remove(struct platform_device *pdev) +{ + flexcan_device_free(pdev); + return 0; +} + +static int flexcan_suspend(struct platform_device *pdev, pm_message_t state) +{ + struct net_device *net; + struct flexcan_device *flexcan; + struct flexcan_platform_data *plat_data; + net = (struct net_device *)dev_get_drvdata(&pdev->dev); + flexcan = netdev_priv(net); + + BUG_ON(!flexcan); + + if (!(net->flags & IFF_UP)) + return 0; + if (flexcan->wakeup) + set_irq_wake(flexcan->irq, 1); + else { + plat_data = (pdev->dev).platform_data; + + if (plat_data && plat_data->xcvr_enable) + plat_data->xcvr_enable(pdev->id, 0); + + if (flexcan->io_reg) + regulator_disable(flexcan->io_reg); + if (flexcan->core_reg) + regulator_disable(flexcan->core_reg); + if (flexcan->clk) + clk_disable(flexcan->clk); + if (plat_data && plat_data->inactive) + plat_data->inactive(pdev->id); + } + return 0; +} + +static int flexcan_resume(struct platform_device *pdev) +{ + struct net_device *net; + struct flexcan_device *flexcan; + struct flexcan_platform_data *plat_data; + net = (struct net_device *)dev_get_drvdata(&pdev->dev); + flexcan = netdev_priv(net); + + BUG_ON(!flexcan); + + if (!(net->flags & IFF_UP)) + return 0; + + if (flexcan->wakeup) + set_irq_wake(flexcan->irq, 0); + else { + plat_data = (pdev->dev).platform_data; + if (plat_data && plat_data->active) + plat_data->active(pdev->id); + + if (flexcan->clk) { + if (clk_enable(flexcan->clk)) + printk(KERN_ERR "%s:enable clock fail\n", + __func__); + } + + if (flexcan->core_reg) { + if (regulator_enable(flexcan->core_reg)) + printk(KERN_ERR "%s:enable core voltage\n", + __func__); + } + if (flexcan->io_reg) { + if (regulator_enable(flexcan->io_reg)) + printk(KERN_ERR "%s:enable io voltage\n", + __func__); + } + + if (plat_data && plat_data->xcvr_enable) + plat_data->xcvr_enable(pdev->id, 1); + } + return 0; +} + +static struct platform_driver flexcan_driver = { + .driver = { + .name = FLEXCAN_DEVICE_NAME, + }, + .probe = flexcan_probe, + .remove = flexcan_remove, + .suspend = flexcan_suspend, + .resume = flexcan_resume, +}; + +static __init int flexcan_init(void) +{ + pr_info("Freescale FlexCAN Driver \n"); + return platform_driver_register(&flexcan_driver); +} + +static __exit void flexcan_exit(void) +{ + return platform_driver_unregister(&flexcan_driver); +} + +module_init(flexcan_init); +module_exit(flexcan_exit); + +MODULE_LICENSE("GPL"); diff --git a/drivers/net/can/flexcan/flexcan.h b/drivers/net/can/flexcan/flexcan.h new file mode 100644 index 000000000000..51a800bd8e55 --- /dev/null +++ b/drivers/net/can/flexcan/flexcan.h @@ -0,0 +1,222 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file flexcan.h + * + * @brief FlexCan definitions. + * + * @ingroup can + */ + +#ifndef __CAN_FLEXCAN_H__ +#define __CAN_FLEXCAN_H__ + +#include +#include +#include +#include +#include +#include +#include + +#define FLEXCAN_DEVICE_NAME "FlexCAN" + +#define CAN_MB_RX_INACTIVE 0x0 +#define CAN_MB_RX_EMPTY 0x4 +#define CAN_MB_RX_FULL 0x2 +#define CAN_MB_RX_OVERRUN 0x6 +#define CAN_MB_RX_BUSY 0x1 + +#define CAN_MB_TX_INACTIVE 0x8 +#define CAN_MB_TX_ABORT 0x9 +#define CAN_MB_TX_ONCE 0xC +#define CAN_MB_TX_REMOTE 0xA + +struct can_hw_mb { + unsigned int mb_cs; + unsigned int mb_id; + unsigned char mb_data[8]; +}; + +#define MB_CS_CODE_OFFSET 24 +#define MB_CS_CODE_MASK (0xF << MB_CS_CODE_OFFSET) +#define MB_CS_SRR_OFFSET 22 +#define MB_CS_SRR_MASK (0x1 << MB_CS_SRR_OFFSET) +#define MB_CS_IDE_OFFSET 21 +#define MB_CS_IDE_MASK (0x1 << MB_CS_IDE_OFFSET) +#define MB_CS_RTR_OFFSET 20 +#define MB_CS_RTR_MASK (0x1 << MB_CS_RTR_OFFSET) +#define MB_CS_LENGTH_OFFSET 16 +#define MB_CS_LENGTH_MASK (0xF << MB_CS_LENGTH_OFFSET) +#define MB_CS_TIMESTAMP_OFFSET 0 +#define MB_CS_TIMESTAMP_MASK (0xFF << MB_CS_TIMESTAMP_OFFSET) + +#define CAN_HW_REG_MCR 0x00 +#define CAN_HW_REG_CTRL 0x04 +#define CAN_HW_REG_TIMER 0x08 +#define CAN_HW_REG_RXGMASK 0x10 +#define CAN_HW_REG_RX14MASK 0x14 +#define CAN_HW_REG_RX15MASK 0x18 +#define CAN_HW_REG_ECR 0x1C +#define CAN_HW_REG_ESR 0x20 +#define CAN_HW_REG_IMASK2 0x24 +#define CAN_HW_REG_IMASK1 0x28 +#define CAN_HW_REG_IFLAG2 0x2C +#define CAN_HW_REG_IFLAG1 0x30 + +#define CAN_MB_BASE 0x0080 +#define CAN_RXMASK_BASE 0x0880 +#define CAN_FIFO_BASE 0xE0 + +#define __MCR_MDIS (1 << 31) +#define __MCR_FRZ (1 << 30) +#define __MCR_FEN (1 << 29) +#define __MCR_HALT (1 << 28) +#define __MCR_NOTRDY (1 << 27) +#define __MCR_WAK_MSK (1 << 26) +#define __MCR_SOFT_RST (1 << 25) +#define __MCR_FRZ_ACK (1 << 24) +#define __MCR_SLF_WAK (1 << 22) +#define __MCR_WRN_EN (1 << 21) +#define __MCR_LPM_ACK (1 << 20) +#define __MCR_WAK_SRC (1 << 19) +#define __MCR_DOZE (1 << 18) +#define __MCR_SRX_DIS (1 << 17) +#define __MCR_BCC (1 << 16) +#define __MCR_LPRIO_EN (1 << 13) +#define __MCR_AEN (1 << 12) +#define __MCR_MAX_IDAM_OFFSET 8 +#define __MCR_MAX_IDAM_MASK (0x3 << __MCR_MAX_IDAM_OFFSET) +#define __MCR_MAX_IDAM_A (0x0 << __MCR_MAX_IDAM_OFFSET) +#define __MCR_MAX_IDAM_B (0x1 << __MCR_MAX_IDAM_OFFSET) +#define __MCR_MAX_IDAM_C (0x2 << __MCR_MAX_IDAM_OFFSET) +#define __MCR_MAX_IDAM_D (0x3 << __MCR_MAX_IDAM_OFFSET) +#define __MCR_MAX_MB_OFFSET 0 +#define __MCR_MAX_MB_MASK (0x3F) + +#define __CTRL_PRESDIV_OFFSET 24 +#define __CTRL_PRESDIV_MASK (0xFF << __CTRL_PRESDIV_OFFSET) +#define __CTRL_RJW_OFFSET 22 +#define __CTRL_RJW_MASK (0x3 << __CTRL_RJW_OFFSET) +#define __CTRL_PSEG1_OFFSET 19 +#define __CTRL_PSEG1_MASK (0x7 << __CTRL_PSEG1_OFFSET) +#define __CTRL_PSEG2_OFFSET 16 +#define __CTRL_PSEG2_MASK (0x7 << __CTRL_PSEG2_OFFSET) +#define __CTRL_BOFF_MSK (0x1 << 15) +#define __CTRL_ERR_MSK (0x1 << 14) +#define __CTRL_CLK_SRC (0x1 << 13) +#define __CTRL_LPB (0x1 << 12) +#define __CTRL_TWRN_MSK (0x1 << 11) +#define __CTRL_RWRN_MSK (0x1 << 10) +#define __CTRL_SMP (0x1 << 7) +#define __CTRL_BOFF_REC (0x1 << 6) +#define __CTRL_TSYN (0x1 << 5) +#define __CTRL_LBUF (0x1 << 4) +#define __CTRL_LOM (0x1 << 3) +#define __CTRL_PROPSEG_OFFSET 0 +#define __CTRL_PROPSEG_MASK (0x7) + +#define __ECR_TX_ERR_COUNTER(x) ((x) & 0xFF) +#define __ECR_RX_ERR_COUNTER(x) (((x) >> 8) & 0xFF) +#define __ECR_PASSIVE_THRESHOLD 128 +#define __ECR_ACTIVE_THRESHOLD 96 + +#define __ESR_TWRN_INT (0x1 << 17) +#define __ESR_RWRN_INT (0x1 << 16) +#define __ESR_BIT1_ERR (0x1 << 15) +#define __ESR_BIT0_ERR (0x1 << 14) +#define __ESR_ACK_ERR (0x1 << 13) +#define __ESR_CRC_ERR (0x1 << 12) +#define __ESR_FRM_ERR (0x1 << 11) +#define __ESR_STF_ERR (0x1 << 10) +#define __ESR_TX_WRN (0x1 << 9) +#define __ESR_RX_WRN (0x1 << 8) +#define __ESR_IDLE (0x1 << 7) +#define __ESR_TXRX (0x1 << 6) +#define __ESR_FLT_CONF_OFF 4 +#define __ESR_FLT_CONF_MASK (0x3 << __ESR_FLT_CONF_OFF) +#define __ESR_BOFF_INT (0x1 << 2) +#define __ESR_ERR_INT (0x1 << 1) +#define __ESR_WAK_INT (0x1) + +#define __ESR_INTERRUPTS (__ESR_WAK_INT | __ESR_ERR_INT | \ + __ESR_BOFF_INT | __ESR_TWRN_INT | \ + __ESR_RWRN_INT) + +#define __FIFO_OV_INT 0x0080 +#define __FIFO_WARN_INT 0x0040 +#define __FIFO_RDY_INT 0x0020 + +struct flexcan_device { + struct mutex mutex; + void *io_base; + struct can_hw_mb *hwmb; + unsigned int *rx_mask; + unsigned int xmit_mb; + unsigned int bitrate; + /* word 1 */ + unsigned int br_presdiv:8; + unsigned int br_rjw:2; + unsigned int br_propseg:3; + unsigned int br_pseg1:3; + unsigned int br_pseg2:3; + unsigned int maxmb:6; + unsigned int xmit_maxmb:6; + unsigned int wd1_resv:1; + + /* word 2 */ + unsigned int fifo:1; + unsigned int wakeup:1; + unsigned int srx_dis:1; + unsigned int wak_src:1; + unsigned int bcc:1; + unsigned int lprio:1; + unsigned int abort:1; + unsigned int br_clksrc:1; + unsigned int loopback:1; + unsigned int smp:1; + unsigned int boff_rec:1; + unsigned int tsyn:1; + unsigned int listen:1; + + unsigned int ext_msg:1; + unsigned int std_msg:1; + + struct timer_list timer; + struct platform_device *dev; + struct regulator *core_reg; + struct regulator *io_reg; + struct clk *clk; + int irq; +}; + +#define FLEXCAN_MAX_FIFO_MB 8 +#define FLEXCAN_MAX_MB 64 +#define FLEXCAN_MAX_PRESDIV 256 +#define FLEXCAN_MAX_RJW 4 +#define FLEXCAN_MAX_PSEG1 8 +#define FLEXCAN_MAX_PSEG2 8 +#define FLEXCAN_MAX_PROPSEG 8 +#define FLEXCAN_MAX_BITRATE 1000000 + +extern struct net_device *flexcan_device_alloc(struct platform_device *pdev, + void (*setup) (struct net_device + *dev)); +extern void flexcan_device_free(struct platform_device *pdev); + +extern void flexcan_mbm_init(struct flexcan_device *flexcan); +extern void flexcan_mbm_isr(struct net_device *dev); +extern int flexcan_mbm_xmit(struct flexcan_device *flexcan, + struct can_frame *frame); +#endif /* __CAN_FLEXCAN_H__ */ diff --git a/drivers/net/can/flexcan/mbm.c b/drivers/net/can/flexcan/mbm.c new file mode 100644 index 000000000000..42266e719ce3 --- /dev/null +++ b/drivers/net/can/flexcan/mbm.c @@ -0,0 +1,361 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mbm.c + * + * @brief Driver for Freescale CAN Controller FlexCAN. + * + * @ingroup can + */ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include "flexcan.h" + +#define flexcan_swab32(x) \ + (((x) << 24) | ((x) >> 24) |\ + (((x) & (__u32)0x0000ff00UL) << 8) |\ + (((x) & (__u32)0x00ff0000UL) >> 8)) + +static inline void flexcan_memcpy(void *dst, void *src, int len) +{ + int i; + unsigned int *d = (unsigned int *)dst, *s = (unsigned int *)src; + len = (len + 3) >> 2; + for (i = 0; i < len; i++, s++, d++) + *d = flexcan_swab32(*s); +} + +static void flexcan_mb_bottom(struct net_device *dev, int index) +{ + struct flexcan_device *flexcan = netdev_priv(dev); + struct net_device_stats *stats = &dev->stats; + struct can_hw_mb *hwmb; + struct can_frame *frame; + struct sk_buff *skb; + unsigned int tmp; + + hwmb = flexcan->hwmb + index; + if (flexcan->fifo || (index >= (flexcan->maxmb - flexcan->xmit_maxmb))) { + if ((hwmb->mb_cs & MB_CS_CODE_MASK) >> MB_CS_CODE_OFFSET == + CAN_MB_TX_ABORT) { + hwmb->mb_cs &= ~MB_CS_CODE_MASK; + hwmb->mb_cs |= CAN_MB_TX_INACTIVE << MB_CS_CODE_OFFSET; + } + + if (hwmb->mb_cs & (CAN_MB_TX_INACTIVE << MB_CS_CODE_OFFSET)) { + if (netif_queue_stopped(dev)) + netif_start_queue(dev); + return; + } + } + skb = dev_alloc_skb(sizeof(struct can_frame)); + if (skb) { + frame = (struct can_frame *)skb_put(skb, sizeof(*frame)); + memset(frame, 0, sizeof(*frame)); + if (hwmb->mb_cs & MB_CS_IDE_MASK) + frame->can_id = + (hwmb->mb_id & CAN_EFF_MASK) | CAN_EFF_FLAG; + else + frame->can_id = (hwmb->mb_id >> 18) & CAN_SFF_MASK; + + if (hwmb->mb_cs & MB_CS_RTR_MASK) + frame->can_id |= CAN_RTR_FLAG; + + frame->can_dlc = + (hwmb->mb_cs & MB_CS_LENGTH_MASK) >> MB_CS_LENGTH_OFFSET; + + if (frame->can_dlc && frame->can_dlc) + flexcan_memcpy(frame->data, hwmb->mb_data, + frame->can_dlc); + + if (flexcan->fifo + || (index >= (flexcan->maxmb - flexcan->xmit_maxmb))) { + hwmb->mb_cs &= ~MB_CS_CODE_MASK; + hwmb->mb_cs |= CAN_MB_TX_INACTIVE << MB_CS_CODE_OFFSET; + if (netif_queue_stopped(dev)) + netif_start_queue(dev); + } + + tmp = __raw_readl(flexcan->io_base + CAN_HW_REG_TIMER); + + dev->last_rx = jiffies; + stats->rx_packets++; + stats->rx_bytes += frame->can_dlc; + + skb->dev = dev; + skb->protocol = __constant_htons(ETH_P_CAN); + skb->ip_summed = CHECKSUM_UNNECESSARY; + netif_rx(skb); + } else { + tmp = hwmb->mb_cs; + tmp = hwmb->mb_id; + tmp = hwmb->mb_data[0]; + if (flexcan->fifo + || (index >= (flexcan->maxmb - flexcan->xmit_maxmb))) { + hwmb->mb_cs &= ~MB_CS_CODE_MASK; + hwmb->mb_cs |= CAN_MB_TX_INACTIVE << MB_CS_CODE_OFFSET; + if (netif_queue_stopped(dev)) + netif_start_queue(dev); + } + tmp = __raw_readl(flexcan->io_base + CAN_HW_REG_TIMER); + stats->rx_dropped++; + } +} + +static void flexcan_fifo_isr(struct net_device *dev, unsigned int iflag1) +{ + struct flexcan_device *flexcan = dev ? netdev_priv(dev) : NULL; + struct net_device_stats *stats = &dev->stats; + struct sk_buff *skb; + struct can_hw_mb *hwmb = flexcan->hwmb; + struct can_frame *frame; + unsigned int tmp; + + if (iflag1 & __FIFO_RDY_INT) { + skb = dev_alloc_skb(sizeof(struct can_frame)); + if (skb) { + frame = + (struct can_frame *)skb_put(skb, sizeof(*frame)); + memset(frame, 0, sizeof(*frame)); + if (hwmb->mb_cs & MB_CS_IDE_MASK) + frame->can_id = + (hwmb->mb_id & CAN_EFF_MASK) | CAN_EFF_FLAG; + else + frame->can_id = + (hwmb->mb_id >> 18) & CAN_SFF_MASK; + + if (hwmb->mb_cs & MB_CS_RTR_MASK) + frame->can_id |= CAN_RTR_FLAG; + + frame->can_dlc = + (hwmb->mb_cs & MB_CS_LENGTH_MASK) >> + MB_CS_LENGTH_OFFSET; + + if (frame->can_dlc && (frame->can_dlc <= 8)) + flexcan_memcpy(frame->data, hwmb->mb_data, + frame->can_dlc); + tmp = __raw_readl(flexcan->io_base + CAN_HW_REG_TIMER); + + dev->last_rx = jiffies; + + stats->rx_packets++; + stats->rx_bytes += frame->can_dlc; + + skb->dev = dev; + skb->protocol = __constant_htons(ETH_P_CAN); + skb->ip_summed = CHECKSUM_UNNECESSARY; + netif_rx(skb); + } else { + tmp = hwmb->mb_cs; + tmp = hwmb->mb_id; + tmp = hwmb->mb_data[0]; + tmp = __raw_readl(flexcan->io_base + CAN_HW_REG_TIMER); + } + } + + if (iflag1 & (__FIFO_OV_INT | __FIFO_WARN_INT)) { + skb = dev_alloc_skb(sizeof(struct can_frame)); + if (skb) { + frame = + (struct can_frame *)skb_put(skb, sizeof(*frame)); + memset(frame, 0, sizeof(*frame)); + frame->can_id = CAN_ERR_FLAG | CAN_ERR_CRTL; + frame->can_dlc = CAN_ERR_DLC; + if (iflag1 & __FIFO_WARN_INT) + frame->data[1] |= + CAN_ERR_CRTL_TX_WARNING | + CAN_ERR_CRTL_RX_WARNING; + if (iflag1 & __FIFO_OV_INT) + frame->data[1] |= CAN_ERR_CRTL_RX_OVERFLOW; + + skb->dev = dev; + skb->protocol = __constant_htons(ETH_P_CAN); + skb->ip_summed = CHECKSUM_UNNECESSARY; + netif_rx(skb); + } + } +} + +/*! + * @brief The function call by CAN ISR to handle mb events. + * + * @param dev the pointer of network device. + * + * @return none + */ +void flexcan_mbm_isr(struct net_device *dev) +{ + int i, iflag1, iflag2, maxmb; + struct flexcan_device *flexcan = dev ? netdev_priv(dev) : NULL; + + if (flexcan->maxmb > 31) { + maxmb = flexcan->maxmb + 1 - 32; + iflag1 = __raw_readl(flexcan->io_base + CAN_HW_REG_IFLAG1) & + __raw_readl(flexcan->io_base + CAN_HW_REG_IMASK1); + iflag2 = __raw_readl(flexcan->io_base + CAN_HW_REG_IFLAG2) & + __raw_readl(flexcan->io_base + CAN_HW_REG_IMASK2); + iflag2 &= (1 << maxmb) - 1; + maxmb = 32; + } else { + maxmb = flexcan->maxmb + 1; + iflag1 = __raw_readl(flexcan->io_base + CAN_HW_REG_IFLAG1) & + __raw_readl(flexcan->io_base + CAN_HW_REG_IMASK1); + iflag1 &= (1 << maxmb) - 1; + iflag2 = 0; + } + + __raw_writel(iflag1, flexcan->io_base + CAN_HW_REG_IFLAG1); + __raw_writel(iflag2, flexcan->io_base + CAN_HW_REG_IFLAG2); + + if (flexcan->fifo) { + flexcan_fifo_isr(dev, iflag1); + iflag1 &= 0xFFFFFF00; + } + for (i = 0; iflag1 && (i < maxmb); i++) { + if (iflag1 & (1 << i)) { + iflag1 &= ~(1 << i); + flexcan_mb_bottom(dev, i); + } + } + + for (i = maxmb; iflag2 && (i <= flexcan->maxmb); i++) { + if (iflag2 & (1 << (i - 32))) { + iflag2 &= ~(1 << (i - 32)); + flexcan_mb_bottom(dev, i); + } + } +} + +/*! + * @brief function to xmit message buffer + * + * @param flexcan the pointer of can hardware device. + * @param frame the pointer of can message frame. + * + * @return Returns 0 if xmit is success. otherwise returns non-zero. + */ +int flexcan_mbm_xmit(struct flexcan_device *flexcan, struct can_frame *frame) +{ + int i = flexcan->xmit_mb; + struct can_hw_mb *hwmb = flexcan->hwmb; + + do { + if ((hwmb[i].mb_cs & MB_CS_CODE_MASK) >> MB_CS_CODE_OFFSET == + CAN_MB_TX_INACTIVE) + break; + if ((++i) > flexcan->maxmb) { + if (flexcan->fifo) + i = FLEXCAN_MAX_FIFO_MB; + else + i = flexcan->xmit_maxmb + 1; + } + if (i == flexcan->xmit_mb) + return -1; + } while (1); + + flexcan->xmit_mb = i + 1; + if (flexcan->xmit_mb > flexcan->maxmb) { + if (flexcan->fifo) + flexcan->xmit_mb = FLEXCAN_MAX_FIFO_MB; + else + flexcan->xmit_mb = flexcan->xmit_maxmb + 1; + } + + if (frame->can_id & CAN_RTR_FLAG) + hwmb[i].mb_cs |= 1 << MB_CS_RTR_OFFSET; + else + hwmb[i].mb_cs &= ~MB_CS_RTR_MASK; + + if (frame->can_id & CAN_EFF_FLAG) { + hwmb[i].mb_cs |= 1 << MB_CS_IDE_OFFSET; + hwmb[i].mb_cs |= 1 << MB_CS_SRR_OFFSET; + hwmb[i].mb_id = frame->can_id & CAN_EFF_MASK; + } else { + hwmb[i].mb_cs &= ~MB_CS_IDE_MASK; + hwmb[i].mb_id = (frame->can_id & CAN_SFF_MASK) << 18; + } + + hwmb[i].mb_cs &= MB_CS_LENGTH_MASK; + hwmb[i].mb_cs |= frame->can_dlc << MB_CS_LENGTH_OFFSET; + flexcan_memcpy(hwmb[i].mb_data, frame->data, frame->can_dlc); + hwmb[i].mb_cs &= ~MB_CS_CODE_MASK; + hwmb[i].mb_cs |= CAN_MB_TX_ONCE << MB_CS_CODE_OFFSET; + return 0; +} + +/*! + * @brief function to initial message buffer + * + * @param flexcan the pointer of can hardware device. + * + * @return none + */ +void flexcan_mbm_init(struct flexcan_device *flexcan) +{ + struct can_hw_mb *hwmb; + int rx_mb, i; + + /* Set global mask to receive all messages */ + __raw_writel(0, flexcan->io_base + CAN_HW_REG_RXGMASK); + __raw_writel(0, flexcan->io_base + CAN_HW_REG_RX14MASK); + __raw_writel(0, flexcan->io_base + CAN_HW_REG_RX15MASK); + + memset(flexcan->hwmb, 0, sizeof(*hwmb) * FLEXCAN_MAX_MB); + /* Set individual mask to receive all messages */ + memset(flexcan->rx_mask, 0, sizeof(unsigned int) * FLEXCAN_MAX_MB); + + if (flexcan->fifo) + rx_mb = FLEXCAN_MAX_FIFO_MB; + else + rx_mb = flexcan->maxmb - flexcan->xmit_maxmb; + + hwmb = flexcan->hwmb; + if (flexcan->fifo) { + unsigned long *id_table = flexcan->io_base + CAN_FIFO_BASE; + for (i = 0; i < rx_mb; i++) + id_table[i] = 0; + } else { + for (i = 0; i < rx_mb; i++) { + hwmb[i].mb_cs &= ~MB_CS_CODE_MASK; + hwmb[i].mb_cs |= CAN_MB_RX_EMPTY << MB_CS_CODE_OFFSET; + /* + * IDE bit can not control by mask registers + * So set message buffer to receive extend + * or standard message. + */ + if (flexcan->ext_msg && flexcan->std_msg) { + hwmb[i].mb_cs &= ~MB_CS_IDE_MASK; + hwmb[i].mb_cs |= (i & 1) << MB_CS_IDE_OFFSET; + } else { + if (flexcan->ext_msg) + hwmb[i].mb_cs |= 1 << MB_CS_IDE_OFFSET; + } + } + } + + for (; i <= flexcan->maxmb; i++) { + hwmb[i].mb_cs &= ~MB_CS_CODE_MASK; + hwmb[i].mb_cs |= CAN_MB_TX_INACTIVE << MB_CS_CODE_OFFSET; + } + + flexcan->xmit_mb = rx_mb; +} diff --git a/drivers/net/enc28j60.c b/drivers/net/enc28j60.c index 750d89bde890..26bdc746b14a 100644 --- a/drivers/net/enc28j60.c +++ b/drivers/net/enc28j60.c @@ -29,8 +29,6 @@ #include #include -#include - #include "enc28j60_hw.h" #define DRV_NAME "enc28j60" @@ -52,9 +50,17 @@ #define MAX_TX_RETRYCOUNT 16 #ifdef CONFIG_ARCH_STMP3XXX +#include #include #include #endif +#ifdef CONFIG_ARCH_MXS +#include +#include +#include +#define REGS_OCOTP_BASE IO_ADDRESS(OCOTP_PHYS_ADDR) +#endif + enum { RXFILTER_NORMAL, RXFILTER_MULTI, @@ -103,12 +109,14 @@ static int enc28j60_get_mac(unsigned char *dev_addr, int idx) return false; if (!mac[idx]) { -#ifdef CONFIG_ARCH_STMP3XXX +#if defined(CONFIG_ARCH_STMP3XXX) || defined(CONFIG_ARCH_MXS) if (get_evk_board_version() >= 1) { int mac1 , mac2 , retry = 0; - stmp3xxx_setl(BM_OCOTP_CTRL_RD_BANK_OPEN, REGS_OCOTP_BASE + HW_OCOTP_CTRL); - while (__raw_readl(REGS_OCOTP_BASE + HW_OCOTP_CTRL) & BM_OCOTP_CTRL_BUSY) { + __raw_writel(BM_OCOTP_CTRL_RD_BANK_OPEN, + REGS_OCOTP_BASE + HW_OCOTP_CTRL_SET); + while (__raw_readl(REGS_OCOTP_BASE + HW_OCOTP_CTRL) & + BM_OCOTP_CTRL_BUSY) { msleep(10); retry++; if (retry > 10) diff --git a/drivers/net/fec.c b/drivers/net/fec.c index edfff92a6d8e..860922459336 100644 --- a/drivers/net/fec.c +++ b/drivers/net/fec.c @@ -40,34 +40,28 @@ #include #include #include +#include #include #include #include #ifndef CONFIG_ARCH_MXC +#ifndef CONFIG_ARCH_MXS #include #include #endif +#endif #include "fec.h" -#ifdef CONFIG_ARCH_MXC -#include +#if defined(CONFIG_ARCH_MXC) || defined(CONFIG_ARCH_MXS) #define FEC_ALIGNMENT 0xf #else #define FEC_ALIGNMENT 0x3 #endif -/* - * Define the fixed address of the FEC hardware. - */ #if defined(CONFIG_M5272) - -static unsigned char fec_mac_default[] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -}; - /* * Some hardware gets it MAC address out of local flash memory. * if this is non-zero then assume it is the address to get MAC from. @@ -131,7 +125,8 @@ static unsigned char fec_mac_default[] = { * account when setting it. */ #if defined(CONFIG_M523x) || defined(CONFIG_M527x) || defined(CONFIG_M528x) || \ - defined(CONFIG_M520x) || defined(CONFIG_M532x) || defined(CONFIG_ARCH_MXC) + defined(CONFIG_M520x) || defined(CONFIG_M532x) || \ + defined(CONFIG_ARCH_MXC) || defined(CONFIG_ARCH_MXS) #define OPT_FRAME_SIZE (PKT_MAXBUF_SIZE << 16) #else #define OPT_FRAME_SIZE 0 @@ -189,6 +184,12 @@ struct fec_enet_private { int full_duplex; }; +/* + * Define the fixed address of the FEC hardware. + */ +static unsigned char fec_mac_default[ETH_ALEN]; +static struct mii_bus *fec_mii_bus; + static irqreturn_t fec_enet_interrupt(int irq, void * dev_id); static void fec_enet_tx(struct net_device *dev); static void fec_enet_rx(struct net_device *dev); @@ -210,6 +211,19 @@ static void fec_stop(struct net_device *dev); /* Transmitter timeout */ #define TX_TIMEOUT (2 * HZ) +#ifdef CONFIG_ARCH_MXS +static void *swap_buffer(void *bufaddr, int len) +{ + int i; + unsigned int *buf = bufaddr; + + for (i = 0; i < (len + 3) / 4; i++, buf++) + *buf = __swab32(*buf); + + return bufaddr; +} +#endif + static int fec_enet_start_xmit(struct sk_buff *skb, struct net_device *dev) { @@ -258,6 +272,9 @@ fec_enet_start_xmit(struct sk_buff *skb, struct net_device *dev) bufaddr = fep->tx_bounce[index]; } +#ifdef CONFIG_ARCH_MXS + swap_buffer(bufaddr, skb->len); +#endif /* Save skb pointer */ fep->tx_skbuff[fep->skb_cur] = skb; @@ -483,7 +500,9 @@ fec_enet_rx(struct net_device *dev) dma_unmap_single(NULL, bdp->cbd_bufaddr, bdp->cbd_datlen, DMA_FROM_DEVICE); - +#ifdef CONFIG_ARCH_MXS + swap_buffer(data, pkt_len); +#endif /* This does 16 byte alignment, exactly what we need. * The packet length includes FCS, but we don't want to * include that when passing upstream as it messes up @@ -530,12 +549,13 @@ rx_processing_done: } /* ------------------------------------------------------------------------- */ -#ifdef CONFIG_M5272 static void __inline__ fec_get_mac(struct net_device *dev) { struct fec_enet_private *fep = netdev_priv(dev); unsigned char *iap, tmpaddr[ETH_ALEN]; + static int index; +#ifdef CONFIG_M5272 if (FEC_FLASHMAC) { /* * Get MAC address from FLASH. @@ -548,19 +568,26 @@ static void __inline__ fec_get_mac(struct net_device *dev) if ((iap[0] == 0xff) && (iap[1] == 0xff) && (iap[2] == 0xff) && (iap[3] == 0xff) && (iap[4] == 0xff) && (iap[5] == 0xff)) iap = fec_mac_default; - } else { - *((unsigned long *) &tmpaddr[0]) = readl(fep->hwp + FEC_ADDR_LOW); - *((unsigned short *) &tmpaddr[4]) = (readl(fep->hwp + FEC_ADDR_HIGH) >> 16); + } +#else + if (is_valid_ether_addr(fec_mac_default)) { + iap = fec_mac_default; + } +#endif + else { + *((unsigned long *) &tmpaddr[0]) = be32_to_cpu(readl(fep->hwp + FEC_ADDR_LOW)); + *((unsigned short *) &tmpaddr[4]) = be16_to_cpu(readl(fep->hwp + FEC_ADDR_HIGH) >> 16); iap = &tmpaddr[0]; } memcpy(dev->dev_addr, iap, ETH_ALEN); /* Adjust MAC if using default MAC address */ - if (iap == fec_mac_default) - dev->dev_addr[ETH_ALEN-1] = fec_mac_default[ETH_ALEN-1] + fep->index; + if (iap == fec_mac_default) { + dev->dev_addr[ETH_ALEN-1] = fec_mac_default[ETH_ALEN-1] + index; + index++; +} } -#endif /* ------------------------------------------------------------------------- */ @@ -651,8 +678,8 @@ static int fec_enet_mdio_write(struct mii_bus *bus, int mii_id, int regnum, /* clear MII end of transfer bit*/ writel(FEC_ENET_MII, fep->hwp + FEC_IEVENT); - /* start a read op */ - writel(FEC_MMFR_ST | FEC_MMFR_OP_READ | + /* start a write op */ + writel(FEC_MMFR_ST | FEC_MMFR_OP_WRITE | FEC_MMFR_PA(mii_id) | FEC_MMFR_RA(regnum) | FEC_MMFR_TA | FEC_MMFR_DATA(value), fep->hwp + FEC_MII_DATA); @@ -680,12 +707,15 @@ static int fec_enet_mii_probe(struct net_device *dev) struct fec_enet_private *fep = netdev_priv(dev); struct phy_device *phy_dev = NULL; int phy_addr; + int fec_index = fep->pdev->id > 0 ? fep->pdev->id : 0; fep->phy_dev = NULL; - /* find the first phy */ + /* find the phy, assuming fec index corresponds to addr */ for (phy_addr = 0; phy_addr < PHY_MAX_ADDR; phy_addr++) { if (fep->mii_bus->phy_map[phy_addr]) { + if (fec_index--) + continue; phy_dev = fep->mii_bus->phy_map[phy_addr]; break; } @@ -699,7 +729,7 @@ static int fec_enet_mii_probe(struct net_device *dev) /* attach the mac to the phy */ phy_dev = phy_connect(dev, dev_name(&phy_dev->dev), &fec_enet_adjust_link, 0, - PHY_INTERFACE_MODE_MII); + fep->phy_interface); if (IS_ERR(phy_dev)) { printk(KERN_ERR "%s: Could not attach to PHY\n", dev->name); return PTR_ERR(phy_dev); @@ -721,7 +751,7 @@ static int fec_enet_mii_probe(struct net_device *dev) return 0; } -static int fec_enet_mii_init(struct platform_device *pdev) +static struct mii_bus *fec_enet_mii_init(struct platform_device *pdev) { struct net_device *dev = platform_get_drvdata(pdev); struct fec_enet_private *fep = netdev_priv(dev); @@ -733,6 +763,10 @@ static int fec_enet_mii_init(struct platform_device *pdev) * Set MII speed to 2.5 MHz (= clk_get_rate() / 2 * phy_speed) */ fep->phy_speed = DIV_ROUND_UP(clk_get_rate(fep->clk), 5000000) << 1; +#ifdef CONFIG_ARCH_MXS + /* Can't get phy(8720) ID when set to 2.5M on MX28, lower it*/ + fep->phy_speed <<= 2; +#endif writel(fep->phy_speed, fep->hwp + FEC_MII_SPEED); fep->mii_bus = mdiobus_alloc(); @@ -763,14 +797,14 @@ static int fec_enet_mii_init(struct platform_device *pdev) if (mdiobus_register(fep->mii_bus)) goto err_out_free_mdio_irq; - return 0; + return fep->mii_bus; err_out_free_mdio_irq: kfree(fep->mii_bus->irq); err_out_free_mdiobus: mdiobus_free(fep->mii_bus); err_out: - return err; + return ERR_PTR(err); } static void fec_enet_mii_remove(struct fec_enet_private *fep) @@ -912,7 +946,7 @@ fec_enet_open(struct net_device *dev) /* I should reset the ring buffers here, but I don't yet know * a simple way to do that. */ - + clk_enable(fep->clk); ret = fec_enet_alloc_buffers(dev); if (ret) return ret; @@ -924,6 +958,7 @@ fec_enet_open(struct net_device *dev) return ret; } phy_start(fep->phy_dev); + fec_restart(dev, fep->phy_dev->duplex); netif_start_queue(dev); fep->opened = 1; return 0; @@ -939,10 +974,12 @@ fec_enet_close(struct net_device *dev) netif_stop_queue(dev); fec_stop(dev); - if (fep->phy_dev) + if (fep->phy_dev) { + phy_stop(fep->phy_dev); phy_disconnect(fep->phy_dev); - + } fec_enet_free_buffers(dev); + clk_disable(fep->clk); return 0; } @@ -1058,6 +1095,31 @@ static const struct net_device_ops fec_netdev_ops = { .ndo_do_ioctl = fec_enet_ioctl, }; +static int fec_mac_addr_setup(char *mac_addr) +{ + char *ptr, *p = mac_addr; + unsigned long tmp; + int i = 0, ret = 0; + + while (p && (*p) && i < 6) { + ptr = strchr(p, ':'); + if (ptr) + *ptr++ = '\0'; + + if (strlen(p)) { + ret = strict_strtoul(p, 16, &tmp); + if (ret < 0 || tmp > 0xff) + break; + fec_mac_default[i++] = tmp; + } + p = ptr; + } + + return 0; +} + +__setup("fec_mac=", fec_mac_addr_setup); + /* * XXX: We need to clean up on failure exits here. * @@ -1085,21 +1147,7 @@ static int fec_enet_init(struct net_device *dev, int index) fep->netdev = dev; /* Set the Ethernet address */ -#ifdef CONFIG_M5272 fec_get_mac(dev); -#else - { - unsigned long l; - l = readl(fep->hwp + FEC_ADDR_LOW); - dev->dev_addr[0] = (unsigned char)((l & 0xFF000000) >> 24); - dev->dev_addr[1] = (unsigned char)((l & 0x00FF0000) >> 16); - dev->dev_addr[2] = (unsigned char)((l & 0x0000FF00) >> 8); - dev->dev_addr[3] = (unsigned char)((l & 0x000000FF) >> 0); - l = readl(fep->hwp + FEC_ADDR_HIGH); - dev->dev_addr[4] = (unsigned char)((l & 0xFF000000) >> 24); - dev->dev_addr[5] = (unsigned char)((l & 0x00FF0000) >> 16); - } -#endif /* Set receive and transmit descriptor base. */ fep->rx_bd_base = cbd_base; @@ -1151,11 +1199,19 @@ fec_restart(struct net_device *dev, int duplex) { struct fec_enet_private *fep = netdev_priv(dev); int i; + u32 temp_mac[2]; + unsigned long reg; + int val; /* Whack a reset. We should wait for this. */ writel(1, fep->hwp + FEC_ECNTRL); udelay(10); + /* Reset fec will reset MAC to zero, reconfig it again */ + memcpy(&temp_mac, dev->dev_addr, ETH_ALEN); + writel(cpu_to_be32(temp_mac[0]), fep->hwp + FEC_ADDR_LOW); + writel(cpu_to_be32(temp_mac[1]), fep->hwp + FEC_ADDR_HIGH); + /* Clear any outstanding interrupt. */ writel(0xffc00000, fep->hwp + FEC_IEVENT); @@ -1199,6 +1255,28 @@ fec_restart(struct net_device *dev, int duplex) } fep->full_duplex = duplex; +#ifdef CONFIG_ARCH_MXS + + reg = readl(fep->hwp + FEC_R_CNTRL); + + /* Enable flow control and length check */ + reg |= (0x40000000 | 0x00000020); + + /* Check MII or RMII */ + if (fep->phy_interface == PHY_INTERFACE_MODE_RMII) + reg |= 0x00000100; + else + reg &= ~0x00000100; + + /* Check 10M or 100M */ + if (fep->phy_dev && fep->phy_dev->speed == SPEED_100) + reg &= ~0x00000200; /* 100M */ + else + reg |= 0x00000200; /* 10M */ + + writel(reg, fep->hwp + FEC_R_CNTRL); + +#endif /* Set MII speed */ writel(fep->phy_speed, fep->hwp + FEC_MII_SPEED); @@ -1210,7 +1288,10 @@ fec_restart(struct net_device *dev, int duplex) udelay(1); /* configure the gasket: RMII, 50 MHz, no loopback, no echo */ - writel(1, fep->hwp + FEC_MIIGSK_CFGR); + val = 1; + if (fep->phy_dev && fep->phy_dev->speed == SPEED_10) + val |= 1 << 6; + writel(val, fep->hwp + FEC_MIIGSK_CFGR); /* re-enable the gasket */ writel(2, fep->hwp + FEC_MIIGSK_ENR); @@ -1313,18 +1394,32 @@ fec_probe(struct platform_device *pdev) } clk_enable(fep->clk); + /* PHY reset should be done during clock on */ + if (pdata && pdata->init) + ret = pdata->init(); + if (ret) + goto failed_platform_init; + ret = fec_enet_init(ndev, 0); if (ret) goto failed_init; - ret = fec_enet_mii_init(pdev); - if (ret) + if (pdev->id == 0) { + fec_mii_bus = fec_enet_mii_init(pdev); + if (IS_ERR(fec_mii_bus)) { + ret = -ENOMEM; goto failed_mii_init; + } + } else { + fep->mii_bus = fec_mii_bus; + } ret = register_netdev(ndev); if (ret) goto failed_register; + clk_disable(fep->clk); + return 0; failed_register: @@ -1342,6 +1437,7 @@ failed_clk: failed_irq: iounmap((void __iomem *)ndev->base_addr); failed_ioremap: +failed_platform_init: free_netdev(ndev); return ret; @@ -1352,11 +1448,14 @@ fec_drv_remove(struct platform_device *pdev) { struct net_device *ndev = platform_get_drvdata(pdev); struct fec_enet_private *fep = netdev_priv(ndev); + struct fec_platform_data *pdata = pdev->dev.platform_data; platform_set_drvdata(pdev, NULL); fec_stop(ndev); fec_enet_mii_remove(fep); + if (pdata && pdata->uninit) + pdata->uninit(); clk_disable(fep->clk); clk_put(fep->clk); iounmap((void __iomem *)ndev->base_addr); @@ -1373,9 +1472,11 @@ fec_suspend(struct platform_device *dev, pm_message_t state) if (ndev) { fep = netdev_priv(ndev); - if (netif_running(ndev)) - fec_enet_close(ndev); + if (netif_running(ndev)) { + netif_device_detach(ndev); + fec_stop(ndev); clk_disable(fep->clk); + } } return 0; } @@ -1388,9 +1489,11 @@ fec_resume(struct platform_device *dev) if (ndev) { fep = netdev_priv(ndev); - clk_enable(fep->clk); - if (netif_running(ndev)) - fec_enet_open(ndev); + if (netif_running(ndev)) { + clk_enable(fep->clk); + fec_restart(ndev, fep->full_duplex); + netif_device_attach(ndev); + } } return 0; } diff --git a/drivers/net/fec.h b/drivers/net/fec.h index 2c48b25668d5..53b3f7db10f4 100644 --- a/drivers/net/fec.h +++ b/drivers/net/fec.h @@ -14,7 +14,8 @@ /****************************************************************************/ #if defined(CONFIG_M523x) || defined(CONFIG_M527x) || defined(CONFIG_M528x) || \ - defined(CONFIG_M520x) || defined(CONFIG_M532x) || defined(CONFIG_ARCH_MXC) + defined(CONFIG_M520x) || defined(CONFIG_M532x) || \ + defined(CONFIG_ARCH_MXC) || defined(CONFIG_ARCH_MXS) /* * Just figures, Motorola would have to change the offsets for * registers in the same peripheral device on different models @@ -78,7 +79,7 @@ /* * Define the buffer descriptor structure. */ -#ifdef CONFIG_ARCH_MXC +#if defined(CONFIG_ARCH_MXC) || defined(CONFIG_ARCH_MXS) struct bufdesc { unsigned short cbd_datlen; /* Data length */ unsigned short cbd_sc; /* Control and status info */ diff --git a/drivers/net/irda/Kconfig b/drivers/net/irda/Kconfig index 25bb2a015e18..c71ccb108a8a 100644 --- a/drivers/net/irda/Kconfig +++ b/drivers/net/irda/Kconfig @@ -403,5 +403,9 @@ config SH_IRDA help Say Y here if your want to enable SuperH IrDA devices. +config MXC_FIR + tristate "Freescale MXC FIR driver" + depends on ARCH_MXC && IRDA + endmenu diff --git a/drivers/net/irda/Makefile b/drivers/net/irda/Makefile index dfc64537f62f..36cbac4c5788 100644 --- a/drivers/net/irda/Makefile +++ b/drivers/net/irda/Makefile @@ -18,6 +18,7 @@ obj-$(CONFIG_VLSI_FIR) += vlsi_ir.o obj-$(CONFIG_VIA_FIR) += via-ircc.o obj-$(CONFIG_PXA_FICP) += pxaficp_ir.o obj-$(CONFIG_MCS_FIR) += mcs7780.o +obj-$(CONFIG_MXC_FIR) += mxc_ir.o obj-$(CONFIG_AU1000_FIR) += au1k_ir.o obj-$(CONFIG_SH_IRDA) += sh_irda.o # SIR drivers diff --git a/drivers/net/irda/mxc_ir.c b/drivers/net/irda/mxc_ir.c new file mode 100644 index 000000000000..c3636d6bc553 --- /dev/null +++ b/drivers/net/irda/mxc_ir.c @@ -0,0 +1,1781 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * Based on sa1100_ir.c - Copyright 2000-2001 Russell King + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mxc_ir.c + * + * @brief Driver for the Freescale Semiconductor MXC FIRI. + * + * This driver is based on drivers/net/irda/sa1100_ir.c, by Russell King. + * + * @ingroup FIRI + */ + +/* + * Include Files + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include "mxc_ir.h" + +#define IS_SIR(mi) ((mi)->speed <= 115200) +#define IS_MIR(mi) ((mi)->speed < 4000000 && (mi)->speed >= 576000) +#define IS_FIR(mi) ((mi)->speed >= 4000000) + +#define SDMA_START_DELAY() { \ + volatile int j, k;\ + int i;\ + for (i = 0; i < 10000; i++)\ + k = j;\ + } + +#define IRDA_FRAME_SIZE_LIMIT 2047 +#define UART_BUFF_SIZE 14384 + +#define UART4_UFCR_TXTL 16 +#define UART4_UFCR_RXTL 1 + +#define FIRI_SDMA_TX +#define FIRI_SDMA_RX + +/*! + * This structure is a way for the low level driver to define their own + * \b mxc_irda structure. This structure includes SK buffers, DMA buffers. + * and has other elements that are specifically required by this driver. + */ +struct mxc_irda { + /*! + * This keeps track of device is running or not + */ + unsigned char open; + + /*! + * This holds current FIRI communication speed + */ + int speed; + + /*! + * This holds FIRI communication speed for next packet + */ + int newspeed; + + /*! + * SK buffer for transmitter + */ + struct sk_buff *txskb; + + /*! + * SK buffer for receiver + */ + struct sk_buff *rxskb; + +#ifdef FIRI_SDMA_RX + /*! + * SK buffer for tasklet + */ + struct sk_buff *tskb; +#endif + + /*! + * DMA address for transmitter + */ + dma_addr_t dma_rx_buff_phy; + + /*! + * DMA address for receiver + */ + dma_addr_t dma_tx_buff_phy; + + /*! + * DMA Transmit buffer length + */ + unsigned int dma_tx_buff_len; + + /*! + * DMA channel for transmitter + */ + int txdma_ch; + + /*! + * DMA channel for receiver + */ + int rxdma_ch; + + /*! + * IrDA network device statistics + */ + struct net_device_stats stats; + + /*! + * The device structure used to get FIRI information + */ + struct device *dev; + + /*! + * Resource structure for UART, which will maintain base addresses and IRQs. + */ + struct resource *uart_res; + + /*! + * Base address of UART, used in readl and writel. + */ + void *uart_base; + + /*! + * Resource structure for FIRI, which will maintain base addresses and IRQs. + */ + struct resource *firi_res; + + /*! + * Base address of FIRI, used in readl and writel. + */ + void *firi_base; + + /*! + * UART IRQ number. + */ + int uart_irq; + + /*! + * Second UART IRQ number in case the interrupt lines are not muxed. + */ + int uart_irq1; + + /*! + * UART clock needed for baud rate calculations + */ + struct clk *uart_clk; + + /*! + * UART clock needed for baud rate calculations + */ + unsigned long uart_clk_rate; + + /*! + * FIRI clock needed for baud rate calculations + */ + struct clk *firi_clk; + + /*! + * FIRI IRQ number. + */ + int firi_irq; + + /*! + * IrLAP layer instance + */ + struct irlap_cb *irlap; + + /*! + * Driver supported baudrate capabilities + */ + struct qos_info qos; + + /*! + * Temporary transmit buffer used by the driver + */ + iobuff_t tx_buff; + + /*! + * Temporary receive buffer used by the driver + */ + iobuff_t rx_buff; + + /*! + * Pointer to platform specific data structure. + */ + struct mxc_ir_platform_data *mxc_ir_plat; + + /*! + * This holds the power management status of this module. + */ + int suspend; + +}; + +extern void gpio_firi_active(void *, unsigned int); +extern void gpio_firi_inactive(void); +extern void gpio_firi_init(void); + +void mxc_irda_firi_init(struct mxc_irda *si); +#ifdef FIRI_SDMA_RX +static void mxc_irda_fir_dma_rx_irq(void *id, int error_status, + unsigned int count); +#endif +#ifdef FIRI_SDMA_TX +static void mxc_irda_fir_dma_tx_irq(void *id, int error_status, + unsigned int count); +#endif + +/*! + * This function allocates and maps the receive buffer, + * unless it is already allocated. + * + * @param si FIRI device specific structure. + * @return The function returns 0 on success and a non-zero value on + * failure. + */ +static int mxc_irda_rx_alloc(struct mxc_irda *si) +{ +#ifdef FIRI_SDMA_RX + mxc_dma_requestbuf_t dma_request; +#endif + if (si->rxskb) { + return 0; + } + + si->rxskb = alloc_skb(IRDA_FRAME_SIZE_LIMIT + 1, GFP_ATOMIC); + + if (!si->rxskb) { + dev_err(si->dev, "mxc_ir: out of memory for RX SKB\n"); + return -ENOMEM; + } + + /* + * Align any IP headers that may be contained + * within the frame. + */ + skb_reserve(si->rxskb, 1); + +#ifdef FIRI_SDMA_RX + si->dma_rx_buff_phy = + dma_map_single(si->dev, si->rxskb->data, IRDA_FRAME_SIZE_LIMIT, + DMA_FROM_DEVICE); + + dma_request.num_of_bytes = IRDA_FRAME_SIZE_LIMIT; + dma_request.dst_addr = si->dma_rx_buff_phy; + dma_request.src_addr = si->firi_res->start; + + mxc_dma_config(si->rxdma_ch, &dma_request, 1, MXC_DMA_MODE_READ); +#endif + return 0; +} + +/*! + * This function is called to disable the FIRI dma + * + * @param si FIRI port specific structure. + */ +static void mxc_irda_disabledma(struct mxc_irda *si) +{ + /* Stop all DMA activity. */ +#ifdef FIRI_SDMA_TX + mxc_dma_disable(si->txdma_ch); +#endif +#ifdef FIRI_SDMA_RX + mxc_dma_disable(si->rxdma_ch); +#endif +} + +/*! + * This function is called to set the IrDA communications speed. + * + * @param si FIRI specific structure. + * @param speed new Speed to be configured for. + * + * @return The function returns 0 on success and a non-zero value on + * failure. + */ +static int mxc_irda_set_speed(struct mxc_irda *si, int speed) +{ + unsigned long flags; + int ret = 0; + unsigned int num, denom, baud; + unsigned int cr; + + dev_dbg(si->dev, "speed:%d\n", speed); + switch (speed) { + case 9600: + case 19200: + case 38400: + case 57600: + case 115200: + dev_dbg(si->dev, "starting SIR\n"); + baud = speed; + if (IS_FIR(si)) { +#ifdef FIRI_SDMA_RX + mxc_dma_disable(si->rxdma_ch); +#endif + cr = readl(si->firi_base + FIRITCR); + cr &= ~FIRITCR_TE; + writel(cr, si->firi_base + FIRITCR); + + cr = readl(si->firi_base + FIRIRCR); + cr &= ~FIRIRCR_RE; + writel(cr, si->firi_base + FIRIRCR); + + } + local_irq_save(flags); + + /* Disable Tx and Rx */ + cr = readl(si->uart_base + MXC_UARTUCR2); + cr &= ~(MXC_UARTUCR2_RXEN | MXC_UARTUCR2_TXEN); + writel(cr, si->uart_base + MXC_UARTUCR2); + + gpio_firi_inactive(); + + num = baud / 100 - 1; + denom = si->uart_clk_rate / 1600 - 1; + if ((denom < 65536) && (si->uart_clk_rate > 1600)) { + writel(num, si->uart_base + MXC_UARTUBIR); + writel(denom, si->uart_base + MXC_UARTUBMR); + } + + si->speed = speed; + + writel(0xFFFF, si->uart_base + MXC_UARTUSR1); + writel(0xFFFF, si->uart_base + MXC_UARTUSR2); + + /* Enable Receive Overrun and Data Ready interrupts. */ + cr = readl(si->uart_base + MXC_UARTUCR4); + cr |= (MXC_UARTUCR4_OREN | MXC_UARTUCR4_DREN); + writel(cr, si->uart_base + MXC_UARTUCR4); + + cr = readl(si->uart_base + MXC_UARTUCR2); + cr |= (MXC_UARTUCR2_RXEN | MXC_UARTUCR2_TXEN); + writel(cr, si->uart_base + MXC_UARTUCR2); + + local_irq_restore(flags); + break; + case 4000000: + local_irq_save(flags); + + /* Disable Receive Overrun and Data Ready interrupts. */ + cr = readl(si->uart_base + MXC_UARTUCR4); + cr &= ~(MXC_UARTUCR4_OREN | MXC_UARTUCR4_DREN); + writel(cr, si->uart_base + MXC_UARTUCR4); + + /* Disable Tx and Rx */ + cr = readl(si->uart_base + MXC_UARTUCR2); + cr &= ~(MXC_UARTUCR2_RXEN | MXC_UARTUCR2_TXEN); + writel(cr, si->uart_base + MXC_UARTUCR2); + + /* + * FIR configuration + */ + mxc_irda_disabledma(si); + + cr = readl(si->firi_base + FIRITCR); + cr &= ~FIRITCR_TE; + writel(cr, si->firi_base + FIRITCR); + + gpio_firi_active(si->firi_base + FIRITCR, FIRITCR_TPP); + + si->speed = speed; + + cr = readl(si->firi_base + FIRIRCR); + cr |= FIRIRCR_RE; + writel(cr, si->firi_base + FIRIRCR); + + dev_dbg(si->dev, "Going for fast IRDA ...\n"); + ret = mxc_irda_rx_alloc(si); + + /* clear RX status register */ + writel(0xFFFF, si->firi_base + FIRIRSR); +#ifdef FIRI_SDMA_RX + if (si->rxskb) { + mxc_dma_enable(si->rxdma_ch); + } +#endif + local_irq_restore(flags); + + break; + default: + dev_err(si->dev, "speed not supported by FIRI\n"); + break; + } + + return ret; +} + +/*! + * This function is called to set the IrDA communications speed. + * + * @param si FIRI specific structure. + * + * @return The function returns 0 on success and a non-zero value on + * failure. + */ +static inline int mxc_irda_fir_error(struct mxc_irda *si) +{ + struct sk_buff *skb = si->rxskb; + unsigned int dd_error, crc_error, overrun_error; + unsigned int sr; + + if (!skb) { + dev_err(si->dev, "no skb!\n"); + return -1; + } + + sr = readl(si->firi_base + FIRIRSR); + dd_error = sr & FIRIRSR_DDE; + crc_error = sr & FIRIRSR_CRCE; + overrun_error = sr & FIRIRSR_RFO; + + if (!(dd_error | crc_error | overrun_error)) { + return 0; + } + dev_err(si->dev, "dde,crce,rfo=%d,%d,%d.\n", dd_error, crc_error, + overrun_error); + si->stats.rx_errors++; + if (crc_error) { + si->stats.rx_crc_errors++; + } + if (dd_error) { + si->stats.rx_frame_errors++; + } + if (overrun_error) { + si->stats.rx_frame_errors++; + } + writel(sr, si->firi_base + FIRIRSR); + + return -1; +} + +#ifndef FIRI_SDMA_RX +/*! + * FIR interrupt service routine to handle receive. + * + * @param dev pointer to the net_device structure + */ +void mxc_irda_fir_irq_rx(struct net_device *dev) +{ + struct mxc_irda *si = dev->priv; + struct sk_buff *skb = si->rxskb; + unsigned int sr, len; + int i; + unsigned char *p = skb->data; + + /* + * Deal with any receive errors. + */ + if (mxc_irda_fir_error(si) != 0) { + return; + } + + sr = readl(si->firi_base + FIRIRSR); + + if (!(sr & FIRIRSR_RPE)) { + return; + } + + /* + * Coming here indicates that fir rx packet has been successfully recieved. + * And No error happened so far. + */ + writel(sr | FIRIRSR_RPE, si->firi_base + FIRIRSR); + + len = (sr & FIRIRSR_RFP) >> 8; + + /* 4 bytes of CRC */ + len -= 4; + + skb_put(skb, len); + + for (i = 0; i < len; i++) { + *p++ = readb(si->firi_base + FIRIRXFIFO); + } + + /* Discard the four CRC bytes */ + for (i = 0; i < 4; i++) { + readb(si->firi_base + FIRIRXFIFO); + } + + /* + * Deal with the case of packet complete. + */ + skb->dev = dev; + skb->mac.raw = skb->data; + skb->protocol = htons(ETH_P_IRDA); + si->stats.rx_packets++; + si->stats.rx_bytes += len; + netif_rx(skb); + + si->rxskb = NULL; + mxc_irda_rx_alloc(si); + + writel(0xFFFF, si->firi_base + FIRIRSR); + +} +#endif + +/*! + * FIR interrupt service routine to handle transmit. + * + * @param dev pointer to the net_device structure + */ +void mxc_irda_fir_irq_tx(struct net_device *dev) +{ + struct mxc_irda *si = netdev_priv(dev); + struct sk_buff *skb = si->txskb; + unsigned int cr, sr; + + sr = readl(si->firi_base + FIRITSR); + writel(sr, si->firi_base + FIRITSR); + + if (sr & FIRITSR_TC) { + +#ifdef FIRI_SDMA_TX + mxc_dma_disable(si->txdma_ch); +#endif + cr = readl(si->firi_base + FIRITCR); + cr &= ~(FIRITCR_TCIE | FIRITCR_TE); + writel(cr, si->firi_base + FIRITCR); + + if (si->newspeed) { + mxc_irda_set_speed(si, si->newspeed); + si->newspeed = 0; + } + si->txskb = NULL; + + cr = readl(si->firi_base + FIRIRCR); + cr |= FIRIRCR_RE; + writel(cr, si->firi_base + FIRIRCR); + + writel(0xFFFF, si->firi_base + FIRIRSR); + /* + * Account and free the packet. + */ + if (skb) { +#ifdef FIRI_SDMA_TX + dma_unmap_single(si->dev, si->dma_tx_buff_phy, skb->len, + DMA_TO_DEVICE); +#endif + si->stats.tx_packets++; + si->stats.tx_bytes += skb->len; + dev_kfree_skb_irq(skb); + } + /* + * Make sure that the TX queue is available for sending + * (for retries). TX has priority over RX at all times. + */ + netif_wake_queue(dev); + } +} + +/*! + * This is FIRI interrupt handler. + * + * @param dev pointer to the net_device structure + */ +void mxc_irda_fir_irq(struct net_device *dev) +{ + struct mxc_irda *si = netdev_priv(dev); + unsigned int sr1, sr2; + + sr1 = readl(si->firi_base + FIRIRSR); + sr2 = readl(si->firi_base + FIRITSR); + + if (sr2 & FIRITSR_TC) + mxc_irda_fir_irq_tx(dev); +#ifndef FIRI_SDMA_RX + if (sr1 & (FIRIRSR_RPE | FIRIRSR_RFO)) + mxc_irda_fir_irq_rx(dev); +#endif + +} + +/*! + * This is the SIR transmit routine. + * + * @param si FIRI specific structure. + * + * @param dev pointer to the net_device structure + * + * @return The function returns 0 on success and a non-zero value on + * failure. + */ +static int mxc_irda_sir_txirq(struct mxc_irda *si, struct net_device *dev) +{ + unsigned int sr1, sr2, cr; + unsigned int status; + + sr1 = readl(si->uart_base + MXC_UARTUSR1); + sr2 = readl(si->uart_base + MXC_UARTUSR2); + cr = readl(si->uart_base + MXC_UARTUCR2); + + /* + * Echo cancellation for IRDA Transmit chars + * Disable the receiver and enable Transmit complete. + */ + cr &= ~MXC_UARTUCR2_RXEN; + writel(cr, si->uart_base + MXC_UARTUCR2); + cr = readl(si->uart_base + MXC_UARTUCR4); + cr |= MXC_UARTUCR4_TCEN; + writel(cr, si->uart_base + MXC_UARTUCR4); + + while ((sr1 & MXC_UARTUSR1_TRDY) && si->tx_buff.len) { + + writel(*si->tx_buff.data++, si->uart_base + MXC_UARTUTXD); + si->tx_buff.len -= 1; + sr1 = readl(si->uart_base + MXC_UARTUSR1); + } + + if (si->tx_buff.len == 0) { + si->stats.tx_packets++; + si->stats.tx_bytes += si->tx_buff.data - si->tx_buff.head; + + /*Yoohoo...we are done...Lets stop Tx */ + cr = readl(si->uart_base + MXC_UARTUCR1); + cr &= ~MXC_UARTUCR1_TRDYEN; + writel(cr, si->uart_base + MXC_UARTUCR1); + + do { + status = readl(si->uart_base + MXC_UARTUSR2); + } while (!(status & MXC_UARTUSR2_TXDC)); + + if (si->newspeed) { + mxc_irda_set_speed(si, si->newspeed); + si->newspeed = 0; + } + /* I'm hungry! */ + netif_wake_queue(dev); + + /* Is the transmit complete to reenable the receiver? */ + if (status & MXC_UARTUSR2_TXDC) { + + cr = readl(si->uart_base + MXC_UARTUCR2); + cr |= MXC_UARTUCR2_RXEN; + writel(cr, si->uart_base + MXC_UARTUCR2); + /* Disable the Transmit complete interrupt bit */ + cr = readl(si->uart_base + MXC_UARTUCR4); + cr &= ~MXC_UARTUCR4_TCEN; + writel(cr, si->uart_base + MXC_UARTUCR4); + } + } + + return 0; +} + +/*! + * This is the SIR receive routine. + * + * @param si FIRI specific structure. + * + * @param dev pointer to the net_device structure + * + * @return The function returns 0 on success and a non-zero value on + * failure. + */ +static int mxc_irda_sir_rxirq(struct mxc_irda *si, struct net_device *dev) +{ + unsigned int data, status; + volatile unsigned int sr2; + + sr2 = readl(si->uart_base + MXC_UARTUSR2); + while ((sr2 & MXC_UARTUSR2_RDR) == 1) { + data = readl(si->uart_base + MXC_UARTURXD); + status = data & 0xf400; + if (status & MXC_UARTURXD_ERR) { + dev_err(si->dev, "Receive an incorrect data =0x%x.\n", + data); + si->stats.rx_errors++; + if (status & MXC_UARTURXD_OVRRUN) { + si->stats.rx_fifo_errors++; + dev_err(si->dev, "Rx overrun.\n"); + } + if (status & MXC_UARTURXD_FRMERR) { + si->stats.rx_frame_errors++; + dev_err(si->dev, "Rx frame error.\n"); + } + if (status & MXC_UARTURXD_PRERR) { + dev_err(si->dev, "Rx parity error.\n"); + } + /* Other: it is the Break char. + * Do nothing for it. throw out the data. + */ + async_unwrap_char(dev, &si->stats, &si->rx_buff, + (data & 0xFF)); + } else { + /* It is correct data. */ + data &= 0xFF; + async_unwrap_char(dev, &si->stats, &si->rx_buff, data); + + dev->last_rx = jiffies; + } + sr2 = readl(si->uart_base + MXC_UARTUSR2); + + writel(0xFFFF, si->uart_base + MXC_UARTUSR1); + writel(0xFFFF, si->uart_base + MXC_UARTUSR2); + } /*while */ + return 0; + +} + +static irqreturn_t mxc_irda_irq(int irq, void *dev_id) +{ + struct net_device *dev = dev_id; + struct mxc_irda *si = netdev_priv(dev); + + if (IS_FIR(si)) { + mxc_irda_fir_irq(dev); + return IRQ_HANDLED; + } + + if (readl(si->uart_base + MXC_UARTUCR2) & MXC_UARTUCR2_RXEN) { + mxc_irda_sir_rxirq(si, dev); + } + if ((readl(si->uart_base + MXC_UARTUCR1) & MXC_UARTUCR1_TRDYEN) && + (readl(si->uart_base + MXC_UARTUSR1) & MXC_UARTUSR1_TRDY)) { + mxc_irda_sir_txirq(si, dev); + } + + return IRQ_HANDLED; +} + +static irqreturn_t mxc_irda_tx_irq(int irq, void *dev_id) +{ + + struct net_device *dev = dev_id; + struct mxc_irda *si = netdev_priv(dev); + + mxc_irda_sir_txirq(si, dev); + + return IRQ_HANDLED; +} + +static irqreturn_t mxc_irda_rx_irq(int irq, void *dev_id) +{ + + struct net_device *dev = dev_id; + struct mxc_irda *si = netdev_priv(dev); + + /* Clear the aging timer bit */ + writel(MXC_UARTUSR1_AGTIM, si->uart_base + MXC_UARTUSR1); + + mxc_irda_sir_rxirq(si, dev); + + return IRQ_HANDLED; +} + +#ifdef FIRI_SDMA_RX +struct tasklet_struct dma_rx_tasklet; + +static void mxc_irda_rx_task(unsigned long tparam) +{ + struct mxc_irda *si = (struct mxc_irda *)tparam; + struct sk_buff *lskb = si->tskb; + + si->tskb = NULL; + if (lskb) { + lskb->mac_header = lskb->data; + lskb->protocol = htons(ETH_P_IRDA); + netif_rx(lskb); + } +} + +/*! + * Receiver DMA callback routine. + * + * @param id pointer to network device structure + * @param error_status used to pass error status to this callback function + * @param count number of bytes received + */ +static void mxc_irda_fir_dma_rx_irq(void *id, int error_status, + unsigned int count) +{ + struct net_device *dev = id; + struct mxc_irda *si = netdev_priv(dev); + struct sk_buff *skb = si->rxskb; + unsigned int cr; + unsigned int len; + + cr = readl(si->firi_base + FIRIRCR); + cr &= ~FIRIRCR_RE; + writel(cr, si->firi_base + FIRIRCR); + cr = readl(si->firi_base + FIRIRCR); + cr |= FIRIRCR_RE; + writel(cr, si->firi_base + FIRIRCR); + len = count - 4; /* remove 4 bytes for CRC */ + skb_put(skb, len); + skb->dev = dev; + si->tskb = skb; + tasklet_schedule(&dma_rx_tasklet); + + if (si->dma_rx_buff_phy != 0) + dma_unmap_single(si->dev, si->dma_rx_buff_phy, + IRDA_FRAME_SIZE_LIMIT, DMA_FROM_DEVICE); + + si->rxskb = NULL; + mxc_irda_rx_alloc(si); + + SDMA_START_DELAY(); + writel(0xFFFF, si->firi_base + FIRIRSR); + + if (si->rxskb) { + mxc_dma_enable(si->rxdma_ch); + } +} +#endif + +#ifdef FIRI_SDMA_TX +/*! + * This function is called by SDMA Interrupt Service Routine to indicate + * requested DMA transfer is completed. + * + * @param id pointer to network device structure + * @param error_status used to pass error status to this callback function + * @param count number of bytes sent + */ +static void mxc_irda_fir_dma_tx_irq(void *id, int error_status, + unsigned int count) +{ + struct net_device *dev = id; + struct mxc_irda *si = netdev_priv(dev); + + mxc_dma_disable(si->txdma_ch); +} +#endif + +/*! + * This function is called by Linux IrDA network subsystem to + * transmit the Infrared data packet. The TX DMA channel is configured + * to transfer SK buffer data to FIRI TX FIFO along with DMA transfer + * completion routine. + * + * @param skb The packet that is queued to be sent + * @param dev net_device structure. + * + * @return The function returns 0 on success and a negative value on + * failure. + */ +static int mxc_irda_hard_xmit(struct sk_buff *skb, struct net_device *dev) +{ + struct mxc_irda *si = netdev_priv(dev); + int speed = irda_get_next_speed(skb); + unsigned int cr; + + /* + * Does this packet contain a request to change the interface + * speed? If so, remember it until we complete the transmission + * of this frame. + */ + if (speed != si->speed && speed != -1) { + si->newspeed = speed; + } + + /* If this is an empty frame, we can bypass a lot. */ + if (skb->len == 0) { + if (si->newspeed) { + si->newspeed = 0; + mxc_irda_set_speed(si, speed); + } + dev_kfree_skb(skb); + return 0; + } + + /* We must not be transmitting... */ + netif_stop_queue(dev); + if (IS_SIR(si)) { + + si->tx_buff.data = si->tx_buff.head; + si->tx_buff.len = async_wrap_skb(skb, si->tx_buff.data, + si->tx_buff.truesize); + cr = readl(si->uart_base + MXC_UARTUCR1); + cr |= MXC_UARTUCR1_TRDYEN; + writel(cr, si->uart_base + MXC_UARTUCR1); + dev_kfree_skb(skb); + } else { + unsigned int mtt = irda_get_mtt(skb); + unsigned char *p = skb->data; + unsigned int skb_len = skb->len; +#ifdef FIRI_SDMA_TX + mxc_dma_requestbuf_t dma_request; +#else + unsigned int i, sr; +#endif + + skb_len = skb_len + ((4 - (skb_len % 4)) % 4); + + if (si->txskb) { + BUG(); + } + si->txskb = skb; + + /* + * If we have a mean turn-around time, impose the specified + * specified delay. We could shorten this by timing from + * the point we received the packet. + */ + if (mtt) { + udelay(mtt); + } + + cr = readl(si->firi_base + FIRIRCR); + cr &= ~FIRIRCR_RE; + writel(cr, si->firi_base + FIRIRCR); + + writel(skb->len - 1, si->firi_base + FIRITCTR); + +#ifdef FIRI_SDMA_TX + /* + * Configure DMA Tx Channel for source and destination addresses, + * Number of bytes in SK buffer to transfer and Transfer complete + * callback function. + */ + si->dma_tx_buff_len = skb_len; + si->dma_tx_buff_phy = + dma_map_single(si->dev, p, skb_len, DMA_TO_DEVICE); + + dma_request.num_of_bytes = skb_len; + dma_request.dst_addr = si->firi_res->start + FIRITXFIFO; + dma_request.src_addr = si->dma_tx_buff_phy; + + mxc_dma_config(si->txdma_ch, &dma_request, 1, + MXC_DMA_MODE_WRITE); + + mxc_dma_enable(si->txdma_ch); +#endif + cr = readl(si->firi_base + FIRITCR); + cr |= FIRITCR_TCIE; + writel(cr, si->firi_base + FIRITCR); + + cr |= FIRITCR_TE; + writel(cr, si->firi_base + FIRITCR); + +#ifndef FIRI_SDMA_TX + for (i = 0; i < skb->len;) { + sr = readl(si->firi_base + FIRITSR); + /* TFP = number of bytes in the TX FIFO for the + * Transmitter + * */ + if ((sr >> 8) < 128) { + writeb(*p, si->firi_base + FIRITXFIFO); + p++; + i++; + } + } +#endif + } + + dev->trans_start = jiffies; + return 0; +} + +/*! + * This function handles network interface ioctls passed to this driver.. + * + * @param dev net device structure + * @param ifreq user request data + * @param cmd command issued + * + * @return The function returns 0 on success and a non-zero value on + * failure. + */ +static int mxc_irda_ioctl(struct net_device *dev, struct ifreq *ifreq, int cmd) +{ + struct if_irda_req *rq = (struct if_irda_req *)ifreq; + struct mxc_irda *si = netdev_priv(dev); + int ret = -EOPNOTSUPP; + + switch (cmd) { + /* This function will be used by IrLAP to change the speed */ + case SIOCSBANDWIDTH: + dev_dbg(si->dev, "%s:with cmd SIOCSBANDWIDTH\n", __FUNCTION__); + if (capable(CAP_NET_ADMIN)) { + /* + * We are unable to set the speed if the + * device is not running. + */ + if (si->open) { + ret = mxc_irda_set_speed(si, rq->ifr_baudrate); + } else { + dev_err(si->dev, "mxc_ir_ioctl: SIOCSBANDWIDTH:\ + !netif_running\n"); + ret = 0; + } + } + break; + case SIOCSMEDIABUSY: + dev_dbg(si->dev, "%s:with cmd SIOCSMEDIABUSY\n", __FUNCTION__); + ret = -EPERM; + if (capable(CAP_NET_ADMIN)) { + irda_device_set_media_busy(dev, TRUE); + ret = 0; + } + break; + case SIOCGRECEIVING: + rq->ifr_receiving = + IS_SIR(si) ? si->rx_buff.state != OUTSIDE_FRAME : 0; + ret = 0; + break; + default: + break; + } + return ret; +} + +/*! + * Kernel interface routine to get current statistics of the device + * which includes the number bytes/packets transmitted/received, + * receive errors, CRC errors, framing errors etc. + * + * @param dev the net_device structure + * + * @return This function returns IrDA network statistics + */ +static struct net_device_stats *mxc_irda_stats(struct net_device *dev) +{ + struct mxc_irda *si = netdev_priv(dev); + return &si->stats; +} + +/*! + * FIRI init function + * + * @param si FIRI device specific structure. + */ +void mxc_irda_firi_init(struct mxc_irda *si) +{ + unsigned int firi_baud, osf = 6; + unsigned int tcr, rcr, cr; + + si->firi_clk = clk_get(si->dev, "firi_clk"); + firi_baud = clk_round_rate(si->firi_clk, 48004500); + if ((firi_baud < 47995500) || + (clk_set_rate(si->firi_clk, firi_baud) < 0)) { + dev_err(si->dev, "Unable to set FIR clock to 48MHz.\n"); + return; + } + clk_enable(si->firi_clk); + + writel(0xFFFF, si->firi_base + FIRITSR); + writel(0xFFFF, si->firi_base + FIRIRSR); + writel(0x00, si->firi_base + FIRITCR); + writel(0x00, si->firi_base + FIRIRCR); + + /* set _BL & _OSF */ + cr = (osf - 1) | (16 << 5); + writel(cr, si->firi_base + FIRICR); + +#ifdef FIRI_SDMA_TX + tcr = + FIRITCR_TDT_FIR | FIRITCR_TM_FIR | FIRITCR_TCIE | + FIRITCR_PCF | FIRITCR_PC; +#else + tcr = FIRITCR_TM_FIR | FIRITCR_TCIE | FIRITCR_PCF | FIRITCR_PC; +#endif + +#ifdef FIRI_SDMA_RX + rcr = + FIRIRCR_RPEDE | FIRIRCR_RM_FIR | FIRIRCR_RDT_FIR | + FIRIRCR_RPA | FIRIRCR_RPP; +#else + rcr = + FIRIRCR_RPEDE | FIRIRCR_RM_FIR | FIRIRCR_RDT_FIR | FIRIRCR_RPEIE | + FIRIRCR_RPA | FIRIRCR_PAIE | FIRIRCR_RFOIE | FIRIRCR_RPP; +#endif + + writel(tcr, si->firi_base + FIRITCR); + writel(rcr, si->firi_base + FIRIRCR); + cr = 0; + writel(cr, si->firi_base + FIRITCTR); +} + +/*! + * This function initialises the UART. + * + * @param si FIRI port specific structure. + * + * @return The function returns 0 on success. + */ +static int mxc_irda_uart_init(struct mxc_irda *si) +{ + unsigned int per_clk; + unsigned int num, denom, baud, ufcr = 0; + unsigned int cr; + int d = 1; + int uart_ir_mux = 0; + + if (si->mxc_ir_plat) + uart_ir_mux = si->mxc_ir_plat->uart_ir_mux; + /* + * Clear Status Registers 1 and 2 + **/ + writel(0xFFFF, si->uart_base + MXC_UARTUSR1); + writel(0xFFFF, si->uart_base + MXC_UARTUSR2); + + /* Configure the IOMUX for the UART */ + gpio_firi_init(); + + per_clk = clk_get_rate(si->uart_clk); + baud = per_clk / 16; + if (baud > 1500000) { + baud = 1500000; + d = per_clk / ((baud * 16) + 1000); + if (d > 6) { + d = 6; + } + } + clk_enable(si->uart_clk); + + si->uart_clk_rate = per_clk / d; + writel(si->uart_clk_rate / 1000, si->uart_base + MXC_UARTONEMS); + + writel(si->mxc_ir_plat->ir_rx_invert | MXC_UARTUCR4_IRSC, + si->uart_base + MXC_UARTUCR4); + + if (uart_ir_mux) { + writel(MXC_UARTUCR3_RXDMUXSEL | si->mxc_ir_plat->ir_tx_invert | + MXC_UARTUCR3_DSR, si->uart_base + MXC_UARTUCR3); + } else { + writel(si->mxc_ir_plat->ir_tx_invert | MXC_UARTUCR3_DSR, + si->uart_base + MXC_UARTUCR3); + } + + writel(MXC_UARTUCR2_IRTS | MXC_UARTUCR2_CTS | MXC_UARTUCR2_WS | + MXC_UARTUCR2_ATEN | MXC_UARTUCR2_TXEN | MXC_UARTUCR2_RXEN, + si->uart_base + MXC_UARTUCR2); + /* Wait till we are out of software reset */ + do { + cr = readl(si->uart_base + MXC_UARTUCR2); + } while (!(cr & MXC_UARTUCR2_SRST)); + + ufcr |= (UART4_UFCR_TXTL << MXC_UARTUFCR_TXTL_OFFSET) | + ((6 - d) << MXC_UARTUFCR_RFDIV_OFFSET) | UART4_UFCR_RXTL; + writel(ufcr, si->uart_base + MXC_UARTUFCR); + + writel(MXC_UARTUCR1_UARTEN | MXC_UARTUCR1_IREN, + si->uart_base + MXC_UARTUCR1); + + baud = 9600; + num = baud / 100 - 1; + denom = si->uart_clk_rate / 1600 - 1; + + if ((denom < 65536) && (si->uart_clk_rate > 1600)) { + writel(num, si->uart_base + MXC_UARTUBIR); + writel(denom, si->uart_base + MXC_UARTUBMR); + } + + writel(0x0000, si->uart_base + MXC_UARTUTS); + return 0; + +} + +/*! + * This function enables FIRI port. + * + * @param si FIRI port specific structure. + * + * @return The function returns 0 on success and a non-zero value on + * failure. + */ +static int mxc_irda_startup(struct mxc_irda *si) +{ + int ret = 0; + + mxc_irda_uart_init(si); + mxc_irda_firi_init(si); + + /* configure FIRI device for speed */ + ret = mxc_irda_set_speed(si, si->speed = 9600); + + return ret; +} + +/*! + * When an ifconfig is issued which changes the device flag to include + * IFF_UP this function is called. It is only called when the change + * occurs, not when the interface remains up. The function grabs the interrupt + * resources and registers FIRI interrupt service routines, requests for DMA + * channels, configures the DMA channel. It then initializes the IOMUX + * registers to configure the pins for FIRI signals and finally initializes the + * various FIRI registers and enables the port for reception. + * + * @param dev net device structure that is being opened + * + * @return The function returns 0 for a successful open and non-zero value + * on failure. + */ +static int mxc_irda_start(struct net_device *dev) +{ + struct mxc_irda *si = netdev_priv(dev); + int err; + int ints_muxed = 0; + mxc_dma_device_t dev_id = 0; + + if (si->uart_irq == si->uart_irq1) + ints_muxed = 1; + + si->speed = 9600; + + if (si->uart_irq == si->firi_irq) { + err = + request_irq(si->uart_irq, mxc_irda_irq, 0, dev->name, dev); + if (err) { + dev_err(si->dev, "%s:Failed to request the IRQ\n", + __FUNCTION__); + return err; + } + /* + * The interrupt must remain disabled for now. + */ + disable_irq(si->uart_irq); + } else { + err = + request_irq(si->firi_irq, mxc_irda_irq, 0, dev->name, dev); + if (err) { + dev_err(si->dev, "%s:Failed to request FIRI IRQ\n", + __FUNCTION__); + return err; + } + /* + * The interrupt must remain disabled for now. + */ + disable_irq(si->firi_irq); + if (ints_muxed) { + + err = request_irq(si->uart_irq, mxc_irda_irq, 0, + dev->name, dev); + if (err) { + dev_err(si->dev, + "%s:Failed to request UART IRQ\n", + __FUNCTION__); + goto err_irq1; + } + /* + * The interrupt must remain disabled for now. + */ + disable_irq(si->uart_irq); + } else { + err = request_irq(si->uart_irq, mxc_irda_tx_irq, 0, + dev->name, dev); + if (err) { + dev_err(si->dev, + "%s:Failed to request UART IRQ\n", + __FUNCTION__); + goto err_irq1; + } + err = request_irq(si->uart_irq1, mxc_irda_rx_irq, 0, + dev->name, dev); + if (err) { + dev_err(si->dev, + "%s:Failed to request UART1 IRQ\n", + __FUNCTION__); + goto err_irq2; + } + /* + * The interrupts must remain disabled for now. + */ + disable_irq(si->uart_irq); + disable_irq(si->uart_irq1); + } + } +#ifdef FIRI_SDMA_RX + dev_id = MXC_DMA_FIR_RX; + si->rxdma_ch = mxc_dma_request(dev_id, "MXC FIRI RX"); + if (si->rxdma_ch < 0) { + dev_err(si->dev, "Cannot allocate FIR DMA channel\n"); + goto err_rx_dma; + } + mxc_dma_callback_set(si->rxdma_ch, mxc_irda_fir_dma_rx_irq, + (void *)dev_get_drvdata(si->dev)); +#endif +#ifdef FIRI_SDMA_TX + + dev_id = MXC_DMA_FIR_TX; + si->txdma_ch = mxc_dma_request(dev_id, "MXC FIRI TX"); + if (si->txdma_ch < 0) { + dev_err(si->dev, "Cannot allocate FIR DMA channel\n"); + goto err_tx_dma; + } + mxc_dma_callback_set(si->txdma_ch, mxc_irda_fir_dma_tx_irq, + (void *)dev_get_drvdata(si->dev)); +#endif + /* Setup the serial port port for the initial speed. */ + err = mxc_irda_startup(si); + if (err) { + goto err_startup; + } + + /* Open a new IrLAP layer instance. */ + si->irlap = irlap_open(dev, &si->qos, "mxc"); + err = -ENOMEM; + if (!si->irlap) { + goto err_irlap; + } + + /* Now enable the interrupt and start the queue */ + si->open = 1; + si->suspend = 0; + + if (si->uart_irq == si->firi_irq) { + enable_irq(si->uart_irq); + } else { + enable_irq(si->firi_irq); + if (ints_muxed == 1) { + enable_irq(si->uart_irq); + } else { + enable_irq(si->uart_irq); + enable_irq(si->uart_irq1); + } + } + + netif_start_queue(dev); + return 0; + + err_irlap: + si->open = 0; + mxc_irda_disabledma(si); + err_startup: +#ifdef FIRI_SDMA_TX + mxc_dma_free(si->txdma_ch); + err_tx_dma: +#endif +#ifdef FIRI_SDMA_RX + mxc_dma_free(si->rxdma_ch); + err_rx_dma: +#endif + if (si->uart_irq1 && !ints_muxed) + free_irq(si->uart_irq1, dev); + err_irq2: + if (si->uart_irq != si->firi_irq) + free_irq(si->uart_irq, dev); + err_irq1: + if (si->firi_irq) + free_irq(si->firi_irq, dev); + return err; +} + +/*! + * This function is called when IFF_UP flag has been cleared by the user via + * the ifconfig irda0 down command. This function stops any further + * transmissions being queued, and then disables the interrupts. + * Finally it resets the device. + * @param dev the net_device structure + * + * @return int the function always returns 0 indicating a success. + */ +static int mxc_irda_stop(struct net_device *dev) +{ + struct mxc_irda *si = netdev_priv(dev); + unsigned long flags; + + /* Stop IrLAP */ + if (si->irlap) { + irlap_close(si->irlap); + si->irlap = NULL; + } + + netif_stop_queue(dev); + + /*Save flags and disable the FIRI interrupts.. */ + if (si->open) { + local_irq_save(flags); + disable_irq(si->uart_irq); + free_irq(si->uart_irq, dev); + if (si->uart_irq != si->firi_irq) { + disable_irq(si->firi_irq); + free_irq(si->firi_irq, dev); + if (si->uart_irq1 != si->uart_irq) { + disable_irq(si->uart_irq1); + free_irq(si->uart_irq1, dev); + } + } + local_irq_restore(flags); + si->open = 0; + } +#ifdef FIRI_SDMA_RX + if (si->rxdma_ch) { + mxc_dma_disable(si->rxdma_ch); + mxc_dma_free(si->rxdma_ch); + if (si->dma_rx_buff_phy) { + dma_unmap_single(si->dev, si->dma_rx_buff_phy, + IRDA_FRAME_SIZE_LIMIT, + DMA_FROM_DEVICE); + si->dma_rx_buff_phy = 0; + } + si->rxdma_ch = 0; + } + tasklet_kill(&dma_rx_tasklet); +#endif +#ifdef FIRI_SDMA_TX + if (si->txdma_ch) { + mxc_dma_disable(si->txdma_ch); + mxc_dma_free(si->txdma_ch); + if (si->dma_tx_buff_phy) { + dma_unmap_single(si->dev, si->dma_tx_buff_phy, + si->dma_tx_buff_len, DMA_TO_DEVICE); + si->dma_tx_buff_phy = 0; + } + si->txdma_ch = 0; + } +#endif + return 0; +} + +#ifdef CONFIG_PM +/*! + * This function is called to put the FIRI in a low power state. Refer to the + * document driver-model/driver.txt in the kernel source tree for more + * information. + * + * @param pdev the device structure used to give information on which FIRI + * to suspend + * @param state the power state the device is entering + * + * @return The function always returns 0. + */ +static int mxc_irda_suspend(struct platform_device *pdev, pm_message_t state) +{ + struct net_device *ndev = platform_get_drvdata(pdev); + struct mxc_irda *si = netdev_priv(ndev); + unsigned int cr; + unsigned long flags; + + if (!si) { + return 0; + } + if (si->suspend == 1) { + dev_err(si->dev, + " suspend - Device is already suspended ... \n"); + return 0; + } + if (si->open) { + + netif_device_detach(ndev); + mxc_irda_disabledma(si); + + /*Save flags and disable the FIRI interrupts.. */ + local_irq_save(flags); + disable_irq(si->uart_irq); + if (si->uart_irq != si->firi_irq) { + disable_irq(si->firi_irq); + if (si->uart_irq != si->uart_irq1) { + disable_irq(si->uart_irq1); + } + } + local_irq_restore(flags); + + /* Disable Tx and Rx and then disable the UART clock */ + cr = readl(si->uart_base + MXC_UARTUCR2); + cr &= ~(MXC_UARTUCR2_TXEN | MXC_UARTUCR2_RXEN); + writel(cr, si->uart_base + MXC_UARTUCR2); + cr = readl(si->uart_base + MXC_UARTUCR1); + cr &= ~MXC_UARTUCR1_UARTEN; + writel(cr, si->uart_base + MXC_UARTUCR1); + clk_disable(si->uart_clk); + + /*Disable Tx and Rx for FIRI and then disable the FIRI clock.. */ + cr = readl(si->firi_base + FIRITCR); + cr &= ~FIRITCR_TE; + writel(cr, si->firi_base + FIRITCR); + cr = readl(si->firi_base + FIRIRCR); + cr &= ~FIRIRCR_RE; + writel(cr, si->firi_base + FIRIRCR); + clk_disable(si->firi_clk); + + gpio_firi_inactive(); + + si->suspend = 1; + si->open = 0; + } + return 0; +} + +/*! + * This function is called to bring the FIRI back from a low power state. Refer + * to the document driver-model/driver.txt in the kernel source tree for more + * information. + * + * @param pdev the device structure used to give information on which FIRI + * to resume + * + * @return The function always returns 0. + */ +static int mxc_irda_resume(struct platform_device *pdev) +{ + struct net_device *ndev = platform_get_drvdata(pdev); + struct mxc_irda *si = netdev_priv(ndev); + unsigned long flags; + + if (!si) { + return 0; + } + + if (si->suspend == 1 && !si->open) { + + /*Initialise the UART first */ + clk_enable(si->uart_clk); + + /*Now init FIRI */ + gpio_firi_active(si->firi_base + FIRITCR, FIRITCR_TPP); + mxc_irda_startup(si); + + /* Enable the UART and FIRI interrupts.. */ + local_irq_save(flags); + enable_irq(si->uart_irq); + if (si->uart_irq != si->firi_irq) { + enable_irq(si->firi_irq); + if (si->uart_irq != si->uart_irq1) { + enable_irq(si->uart_irq1); + } + } + local_irq_restore(flags); + + /* Let the kernel know that we are alive and kicking.. */ + netif_device_attach(ndev); + + si->suspend = 0; + si->open = 1; + } + return 0; +} +#else +#define mxc_irda_suspend NULL +#define mxc_irda_resume NULL +#endif + +static int mxc_irda_init_iobuf(iobuff_t *io, int size) +{ + io->head = kmalloc(size, GFP_KERNEL | GFP_DMA); + if (io->head != NULL) { + io->truesize = size; + io->in_frame = FALSE; + io->state = OUTSIDE_FRAME; + io->data = io->head; + } + return io->head ? 0 : -ENOMEM; + +} + +static struct net_device_ops mxc_irda_ops = { + .ndo_start_xmit = mxc_irda_hard_xmit, + .ndo_open = mxc_irda_start, + .ndo_stop = mxc_irda_stop, + .ndo_do_ioctl = mxc_irda_ioctl, + .ndo_get_stats = mxc_irda_stats, +}; + +/*! + * This function is called during the driver binding process. + * This function requests for memory, initializes net_device structure and + * registers with kernel. + * + * @param pdev the device structure used to store device specific + * information that is used by the suspend, resume and remove + * functions + * + * @return The function returns 0 on success and a non-zero value on failure + */ +static int mxc_irda_probe(struct platform_device *pdev) +{ + struct net_device *dev; + struct mxc_irda *si; + struct resource *uart_res, *firi_res; + int uart_irq, firi_irq, uart_irq1; + unsigned int baudrate_mask = 0; + int err; + + uart_res = &pdev->resource[0]; + uart_irq = pdev->resource[1].start; + + firi_res = &pdev->resource[2]; + firi_irq = pdev->resource[3].start; + + uart_irq1 = pdev->resource[4].start; + + if (!uart_res || uart_irq == NO_IRQ || !firi_res || firi_irq == NO_IRQ) { + dev_err(&pdev->dev, "Unable to find resources\n"); + return -ENXIO; + } + + err = + request_mem_region(uart_res->start, SZ_16K, + "MXC_IRDA") ? 0 : -EBUSY; + if (err) { + dev_err(&pdev->dev, "Failed to request UART memory region\n"); + return -ENOMEM; + } + + err = + request_mem_region(firi_res->start, SZ_16K, + "MXC_IRDA") ? 0 : -EBUSY; + if (err) { + dev_err(&pdev->dev, "Failed to request FIRI memory region\n"); + goto err_mem_1; + } + + dev = alloc_irdadev(sizeof(struct mxc_irda)); + if (!dev) { + goto err_mem_2; + } + + si = netdev_priv(dev); + si->dev = &pdev->dev; + + si->mxc_ir_plat = pdev->dev.platform_data; + si->uart_clk = si->mxc_ir_plat->uart_clk; + + si->uart_res = uart_res; + si->firi_res = firi_res; + si->uart_irq = uart_irq; + si->firi_irq = firi_irq; + si->uart_irq1 = uart_irq1; + + si->uart_base = ioremap(uart_res->start, SZ_16K); + si->firi_base = ioremap(firi_res->start, SZ_16K); + + if (!(si->uart_base || si->firi_base)) { + err = -ENOMEM; + goto err_mem_3; + } + + /* + * Initialise the SIR buffers + */ + err = mxc_irda_init_iobuf(&si->rx_buff, UART_BUFF_SIZE); + if (err) { + goto err_mem_4; + } + + err = mxc_irda_init_iobuf(&si->tx_buff, UART_BUFF_SIZE); + if (err) { + goto err_mem_5; + } + + dev->netdev_ops = &mxc_irda_ops; + + irda_init_max_qos_capabilies(&si->qos); + + /* + * We support + * SIR(9600, 19200,38400, 57600 and 115200 bps) + * FIR(4 Mbps) + * Min Turn Time set to 1ms or greater. + */ + baudrate_mask |= IR_9600 | IR_19200 | IR_38400 | IR_57600 | IR_115200; + baudrate_mask |= IR_4000000 << 8; + + si->qos.baud_rate.bits &= baudrate_mask; + si->qos.min_turn_time.bits = 0x7; + + irda_qos_bits_to_value(&si->qos); + +#ifdef FIRI_SDMA_RX + si->tskb = NULL; + tasklet_init(&dma_rx_tasklet, mxc_irda_rx_task, (unsigned long)si); +#endif + err = register_netdev(dev); + if (err == 0) { + platform_set_drvdata(pdev, dev); + } else { + kfree(si->tx_buff.head); + err_mem_5: + kfree(si->rx_buff.head); + err_mem_4: + iounmap(si->uart_base); + iounmap(si->firi_base); + err_mem_3: + free_netdev(dev); + err_mem_2: + release_mem_region(firi_res->start, SZ_16K); + err_mem_1: + release_mem_region(uart_res->start, SZ_16K); + } + return err; +} + +/*! + * Dissociates the driver from the FIRI device. Removes the appropriate FIRI + * port structure from the kernel. + * + * @param pdev the device structure used to give information on which FIRI + * to remove + * + * @return The function always returns 0. + */ +static int mxc_irda_remove(struct platform_device *pdev) +{ + struct net_device *dev = platform_get_drvdata(pdev); + struct mxc_irda *si = netdev_priv(dev); + + if (si->uart_base) + iounmap(si->uart_base); + if (si->firi_base) + iounmap(si->firi_base); + if (si->firi_res->start) + release_mem_region(si->firi_res->start, SZ_16K); + if (si->uart_res->start) + release_mem_region(si->uart_res->start, SZ_16K); + if (si->tx_buff.head) + kfree(si->tx_buff.head); + if (si->rx_buff.head) + kfree(si->rx_buff.head); + + platform_set_drvdata(pdev, NULL); + unregister_netdev(dev); + free_netdev(dev); + + return 0; +} + +/*! + * This structure contains pointers to the power management callback functions. + */ +static struct platform_driver mxcir_driver = { + .driver = { + .name = "mxcir", + }, + .probe = mxc_irda_probe, + .remove = mxc_irda_remove, + .suspend = mxc_irda_suspend, + .resume = mxc_irda_resume, +}; + +/*! + * This function is used to initialize the FIRI driver module. The function + * registers the power management callback functions with the kernel and also + * registers the FIRI callback functions. + * + * @return The function returns 0 on success and a non-zero value on failure. + */ +static int __init mxc_irda_init(void) +{ + return platform_driver_register(&mxcir_driver); +} + +/*! + * This function is used to cleanup all resources before the driver exits. + */ +static void __exit mxc_irda_exit(void) +{ + platform_driver_unregister(&mxcir_driver); +} + +module_init(mxc_irda_init); +module_exit(mxc_irda_exit); + +MODULE_AUTHOR("Freescale Semiconductor"); +MODULE_DESCRIPTION("MXC IrDA(SIR/FIR) driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/net/irda/mxc_ir.h b/drivers/net/irda/mxc_ir.h new file mode 100644 index 000000000000..601731029024 --- /dev/null +++ b/drivers/net/irda/mxc_ir.h @@ -0,0 +1,131 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#ifndef __MXC_FIRI_REG_H__ +#define __MXC_FIRI_REG_H__ + +/*! + * @defgroup FIRI Fast IR Driver + */ + +/*! + * @file mxc_ir.h + * + * @brief MXC FIRI header file + * + * This file defines base address and bits of FIRI registers + * + * @ingroup FIRI + */ + +/*! + * FIRI maximum packet length + */ +#define FIR_MAX_RXLEN 2047 + +/* + * FIRI Transmitter Control Register + */ +#define FIRITCR 0x00 +/* + * FIRI Transmitter Count Register + */ +#define FIRITCTR 0x04 +/* + * FIRI Receiver Control Register + */ +#define FIRIRCR 0x08 +/* + * FIRI Transmitter Status Register + */ +#define FIRITSR 0x0C +/* + * FIRI Receiver Status Register + */ +#define FIRIRSR 0x10 +/* + * FIRI Transmitter FIFO + */ +#define FIRITXFIFO 0x14 +/* + * FIRI Receiver FIFO + */ +#define FIRIRXFIFO 0x18 +/* + * FIRI Control Register + */ +#define FIRICR 0x1C + +/* + * Bit definitions of Transmitter Controller Register + */ +#define FIRITCR_HAG (1<<24) /* H/W address generator */ +#define FIRITCR_SRF_FIR (0<<13) /* Start field repeat factor */ +#define FIRITCR_SRF_MIR (1<<13) /* Start field Repeat Factor */ +#define FIRITCR_TDT_MIR (2<<10) /* TX trigger for MIR is set to 32 bytes) */ +#define FIRITCR_TDT_FIR (1<<10) /* TX trigger for FIR is set to 16 bytes) */ +#define FIRITCR_TCIE (1<<9) /* TX Complete Interrupt Enable */ +#define FIRITCR_TPEIE (1<<8) /* TX Packet End Interrupt Enable */ +#define FIRITCR_TFUIE (1<<7) /* TX FIFO Under-run Interrupt Enable */ +#define FIRITCR_PCF (1<<6) /* Packet Complete by FIFO */ +#define FIRITCR_PC (1<<5) /* Packet Complete */ +#define FIRITCR_SIP (1<<4) /* TX Enable of SIP */ +#define FIRITCR_TPP (1<<3) /* TX Pulse Polarity bit */ +#define FIRITCR_TM_FIR (0<<1) /* TX Mode 4 Mbps */ +#define FIRITCR_TM_MIR1 (1<<1) /* TX Mode 0.576 Mbps */ +#define FIRITCR_TM_MIR2 (1<<2) /* TX Mode 1.152 Mbps */ +#define FIRITCR_TE (1<<0) /* TX Enable */ + +/* + * Bit definitions of Transmitter Count Register + */ +#define FIRITCTR_TPL 511 /* TX Packet Length set to 512 bytes */ + +/* + * Bit definitions of Receiver Control Register + */ +#define FIRIRCR_RAM (1<<24) /* RX Address Match */ +#define FIRIRCR_RPEDE (1<<11) /* Packet End DMA request Enable */ +#define FIRIRCR_RDT_MIR (2<<8) /* DMA Trigger level(64 bytes in RXFIFO) */ +#define FIRIRCR_RDT_FIR (1<<8) /* DMA Trigger level(16 bytes in RXFIFO) */ +#define FIRIRCR_RPA (1<<7) /* RX Packet Abort */ +#define FIRIRCR_RPEIE (1<<6) /* RX Packet End Interrupt Enable */ +#define FIRIRCR_PAIE (1<<5) /* Packet Abort Interrupt Enable */ +#define FIRIRCR_RFOIE (1<<4) /* RX FIFO Overrun Interrupt Enable */ +#define FIRIRCR_RPP (1<<3) /* RX Pulse Polarity bit */ +#define FIRIRCR_RM_FIR (0<<1) /* 4 Mbps */ +#define FIRIRCR_RM_MIR1 (1<<1) /* 0.576 Mbps */ +#define FIRIRCR_RM_MIR2 (1<<2) /* 1.152 Mbps */ +#define FIRIRCR_RE (1<<0) /* RX Enable */ + +/* Transmitter Status Register */ +#define FIRITSR_TFP 0xFF00 /* Mask for available bytes in TX FIFO */ +#define FIRITSR_TC (1<<3) /* Transmit Complete bit */ +#define FIRITSR_SIPE (1<<2) /* SIP End bit */ +#define FIRITSR_TPE (1<<1) /* Transmit Packet End */ +#define FIRITSR_TFU (1<<0) /* TX FIFO Under-run */ + +/* Receiver Status Register */ +#define FIRIRSR_RFP 0xFF00 /* mask for available bytes RX FIFO */ +#define FIRIRSR_PAS (1<<5) /* preamble search */ +#define FIRIRSR_RPE (1<<4) /* RX Packet End */ +#define FIRIRSR_RFO (1<<3) /* RX FIFO Overrun */ +#define FIRIRSR_BAM (1<<2) /* Broadcast Address Match */ +#define FIRIRSR_CRCE (1<<1) /* CRC error */ +#define FIRIRSR_DDE (1<<0) /* Address, control or data field error */ + +/* FIRI Control Register */ +#define FIRICR_BL (32<<5) /* Burst Length is set to 32 */ +#define FIRICR_OSF (0<<1) /* Over Sampling Factor */ + +#endif /* __MXC_FIRI_REG_H__ */ diff --git a/drivers/pcmcia/Kconfig b/drivers/pcmcia/Kconfig index d0f5ad306078..d41e74acf785 100644 --- a/drivers/pcmcia/Kconfig +++ b/drivers/pcmcia/Kconfig @@ -290,6 +290,14 @@ config AT91_CF Say Y here to support the CompactFlash controller on AT91 chips. Or choose M to compile the driver as a module named "at91_cf". +config PCMCIA_MX31ADS + tristate "MX31ADS PCMCIA support" + depends on ARM && MACH_MX31ADS && PCMCIA + help + Say Y here to include support for the Freescale i.MX31 PCMCIA controller. + + This driver is also available as a module called mx31ads_pcmcia. + config ELECTRA_CF tristate "Electra CompactFlash Controller" depends on PCMCIA && PPC_PASEMI diff --git a/drivers/pcmcia/Makefile b/drivers/pcmcia/Makefile index d006e8beab9c..2eebf736d600 100644 --- a/drivers/pcmcia/Makefile +++ b/drivers/pcmcia/Makefile @@ -39,6 +39,7 @@ obj-$(CONFIG_BFIN_CFPCMCIA) += bfin_cf_pcmcia.o obj-$(CONFIG_AT91_CF) += at91_cf.o obj-$(CONFIG_ELECTRA_CF) += electra_cf.o obj-$(CONFIG_PCMCIA_ALCHEMY_DEVBOARD) += db1xxx_ss.o +obj-$(CONFIG_PCMCIA_MX31ADS) += mx31ads-pcmcia.o au1x00_ss-y += au1000_generic.o au1x00_ss-$(CONFIG_MIPS_PB1000) += au1000_pb1x00.o diff --git a/drivers/pcmcia/mx31ads-pcmcia.c b/drivers/pcmcia/mx31ads-pcmcia.c new file mode 100644 index 000000000000..1f7c8ec2c7e0 --- /dev/null +++ b/drivers/pcmcia/mx31ads-pcmcia.c @@ -0,0 +1,1293 @@ +/*====================================================================== + drivers/pcmcia/mx31ads-pcmica.c + + Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + + Device driver for the PCMCIA control functionality of i.Mx31 + microprocessors. + + The contents of this file are subject to the Mozilla Public + License Version 1.1 (the "License"); you may not use this file + except in compliance with the License. You may obtain a copy of + the License at http://www.mozilla.org/MPL/ + + Software distributed under the License is distributed on an "AS + IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or + implied. See the License for the specific language governing + rights and limitations under the License. + + The initial developer of the original code is John G. Dorsey + . Portions created by John G. Dorsey are + Copyright (C) 1999 John G. Dorsey. All Rights Reserved. + + Alternatively, the contents of this file may be used under the + terms of the GNU Public License version 2 (the "GPL"), in which + case the provisions of the GPL are applicable instead of the + above. If you wish to allow the use of your version of this file + only under the terms of the GPL and not to allow others to use + your version of this file under the MPL, indicate your decision + by deleting the provisions above and replace them with the notice + and other provisions required by the GPL. If you do not delete + the provisions above, a recipient may use your version of this + file under either the MPL or the GPL. + +======================================================================*/ + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "mx31ads-pcmcia.h" +#include + +#define MX31ADS_PCMCIA_IRQ MXC_INT_PCMCIA + +/* + * The mapping of window size to bank size value + */ +static bsize_map_t bsize_map[] = { + /* Window size Bank size */ + {POR_1, POR_BSIZE_1}, + {POR_2, POR_BSIZE_2}, + {POR_4, POR_BSIZE_4}, + {POR_8, POR_BSIZE_8}, + {POR_16, POR_BSIZE_16}, + {POR_32, POR_BSIZE_32}, + {POR_64, POR_BSIZE_64}, + {POR_128, POR_BSIZE_128}, + {POR_256, POR_BSIZE_256}, + {POR_512, POR_BSIZE_512}, + + {POR_1K, POR_BSIZE_1K}, + {POR_2K, POR_BSIZE_2K}, + {POR_4K, POR_BSIZE_4K}, + {POR_8K, POR_BSIZE_8K}, + {POR_16K, POR_BSIZE_16K}, + {POR_32K, POR_BSIZE_32K}, + {POR_64K, POR_BSIZE_64K}, + {POR_128K, POR_BSIZE_128K}, + {POR_256K, POR_BSIZE_256K}, + {POR_512K, POR_BSIZE_512K}, + + {POR_1M, POR_BSIZE_1M}, + {POR_2M, POR_BSIZE_2M}, + {POR_4M, POR_BSIZE_4M}, + {POR_8M, POR_BSIZE_8M}, + {POR_16M, POR_BSIZE_16M}, + {POR_32M, POR_BSIZE_32M}, + {POR_64M, POR_BSIZE_64M} +}; + +#define to_mx31ads_pcmcia_socket(x) container_of(x, struct mx31ads_pcmcia_socket, socket) + +/* mx31ads_pcmcia_find_bsize() + * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + * + * Find the bsize according to the window size passed in + * + * Return: + */ +static int mx31ads_pcmcia_find_bsize(unsigned long win_size) +{ + int i, nr = sizeof(bsize_map) / sizeof(bsize_map_t); + int bsize = -1; + + for (i = 0; i < nr; i++) { + if (bsize_map[i].win_size == win_size) { + bsize = bsize_map[i].bsize; + break; + } + } + + pr_debug(KERN_INFO "nr = %d bsize = 0x%0x\n", nr, bsize); + if (bsize < 0 || i > nr) { + pr_debug(KERN_INFO "No such bsize\n"); + return -ENODEV; + } + + return bsize; +} + +/* mx31ads_common_pcmcia_sock_init() + * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + * + * (Re-)Initialise the socket, turning on status interrupts + * and PCMCIA bus. This must wait for power to stabilise + * so that the card status signals report correctly. + * + * Returns: 0 + */ +static int mx31ads_common_pcmcia_sock_init(struct pcmcia_socket *sock) +{ + struct mx31ads_pcmcia_socket *skt = to_mx31ads_pcmcia_socket(sock); + + pr_debug(KERN_INFO "initializing socket\n"); + + skt->ops->socket_init(skt); + return 0; +} + +/* + * mx31ads_common_pcmcia_config_skt + * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + * + * Convert PCMCIA socket state to our socket configure structure. + */ +static int +mx31ads_common_pcmcia_config_skt(struct mx31ads_pcmcia_socket *skt, + socket_state_t *state) +{ + int ret; + + ret = skt->ops->configure_socket(skt, state); + if (ret == 0) { + /* + * This really needs a better solution. The IRQ + * may or may not be claimed by the driver. + */ + if (skt->irq_state != 1 && state->io_irq) { + skt->irq_state = 1; + set_irq_type(skt->irq, IRQF_TRIGGER_FALLING); + } else if (skt->irq_state == 1 && state->io_irq == 0) { + skt->irq_state = 0; + set_irq_type(skt->irq, IRQF_TRIGGER_RISING); + } + + skt->cs_state = *state; + } + + if (ret < 0) + pr_debug(KERN_ERR "mx31ads_common_pcmcia: unable to configure" + " socket\n"); + + return ret; +} + +/* + * mx31ads_common_pcmcia_suspend() + * ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + * + * Remove power on the socket, disable IRQs from the card. + * Turn off status interrupts, and disable the PCMCIA bus. + * + * Returns: 0 + */ +static int mx31ads_common_pcmcia_suspend(struct pcmcia_socket *sock) +{ + struct mx31ads_pcmcia_socket *skt = to_mx31ads_pcmcia_socket(sock); + int ret; + + pr_debug(KERN_INFO "suspending socket\n"); + + ret = mx31ads_common_pcmcia_config_skt(skt, &dead_socket); + if (ret == 0) + skt->ops->socket_suspend(skt); + + return ret; +} + +static unsigned int mx31ads_common_pcmcia_skt_state(struct mx31ads_pcmcia_socket + *skt) +{ + struct pcmcia_state state; + unsigned int stat; + + memset(&state, 0, sizeof(struct pcmcia_state)); + + skt->ops->socket_state(skt, &state); + + stat = state.detect ? SS_DETECT : 0; + stat |= state.ready ? SS_READY : 0; + stat |= state.wrprot ? SS_WRPROT : 0; + stat |= state.vs_3v ? SS_3VCARD : 0; + stat |= state.vs_Xv ? SS_XVCARD : 0; + + /* The power status of individual sockets is not available + * explicitly from the hardware, so we just remember the state + * and regurgitate it upon request: + */ + stat |= skt->cs_state.Vcc ? SS_POWERON : 0; + + if (skt->cs_state.flags & SS_IOCARD) + stat |= state.bvd1 ? SS_STSCHG : 0; + else { + if (state.bvd1 == 0) + stat |= SS_BATDEAD; + else if (state.bvd2 == 0) + stat |= SS_BATWARN; + } + + pr_debug(KERN_INFO "stat = 0x%08x\n", stat); + + return stat; +} + +/* + * Implements the get_status() operation for the in-kernel PCMCIA + * service (formerly SS_GetStatus in Card Services). Essentially just + * fills in bits in `status' according to internal driver state or + * the value of the voltage detect chipselect register. + * + * As a debugging note, during card startup, the PCMCIA core issues + * three set_socket() commands in a row the first with RESET deasserted, + * the second with RESET asserted, and the last with RESET deasserted + * again. Following the third set_socket(), a get_status() command will + * be issued. The kernel is looking for the SS_READY flag (see + * setup_socket(), reset_socket(), and unreset_socket() in cs.c). + * + * Returns: 0 + */ +static int mx31ads_common_pcmcia_get_status(struct pcmcia_socket *sock, + unsigned int *status) +{ + struct mx31ads_pcmcia_socket *skt = to_mx31ads_pcmcia_socket(sock); + + skt->status = mx31ads_common_pcmcia_skt_state(skt); + *status = skt->status; + + return 0; +} + +/* + * Implements the set_socket() operation for the in-kernel PCMCIA + * service (formerly SS_SetSocket in Card Services). We more or + * less punt all of this work and let the kernel handle the details + * of power configuration, reset, &c. We also record the value of + * `state' in order to regurgitate it to the PCMCIA core later. + * + * Returns: 0 + */ +static int mx31ads_common_pcmcia_set_socket(struct pcmcia_socket *sock, + socket_state_t *state) +{ + struct mx31ads_pcmcia_socket *skt = to_mx31ads_pcmcia_socket(sock); + + pr_debug(KERN_INFO + "mask: %s%s%s%s%s%sflags: %s%s%s%s%s%sVcc %d Vpp %d irq %d\n", + (state->csc_mask == 0) ? " " : "", + (state->csc_mask & SS_DETECT) ? "DETECT " : "", + (state->csc_mask & SS_READY) ? "READY " : "", + (state->csc_mask & SS_BATDEAD) ? "BATDEAD " : "", + (state->csc_mask & SS_BATWARN) ? "BATWARN " : "", + (state->csc_mask & SS_STSCHG) ? "STSCHG " : "", + (state->flags == 0) ? " " : "", + (state->flags & SS_PWR_AUTO) ? "PWR_AUTO " : "", + (state->flags & SS_IOCARD) ? "IOCARD " : "", + (state->flags & SS_RESET) ? "RESET " : "", + (state->flags & SS_SPKR_ENA) ? "SPKR_ENA " : "", + (state->flags & SS_OUTPUT_ENA) ? "OUTPUT_ENA " : "", + state->Vcc, state->Vpp, state->io_irq); + + pr_debug(KERN_INFO + "csc_mask: %08x flags: %08x Vcc: %d Vpp: %d io_irq: %d\n", + state->csc_mask, state->flags, state->Vcc, state->Vpp, + state->io_irq); + + return mx31ads_common_pcmcia_config_skt(skt, state); +} + +/* + * Set address and profile to window registers PBR, POR, POFR + */ +static int mx31ads_pcmcia_set_window_reg(ulong start, ulong end, u_int window) +{ + int bsize; + ulong size = end - start + 1; + + bsize = mx31ads_pcmcia_find_bsize(size); + if (bsize < 0) { + pr_debug("Cannot set the window register\n"); + return -1; + } + /* Disable the window */ + _reg_PCMCIA_POR(window) &= ~PCMCIA_POR_PV; + + /* Set PBR, POR, POFR */ + _reg_PCMCIA_PBR(window) = start; + _reg_PCMCIA_POR(window) &= ~(PCMCIA_POR_PRS_MASK + | PCMCIA_POR_WPEN + | PCMCIA_POR_WP + | PCMCIA_POR_BSIZE_MASK + | PCMCIA_POR_PPS_8); + _reg_PCMCIA_POR(window) |= bsize | PCMCIA_POR_PPS_16; + + switch (window) { + case IO_WINDOW: + _reg_PCMCIA_POR(window) |= PCMCIA_POR_PRS(PCMCIA_POR_PRS_IO); + break; + + case ATTRIBUTE_MEMORY_WINDOW: + _reg_PCMCIA_POR(window) |= + PCMCIA_POR_PRS(PCMCIA_POR_PRS_ATTRIBUTE); + break; + + case COMMON_MEMORY_WINDOW: + _reg_PCMCIA_POR(window) |= + PCMCIA_POR_PRS(PCMCIA_POR_PRS_COMMON); + break; + + default: + pr_debug("Window %d is not support\n", window); + return -1; + } + _reg_PCMCIA_POFR(window) = 0; + + /* Enable the window */ + _reg_PCMCIA_POR(window) |= PCMCIA_POR_PV; + + return 0; +} + +/* + * Implements the set_io_map() operation for the in-kernel PCMCIA + * service (formerly SS_SetIOMap in Card Services). We configure + * the map speed as requested, but override the address ranges + * supplied by Card Services. + * + * Returns: 0 on success, -1 on error + */ +static int +mx31ads_common_pcmcia_set_io_map(struct pcmcia_socket *sock, + struct pccard_io_map *map) +{ + struct mx31ads_pcmcia_socket *skt = to_mx31ads_pcmcia_socket(sock); + unsigned short speed = map->speed; + + pr_debug("map %u speed %u start 0x%08x stop 0x%08x\n", + map->map, map->speed, map->start, map->stop); + pr_debug("flags: %s%s%s%s%s%s%s%s\n", + (map->flags == 0) ? "" : "", + (map->flags & MAP_ACTIVE) ? "ACTIVE " : "", + (map->flags & MAP_16BIT) ? "16BIT " : "", + (map->flags & MAP_AUTOSZ) ? "AUTOSZ " : "", + (map->flags & MAP_0WS) ? "0WS " : "", + (map->flags & MAP_WRPROT) ? "WRPROT " : "", + (map->flags & MAP_USE_WAIT) ? "USE_WAIT " : "", + (map->flags & MAP_PREFETCH) ? "PREFETCH " : ""); + + if (map->map >= MAX_IO_WIN) { + pr_debug(KERN_ERR "%s(): map (%d) out of range\n", __FUNCTION__, + map->map); + return -1; + } + + if (map->flags & MAP_ACTIVE) { + if (speed == 0) + speed = PCMCIA_IO_ACCESS; + } else { + speed = 0; + } + + skt->spd_io[map->map] = speed; + skt->ops->set_timing(skt); + + if (map->stop == 1) + map->stop = PAGE_SIZE - 1; + + skt->socket.io_offset = (unsigned long)skt->virt_io; + map->stop -= map->start; + map->stop += (unsigned long)skt->virt_io; + map->start = (unsigned long)skt->virt_io; + + mx31ads_pcmcia_set_window_reg(skt->res_io.start, skt->res_io.end, + IO_WINDOW); + + pr_debug(KERN_ERR "IO window: _reg_PCMCIA_PBR(%d) = %08x\n", + IO_WINDOW, _reg_PCMCIA_PBR(IO_WINDOW)); + pr_debug(KERN_ERR "IO window: _reg_PCMCIA_POR(%d) = %08x\n", + IO_WINDOW, _reg_PCMCIA_POR(IO_WINDOW)); + + return 0; +} + +/* + * Implements the set_mem_map() operation for the in-kernel PCMCIA + * service (formerly SS_SetMemMap in Card Services). We configure + * the map speed as requested, but override the address ranges + * supplied by Card Services. + * + * Returns: 0 on success, -1 on error + */ +static int +mx31ads_common_pcmcia_set_mem_map(struct pcmcia_socket *sock, + struct pccard_mem_map *map) +{ + struct mx31ads_pcmcia_socket *skt = to_mx31ads_pcmcia_socket(sock); + struct resource *res; + unsigned short speed = map->speed; + + pr_debug + (KERN_INFO + "map %u speed %u card_start %08x flags%08x static_start %08lx\n", + map->map, map->speed, map->card_start, map->flags, + map->static_start); + pr_debug(KERN_INFO "flags: %s%s%s%s%s%s%s%s\n", + (map->flags == 0) ? "" : "", + (map->flags & MAP_ACTIVE) ? "ACTIVE " : "", + (map->flags & MAP_16BIT) ? "16BIT " : "", + (map->flags & MAP_AUTOSZ) ? "AUTOSZ " : "", + (map->flags & MAP_0WS) ? "0WS " : "", + (map->flags & MAP_WRPROT) ? "WRPROT " : "", + (map->flags & MAP_ATTRIB) ? "ATTRIB " : "", + (map->flags & MAP_USE_WAIT) ? "USE_WAIT " : ""); + + if (map->map >= MAX_WIN) + return -EINVAL; + + if (map->flags & MAP_ACTIVE) { + if (speed == 0) + speed = 300; + } else { + speed = 0; + } + + if (map->flags & MAP_ATTRIB) { + res = &skt->res_attr; + skt->spd_attr[map->map] = speed; + skt->spd_mem[map->map] = 0; + mx31ads_pcmcia_set_window_reg(res->start, res->end, + ATTRIBUTE_MEMORY_WINDOW); + + pr_debug(KERN_INFO "Attr window: _reg_PCMCIA_PBR(%d) = %08x\n", + ATTRIBUTE_MEMORY_WINDOW, + _reg_PCMCIA_PBR(ATTRIBUTE_MEMORY_WINDOW)); + pr_debug(KERN_INFO "_reg_PCMCIA_POR(%d) = %08x\n", + ATTRIBUTE_MEMORY_WINDOW, + _reg_PCMCIA_POR(ATTRIBUTE_MEMORY_WINDOW)); + + } else { + res = &skt->res_mem; + skt->spd_attr[map->map] = 0; + skt->spd_mem[map->map] = speed; + mx31ads_pcmcia_set_window_reg(res->start, res->end, + COMMON_MEMORY_WINDOW); + + pr_debug(KERN_INFO "Com window: _reg_PCMCIA_PBR(%d) = %08x\n", + COMMON_MEMORY_WINDOW, + _reg_PCMCIA_PBR(COMMON_MEMORY_WINDOW)); + pr_debug(KERN_INFO "Com window: _reg_PCMCIA_POR(%d) = %08x\n", + COMMON_MEMORY_WINDOW, + _reg_PCMCIA_POR(COMMON_MEMORY_WINDOW)); + } + + skt->ops->set_timing(skt); + + map->static_start = res->start + map->card_start; + + return 0; +} + +static struct pccard_operations mx31ads_common_pcmcia_operations = { + .init = mx31ads_common_pcmcia_sock_init, + .suspend = mx31ads_common_pcmcia_suspend, + .get_status = mx31ads_common_pcmcia_get_status, + .set_socket = mx31ads_common_pcmcia_set_socket, + .set_io_map = mx31ads_common_pcmcia_set_io_map, + .set_mem_map = mx31ads_common_pcmcia_set_mem_map, +}; + +/* ============================================================================== */ + +static inline void mx31ads_pcmcia_irq_config(void) +{ + /* Setup irq */ + _reg_PCMCIA_PER = + (PCMCIA_PER_RDYLE | PCMCIA_PER_CDE1 | PCMCIA_PER_CDE2); +} + +static inline void mx31ads_pcmcia_invalidate_windows(void) +{ + int i; + + for (i = 0; i < PCMCIA_WINDOWS; i++) { + _reg_PCMCIA_PBR(i) = 0; + _reg_PCMCIA_POR(i) = 0; + _reg_PCMCIA_POFR(i) = 0; + } +} + +extern void gpio_pcmcia_active(void); +extern void gpio_pcmcia_inactive(void); + +static int mx31ads_pcmcia_hw_init(struct mx31ads_pcmcia_socket *skt) +{ + /* Configure the pins for PCMCIA */ + gpio_pcmcia_active(); + + /* + * enabling interrupts at this time causes a flood of interrupts + * if a card is present, so wait for configure_socket + * to enable them when requested. + * + * mx31ads_pcmcia_irq_config(); + */ + mx31ads_pcmcia_invalidate_windows(); + + /* Register interrupt. */ + skt->irq = MX31ADS_PCMCIA_IRQ; + + return 0; +} + +static void mx31ads_pcmcia_free_irq(struct mx31ads_pcmcia_socket *skt, + unsigned int irq) +{ + free_irq(irq, skt); +} + +static void mx31ads_pcmcia_hw_shutdown(struct mx31ads_pcmcia_socket *skt) +{ + mx31ads_pcmcia_invalidate_windows(); + mx31ads_pcmcia_free_irq(skt, MX31ADS_PCMCIA_IRQ); + + /* Disable the pins */ + gpio_pcmcia_inactive(); +} + +/* + * Get the socket state + */ +static void +mx31ads_pcmcia_socket_state(struct mx31ads_pcmcia_socket *skt, + struct pcmcia_state *state) +{ + unsigned long pins; + + pins = _reg_PCMCIA_PIPR; + pr_debug(KERN_INFO "_reg_PCMCIA_PIPR = 0x%08lx\n", pins); + + state->ready = (pins & PCMCIA_PIPR_RDY) ? 1 : 0; + state->bvd2 = (pins & PCMCIA_PIPR_BVD2) ? 1 : 0; + state->bvd1 = (pins & PCMCIA_PIPR_BVD1) ? 1 : 0; + + if ((pins & PCMCIA_PIPR_CD) == PCMCIA_PIPR_CD) { + state->detect = 0; + skt->cs_state.csc_mask |= SS_INSERTION; + } else { + state->detect = 1; + } + state->detect = (pins & PCMCIA_PIPR_CD) ? 0 : 1; + state->wrprot = (pins & PCMCIA_PIPR_WP) ? 1 : 0; + state->poweron = (pins & PCMCIA_PIPR_POWERON) ? 1 : 0; +#if 0 + if ((pins & PCMCIA_PIPR_CD) == PCMCIA_PIPR_CD) { + state->detect = 0; + skt->cs_state.csc_mask |= SS_INSERTION; + } else { + state->detect = 1; + } + if (pins & PCMCIA_PIPR_VS_5V) { + state->vs_3v = 0; + skt->cs_state.Vcc = 33; + } else { + state->vs_3v = 1; + skt->cs_state.Vcc = 50; + } +#endif + state->vs_3v = (pins & PCMCIA_PIPR_VS_5V) ? 0 : 1; + state->vs_Xv = 0; +} + +static __inline__ void mx31ads_pcmcia_low_power(bool enable) +{ + if (enable) + _reg_PCMCIA_PGCR |= PCMCIA_PGCR_LPMEN; + else + _reg_PCMCIA_PGCR &= ~PCMCIA_PGCR_LPMEN; +} + +static __inline__ void mx31ads_pcmcia_soft_reset(void) +{ + _reg_PCMCIA_PGCR |= PCMCIA_PGCR_RESET; + msleep(2); + + _reg_PCMCIA_PGCR &= ~(PCMCIA_PGCR_RESET | PCMCIA_PGCR_LPMEN); + _reg_PCMCIA_PGCR |= PCMCIA_PGCR_POE; + msleep(2); + pr_debug(KERN_INFO "_reg_PCMCIA_PGCR = %08x\n", _reg_PCMCIA_PGCR); +} + +static int +mx31ads_pcmcia_configure_socket(struct mx31ads_pcmcia_socket *skt, + const socket_state_t *state) +{ + int ret = 0; + + if (state->Vcc != 0 && state->Vcc != 33 && state->Vcc != 50) { + pr_debug(KERN_ERR "mx31ads-pcmcia: unrecognized Vcc %d\n", + state->Vcc); + return -1; + } + + pr_debug(KERN_INFO "PIPR = %x, desired Vcc = %d.%dV\n", + _reg_PCMCIA_PIPR, state->Vcc / 10, state->Vcc % 10); + + if (!(skt->socket.state & SOCKET_PRESENT) && (skt->pre_stat == 1)) { + pr_debug(KERN_INFO "Socket enter low power mode\n"); + skt->pre_stat = 0; + mx31ads_pcmcia_low_power(1); + } + + if (state->flags & SS_RESET) { + mx31ads_pcmcia_soft_reset(); + + /* clean out previous tenant's trash */ + _reg_PCMCIA_PGSR = (PCMCIA_PGSR_NWINE + | PCMCIA_PGSR_LPE + | PCMCIA_PGSR_SE + | PCMCIA_PGSR_CDE | PCMCIA_PGSR_WPE); + } + /* enable interrupts if requested, else turn 'em off */ + if (skt->irq) + mx31ads_pcmcia_irq_config(); + else + _reg_PCMCIA_PER = 0; + + if (skt->socket.state & SOCKET_PRESENT) { + skt->pre_stat = 1; + } + return ret; +} + +static void mx31ads_pcmcia_enable_irq(struct mx31ads_pcmcia_socket *skt, + unsigned int irq) +{ + set_irq_type(irq, IRQF_TRIGGER_RISING); + set_irq_type(irq, IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING); +} + +static void mx31ads_pcmcia_disable_irq(struct mx31ads_pcmcia_socket *skt, + unsigned int irq) +{ + set_irq_type(irq, IRQF_TRIGGER_NONE); +} + +/* + * Enable card status IRQs on (re-)initialisation. This can + * be called at initialisation, power management event, or + * pcmcia event. + */ +static void mx31ads_pcmcia_socket_init(struct mx31ads_pcmcia_socket *skt) +{ + mx31ads_pcmcia_soft_reset(); + + mx31ads_pcmcia_enable_irq(skt, MX31ADS_PCMCIA_IRQ); +} + +/* + * Disable card status IRQ on suspend. + */ +static void mx31ads_pcmcia_socket_suspend(struct mx31ads_pcmcia_socket *skt) +{ + mx31ads_pcmcia_disable_irq(skt, MX31ADS_PCMCIA_IRQ); + mx31ads_pcmcia_low_power(1); +} + +/* ==================================================================================== */ + +/* + * PCMCIA strobe hold time + */ +static inline u_int mx31ads_pcmcia_por_psht(u_int pcmcia_cycle_ns, + u_int hclk_cycle_ns) +{ + u_int psht; + + return psht = pcmcia_cycle_ns / hclk_cycle_ns; +} + +/* + * PCMCIA strobe set up time + */ +static inline u_int mx31ads_pcmcia_por_psst(u_int pcmcia_cycle_ns, + u_int hclk_cycle_ns) +{ + u_int psst; + + return psst = pcmcia_cycle_ns / hclk_cycle_ns; +} + +/* + * PCMCIA strobe length time + */ +static inline u_int mx31ads_pcmcia_por_pslt(u_int pcmcia_cycle_ns, + u_int hclk_cycle_ns) +{ + u_int pslt; + + return pslt = pcmcia_cycle_ns / hclk_cycle_ns + 2; +} + +/* + * mx31ads_pcmcia_default_mecr_timing + * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + * + * Calculate MECR clock wait states for given CPU clock + * speed and command wait state. This function can be over- + * written by a board specific version. + * + * The default is to simply calculate the BS values as specified in + * the INTEL SA1100 development manual + * "Expansion Memory (PCMCIA) Configuration Register (MECR)" + * that's section 10.2.5 in _my_ version of the manual ;) + */ +static unsigned int mx31ads_pcmcia_default_mecr_timing(struct + mx31ads_pcmcia_socket + *skt, + unsigned int cpu_speed, + unsigned int cmd_time) +{ + return 0; +} + +/* + * Calculate the timing code + */ +static u_int mx31ads_pcmcia_cal_code(u_int speed_ns, u_int clk_ns) +{ + u_int code; + + code = PCMCIA_POR_PSHT(mx31ads_pcmcia_por_psht(speed_ns, clk_ns)) + | PCMCIA_POR_PSST(mx31ads_pcmcia_por_psst(speed_ns, clk_ns)) + | PCMCIA_POR_PSL(mx31ads_pcmcia_por_pslt(speed_ns, clk_ns)); + + return code; +} + +/* + * set MECR value for socket based on this sockets + * io, mem and attribute space access speed. + * Call board specific BS value calculation to allow boards + * to tweak the BS values. + */ +static int mx31ads_pcmcia_set_window_timing(u_int speed_ns, u_int window, + u_int clk_ns) +{ + u_int code = 0; + + switch (window) { + case IO_WINDOW: + code = mx31ads_pcmcia_cal_code(speed_ns, clk_ns); + break; + case COMMON_MEMORY_WINDOW: + code = mx31ads_pcmcia_cal_code(speed_ns, clk_ns); + break; + case ATTRIBUTE_MEMORY_WINDOW: + code = mx31ads_pcmcia_cal_code(speed_ns, clk_ns); + break; + default: + break; + } + + /* Disable the window */ + _reg_PCMCIA_POR(window) &= ~PCMCIA_POR_PV; + + /* Clear the register fisrt */ + _reg_PCMCIA_POR(window) &= ~(PCMCIA_POR_PSST_MASK + | PCMCIA_POR_PSL_MASK + | PCMCIA_POR_PSHT_MASK); + /* And then set the register */ + _reg_PCMCIA_POR(window) |= code; + + /* Enable the window */ + _reg_PCMCIA_POR(window) |= PCMCIA_POR_PV; + + return 0; +} + +static unsigned short calc_speed(unsigned short *spds, int num, + unsigned short dflt) +{ + unsigned short speed = 0; + int i; + + for (i = 0; i < num; i++) + if (speed < spds[i]) + speed = spds[i]; + if (speed == 0) + speed = dflt; + + return speed; +} + +static void +mx31ads_common_pcmcia_get_timing(struct mx31ads_pcmcia_socket *skt, + struct mx31ads_pcmcia_timing *timing) +{ + timing->io = calc_speed(skt->spd_io, MAX_IO_WIN, PCMCIA_IO_ACCESS); + timing->mem = calc_speed(skt->spd_mem, MAX_WIN, PCMCIA_3V_MEM_ACCESS); + timing->attr = + calc_speed(skt->spd_attr, MAX_WIN, PCMCIA_ATTR_MEM_ACCESS); +} + +static int mx31ads_pcmcia_set_timing(struct mx31ads_pcmcia_socket *skt) +{ + u_int clk_ns; + struct mx31ads_pcmcia_timing timing; + + /* How many nanoseconds */ + clk_ns = (1000 * 1000 * 1000) / clk_get_rate(skt->clk); + pr_debug(KERN_INFO "clk_ns = %d\n", clk_ns); + + mx31ads_common_pcmcia_get_timing(skt, &timing); + pr_debug(KERN_INFO "timing: io %d, mem %d, attr %d\n", timing.io, + timing.mem, timing.attr); + + mx31ads_pcmcia_set_window_timing(timing.io, IO_WINDOW, clk_ns); + mx31ads_pcmcia_set_window_timing(timing.mem, COMMON_MEMORY_WINDOW, + clk_ns); + mx31ads_pcmcia_set_window_timing(timing.attr, ATTRIBUTE_MEMORY_WINDOW, + clk_ns); + + return 0; +} + +static int mx31ads_pcmcia_show_timing(struct mx31ads_pcmcia_socket *skt, + char *buf) +{ + return 0; +} + +static struct pcmcia_low_level mx31ads_pcmcia_ops = { + .owner = THIS_MODULE, + .hw_init = mx31ads_pcmcia_hw_init, + .hw_shutdown = mx31ads_pcmcia_hw_shutdown, + .socket_state = mx31ads_pcmcia_socket_state, + .configure_socket = mx31ads_pcmcia_configure_socket, + + .socket_init = mx31ads_pcmcia_socket_init, + .socket_suspend = mx31ads_pcmcia_socket_suspend, + + .get_timing = mx31ads_pcmcia_default_mecr_timing, + .set_timing = mx31ads_pcmcia_set_timing, + .show_timing = mx31ads_pcmcia_show_timing, +}; + +/* =================================================================================== */ + +LIST_HEAD(mx31ads_pcmcia_sockets); +DECLARE_MUTEX(mx31ads_pcmcia_sockets_lock); + +static DEFINE_SPINLOCK(status_lock); + +struct bittbl { + unsigned int mask; + const char *name; +}; + +static struct bittbl status_bits[] = { + {SS_WRPROT, "SS_WRPROT"}, + {SS_BATDEAD, "SS_BATDEAD"}, + {SS_BATWARN, "SS_BATWARN"}, + {SS_READY, "SS_READY"}, + {SS_DETECT, "SS_DETECT"}, + {SS_POWERON, "SS_POWERON"}, + {SS_STSCHG, "SS_STSCHG"}, + {SS_3VCARD, "SS_3VCARD"}, + {SS_XVCARD, "SS_XVCARD"}, +}; + +static struct bittbl conf_bits[] = { + {SS_PWR_AUTO, "SS_PWR_AUTO"}, + {SS_IOCARD, "SS_IOCARD"}, + {SS_RESET, "SS_RESET"}, + {SS_DMA_MODE, "SS_DMA_MODE"}, + {SS_SPKR_ENA, "SS_SPKR_ENA"}, + {SS_OUTPUT_ENA, "SS_OUTPUT_ENA"}, +}; + +static void +dump_bits(char **p, const char *prefix, unsigned int val, struct bittbl *bits, + int sz) +{ + char *b = *p; + int i; + + b += sprintf(b, "%-9s:", prefix); + for (i = 0; i < sz; i++) + if (val & bits[i].mask) + b += sprintf(b, " %s", bits[i].name); + *b++ = '\n'; + *p = b; +} + +/* + * Implements the /sys/class/pcmcia_socket/??/status file. + * + * Returns: the number of characters added to the buffer + */ +static ssize_t show_status(struct device *dev, struct device_attribute *attr, + char *buf) +{ + struct mx31ads_pcmcia_socket *skt = + container_of(dev, struct mx31ads_pcmcia_socket, socket.dev); + char *p = buf; + + p += sprintf(p, "slot : %d\n", skt->nr); + + dump_bits(&p, "status", skt->status, + status_bits, ARRAY_SIZE(status_bits)); + dump_bits(&p, "csc_mask", skt->cs_state.csc_mask, + status_bits, ARRAY_SIZE(status_bits)); + dump_bits(&p, "cs_flags", skt->cs_state.flags, + conf_bits, ARRAY_SIZE(conf_bits)); + + p += sprintf(p, "Vcc : %d\n", skt->cs_state.Vcc); + p += sprintf(p, "Vpp : %d\n", skt->cs_state.Vpp); + p += sprintf(p, "IRQ : %d (%d)\n", skt->cs_state.io_irq, skt->irq); + if (skt->ops->show_timing) + p += skt->ops->show_timing(skt, p); + + return p - buf; +} + +static DEVICE_ATTR(status, S_IRUGO, show_status, NULL); + +static void mx31ads_common_check_status(struct mx31ads_pcmcia_socket *skt) +{ + unsigned int events; + + pr_debug(KERN_INFO "entering PCMCIA monitoring thread\n"); + + do { + unsigned int status; + unsigned long flags; + + status = mx31ads_common_pcmcia_skt_state(skt); + + spin_lock_irqsave(&status_lock, flags); + events = (status ^ skt->status) & skt->cs_state.csc_mask; + skt->status = status; + spin_unlock_irqrestore(&status_lock, flags); + + pr_debug(KERN_INFO "events: %s%s%s%s%s%s\n", + events == 0 ? "" : "", + events & SS_DETECT ? "DETECT " : "", + events & SS_READY ? "READY " : "", + events & SS_BATDEAD ? "BATDEAD " : "", + events & SS_BATWARN ? "BATWARN " : "", + events & SS_STSCHG ? "STSCHG " : ""); + + if (events) + pcmcia_parse_events(&skt->socket, events); + } while (events); +} + +/* + * Service routine for socket driver interrupts (requested by the + * low-level PCMCIA init() operation via mx31ads_common_pcmcia_thread()). + * The actual interrupt-servicing work is performed by + * mx31ads_common_pcmcia_thread(), largely because the Card Services event- + * handling code performs scheduling operations which cannot be + * executed from within an interrupt context. + */ +static irqreturn_t mx31ads_common_pcmcia_interrupt(int irq, void *dev) +{ + struct mx31ads_pcmcia_socket *skt = dev; + volatile u32 pscr, pgsr; + + dev_dbg(dev, "servicing IRQ %d\n", irq); + + /* clear interrupt states */ + pscr = _reg_PCMCIA_PSCR; + _reg_PCMCIA_PSCR = pscr; + + pgsr = _reg_PCMCIA_PGSR; + _reg_PCMCIA_PGSR = pgsr; + + mx31ads_common_check_status(skt); + + return IRQ_HANDLED; +} + +/* Let's poll for events in addition to IRQs since IRQ only is unreliable... */ +static void mx31ads_common_pcmcia_poll_event(unsigned long dummy) +{ + struct mx31ads_pcmcia_socket *skt = + (struct mx31ads_pcmcia_socket *)dummy; + pr_debug(KERN_INFO "polling for events\n"); + + mod_timer(&skt->poll_timer, jiffies + PCMCIA_POLL_PERIOD); + + mx31ads_common_check_status(skt); +} + +#define mx31ads_pcmcia_cpufreq_register() +#define mx31ads_pcmcia_cpufreq_unregister() + +static int mx31ads_common_drv_pcmcia_probe(struct platform_device *pdev, + struct pcmcia_low_level *ops) +{ + struct mx31ads_pcmcia_socket *skt; + int vs, value, ret; + struct pccard_io_map map; + + down(&mx31ads_pcmcia_sockets_lock); + + skt = kzalloc(sizeof(struct mx31ads_pcmcia_socket), GFP_KERNEL); + if (!skt) { + ret = -ENOMEM; + goto out; + } + + /* + * Initialise the socket structure. + */ + skt->socket.ops = &mx31ads_common_pcmcia_operations; + skt->socket.owner = ops->owner; + skt->socket.driver_data = skt; + + init_timer(&skt->poll_timer); + skt->poll_timer.function = mx31ads_common_pcmcia_poll_event; + skt->poll_timer.data = (unsigned long)skt; + skt->poll_timer.expires = jiffies + PCMCIA_POLL_PERIOD; + + skt->irq = MX31ADS_PCMCIA_IRQ; + skt->socket.dev.parent = &pdev->dev; + skt->ops = ops; + + skt->clk = clk_get(NULL, "ahb_clk"); + + skt->res_skt.start = _PCMCIA(0); + skt->res_skt.end = _PCMCIA(0) + PCMCIASp - 1; + skt->res_skt.name = MX31ADS_PCMCIA; + skt->res_skt.flags = IORESOURCE_MEM; + + ret = request_resource(&iomem_resource, &skt->res_skt); + if (ret) + goto out_err_1; + + skt->res_io.start = _PCMCIAIO(0); + skt->res_io.end = _PCMCIAIO(0) + PCMCIAIOSp - 1; + skt->res_io.name = "io"; + skt->res_io.flags = IORESOURCE_MEM | IORESOURCE_BUSY; + + ret = request_resource(&skt->res_skt, &skt->res_io); + if (ret) + goto out_err_2; + + skt->res_mem.start = _PCMCIAMem(0); + skt->res_mem.end = _PCMCIAMem(0) + PCMCIAMemSp - 1; + skt->res_mem.name = "memory"; + skt->res_mem.flags = IORESOURCE_MEM; + + ret = request_resource(&skt->res_skt, &skt->res_mem); + if (ret) + goto out_err_3; + + skt->res_attr.start = _PCMCIAAttr(0); + skt->res_attr.end = _PCMCIAAttr(0) + PCMCIAAttrSp - 1; + skt->res_attr.name = "attribute"; + skt->res_attr.flags = IORESOURCE_MEM; + + ret = request_resource(&skt->res_skt, &skt->res_attr); + if (ret) + goto out_err_4; + + skt->virt_io = ioremap(skt->res_io.start, 0x10000); + if (skt->virt_io == NULL) { + ret = -ENOMEM; + goto out_err_5; + } + + if (list_empty(&mx31ads_pcmcia_sockets)) + mx31ads_pcmcia_cpufreq_register(); + + list_add(&skt->node, &mx31ads_pcmcia_sockets); + + /* + * We initialize default socket timing here, because + * we are not guaranteed to see a SetIOMap operation at + * runtime. + */ + ops->set_timing(skt); + + ret = ops->hw_init(skt); + if (ret) + goto out_err_6; + + ret = request_irq(skt->irq, mx31ads_common_pcmcia_interrupt, + IRQF_SHARED | IRQF_DISABLED, "PCMCIA IRQ", skt); + if (ret) + goto out_err_6; + + skt->socket.features = SS_CAP_STATIC_MAP | SS_CAP_PCCARD; + skt->socket.resource_ops = &pccard_static_ops; + skt->socket.irq_mask = 0; + skt->socket.map_size = PCMCIAPrtSp; + skt->socket.pci_irq = skt->irq; + skt->socket.io_offset = (unsigned long)skt->virt_io; + + skt->status = mx31ads_common_pcmcia_skt_state(skt); + skt->pre_stat = 0; + ret = pcmcia_register_socket(&skt->socket); + if (ret) + goto out_err_7; + /* FIXED ME workaround for binding with ide-cs. ide usage io port 0x100~0x107 and 0x10e */ + map.map = 0; + map.flags = MAP_ACTIVE | MAP_16BIT; + map.start = 0; + map.stop = PCMCIAIOSp - 1; + map.speed = 0; + mx31ads_common_pcmcia_set_io_map(&skt->socket, &map); + + vs = _reg_PCMCIA_PIPR & PCMCIA_PIPR_VS; + value = vs & PCMCIA_PIPR_VS_5V ? 50 : 33; + dev_dbg(&pdev->dev, "PCMCIA: Voltage the card supports: %d.%dV\n", + value / 10, value % 10); + + add_timer(&skt->poll_timer); + + ret = device_create_file(&skt->socket.dev, &dev_attr_status); + if (ret < 0) + goto out_err_8; + + platform_set_drvdata(pdev, skt); + ret = 0; + goto out; + + out_err_8: + del_timer_sync(&skt->poll_timer); + pcmcia_unregister_socket(&skt->socket); + + out_err_7: + flush_scheduled_work(); + free_irq(skt->irq, skt); + ops->hw_shutdown(skt); + out_err_6: + list_del(&skt->node); + iounmap(skt->virt_io); + out_err_5: + release_resource(&skt->res_attr); + out_err_4: + release_resource(&skt->res_mem); + out_err_3: + release_resource(&skt->res_io); + out_err_2: + release_resource(&skt->res_skt); + out_err_1: + + kfree(skt); + out: + up(&mx31ads_pcmcia_sockets_lock); + return ret; +} + +static int mx31ads_drv_pcmcia_remove(struct platform_device *pdev) +{ + struct mx31ads_pcmcia_socket *skt = platform_get_drvdata(pdev); + + platform_set_drvdata(pdev, NULL); + + down(&mx31ads_pcmcia_sockets_lock); + + del_timer_sync(&skt->poll_timer); + + pcmcia_unregister_socket(&skt->socket); + + flush_scheduled_work(); + + skt->ops->hw_shutdown(skt); + + mx31ads_common_pcmcia_config_skt(skt, &dead_socket); + + list_del(&skt->node); + iounmap(skt->virt_io); + skt->virt_io = NULL; + release_resource(&skt->res_attr); + release_resource(&skt->res_mem); + release_resource(&skt->res_io); + release_resource(&skt->res_skt); + + if (list_empty(&mx31ads_pcmcia_sockets)) + mx31ads_pcmcia_cpufreq_unregister(); + + up(&mx31ads_pcmcia_sockets_lock); + + kfree(skt); + + return 0; +} + +static int mx31ads_drv_pcmcia_probe(struct platform_device *pdev) +{ + if (!machine_is_mx31ads()) + return -ENODEV; + + return mx31ads_common_drv_pcmcia_probe(pdev, &mx31ads_pcmcia_ops); +} + +static int mx31ads_drv_pcmcia_suspend(struct platform_device *pdev, + pm_message_t state) +{ + return pcmcia_socket_dev_suspend(&pdev->dev, state); +} + +static int mx31ads_drv_pcmcia_resume(struct platform_device *pdev) +{ + return pcmcia_socket_dev_resume(&pdev->dev); +} + +/* + * Low level functions + */ +static struct platform_driver mx31ads_pcmcia_driver = { + .driver = { + .name = MX31ADS_PCMCIA, + }, + .probe = mx31ads_drv_pcmcia_probe, + .remove = mx31ads_drv_pcmcia_remove, + .suspend = mx31ads_drv_pcmcia_suspend, + .resume = mx31ads_drv_pcmcia_resume, +}; + +/* mx31ads_pcmcia_init() + * + */ +static int __init mx31ads_pcmcia_init(void) +{ + int ret; + + ret = platform_driver_register(&mx31ads_pcmcia_driver); + if (ret) + return ret; + pr_debug(KERN_INFO "PCMCIA: Initialize i.Mx31 pcmcia socket\n"); + + return ret; +} + +/* mx31ads_pcmcia_exit() + * + */ +static void __exit mx31ads_pcmcia_exit(void) +{ + platform_driver_unregister(&mx31ads_pcmcia_driver); +} + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("i.MX31 PCMCIA Socket Controller"); +MODULE_LICENSE("GPL"); + +module_init(mx31ads_pcmcia_init); +module_exit(mx31ads_pcmcia_exit); diff --git a/drivers/pcmcia/mx31ads-pcmcia.h b/drivers/pcmcia/mx31ads-pcmcia.h new file mode 100644 index 000000000000..5d7d71f421ac --- /dev/null +++ b/drivers/pcmcia/mx31ads-pcmcia.h @@ -0,0 +1,155 @@ +/* + * linux/drivers/pcmcia/mx31ads-pcmcia.h + * + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + * + * This file contains definitions for the PCMCIA support code common to + * integrated SOCs like the i.Mx31 microprocessors. + */ +#ifndef _ASM_ARCH_PCMCIA +#define _ASM_ARCH_PCMCIA + +/* include the world */ +#include +#include +#include +#include +#include +#include "cs_internal.h" + +#define MX31ADS_PCMCIA "Mx31ads_pcmcia_socket" + +struct device; +struct pcmcia_low_level; + +/* + * This structure encapsulates per-socket state which we might need to + * use when responding to a Card Services query of some kind. + */ +struct mx31ads_pcmcia_socket { + struct pcmcia_socket socket; + + /* + * Info from low level handler + */ + struct device *dev; + unsigned int nr; + unsigned int irq; + + struct clk *clk; + + /* + * Core PCMCIA state + */ + struct pcmcia_low_level *ops; + + unsigned int status; + unsigned int pre_stat; + socket_state_t cs_state; + + unsigned short spd_io[MAX_IO_WIN]; + unsigned short spd_mem[MAX_WIN]; + unsigned short spd_attr[MAX_WIN]; + + struct resource res_skt; + struct resource res_io; + struct resource res_mem; + struct resource res_attr; + void *virt_io; + + unsigned int irq_state; + + struct timer_list poll_timer; + struct list_head node; +}; + +struct pcmcia_state { + unsigned detect:1, + ready:1, bvd1:1, bvd2:1, wrprot:1, vs_3v:1, vs_Xv:1, poweron:1; +}; + +struct pcmcia_low_level { + struct module *owner; + + /* first socket in system */ + int first; + /* nr of sockets */ + int nr; + + int (*hw_init) (struct mx31ads_pcmcia_socket *); + void (*hw_shutdown) (struct mx31ads_pcmcia_socket *); + + void (*socket_state) (struct mx31ads_pcmcia_socket *, + struct pcmcia_state *); + int (*configure_socket) (struct mx31ads_pcmcia_socket *, + const socket_state_t *); + + /* + * Enable card status IRQs on (re-)initialisation. This can + * be called at initialisation, power management event, or + * pcmcia event. + */ + void (*socket_init) (struct mx31ads_pcmcia_socket *); + + /* + * Disable card status IRQs and PCMCIA bus on suspend. + */ + void (*socket_suspend) (struct mx31ads_pcmcia_socket *); + + /* + * Hardware specific timing routines. + * If provided, the get_timing routine overrides the SOC default. + */ + unsigned int (*get_timing) (struct mx31ads_pcmcia_socket *, + unsigned int, unsigned int); + int (*set_timing) (struct mx31ads_pcmcia_socket *); + int (*show_timing) (struct mx31ads_pcmcia_socket *, char *); + +#ifdef CONFIG_CPU_FREQ + /* + * CPUFREQ support. + */ + int (*frequency_change) (struct mx31ads_pcmcia_socket *, unsigned long, + struct cpufreq_freqs *); +#endif +}; + +struct mx31ads_pcmcia_timing { + unsigned short io; + unsigned short mem; + unsigned short attr; +}; + +typedef struct { + ulong win_size; + int bsize; +} bsize_map_t; + +/* + * The PC Card Standard, Release 7, section 4.13.4, says that twIORD + * has a minimum value of 165ns. Section 4.13.5 says that twIOWR has + * a minimum value of 165ns, as well. Section 4.7.2 (describing + * common and attribute memory write timing) says that twWE has a + * minimum value of 150ns for a 250ns cycle time (for 5V operation; + * see section 4.7.4), or 300ns for a 600ns cycle time (for 3.3V + * operation, also section 4.7.4). Section 4.7.3 says that taOE + * has a maximum value of 150ns for a 300ns cycle time (for 5V + * operation), or 300ns for a 600ns cycle time (for 3.3V operation). + * + * When configuring memory maps, Card Services appears to adopt the policy + * that a memory access time of "0" means "use the default." The default + * PCMCIA I/O command width time is 165ns. The default PCMCIA 5V attribute + * and memory command width time is 150ns; the PCMCIA 3.3V attribute and + * memory command width time is 300ns. + */ +#define PCMCIA_IO_ACCESS (165) +#define PCMCIA_5V_MEM_ACCESS (150) +#define PCMCIA_3V_MEM_ACCESS (300) +#define PCMCIA_ATTR_MEM_ACCESS (300) + +/* + * The socket driver actually works nicely in interrupt-driven form, + * so the (relatively infrequent) polling is "just to be sure." + */ +#define PCMCIA_POLL_PERIOD (2*HZ) +#endif diff --git a/drivers/power/Kconfig b/drivers/power/Kconfig index 8e9ba177d817..e0638956fe0b 100644 --- a/drivers/power/Kconfig +++ b/drivers/power/Kconfig @@ -142,4 +142,25 @@ config CHARGER_PCF50633 help Say Y to include support for NXP PCF50633 Main Battery Charger. +config BATTERY_STMP3XXX + tristate "Sigmatel STMP3xxx SoC battery charger driver" + depends on ARCH_STMP3XXX + help + Say Y to enable support for the battery charger state machine + for the Sigmatel STMP3xxx based SoC's. + +config BATTERY_MXS + tristate "MXS SoC battery charger driver" + depends on ARCH_MXS + help + Say Y to enable support for the battery charger state machine + for the Sigmatel MXS based SoC's. + +config MXS_VBUS_CURRENT_DRAW + tristate "MXS SoC USB2.0 VBUS Current Limitation" + depends on ARCH_MXS + help + Say Y to enable 100mA limitation when USB vbus power on system + before enumeration to match USB2.0 requirement. + endif # POWER_SUPPLY diff --git a/drivers/power/Makefile b/drivers/power/Makefile index 00050809a6c7..66a925fd9807 100644 --- a/drivers/power/Makefile +++ b/drivers/power/Makefile @@ -34,3 +34,4 @@ obj-$(CONFIG_BATTERY_DA9030) += da9030_battery.o obj-$(CONFIG_BATTERY_MAX17040) += max17040_battery.o obj-$(CONFIG_BATTERY_Z2) += z2_battery.o obj-$(CONFIG_CHARGER_PCF50633) += pcf50633-charger.o +obj-$(CONFIG_BATTERY_MXS) += mxs/ diff --git a/drivers/power/mxs/Makefile b/drivers/power/mxs/Makefile new file mode 100644 index 000000000000..c7675a9ec52b --- /dev/null +++ b/drivers/power/mxs/Makefile @@ -0,0 +1,9 @@ +# +# Makefile for the MXS battery charger driver +# + +obj-$(CONFIG_BATTERY_MXS) += mxs-battery.o + +mxs-battery-objs := ddi_bc_api.o ddi_bc_hw.o ddi_bc_init.o \ + ddi_bc_ramp.o ddi_bc_sm.o ddi_power_battery.o linux.o fiq.o + diff --git a/drivers/power/mxs/ddi_bc_api.c b/drivers/power/mxs/ddi_bc_api.c new file mode 100644 index 000000000000..26d064bff9a2 --- /dev/null +++ b/drivers/power/mxs/ddi_bc_api.c @@ -0,0 +1,559 @@ +/* + * Copyright (C) 2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + + +/* Includes */ + + +#include +#include "ddi_bc_internal.h" + + +/* Variables */ + + +/* This structure holds the current Battery Charger configuration. */ + +ddi_bc_Cfg_t g_ddi_bc_Configuration; + +extern uint32_t g_ddi_bc_u32StateTimer; +extern ddi_bc_BrokenReason_t ddi_bc_gBrokenReason; +extern bool bRestartChargeCycle; + + +/* Code */ + + + + +/* brief Report the Battery Charger configuration. */ + +/* fntype Function */ + +/* This function reports the Battery Charger configuration. */ + +/* Note that, if the Battery Charger has not yet been initialized, the data */ +/* returned by this function is unknown. */ + +/* param[in,out] pCfg A pointer to a structure that will receive the data. */ + + +void ddi_bc_QueryCfg(ddi_bc_Cfg_t *pCfg) +{ + + /* -------------------------------------------------------------------------- */ + /* Return the current configuration. */ + /* -------------------------------------------------------------------------- */ + + *pCfg = g_ddi_bc_Configuration; + +} + + + +/* brief Shut down the Battery Charger. */ + +/* fntype Function */ + +/* This function immediately shuts down the Battery Charger hardware and */ +/* returns the state machine to the Uninitialized state. Use this function to */ +/* safely mummify the battery charger before retiring it from memory. */ + + +void ddi_bc_ShutDown() +{ + + /* -------------------------------------------------------------------------- */ + /* Reset the current ramp. */ + /* -------------------------------------------------------------------------- */ + + ddi_bc_RampReset(); + + /* -------------------------------------------------------------------------- */ + /* Move to the Uninitialized state. */ + /* -------------------------------------------------------------------------- */ + + g_ddi_bc_State = DDI_BC_STATE_UNINITIALIZED; + +} + + + +/* brief Advances the state machine. */ + +/* fntype Function */ + +/* This function advances the state machine. */ + +/* retval DDI_BC_STATUS_SUCCESS If all goes well */ +/* retval DDI_BC_STATUS_NOT_INITIALIZED If the Battery Charger is not yet */ +/* initialized. */ +/* retval DDI_BC_STATUS_BROKEN If the battery violated a time-out */ +/* and has been declared broken. */ + + +ddi_bc_Status_t ddi_bc_StateMachine() +{ + int ret, state; + + /* -------------------------------------------------------------------------- */ + /* Check if we've been initialized yet. */ + /* -------------------------------------------------------------------------- */ + + if (g_ddi_bc_State == DDI_BC_STATE_UNINITIALIZED) { + return DDI_BC_STATUS_NOT_INITIALIZED; + } + /* -------------------------------------------------------------------------- */ + /* Execute the function for the current state. */ + /* -------------------------------------------------------------------------- */ + + state = g_ddi_bc_State; + ret = (stateFunctionTable[g_ddi_bc_State] ()); + if (state != g_ddi_bc_State) + pr_debug("Charger: transit from state %d to %d\n", + state, g_ddi_bc_State); + return ret; + +} + + + +/* brief Get the Battery Charger's current state. */ + +/* fntype Function */ + +/* This function returns the current state. */ + +/* retval The current state. */ + + +ddi_bc_State_t ddi_bc_GetState() +{ + /* -------------------------------------------------------------------------- */ + /* Return the current state. */ + /* -------------------------------------------------------------------------- */ + + return g_ddi_bc_State; + +} + + + +/* brief Disable the Battery Charger. */ + +/* fntype Function */ + +/* This function forces the Battery Charger into the Disabled state. */ + +/* retval DDI_BC_STATUS_SUCCESS If all goes well */ +/* retval DDI_BC_STATUS_NOT_INITIALIZED If the Battery Charger is not yet */ +/* initialized. */ + + +ddi_bc_Status_t ddi_bc_SetDisable() +{ + + /* -------------------------------------------------------------------------- */ + /* Check if we've been initialized yet. */ + /* -------------------------------------------------------------------------- */ + + if (g_ddi_bc_State == DDI_BC_STATE_UNINITIALIZED) { + return DDI_BC_STATUS_NOT_INITIALIZED; + } + /* -------------------------------------------------------------------------- */ + /* Check if we've been initialized yet. */ + /* -------------------------------------------------------------------------- */ + + if (g_ddi_bc_State == DDI_BC_STATE_BROKEN) { + return DDI_BC_STATUS_BROKEN; + } + /* -------------------------------------------------------------------------- */ + /* Reset the current ramp. This will jam the current to zero and power off */ + /* the charging hardware. */ + /* -------------------------------------------------------------------------- */ + + ddi_bc_RampReset(); + + /* -------------------------------------------------------------------------- */ + /* Reset the state timer. */ + /* -------------------------------------------------------------------------- */ + + g_ddi_bc_u32StateTimer = 0; + + /* -------------------------------------------------------------------------- */ + /* Move to the Disabled state. */ + /* -------------------------------------------------------------------------- */ + + g_ddi_bc_State = DDI_BC_STATE_DISABLED; + + /* -------------------------------------------------------------------------- */ + /* Return success. */ + /* -------------------------------------------------------------------------- */ + + return DDI_BC_STATUS_SUCCESS; + +} + + + +/* brief Enable the Battery Charger. */ + +/* fntype Function */ + +/* If the Battery Charger is in the Disabled state, this function moves it to */ +/* the Waiting to Charge state. */ + +/* retval DDI_BC_STATUS_SUCCESS If all goes well */ +/* retval DDI_BC_STATUS_NOT_INITIALIZED If the Battery Charger is not yet */ +/* initialized. */ +/* retval DDI_BC_STATUS_NOT_DISABLED If the Battery Charger is not */ +/* disabled. */ + + +ddi_bc_Status_t ddi_bc_SetEnable() +{ + + /* -------------------------------------------------------------------------- */ + /* Check if we've been initialized yet. */ + /* -------------------------------------------------------------------------- */ + + if (g_ddi_bc_State == DDI_BC_STATE_UNINITIALIZED) { + return DDI_BC_STATUS_NOT_INITIALIZED; + } + /* -------------------------------------------------------------------------- */ + /* If we're not in the Disabled state, this is pointless. */ + /* -------------------------------------------------------------------------- */ + + if (g_ddi_bc_State != DDI_BC_STATE_DISABLED) { + return DDI_BC_STATUS_NOT_DISABLED; + } + /* -------------------------------------------------------------------------- */ + /* Reset the state timer. */ + /* -------------------------------------------------------------------------- */ + + g_ddi_bc_u32StateTimer = 0; + /* -------------------------------------------------------------------------- */ + /* Move to the Waiting to Charge state. */ + /* -------------------------------------------------------------------------- */ + + g_ddi_bc_State = DDI_BC_STATE_WAITING_TO_CHARGE; + + /* -------------------------------------------------------------------------- */ + /* Return success. */ + /* -------------------------------------------------------------------------- */ + + return DDI_BC_STATUS_SUCCESS; + +} + + + +/* brief Declare the battery to be broken. */ + +/* fntype Function */ + +/* This function forces the Battery Charger into the Broken state. */ + +/* retval DDI_BC_STATUS_SUCCESS If all goes well */ +/* retval DDI_BC_STATUS_NOT_INITIALIZED If the Battery Charger is not yet */ +/* initialized. */ + + +ddi_bc_Status_t ddi_bc_SetBroken() +{ + + /* -------------------------------------------------------------------------- */ + /* Check if we've been initialized yet. */ + /* -------------------------------------------------------------------------- */ + + if (g_ddi_bc_State == DDI_BC_STATE_UNINITIALIZED) { + return DDI_BC_STATUS_NOT_INITIALIZED; + } + /* -------------------------------------------------------------------------- */ + /* Reset the current ramp. This will jam the current to zero and power off */ + /* the charging hardware. */ + /* -------------------------------------------------------------------------- */ + + ddi_bc_RampReset(); + + /* -------------------------------------------------------------------------- */ + /* Reset the state timer. */ + /* -------------------------------------------------------------------------- */ + + g_ddi_bc_u32StateTimer = 0; + + /* -------------------------------------------------------------------------- */ + /* Move to the Broken state. */ + /* -------------------------------------------------------------------------- */ + + ddi_bc_gBrokenReason = DDI_BC_BROKEN_CHARGING_TIMEOUT; + + g_ddi_bc_State = DDI_BC_STATE_BROKEN; + + /* -------------------------------------------------------------------------- */ + /* Return success. */ + /* -------------------------------------------------------------------------- */ + + return DDI_BC_STATUS_SUCCESS; + +} + + + +/* brief Declare the battery to be fixed. */ + +/* fntype Function */ + +/* If the Battery Charger is in the Broken state, this function moves it to */ +/* the Disabled state. */ + +/* retval DDI_BC_STATUS_SUCCESS If all goes well */ +/* retval DDI_BC_STATUS_NOT_INITIALIZED If the Battery Charger is not yet */ +/* initialized. */ +/* retval DDI_BC_STATUS_NOT_BROKEN If the Battery Charger is not broken. */ + + +ddi_bc_Status_t ddi_bc_SetFixed() +{ + + /* -------------------------------------------------------------------------- */ + /* Check if we've been initialized yet. */ + /* -------------------------------------------------------------------------- */ + + if (g_ddi_bc_State == DDI_BC_STATE_UNINITIALIZED) { + return DDI_BC_STATUS_NOT_INITIALIZED; + } + /* -------------------------------------------------------------------------- */ + /* If we're not in the Broken state, this is pointless. */ + /* -------------------------------------------------------------------------- */ + + if (g_ddi_bc_State != DDI_BC_STATE_BROKEN) { + return DDI_BC_STATUS_NOT_BROKEN; + } + /* -------------------------------------------------------------------------- */ + /* Reset the state timer. */ + /* -------------------------------------------------------------------------- */ + + g_ddi_bc_u32StateTimer = 0; + + /* -------------------------------------------------------------------------- */ + /* Unitialize the Broken Reason */ + /* -------------------------------------------------------------------------- */ + + ddi_bc_gBrokenReason = DDI_BC_BROKEN_UNINITIALIZED; + + /* -------------------------------------------------------------------------- */ + /* Move to the Disabled state. */ + /* -------------------------------------------------------------------------- */ + + g_ddi_bc_State = DDI_BC_STATE_DISABLED; + + /* -------------------------------------------------------------------------- */ + /* Return success. */ + /* -------------------------------------------------------------------------- */ + + return DDI_BC_STATUS_SUCCESS; + +} + + + +/* brief Set the current limit. */ + +/* fntype Function */ + +/* This function applies a limit to the current that the Battery Charger can */ +/* draw. */ + +/* param[in] u16Limit The maximum current the Battery Charger can draw */ +/* (in mA). */ + +/* retval The expressible version of the limit. */ + + +uint16_t ddi_bc_SetCurrentLimit(uint16_t u16Limit) +{ + + /* -------------------------------------------------------------------------- */ + /* Set the limit and return what is actually expressible. */ + /* -------------------------------------------------------------------------- */ + + return ddi_bc_RampSetLimit(u16Limit); + +} + + + +/* brief Report the current limit. */ + +/* fntype Function */ + +/* This function reports the limit to the current that the Battery Charger can */ +/* draw. */ + +/* retval The current limit. */ + + +uint16_t ddi_bc_GetCurrentLimit(void) +{ + + /* -------------------------------------------------------------------------- */ + /* Set the limit and return what is actually expressible. */ + /* -------------------------------------------------------------------------- */ + + return ddi_bc_RampGetLimit(); + +} + + + +/* brief Set the battery charger state machine period. */ + +/* fntype Function */ + +/* This function sets a new state machine period. The Period and Slope should */ +/* be coordinated to achieve the minimal ramp step current which will minimize */ +/* transients on the system. */ + +/* param[in] u32StateMachinePeriod (in milliseconds) */ +/* param[in] u16CurrentRampSlope (in mA/s) */ + +/* retval SUCCESS If all goes well */ +/* retval ERROR_DDI_BCM_NOT_INITIALIZED If the Battery Charger is not yet */ +/* initialized. */ + + +ddi_bc_Status_t ddi_bc_SetNewPeriodAndSlope(uint32_t u32StateMachinePeriod, + uint16_t u16CurrentRampSlope) +{ + /* -------------------------------------------------------------------------- */ + /* Check if we've been initialized yet. */ + /* -------------------------------------------------------------------------- */ + bool bDisableRequired; + + if (g_ddi_bc_State == DDI_BC_STATE_UNINITIALIZED) { + return DDI_BC_STATUS_NOT_INITIALIZED; + } + + if (g_ddi_bc_State == DDI_BC_STATE_DISABLED) + bDisableRequired = false; + else { + bDisableRequired = true; + ddi_bc_SetDisable(); + } + + /* Looking at the code, changing the period while the battery charger is running */ + /* doesn't seem to have a negative affect. One could wrap this in the mutex */ + /* or implement further coordination if it did. */ + g_ddi_bc_Configuration.u32StateMachinePeriod = u32StateMachinePeriod; + g_ddi_bc_Configuration.u16CurrentRampSlope = u16CurrentRampSlope; + + if (bDisableRequired) + ddi_bc_SetEnable(); + + return DDI_BC_STATUS_SUCCESS; + +} + + + +/* brief Report the state machine period. */ + +/* fntype Function */ + +/* This function reports the battery charger period. */ + +/* retval The battery charger period (in milliseconds). */ + + +uint32_t ddi_bc_GetStateMachinePeriod() +{ + return g_ddi_bc_Configuration.u32StateMachinePeriod; +} + + + +/* brief Report the current ramp slope. */ + +/* fntype Function */ + +/* This function reports the current ramp slope. */ + +/* retval The current ramp slope (in mA/s). */ + + +uint32_t ddi_bc_GetCurrentRampSlope() +{ + return g_ddi_bc_Configuration.u16CurrentRampSlope; +} + + + +/* brief Report the time spent in the present state (milliseconds) */ + +/* fntype Function */ + +/* This function reports the time spent in the present charging state. Note that */ +/* for the states that actually charge the battery, this time does not include the */ +/* time spent under alarm conditions such as die termperature alarm or battery */ +/* temperature alarm. */ + +/* retval The time spent in the current state in milliseconds. */ + + +uint32_t ddi_bc_GetStateTime(void) +{ + return g_ddi_bc_u32StateTimer; +} + + + +/* brief Report the reason for being in the broken state */ + +/* fntype Function */ + + +/* retval ddi_bc_BrokenReason_t enumeration */ + + +ddi_bc_BrokenReason_t ddi_bc_GetBrokenReason(void) +{ + return ddi_bc_gBrokenReason; +} + + + +/* brief Restart the charge cycle */ + +/* fntype Function */ + + +/* retval SUCCESS */ + + +ddi_bc_Status_t ddi_bc_ForceChargingToStart(void) +{ + static int16_t restarts; + + if (restarts < DDI_BC_MAX_RESTART_CYCLES) { + restarts++; + bRestartChargeCycle = true; + } + + return DDI_BC_STATUS_SUCCESS; +} + + +/* End of file */ + +/* @} */ diff --git a/drivers/power/mxs/ddi_bc_hw.c b/drivers/power/mxs/ddi_bc_hw.c new file mode 100644 index 000000000000..f1fdb6f2b065 --- /dev/null +++ b/drivers/power/mxs/ddi_bc_hw.c @@ -0,0 +1,397 @@ +/* + * Copyright (C) 2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include "ddi_bc_internal.h" + + +/* Includes and external references */ + + + +/* Variables */ + + + +/* Code */ + + + +/* */ +/* brief Report if the battery charging hardware is available. */ +/* */ +/* fntype Function */ +/* */ +/* This function reports if the battery charging hardware is available by */ +/* reading the corresponding laser fuse bit. */ +/* */ +/* retval Zero if the battery charging hardware is not available. Non-zero */ +/* otherwise. */ +/* */ + +int ddi_bc_hwBatteryChargerIsEnabled(void) +{ + /* TODO: replace ddi_bc_hwBatteryChargerIsEnabled with the function below in the code */ + return (int)ddi_power_GetBatteryChargerEnabled(); +} + + +/* */ +/* brief Report the battery configuration. */ +/* */ +/* fntype Function */ +/* */ +/* This function reports the hardware battery configuration. */ +/* */ +/* retval A value that indicates the battery configuration. */ +/* */ + +ddi_bc_BatteryMode_t ddi_bc_hwGetBatteryMode(void) +{ + /* TODO: replace ddi_bc_hwGetBatteryMode() with the function below. */ + return (ddi_bc_BatteryMode_t) ddi_power_GetBatteryMode(); +} + + + +/* */ +/* brief Report the voltage across the battery. */ +/* */ +/* fntype Function */ +/* */ +/* This function reports the voltage across the battery. */ +/* */ +/* retval The voltage across the battery, in mV. */ +/* */ + +uint16_t ddi_bc_hwGetBatteryVoltage(void) +{ + /* TODO: replace ddi_bc_hwGetBattery with function below */ + return ddi_power_GetBattery(); +} + + +/* */ +/* brief Report on the presence of the power supply. */ +/* */ +/* fntype Function */ +/* */ +/* This function repots on whether or not the 5V power supply is present. */ +/* */ +/* retval Zero if the power supply is not present. Non-zero otherwise. */ +/* */ + +int ddi_bc_hwPowerSupplyIsPresent(void) +{ + /* TODO: replace ddi_bc_hwPowerSupplyIsPresent with the functino below. */ + return (int)ddi_power_Get5vPresentFlag(); +} + + +/* */ +/* brief Report the maximum charging current. */ +/* */ +/* fntype Function */ +/* */ +/* This function reports the maximum charging current that will be offered to */ +/* the battery, as currently set in the hardware. */ +/* */ +/* retval The maximum current setting in the hardware. */ +/* */ + +uint16_t ddi_bc_hwGetMaxCurrent(void) +{ + /* TODO: replace ddi_bc_hwGetMaxCurrent() with the below function */ + return (uint16_t) ddi_power_GetMaxBatteryChargeCurrent(); +} + + +/* */ +/* brief Set the maximum charging current. */ +/* */ +/* fntype Function */ +/* */ +/* This function sets the maximum charging current that will be offered to the */ +/* battery. */ +/* */ +/* Note that the hardware has a minimum resolution of 10mA and a maximum */ +/* expressible value of 780mA (see the data sheet for details). If the given */ +/* current cannot be expressed exactly, then the largest expressible smaller */ +/* value will be used. The return reports the actual value that was effected. */ +/* */ +/* param[in] u16Limit The maximum charging current, in mA. */ +/* */ +/* retval The actual value that was effected. */ +/* */ + +uint16_t ddi_bc_hwSetMaxCurrent(uint16_t u16Limit) +{ + /* TODO: replace ddi_bc_hwSetMaxChargeCurrent */ + return ddi_power_SetMaxBatteryChargeCurrent(u16Limit); +} + + +/* */ +/* brief Set the charging current threshold. */ +/* */ +/* fntype Function */ +/* */ +/* This function sets the charging current threshold. When the actual current */ +/* flow to the battery is less than this threshold, the HW_POWER_STS.CHRGSTS */ +/* flag is clear. */ +/* */ +/* Note that the hardware has a minimum resolution of 10mA and a maximum */ +/* expressible value of 180mA (see the data sheet for details). If the given */ +/* current cannot be expressed exactly, then the largest expressible smaller */ +/* value will be used. The return reports the actual value that was effected. */ +/* */ +/* param[in] u16Threshold The charging current threshold, in mA. */ +/* */ +/* retval The actual value that was effected. */ +/* */ + +uint16_t ddi_bc_hwSetCurrentThreshold(uint16_t u16Threshold) +{ + /* TODO: replace calls to ddi_bc_hwSetCurrentThreshold with the one below */ + return ddi_power_SetBatteryChargeCurrentThreshold(u16Threshold); + +} + + +/* */ +/* brief Report the charging current threshold. */ +/* */ +/* fntype Function */ +/* */ +/* This function reports the charging current threshold. When the actual */ +/* current flow to the battery is less than this threshold, the */ +/* HW_POWER_STS.CHRGSTS flag is clear. */ +/* */ +/* Note that the hardware has a minimum resolution of 10mA and a maximum */ +/* expressible value of 180mA (see the data sheet for details). */ +/* */ +/* retval The charging current threshold, in mA. */ +/* */ + +uint16_t ddi_bc_hwGetCurrentThreshold(void) +{ + /* TODO: replace calls to ddi_bc_hwGetCurrentThreshold with function below */ + return ddi_power_GetBatteryChargeCurrentThreshold(); +} + + +/* */ +/* brief Report if the charger hardware power is on. */ +/* */ +/* fntype Function */ +/* */ +/* This function reports if the charger hardware power is on. */ +/* */ +/* retval Zero if the charger hardware is not powered. Non-zero otherwise. */ +/* */ + +int ddi_bc_hwChargerPowerIsOn(void) +{ + + /* -------------------------------------------------------------------------- */ + /* Note that the bit we're looking at is named PWD_BATTCHRG. The "PWD" */ + /* stands for "power down". Thus, when the bit is set, the battery charger */ + /* hardware is POWERED DOWN. */ + /* -------------------------------------------------------------------------- */ + + /* -------------------------------------------------------------------------- */ + /* Read the register and return the result. */ + /* -------------------------------------------------------------------------- */ + + /* TODO: replace ddi_bc_hwChargerPowerIsOn with function below */ + return ddi_power_GetChargerPowered(); +} + + +/* */ +/* brief Turn the charging hardware on or off. */ +/* */ +/* fntype Function */ +/* */ +/* This function turns the charging hardware on or off. */ +/* */ +/* param[in] on Indicates whether the charging hardware should be on or off. */ +/* */ + +void ddi_bc_hwSetChargerPower(int on) +{ + + /* -------------------------------------------------------------------------- */ + /* Note that the bit we're looking at is named PWD_BATTCHRG. The "PWD" */ + /* stands for "power down". Thus, when the bit is set, the battery charger */ + /* hardware is POWERED DOWN. */ + /* -------------------------------------------------------------------------- */ + + /* -------------------------------------------------------------------------- */ + /* Hit the power switch. */ + /* -------------------------------------------------------------------------- */ + + /* TODO: replace ddi_bc_hwSetChargerPower with functino below */ + ddi_power_SetChargerPowered(on); +} + + +/* */ +/* brief Reports if the charging current has fallen below the threshold. */ +/* */ +/* fntype Function */ +/* */ +/* This function reports if the charging current that the battery is accepting */ +/* has fallen below the threshold. */ +/* */ +/* Note that this bit is regarded by the hardware guys as very slightly */ +/* unreliable. They recommend that you don't believe a value of zero until */ +/* you've sampled it twice. */ +/* */ +/* retval Zero if the battery is accepting less current than indicated by the */ +/* charging threshold. Non-zero otherwise. */ +/* */ + +int ddi_bc_hwGetChargeStatus(void) +{ + return ddi_power_GetChargeStatus(); +} + + +/* */ +/* brief Report on the die temperature. */ +/* */ +/* fntype Function */ +/* */ +/* This function reports on the die temperature. */ +/* */ +/* param[out] pLow The low end of the temperature range. */ +/* param[out] pHigh The high end of the temperature range. */ +/* */ + +void ddi_bc_hwGetDieTemp(int16_t *pLow, int16_t *pHigh) +{ + /* TODO: replace ddi_bc_hwGetDieTemp with function below */ + ddi_power_GetDieTemp(pLow, pHigh); +} + + +/* */ +/* brief Report the battery temperature reading. */ +/* */ +/* fntype Function */ +/* */ +/* This function examines the configured LRADC channel and reports the battery */ +/* temperature reading. */ +/* */ +/* param[out] pReading A pointer to a variable that will receive the */ +/* temperature reading. */ +/* */ +/* retval DDI_BC_STATUS_SUCCESS If the operation succeeded. */ +/* retval DDI_BC_STATUS_NOT_INITIALIZED If the Battery Charger is not yet */ +/* initialized. */ +/* */ + +ddi_bc_Status_t ddi_bc_hwGetBatteryTemp(uint16_t *pReading) +{ + return (ddi_bc_Status_t)DDI_BC_STATUS_HARDWARE_DISABLED; +} + + +/* */ +/* brief Convert a current in mA to a hardware setting. */ +/* */ +/* fntype Function */ +/* */ +/* This function converts a current measurement in mA to a hardware setting */ +/* used by HW_POWER_BATTCHRG.STOP_ILIMIT or HW_POWER_BATTCHRG.BATTCHRG_I. */ +/* */ +/* Note that the hardware has a minimum resolution of 10mA and a maximum */ +/* expressible value of 780mA (see the data sheet for details). If the given */ +/* current cannot be expressed exactly, then the largest expressible smaller */ +/* value will be used. */ +/* */ +/* param[in] u16Current The current of interest. */ +/* */ +/* retval The corresponding setting. */ +/* */ + +uint8_t ddi_bc_hwCurrentToSetting(uint16_t u16Current) +{ + return ddi_power_convert_current_to_setting(u16Current); +} + + +/* */ +/* brief Convert a hardware current setting to a value in mA. */ +/* */ +/* fntype Function */ +/* */ +/* This function converts a setting used by HW_POWER_BATTCHRG.STOP_ILIMIT or */ +/* HW_POWER_BATTCHRG.BATTCHRG_I into an actual current measurement in mA. */ +/* */ +/* Note that the hardware current fields are 6 bits wide. The higher bits in */ +/* the 8-bit input parameter are ignored. */ +/* */ +/* param[in] u8Setting A hardware current setting. */ +/* */ +/* retval The corresponding current in mA. */ +/* */ + +uint16_t ddi_bc_hwSettingToCurrent(uint8_t u8Setting) +{ + return ddi_power_convert_setting_to_current(u8Setting); +} + + +/* */ +/* brief Compute the actual current expressible in the hardware. */ +/* */ +/* fntype Function */ +/* */ +/* Given a desired current, this function computes the actual current */ +/* expressible in the hardware. */ +/* */ +/* Note that the hardware has a minimum resolution of 10mA and a maximum */ +/* expressible value of 780mA (see the data sheet for details). If the given */ +/* current cannot be expressed exactly, then the largest expressible smaller */ +/* value will be used. */ +/* */ +/* param[in] u16Current The current of interest. */ +/* */ +/* retval The corresponding current in mA. */ +/* */ + +uint16_t ddi_bc_hwExpressibleCurrent(uint16_t u16Current) +{ + /* TODO: replace the bc function with this one */ + return ddi_power_ExpressibleCurrent(u16Current); +} + + +/* */ +/* brief Checks to see if the DCDC has been manually enabled */ +/* */ +/* fntype Function */ +/* */ +/* retval true if DCDC is ON, false if DCDC is OFF. */ +/* */ + +bool ddi_bc_hwIsDcdcOn(void) +{ + return ddi_power_IsDcdcOn(); +} + + +/* End of file */ + +/* @} */ diff --git a/drivers/power/mxs/ddi_bc_hw.h b/drivers/power/mxs/ddi_bc_hw.h new file mode 100644 index 000000000000..9275c5b3a7ba --- /dev/null +++ b/drivers/power/mxs/ddi_bc_hw.h @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#ifndef _DDI_BC_HW_H +#define _DDI_BC_HW_H + + +/* Definitions */ + + +/* The enumeration of battery modes. */ + +typedef enum _ddi_bc_BatteryMode { + DDI_BC_BATTERY_MODE_LI_ION_2_CELLS = 0, + DDI_BC_BATTERY_MODE_LI_ION_1_CELL = 1, + DDI_BC_BATTERY_MODE_2_CELLS = 2, + DDI_BC_BATTERY_MODE_1_CELL = 3 +} ddi_bc_BatteryMode_t; + +/* The enumeration of bias current sources. */ + +typedef enum _ddi_bc_BiasCurrentSource { + DDI_BC_EXTERNAL_BIAS_CURRENT = 0, + DDI_BC_INTERNAL_BIAS_CURRENT = 1, +} ddi_bc_BiasCurrentSource_t; + + +/* Prototypes */ + + +extern int ddi_bc_hwBatteryChargerIsEnabled(void); +extern ddi_bc_BatteryMode_t ddi_bc_hwGetBatteryMode(void); +extern ddi_bc_BiasCurrentSource_t ddi_bc_hwGetBiasCurrentSource(void); +extern ddi_bc_Status_t +ddi_bc_hwSetBiasCurrentSource(ddi_bc_BiasCurrentSource_t); +extern ddi_bc_Status_t ddi_bc_hwSetChargingVoltage(uint16_t); +extern uint16_t ddi_bc_hwGetBatteryVoltage(void); +extern int ddi_bc_hwPowerSupplyIsPresent(void); +extern uint16_t ddi_bc_hwSetMaxCurrent(uint16_t); +extern uint16_t ddi_bc_hwGetMaxCurrent(void); +extern uint16_t ddi_bc_hwSetCurrentThreshold(uint16_t); +extern uint16_t ddi_bc_hwGetCurrentThreshold(void); +extern int ddi_bc_hwChargerPowerIsOn(void); +extern void ddi_bc_hwSetChargerPower(int); +extern int ddi_bc_hwGetChargeStatus(void); +extern void ddi_bc_hwGetDieTemp(int16_t *, int16_t *); +extern ddi_bc_Status_t ddi_bc_hwGetBatteryTemp(uint16_t *); +uint8_t ddi_bc_hwCurrentToSetting(uint16_t); +uint16_t ddi_bc_hwSettingToCurrent(uint8_t); +uint16_t ddi_bc_hwExpressibleCurrent(uint16_t); + + +/* */ +/* brief Checks to see if the DCDC has been manually enabled */ +/* */ +/* fntype Function */ +/* */ +/* retval true if DCDC is ON, false if DCDC is OFF. */ +/* */ + +bool ddi_bc_hwIsDcdcOn(void); + + +/* End of file */ + +#endif /* _DDI_BC_H */ +/* @} */ diff --git a/drivers/power/mxs/ddi_bc_init.c b/drivers/power/mxs/ddi_bc_init.c new file mode 100644 index 000000000000..c93f8969f92c --- /dev/null +++ b/drivers/power/mxs/ddi_bc_init.c @@ -0,0 +1,188 @@ +/* + * Copyright (C) 2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include "ddi_bc_internal.h" + + +/* addtogroup ddi_bc */ +/* @{ */ +/* */ +/* Copyright (c) 2004-2005 SigmaTel, Inc. */ +/* */ +/* file ddi_bc_init.c */ +/* brief Contains the Battery Charger initialization function. */ +/* date 06/2005 */ +/* */ +/* This file contains Battery Charger initialization function. */ +/* */ + + + +/* Includes and external references */ + +#include +#include "ddi_bc_internal.h" + + +/* Code */ + + + +/* brief Initialize the Battery Charger. */ +/* */ +/* fntype Function */ +/* */ +/* This function initializes the Battery Charger. */ +/* */ +/* param[in] pCfg A pointer to the new configuration. */ +/* */ +/* retval DDI_BC_STATUS_SUCCESS */ +/* If the operation succeeded. */ +/* retval DDI_BC_STATUS_ALREADY_INITIALIZED */ +/* If the Battery Charger is already initialized. */ +/* retval DDI_BC_STATUS_HARDWARE_DISABLED */ +/* If the Battery Charger hardware is disabled by a laser fuse. */ +/* retval DDI_BC_STATUS_BAD_BATTERY_MODE */ +/* If the power supply is set up for a non-rechargeable battery. */ +/* retval DDI_BC_STATUS_CLOCK_GATE_CLOSED */ +/* If the clock gate for the power supply registers is closed. */ +/* retval DDI_BC_STATUS_CFG_BAD_CHARGING_VOLTAGE */ +/* If the charging voltage is not either 4100 or 4200. */ +/* retval DDI_BC_STATUS_CFG_BAD_BATTERY_TEMP_CHANNEL */ +/* If the LRADC channel number for monitoring battery temperature */ +/* is bad. */ +/* */ + +ddi_bc_Status_t ddi_bc_Init(ddi_bc_Cfg_t *pCfg) +{ + + /* -------------------------------------------------------------------------- */ + /* We can only be initialized if we're in the Uninitialized state. */ + /* -------------------------------------------------------------------------- */ + + if (g_ddi_bc_State != DDI_BC_STATE_UNINITIALIZED) { + return DDI_BC_STATUS_ALREADY_INITIALIZED; + } + /* -------------------------------------------------------------------------- */ + /* Check if the battery charger hardware has been disabled by laser fuse. */ + /* -------------------------------------------------------------------------- */ + + if (!ddi_power_GetBatteryChargerEnabled()) + return DDI_BC_STATUS_HARDWARE_DISABLED; + + /* -------------------------------------------------------------------------- */ + /* Check if the power supply has been set up for a non-rechargeable battery. */ + /* -------------------------------------------------------------------------- */ + + switch (ddi_power_GetBatteryMode()) { + + case DDI_POWER_BATT_MODE_LIION: + break; + + /* TODO: we'll need to do NiMH also */ + default: + return DDI_BC_STATUS_BAD_BATTERY_MODE; + /* break; */ + + } + + /* -------------------------------------------------------------------------- */ + /* Make sure that the clock gate has been opened for the power supply */ + /* registers. If not, then none of our writes to those registers will */ + /* succeed, which will kind of slow us down... */ + /* -------------------------------------------------------------------------- */ + + if (ddi_power_GetPowerClkGate()) { + return DDI_BC_STATUS_CLOCK_GATE_CLOSED; + } + /* -------------------------------------------------------------------------- */ + /* Check the incoming configuration for nonsense. */ + /* -------------------------------------------------------------------------- */ + + /* */ + /* Only permitted charging voltage: 4200mV. */ + /* */ + + if (pCfg->u16ChargingVoltage != DDI_BC_LIION_CHARGING_VOLTAGE) { + return DDI_BC_STATUS_CFG_BAD_CHARGING_VOLTAGE; + } + /* */ + /* There are 8 LRADC channels. */ + /* */ + + if (pCfg->u8BatteryTempChannel > 7) { + return DDI_BC_STATUS_CFG_BAD_BATTERY_TEMP_CHANNEL; + } + /* -------------------------------------------------------------------------- */ + /* Accept the configuration. */ + /* -------------------------------------------------------------------------- */ + + /* -------------------------------------------------------------------------- */ + /* ddi_bc_Cfg_t.u16ChargingThresholdCurrent is destined for the */ + /* register field HW_POWER_BATTCHRG.STOP_ILIMIT. This 4-bit field */ + /* is unevenly quantized to provide a useful range of currents. A */ + /* side effect of the quantization is that the field can only be */ + /* set to certain unevenly-spaced values. */ + /* */ + /* Here, we use the two functions that manipulate the register field */ + /* to adjust u16ChargingThresholdCurrent to match the quantized value. */ + /* -------------------------------------------------------------------------- */ + pCfg->u16ChargingThresholdCurrent = + ddi_power_ExpressibleCurrent(pCfg->u16ChargingThresholdCurrent); + + /* -------------------------------------------------------------------------- */ + /* ...similar situation with ddi_bc_Cfg_t.u16BatteryTempSafeCurrent and */ + /* u16DieTempSafeCurrent. */ + /* -------------------------------------------------------------------------- */ + pCfg->u16BatteryTempSafeCurrent = + ddi_power_ExpressibleCurrent(pCfg->u16BatteryTempSafeCurrent); + pCfg->u16DieTempSafeCurrent = + ddi_power_ExpressibleCurrent(pCfg->u16DieTempSafeCurrent); + + g_ddi_bc_Configuration = *pCfg; + + /* -------------------------------------------------------------------------- */ + /* Turn the charger hardware off. This is a very important initial condition */ + /* because we only flip the power switch on the hardware when we make */ + /* transitions. Baseline, it needs to be off. */ + /* -------------------------------------------------------------------------- */ + + ddi_power_SetChargerPowered(0); + + /* -------------------------------------------------------------------------- */ + /* Reset the current ramp. This will jam the current to zero and power off */ + /* the charging hardware. */ + /* -------------------------------------------------------------------------- */ + + ddi_bc_RampReset(); + + /* -------------------------------------------------------------------------- */ + /* Move to the Disabled state. */ + /* -------------------------------------------------------------------------- */ + + g_ddi_bc_State = DDI_BC_STATE_DISABLED; + + /* -------------------------------------------------------------------------- */ + /* Return success. */ + /* -------------------------------------------------------------------------- */ +#ifdef CONFIG_POWER_SUPPLY_DEBUG + printk("%s: success\n", __func__); +#endif + return DDI_BC_STATUS_SUCCESS; + +} + + +/* End of file */ + +/* @} */ diff --git a/drivers/power/mxs/ddi_bc_internal.h b/drivers/power/mxs/ddi_bc_internal.h new file mode 100644 index 000000000000..b5bceeffae98 --- /dev/null +++ b/drivers/power/mxs/ddi_bc_internal.h @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2010 Freescale Semiconductor, Inc. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + + +/* addtogroup ddi_bc */ +/* @{ */ +/* */ +/* Copyright (c) 2004-2005 SigmaTel, Inc. */ +/* */ +/* file ddi_bc_internal.h */ +/* brief Internal header file for the Battery Charger device driver. */ +/* date 06/2005 */ +/* */ +/* This file contains internal declarations for the Battery Charger device */ +/* driver. */ + + +#ifndef _DDI_BC_INTERNAL_H +#define _DDI_BC_INTERNAL_H + + +/* Includes */ + + +#include +#include "ddi_bc_hw.h" +#include "ddi_bc_ramp.h" +#include "ddi_bc_sm.h" +#include "ddi_power_battery.h" + + +/* Externs */ + +#include + +extern bool g_ddi_bc_Configured; +extern ddi_bc_Cfg_t g_ddi_bc_Configuration; + + +/* End of file */ + +#endif /* _DDI_BC_H */ +/* @} */ diff --git a/drivers/power/mxs/ddi_bc_ramp.c b/drivers/power/mxs/ddi_bc_ramp.c new file mode 100644 index 000000000000..76efc0d5c32d --- /dev/null +++ b/drivers/power/mxs/ddi_bc_ramp.c @@ -0,0 +1,724 @@ +/* + * Copyright (C) 2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + + +/* addtogroup ddi_bc */ +/* @{ */ +/* */ +/* Copyright (c) 2004-2005 SigmaTel, Inc. */ +/* */ +/* file ddi_bc_ramp.c */ +/* brief Contains the Battery Charger current ramp controller. */ +/* date 06/2005 */ +/* */ +/* This file contains Battery Charger current ramp controller. */ +/* */ + + + +/* Includes and external references */ + + +#include +#include "ddi_bc_internal.h" + + +/* Definitions */ + + +/* This is the control structure for the current ramp. */ + +typedef struct _ddi_bc_RampControl { + + uint32_t u32AccumulatedTime; + + /* < The accumulated time since we last changed the actual */ + /* < current setting in the hardware. If the time between */ + /* < steps is quite short, we may have to wait for several steps */ + /* < before we can actually change the hardware setting. */ + + uint16_t u16Target; + + /* < The target current, regardless of expressibility. */ + + uint16_t u16Limit; + + /* < The current limit, regardless of expressibility. */ + + uint8_t dieTempAlarm:1; + + /* < Indicates if we are operating under a die temperature */ + /* < alarm. */ + + uint8_t batteryTempAlarm:1; + + /* < Indicates if we are operating under a battery temperature */ + /* < alarm. */ + + uint8_t ambientTempAlarm:1; + + /* < Indicates if we are operating under an ambient temperature */ + /* < alarm. */ + +} ddi_bc_RampControl_t; + + +/* Variables */ + + +/* This structure contains control information for the current ramp. */ + +static ddi_bc_RampControl_t g_RampControl; + + +/* Code */ + + + +/* */ +/* brief Reset the current ramp. */ +/* */ +/* fntype Function */ +/* */ +/* This function resets the current ramp. */ +/* */ +/* Note that this function does NOT reset the temperature alarms or the current */ +/* limit. Those can only be changed explicitly. */ +/* */ + +void ddi_bc_RampReset() +{ + + /* -------------------------------------------------------------------------- */ + /* Reset the control structure. */ + /* -------------------------------------------------------------------------- */ + + g_RampControl.u32AccumulatedTime = 0; + g_RampControl.u16Target = 0; + + /* -------------------------------------------------------------------------- */ + /* Step the ramp. Note that we don't care if this function returns an error. */ + /* We're stepping the ramp to make sure it takes immediate effect, if */ + /* possible. But, for example, if the Battery Charger is not yet */ + /* initialized, it doesn't matter. */ + /* -------------------------------------------------------------------------- */ + + ddi_bc_RampStep(0); + +} + + +/* */ +/* brief Set the target current. */ +/* */ +/* fntype Function */ +/* */ +/* This function sets the target current and implements it immediately. */ +/* */ +/* Note that this function does NOT reset the temperature alarms. Those can */ +/* only be reset explicitly. */ +/* */ +/* param[in] u16Target The target current. */ +/* */ +/* retval The expressible version of the target. */ +/* */ + +uint16_t ddi_bc_RampSetTarget(uint16_t u16Target) +{ + + /* -------------------------------------------------------------------------- */ + /* Set the target. */ + /* -------------------------------------------------------------------------- */ + + g_RampControl.u16Target = u16Target; + + /* -------------------------------------------------------------------------- */ + /* Step the ramp. Note that we don't care if this function returns an error. */ + /* We're stepping the ramp to make sure it takes immediate effect, if */ + /* possible. But, for example, if the Battery Charger is not yet */ + /* initialized, it doesn't matter. */ + /* -------------------------------------------------------------------------- */ + + ddi_bc_RampStep(0); + + /* -------------------------------------------------------------------------- */ + /* Compute and return the expressible target. */ + /* -------------------------------------------------------------------------- */ + + return ddi_bc_hwExpressibleCurrent(u16Target); + +} + + +/* */ +/* brief Report the target. */ +/* */ +/* fntype Function */ +/* */ +/* This function reports the target. */ +/* */ +/* retval The target. */ +/* */ + +uint16_t ddi_bc_RampGetTarget(void) +{ + + /* -------------------------------------------------------------------------- */ + /* Return the target. */ + /* -------------------------------------------------------------------------- */ + + return g_RampControl.u16Target; + +} + + +/* */ +/* brief Set the current limit. */ +/* */ +/* fntype Function */ +/* */ +/* This function sets the current limit and implements it immediately. */ +/* */ +/* param[in] u16Limit The current limit. */ +/* */ +/* retval The expressible version of the limit. */ +/* */ + +uint16_t ddi_bc_RampSetLimit(uint16_t u16Limit) +{ + + /* -------------------------------------------------------------------------- */ + /* Set the limit. */ + /* -------------------------------------------------------------------------- */ + + g_RampControl.u16Limit = u16Limit; + + /* -------------------------------------------------------------------------- */ + /* Step the ramp. Note that we don't care if this function returns an error. */ + /* We're stepping the ramp to make sure it takes immediate effect, if */ + /* possible. But, for example, if the Battery Charger is not yet */ + /* initialized, it doesn't matter. */ + /* -------------------------------------------------------------------------- */ + + ddi_bc_RampStep(0); + + /* -------------------------------------------------------------------------- */ + /* Compute and return the expressible limit. */ + /* -------------------------------------------------------------------------- */ + + return ddi_bc_hwExpressibleCurrent(u16Limit); + +} + + +/* */ +/* brief Report the current limit. */ +/* */ +/* fntype Function */ +/* */ +/* This function reports the current limit. */ +/* */ +/* retval The current limit. */ +/* */ + +uint16_t ddi_bc_RampGetLimit(void) +{ + + /* -------------------------------------------------------------------------- */ + /* Return the current limit. */ + /* -------------------------------------------------------------------------- */ + + return g_RampControl.u16Limit; + +} + + +/* */ +/* brief Update alarms. */ +/* */ +/* fntype Function */ +/* */ +/* This function checks for all alarms and updates the current ramp */ +/* accordingly. */ +/* */ + +void ddi_bc_RampUpdateAlarms() +{ + + /* Set to true if something changed and we need to step the ramp right away. */ + + int iStepTheRamp = 0; + + /* -------------------------------------------------------------------------- */ + /* Are we monitoring die temperature? */ + /* -------------------------------------------------------------------------- */ + + if (g_ddi_bc_Configuration.monitorDieTemp) { + + /* ---------------------------------------------------------------------- */ + /* Get the die temperature range. */ + /* ---------------------------------------------------------------------- */ + + int16_t i16Low; + int16_t i16High; + + ddi_bc_hwGetDieTemp(&i16Low, &i16High); + + /* ---------------------------------------------------------------------- */ + /* Now we need to decide if it's time to raise or lower the alarm. The */ + /* first question to ask is: Were we already under an alarm? */ + /* ---------------------------------------------------------------------- */ + + if (g_RampControl.dieTempAlarm) { + + /* ------------------------------------------------------------------ */ + /* If control arrives here, we were already under an alarm. We'll */ + /* change that if the high end of the temperature range drops below */ + /* the low temperature mark. */ + /* ------------------------------------------------------------------ */ + + if (i16High < g_ddi_bc_Configuration.u8DieTempLow) { + + /* -------------------------------------------------------------- */ + /* If control arrives here, we're safe now. Drop the alarm. */ + /* -------------------------------------------------------------- */ + + g_RampControl.dieTempAlarm = 0; + + iStepTheRamp = !0; + +#ifdef CONFIG_POWER_SUPPLY_DEBUG + printk("Battery charger: releasing " + "die temp alarm: [%d, %d] < %d\r\n", + (int32_t) i16Low, (int32_t) i16High, + (int32_t) g_ddi_bc_Configuration. + u8DieTempLow); +#endif + + } + + } else { + + /* ------------------------------------------------------------------ */ + /* If control arrives here, we were not under an alarm. We'll change */ + /* that if the high end of the temperature range rises above the */ + /* high temperature mark. */ + /* ------------------------------------------------------------------ */ + + if (i16High >= g_ddi_bc_Configuration.u8DieTempHigh) { + + /* -------------------------------------------------------------- */ + /* If control arrives here, we're running too hot. Raise the */ + /* alarm. */ + /* -------------------------------------------------------------- */ + + g_RampControl.dieTempAlarm = 1; + + iStepTheRamp = !0; + +#ifdef CONFIG_POWER_SUPPLY_DEBUG + printk("Battery charger: declaring " + "die temp alarm: [%d, %d] >= %d\r\n", + (int32_t) i16Low, (int32_t) i16High, + (int32_t) g_ddi_bc_Configuration. + u8DieTempLow); +#endif + } + + } + + } + /* -------------------------------------------------------------------------- */ + /* Are we monitoring battery temperature? */ + /* -------------------------------------------------------------------------- */ + + if (g_ddi_bc_Configuration.monitorBatteryTemp) { + + ddi_bc_Status_t status; + + /* ---------------------------------------------------------------------- */ + /* Get the battery temperature reading. */ + /* ---------------------------------------------------------------------- */ + + uint16_t u16Reading; + + status = ddi_bc_hwGetBatteryTemp(&u16Reading); + + /* ---------------------------------------------------------------------- */ + /* If there was a problem, then we ignore the reading. Otherwise, let's */ + /* have a look. */ + /* ---------------------------------------------------------------------- */ + + if (status == DDI_BC_STATUS_SUCCESS) { + + /* ------------------------------------------------------------------ */ + /* Now we need to decide if it's time to raise or lower the alarm. */ + /* The first question to ask is: Were we already under an alarm? */ + /* ------------------------------------------------------------------ */ + + if (g_RampControl.batteryTempAlarm) { + + /* -------------------------------------------------------------- */ + /* If control arrives here, we were already under an alarm. */ + /* We'll change that if the reading drops below the low mark. */ + /* -------------------------------------------------------------- */ + + if (u16Reading < + g_ddi_bc_Configuration.u16BatteryTempLow) { + + /* ---------------------------------------------------------- */ + /* If control arrives here, we're safe now. Drop the alarm. */ + /* ---------------------------------------------------------- */ + + g_RampControl.batteryTempAlarm = 0; + + iStepTheRamp = !0; + + } + + } else { + + /* -------------------------------------------------------------- */ + /* If control arrives here, we were not under an alarm. We'll */ + /* change that if the reading rises above the high mark. */ + /* -------------------------------------------------------------- */ + + if (u16Reading >= + g_ddi_bc_Configuration.u16BatteryTempHigh) { + + /* ---------------------------------------------------------- */ + /* If control arrives here, we're running too hot. Raise the */ + /* alarm. */ + /* ---------------------------------------------------------- */ + + g_RampControl.batteryTempAlarm = 1; + + iStepTheRamp = !0; + + } + + } + + } + + } + /* -------------------------------------------------------------------------- */ + /* Do we need to step the ramp? */ + /* -------------------------------------------------------------------------- */ + + if (iStepTheRamp) + ddi_bc_RampStep(0); + +} + + +/* */ +/* brief Reports the state of the die temperature alarm. */ +/* */ +/* fntype Function */ +/* */ +/* This function reports the state of the die temperature alarm. */ +/* */ +/* retval The state of the die temperature alarm. */ +/* */ + +int ddi_bc_RampGetDieTempAlarm(void) +{ + return g_RampControl.dieTempAlarm; +} + + +/* */ +/* brief Reports the state of the battery temperature alarm. */ +/* */ +/* fntype Function */ +/* */ +/* This function reports the state of the battery temperature alarm. */ +/* */ +/* retval The state of the battery temperature alarm. */ +/* */ + +int ddi_bc_RampGetBatteryTempAlarm(void) +{ + return g_RampControl.batteryTempAlarm; +} + + +/* */ +/* brief Reports the state of the ambient temperature alarm. */ +/* */ +/* fntype Function */ +/* */ +/* This function reports the state of the ambient temperature alarm. */ +/* */ +/* retval The state of the ambient temperature alarm. */ +/* */ + +int ddi_bc_RampGetAmbientTempAlarm(void) +{ + return g_RampControl.ambientTempAlarm; +} + + +/* */ +/* brief Step the current ramp. */ +/* */ +/* fntype Function */ +/* */ +/* This function steps the current ramp forward through the given amount of time. */ +/* */ +/* param[in] u32Time The time increment to add. */ +/* */ +/* retval DDI_BC_STATUS_SUCCESS If the operation succeeded. */ +/* retval DDI_BC_STATUS_NOT_INITIALIZED If the Battery Charger is not yet */ +/* initialized. */ +/* */ + +ddi_bc_Status_t ddi_bc_RampStep(uint32_t u32Time) +{ + + uint16_t u16MaxNow; + uint16_t u16Target; + uint16_t u16Cart; + int32_t i32Delta; + + /* -------------------------------------------------------------------------- */ + /* Make sure the Battery Charger is initialized. */ + /* -------------------------------------------------------------------------- */ + + if (g_ddi_bc_State == DDI_BC_STATE_UNINITIALIZED) { + return DDI_BC_STATUS_NOT_INITIALIZED; + } + /* -------------------------------------------------------------------------- */ + /* Figure out how much current the hardware is set to draw right now. */ + /* -------------------------------------------------------------------------- */ + + u16MaxNow = ddi_bc_hwGetMaxCurrent(); + + /* -------------------------------------------------------------------------- */ + /* Start with the target. */ + /* -------------------------------------------------------------------------- */ + + u16Target = g_RampControl.u16Target; + + /* -------------------------------------------------------------------------- */ + /* Check the target against the hard limit. */ + /* -------------------------------------------------------------------------- */ + + if (u16Target > g_RampControl.u16Limit) + u16Target = g_RampControl.u16Limit; + + /* -------------------------------------------------------------------------- */ + /* Check if the die temperature alarm is active. */ + /* -------------------------------------------------------------------------- */ + + if (g_RampControl.dieTempAlarm) { + + /* ---------------------------------------------------------------------- */ + /* If control arrives here, we are under a die temperature alarm. Clamp */ + /* the target current. */ + /* ---------------------------------------------------------------------- */ + + if (u16Target > g_ddi_bc_Configuration.u16DieTempSafeCurrent) { + u16Target = + g_ddi_bc_Configuration.u16DieTempSafeCurrent; + } + + } + /* -------------------------------------------------------------------------- */ + /* Check if the battery temperature alarm is active. */ + /* -------------------------------------------------------------------------- */ + + if (g_RampControl.batteryTempAlarm) { + + /* ---------------------------------------------------------------------- */ + /* If control arrives here, we are under a battery temperature alarm. */ + /* Clamp the target current. */ + /* ---------------------------------------------------------------------- */ + + if (u16Target > + g_ddi_bc_Configuration.u16BatteryTempSafeCurrent) { + u16Target = + g_ddi_bc_Configuration.u16BatteryTempSafeCurrent; + } + + } + /* -------------------------------------------------------------------------- */ + /* Now we know the target current. Figure out what is actually expressible */ + /* in the hardware. */ + /* -------------------------------------------------------------------------- */ + + u16Target = ddi_bc_hwExpressibleCurrent(u16Target); + + /* -------------------------------------------------------------------------- */ + /* Compute the difference between the expressible target and what's actually */ + /* set in the hardware right now. */ + /* -------------------------------------------------------------------------- */ + + i32Delta = ((int32_t) u16Target) - ((int32_t) u16MaxNow); + + /* -------------------------------------------------------------------------- */ + /* Check if the delta is zero. */ + /* -------------------------------------------------------------------------- */ + + if (i32Delta == 0) { + + /* ---------------------------------------------------------------------- */ + /* If control arrives here, there is no difference between what we want */ + /* and what's set in the hardware. */ + /* */ + /* Before we leave, though, we don't want to leave any accumulated time */ + /* laying around for the next ramp up. Zero it out. */ + /* ---------------------------------------------------------------------- */ + + g_RampControl.u32AccumulatedTime = 0; + + /* ---------------------------------------------------------------------- */ + /* Return success. */ + /* ---------------------------------------------------------------------- */ + + return DDI_BC_STATUS_SUCCESS; + + } + /* -------------------------------------------------------------------------- */ + /* Check if the delta is negative. */ + /* -------------------------------------------------------------------------- */ + + if (i32Delta < 0) { + + /* ---------------------------------------------------------------------- */ + /* If control arrives here, the new target is lower than what's */ + /* currently set in the hardware. Since that means we're *reducing* the */ + /* current draw, we can do it right now. Just gimme a sec here... */ + /* ---------------------------------------------------------------------- */ + + ddi_bc_hwSetMaxCurrent(u16Target); + +#ifdef CONFIG_POWER_SUPPLY_DEBUG + printk("Battery charger: setting max charge " + "current to: %hdmA\r\n", u16Target); +#endif + + /* ---------------------------------------------------------------------- */ + /* Flip the power switch on the charging hardware according to the new */ + /* current setting. */ + /* ---------------------------------------------------------------------- */ + + ddi_bc_hwSetChargerPower(u16Target != 0); + + /* ---------------------------------------------------------------------- */ + /* We don't want to leave any accumulated time laying around for the */ + /* next ramp up. Zero it out. */ + /* ---------------------------------------------------------------------- */ + + g_RampControl.u32AccumulatedTime = 0; + + /* ---------------------------------------------------------------------- */ + /* Return success. */ + /* ---------------------------------------------------------------------- */ + + return DDI_BC_STATUS_SUCCESS; + + } + /* -------------------------------------------------------------------------- */ + /* If control arrives here, the target current is higher than what's set in */ + /* the hardware right now. That means we're going to ramp it up. To do that, */ + /* we're going to "buy" more milliamps by "spending" milliseconds of time. */ + /* Add the time we've "banked" to the time we've been credited in this call. */ + /* -------------------------------------------------------------------------- */ + + u32Time += g_RampControl.u32AccumulatedTime; + + /* -------------------------------------------------------------------------- */ + /* Now we know how much we can spend. How much current will it buy? */ + /* -------------------------------------------------------------------------- */ + + u16Cart = (g_ddi_bc_Configuration.u16CurrentRampSlope * u32Time) / 1000; + + /* -------------------------------------------------------------------------- */ + /* Check how the current we can afford stacks up against the target we want. */ + /* -------------------------------------------------------------------------- */ + + if ((u16MaxNow + u16Cart) < u16Target) { + + /* ---------------------------------------------------------------------- */ + /* If control arrives here, we can't afford to buy all the current we */ + /* want. Compute the maximum we can afford, and then figure out what we */ + /* can actually express in the hardware. */ + /* ---------------------------------------------------------------------- */ + + u16Target = ddi_bc_hwExpressibleCurrent(u16MaxNow + u16Cart); + + /* ---------------------------------------------------------------------- */ + /* Check if the result isn't actually different from what's set in the */ + /* the hardware right now. */ + /* ---------------------------------------------------------------------- */ + + if (u16Target == u16MaxNow) { + + /* ------------------------------------------------------------------ */ + /* If control arrives here, we are so poor that we can't yet afford */ + /* to buy enough current to make a change in the expressible */ + /* hardware setting. Since we didn't spend any of our time, put the */ + /* new balance back in the bank. */ + /* ------------------------------------------------------------------ */ + + g_RampControl.u32AccumulatedTime = u32Time; + + /* ------------------------------------------------------------------ */ + /* Leave dispiritedly. */ + /* ------------------------------------------------------------------ */ + + return DDI_BC_STATUS_SUCCESS; + + } + + } + /* -------------------------------------------------------------------------- */ + /* If control arrives here, we can afford to buy enough current to get us */ + /* all the way to the target. Set it. */ + /* -------------------------------------------------------------------------- */ + + ddi_bc_hwSetMaxCurrent(u16Target); + +#ifdef CONFIG_POWER_SUPPLY_DEBUG + printk("Battery charger: setting max charge" + "current to: %hdmA\r\n", u16Target); +#endif + + /* -------------------------------------------------------------------------- */ + /* Flip the power switch on the charging hardware according to the new */ + /* current setting. */ + /* -------------------------------------------------------------------------- */ + + ddi_bc_hwSetChargerPower(u16Target != 0); + + /* -------------------------------------------------------------------------- */ + /* We're at the target, so we're finished buying current. Zero out the */ + /* account. */ + /* -------------------------------------------------------------------------- */ + + g_RampControl.u32AccumulatedTime = 0; + + /* -------------------------------------------------------------------------- */ + /* Return success. */ + /* -------------------------------------------------------------------------- */ + + return DDI_BC_STATUS_SUCCESS; + +} + + +/* End of file */ + +/* @} */ diff --git a/drivers/power/mxs/ddi_bc_ramp.h b/drivers/power/mxs/ddi_bc_ramp.h new file mode 100644 index 000000000000..b43db8147f52 --- /dev/null +++ b/drivers/power/mxs/ddi_bc_ramp.h @@ -0,0 +1,50 @@ +/* + * Copyright (C) 2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + + +/* addtogroup ddi_bc */ +/* ! @{ */ +/* */ +/* Copyright (c) 2004-2005 SigmaTel, Inc. */ +/* */ +/* file ddi_bc_ramp.h */ +/* brief Internal header file for Battery Charger current ramp controller. */ +/* date 06/2005 */ +/* ! */ +/* ! This file contains internal declarations for Battery current ramp */ +/* ! controller. */ + + +#ifndef _DDI_BC_RAMP_H +#define _DDI_BC_RAMP_H + + +/* Prototypes */ + + +extern void ddi_bc_RampReset(void); +extern uint16_t ddi_bc_RampSetTarget(uint16_t); +extern uint16_t ddi_bc_RampGetTarget(void); +extern uint16_t ddi_bc_RampSetLimit(uint16_t); +extern uint16_t ddi_bc_RampGetLimit(void); +extern void ddi_bc_RampUpdateAlarms(void); +extern int ddi_bc_RampGetDieTempAlarm(void); +extern int ddi_bc_RampGetBatteryTempAlarm(void); +extern int ddi_bc_RampGetAmbientTempAlarm(void); +extern ddi_bc_Status_t ddi_bc_RampStep(uint32_t); + + +/* End of file */ + +#endif /* _DDI_BC_H */ +/* ! @} */ diff --git a/drivers/power/mxs/ddi_bc_sm.c b/drivers/power/mxs/ddi_bc_sm.c new file mode 100644 index 000000000000..6626ed82c192 --- /dev/null +++ b/drivers/power/mxs/ddi_bc_sm.c @@ -0,0 +1,918 @@ +/* + * Copyright (C) 2010 Freescale Semiconductor, Inc. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + + +/* addtogroup ddi_bc */ +/* @{ */ +/* */ +/* Copyright (c) 2004-2005 SigmaTel, Inc. */ +/* */ +/* file ddi_bc_sm.c */ +/* brief Contains the Battery Charger state machine. */ + + + +/* Includes */ + + +#include +#include "ddi_bc_internal.h" + +#include + + +/* Definitions */ + + +/* This is the minimum time we must charge before we transition from */ +/* the charging state to the topping off. If we reach the */ +/* u16ChargingThresholdCurrent charge curent before then, the battery was */ +/* already full so we can avoid the risk of charging it past .1C for */ +/* too long. */ + +#define TRANSITION_TO_TOPOFF_MINIMUM_CHARGE_TIME_mS (1 * 60 * 1000) /* 1 minute */ + + +/* Variables */ + + +/* The current state. */ + +ddi_bc_State_t g_ddi_bc_State = DDI_BC_STATE_UNINITIALIZED; + +/* This table contains pointers to the functions that implement states. The */ +/* table is indexed by state. Note that it's critically important for this */ +/* table to agree with the state enumeration in ddi_bc.h. */ + +static ddi_bc_Status_t ddi_bc_Uninitialized(void); +static ddi_bc_Status_t ddi_bc_Broken(void); +static ddi_bc_Status_t ddi_bc_Disabled(void); +static ddi_bc_Status_t ddi_bc_WaitingToCharge(void); +static ddi_bc_Status_t ddi_bc_Conditioning(void); +static ddi_bc_Status_t ddi_bc_Charging(void); +static ddi_bc_Status_t ddi_bc_ToppingOff(void); + + +ddi_bc_Status_t(*const (stateFunctionTable[])) (void) = { +ddi_bc_Uninitialized, + ddi_bc_Broken, + ddi_bc_Disabled, + ddi_bc_WaitingToCharge, + ddi_bc_Conditioning, + ddi_bc_Charging, ddi_bc_ToppingOff}; + +/* Used by states that need to watch the time. */ +uint32_t g_ddi_bc_u32StateTimer; + +/* Always attempt to charge on first 5V connection */ +bool bRestartChargeCycle = true; + +#ifdef CONFIG_POWER_SUPPLY_DEBUG +static uint16_t u16ExternalBatteryPowerVoltageCheck; +#endif + +ddi_bc_BrokenReason_t ddi_bc_gBrokenReason = DDI_BC_BROKEN_UNINITIALIZED; + + +/* Code */ + + + +/* */ +/* brief Transition to the Waiting to Charge state. */ +/* */ +/* fntype Function */ +/* */ +/* This function implements the transition to the Waiting to Charge state. */ +/* */ + +static void TransitionToWaitingToCharge(void) +{ + + /* -------------------------------------------------------------------------- */ + /* Reset the state timer. */ + /* -------------------------------------------------------------------------- */ + + g_ddi_bc_u32StateTimer = 0; + + /* -------------------------------------------------------------------------- */ + /* Reset the current ramp. */ + /* -------------------------------------------------------------------------- */ + + ddi_bc_RampReset(); + + /* -------------------------------------------------------------------------- */ + /* Move to the Waiting to Charge state. */ + /* -------------------------------------------------------------------------- */ + + g_ddi_bc_State = DDI_BC_STATE_WAITING_TO_CHARGE; + +#ifdef CONFIG_POWER_SUPPLY_DEBUG + printk("Battery charger: now waiting to charge\n"); +#endif + +} + + +/* */ +/* brief Transition to the Conditioning state. */ +/* */ +/* fntype Function */ +/* */ +/* This function implements the transition to the Conditioning state. */ +/* */ + +static void TransitionToConditioning(void) +{ + + /* -------------------------------------------------------------------------- */ + /* Reset the state timer. */ + /* -------------------------------------------------------------------------- */ + + g_ddi_bc_u32StateTimer = 0; + + /* -------------------------------------------------------------------------- */ + /* Set up the current ramp for conditioning. */ + /* -------------------------------------------------------------------------- */ + + ddi_bc_RampSetTarget(g_ddi_bc_Configuration.u16ConditioningCurrent); + + /* -------------------------------------------------------------------------- */ + /* Move to the Conditioning state. */ + /* -------------------------------------------------------------------------- */ + + g_ddi_bc_State = DDI_BC_STATE_CONDITIONING; + +#ifdef CONFIG_POWER_SUPPLY_DEBUG + printk("Battery charger: now conditioning\n"); +#endif + +} + + +/* */ +/* brief Transition to the Charging state. */ +/* */ +/* fntype Function */ +/* */ +/* This function implements the transition to the Charging state. */ +/* */ + +static void TransitionToCharging(void) +{ + + /* -------------------------------------------------------------------------- */ + /* Reset the state timer. */ + /* -------------------------------------------------------------------------- */ + + g_ddi_bc_u32StateTimer = 0; + + /* -------------------------------------------------------------------------- */ + /* Set up the current ramp for charging. */ + /* -------------------------------------------------------------------------- */ + + ddi_bc_RampSetTarget(g_ddi_bc_Configuration.u16ChargingCurrent); + + /* -------------------------------------------------------------------------- */ + /* We'll be finished charging when the current flow drops below this level. */ + /* -------------------------------------------------------------------------- */ + + ddi_bc_hwSetCurrentThreshold(g_ddi_bc_Configuration. + u16ChargingThresholdCurrent); + + /* -------------------------------------------------------------------------- */ + /* Move to the Charging state. */ + /* -------------------------------------------------------------------------- */ + + g_ddi_bc_State = DDI_BC_STATE_CHARGING; +#ifdef CONFIG_POWER_SUPPLY_DEBUG + printk("Battery charger: now charging\n"); +#endif +} + + +/* */ +/* brief Transition to the Topping Off state. */ +/* */ +/* fntype Function */ +/* */ +/* This function implements the transition to the Topping Off state. */ +/* */ + +static void TransitionToToppingOff(void) +{ + + /* -------------------------------------------------------------------------- */ + /* Reset the state timer. */ + /* -------------------------------------------------------------------------- */ + + g_ddi_bc_u32StateTimer = 0; + + /* -------------------------------------------------------------------------- */ + /* Set up the current ramp for topping off. */ + /* -------------------------------------------------------------------------- */ + + ddi_bc_RampSetTarget(g_ddi_bc_Configuration.u16ChargingCurrent); + + /* -------------------------------------------------------------------------- */ + /* Move to the Topping Off state. */ + /* -------------------------------------------------------------------------- */ + + g_ddi_bc_State = DDI_BC_STATE_TOPPING_OFF; + +#ifdef CONFIG_POWER_SUPPLY_DEBUG + printk("Battery charger: now topping off\n"); +#endif + +} + + +/* */ +/* brief Transition to the Broken state. */ +/* */ +/* fntype Function */ +/* */ +/* This function implements the transition to the Broken state. */ +/* */ + +static void TransitionToBroken(void) +{ + + /* -------------------------------------------------------------------------- */ + /* Reset the state timer. */ + /* -------------------------------------------------------------------------- */ + + g_ddi_bc_u32StateTimer = 0; + + /* -------------------------------------------------------------------------- */ + /* Reset the current ramp. */ + /* -------------------------------------------------------------------------- */ + + ddi_bc_RampReset(); + + /* -------------------------------------------------------------------------- */ + /* Move to the Broken state. */ + /* -------------------------------------------------------------------------- */ + + g_ddi_bc_State = DDI_BC_STATE_BROKEN; + + pr_info("charger------ ddi_bc_gBrokenReason=%d\n", + ddi_bc_gBrokenReason); +#ifdef CONFIG_POWER_SUPPLY_DEBUG + printk("Battery charger: declaring a broken battery\n"); +#endif + +} + + +/* */ +/* brief Uninitialized state function. */ +/* */ +/* fntype Function */ +/* */ +/* This function implements the Uninitialized state. */ +/* */ + +static ddi_bc_Status_t ddi_bc_Uninitialized(void) +{ + + /* -------------------------------------------------------------------------- */ + /* The first order of business is to update alarms. */ + /* -------------------------------------------------------------------------- */ + + ddi_bc_RampUpdateAlarms(); + + /* -------------------------------------------------------------------------- */ + /* Increment the state timer. */ + /* -------------------------------------------------------------------------- */ + + g_ddi_bc_u32StateTimer += g_ddi_bc_Configuration.u32StateMachinePeriod; + + /* -------------------------------------------------------------------------- */ + /* The only way to leave this state is with a call to ddi_bc_Initialize. So, */ + /* calling this state function does nothing. */ + /* -------------------------------------------------------------------------- */ + + return DDI_BC_STATUS_SUCCESS; + +} + + +/* */ +/* brief Broken state function. */ +/* */ +/* fntype Function */ +/* */ +/* This function implements the Broken state. */ +/* */ + +static ddi_bc_Status_t ddi_bc_Broken(void) +{ + + /* -------------------------------------------------------------------------- */ + /* The first order of business is to update alarms. */ + /* -------------------------------------------------------------------------- */ + + ddi_bc_RampUpdateAlarms(); + + /* -------------------------------------------------------------------------- */ + /* Increment the state timer. */ + /* -------------------------------------------------------------------------- */ + + g_ddi_bc_u32StateTimer += g_ddi_bc_Configuration.u32StateMachinePeriod; + + /* -------------------------------------------------------------------------- */ + /* The only way to leave this state is with a call to ddi_bc_SetFixed. So, */ + /* calling this state function does nothing. */ + /* -------------------------------------------------------------------------- */ + + return DDI_BC_STATUS_SUCCESS; + +} + + +/* */ +/* brief Disabled state function. */ +/* */ +/* fntype Function */ +/* */ +/* This function implements the Disabled state. */ +/* */ + +static ddi_bc_Status_t ddi_bc_Disabled(void) +{ + + /* -------------------------------------------------------------------------- */ + /* The first order of business is to update alarms. */ + /* -------------------------------------------------------------------------- */ + + ddi_bc_RampUpdateAlarms(); + + /* -------------------------------------------------------------------------- */ + /* Increment the state timer. */ + /* -------------------------------------------------------------------------- */ + + g_ddi_bc_u32StateTimer += g_ddi_bc_Configuration.u32StateMachinePeriod; + + /* -------------------------------------------------------------------------- */ + /* The only way to leave this state is with a call to ddi_bc_SetEnable. So, */ + /* calling this state function does nothing. */ + /* -------------------------------------------------------------------------- */ + + return DDI_BC_STATUS_SUCCESS; + +} + + +/* */ +/* brief Waitin to Charge state function. */ +/* */ +/* fntype Function */ +/* */ +/* This function implements the Waiting to Charge state. */ +/* */ + +static ddi_bc_Status_t ddi_bc_WaitingToCharge(void) +{ + uint16_t u16BatteryVoltage; + /* -------------------------------------------------------------------------- */ + /* The first order of business is to update alarms. */ + /* -------------------------------------------------------------------------- */ + + ddi_bc_RampUpdateAlarms(); + + /* -------------------------------------------------------------------------- */ + /* Increment the state timer. */ + /* -------------------------------------------------------------------------- */ + + g_ddi_bc_u32StateTimer += g_ddi_bc_Configuration.u32StateMachinePeriod; + + /* -------------------------------------------------------------------------- */ + /* Check if the power supply is present. If not, we're not going anywhere. */ + /* -------------------------------------------------------------------------- */ + + if (!ddi_bc_hwPowerSupplyIsPresent()) { +#ifdef CONFIG_POWER_SUPPLY_DEBUG + u16ExternalBatteryPowerVoltageCheck = 0; +#endif + return DDI_BC_STATUS_SUCCESS; + } + /* -------------------------------------------------------------------------- */ + /* If control arrives here, we're connected to a power supply. Have a look */ + /* at the battery voltage. */ + /* -------------------------------------------------------------------------- */ + + u16BatteryVoltage = ddi_bc_hwGetBatteryVoltage(); + +#ifdef CONFIG_POWER_SUPPLY_DEBUG + if (u16ExternalBatteryPowerVoltageCheck) { + if ((u16ExternalBatteryPowerVoltageCheck - u16BatteryVoltage) > + 300) { + /* + * If control arrives here, battery voltage has + * dropped too quickly after the first charge + * cycle. We think an external voltage regulator is + * connected. + */ + + ddi_bc_gBrokenReason = + DDI_BC_BROKEN_EXTERNAL_BATTERY_VOLTAGE_DETECTED; + + TransitionToBroken(); + + /* ---------------------------------------------------------------------- */ + /* Tell our caller the battery appears to be broken. */ + /* ---------------------------------------------------------------------- */ + + return DDI_BC_STATUS_BROKEN; + } else { + /* reset this check */ + u16ExternalBatteryPowerVoltageCheck = 0; + } + + } +#endif + + + /* -------------------------------------------------------------------------- */ + /* If the battery voltage isn't low, we don't need to be charging it. We */ + /* use a 5% margin to decide. */ + /* -------------------------------------------------------------------------- */ + + if (!bRestartChargeCycle) { + uint16_t x; + + x = u16BatteryVoltage + (u16BatteryVoltage / 20); + + if (x >= g_ddi_bc_Configuration.u16ChargingVoltage) + return DDI_BC_STATUS_SUCCESS; + + } + + bRestartChargeCycle = false; + /* -------------------------------------------------------------------------- */ + /* If control arrives here, the battery is low. How low? */ + /* -------------------------------------------------------------------------- */ + + if (u16BatteryVoltage < + g_ddi_bc_Configuration.u16ConditioningThresholdVoltage) { + + /* ---------------------------------------------------------------------- */ + /* If control arrives here, the battery is very low and it needs to be */ + /* conditioned. */ + /* ---------------------------------------------------------------------- */ + + TransitionToConditioning(); + + } else { + + /* ---------------------------------------------------------------------- */ + /* If control arrives here, the battery isn't too terribly low. */ + /* ---------------------------------------------------------------------- */ + + TransitionToCharging(); + + } + + /* -------------------------------------------------------------------------- */ + /* Return success. */ + /* -------------------------------------------------------------------------- */ + + return DDI_BC_STATUS_SUCCESS; + +} + + +/* */ +/* brief Conditioning state function. */ +/* */ +/* fntype Function */ +/* */ +/* This function implements the Conditioning state. */ +/* */ + +static ddi_bc_Status_t ddi_bc_Conditioning(void) +{ + + /* -------------------------------------------------------------------------- */ + /* The first order of business is to update alarms. */ + /* -------------------------------------------------------------------------- */ + + ddi_bc_RampUpdateAlarms(); + + /* -------------------------------------------------------------------------- */ + /* If we're not under an alarm, increment the state timer. */ + /* -------------------------------------------------------------------------- */ + + if (!ddi_bc_RampGetDieTempAlarm() && !ddi_bc_RampGetBatteryTempAlarm()) { + g_ddi_bc_u32StateTimer += + g_ddi_bc_Configuration.u32StateMachinePeriod; + } + /* -------------------------------------------------------------------------- */ + /* Check if the power supply is still around. */ + /* -------------------------------------------------------------------------- */ + + if (!ddi_bc_hwPowerSupplyIsPresent()) { + + /* ---------------------------------------------------------------------- */ + /* If control arrives here, the power supply has been removed. Go back */ + /* and wait. */ + /* ---------------------------------------------------------------------- */ + + TransitionToWaitingToCharge(); + + /* ---------------------------------------------------------------------- */ + /* Return success. */ + /* ---------------------------------------------------------------------- */ + + return DDI_BC_STATUS_SUCCESS; + + } + + /* -------------------------------------------------------------------------- */ + /* If control arrives here, we're still connected to a power supply. */ + /* Check if a battery is connected. If the voltage rises to high with only */ + /* conditioning charge current, we determine that a battery is not connected. */ + /* If that is not the case and a battery is connected, check */ + /* if the battery voltage indicates it still needs conditioning. */ + /* -------------------------------------------------------------------------- */ + +/* if (ddi_bc_hwGetBatteryVoltage() >= 3900) { */ + if ((ddi_bc_hwGetBatteryVoltage() > + g_ddi_bc_Configuration.u16ConditioningMaxVoltage) && + (ddi_power_GetMaxBatteryChargeCurrent() < + g_ddi_bc_Configuration.u16ConditioningCurrent)) { + /* ---------------------------------------------------------------------- */ + /* If control arrives here, voltage has risen too quickly for so */ + /* little charge being applied so their must be no battery connected. */ + /* ---------------------------------------------------------------------- */ + + ddi_bc_gBrokenReason = DDI_BC_BROKEN_NO_BATTERY_DETECTED; + + TransitionToBroken(); + + /* ---------------------------------------------------------------------- */ + /* Tell our caller the battery appears to be broken. */ + /* ---------------------------------------------------------------------- */ + + return DDI_BC_STATUS_BROKEN; + + } + + if (ddi_bc_hwGetBatteryVoltage() >= + g_ddi_bc_Configuration.u16ConditioningMaxVoltage) { + + /* ---------------------------------------------------------------------- */ + /* If control arrives here, this battery no longer needs conditioning. */ + /* ---------------------------------------------------------------------- */ + + TransitionToCharging(); + + /* ---------------------------------------------------------------------- */ + /* Return success. */ + /* ---------------------------------------------------------------------- */ + + return DDI_BC_STATUS_SUCCESS; + + } + /* -------------------------------------------------------------------------- */ + /* Have we been in this state too long? */ + /* -------------------------------------------------------------------------- */ + + if (g_ddi_bc_u32StateTimer >= + g_ddi_bc_Configuration.u32ConditioningTimeout) { + + /* ---------------------------------------------------------------------- */ + /* If control arrives here, we've been here too long. */ + /* ---------------------------------------------------------------------- */ + + ddi_bc_gBrokenReason = DDI_BC_BROKEN_CHARGING_TIMEOUT; + + TransitionToBroken(); + + /* ---------------------------------------------------------------------- */ + /* Tell our caller the battery appears to be broken. */ + /* ---------------------------------------------------------------------- */ + + return DDI_BC_STATUS_BROKEN; + + } + /* -------------------------------------------------------------------------- */ + /* If control arrives here, we're staying in this state. Step the current */ + /* ramp. */ + /* -------------------------------------------------------------------------- */ + + ddi_bc_RampStep(g_ddi_bc_Configuration.u32StateMachinePeriod); + + /* -------------------------------------------------------------------------- */ + /* Return success. */ + /* -------------------------------------------------------------------------- */ + + return DDI_BC_STATUS_SUCCESS; + +} + + +/* */ +/* brief Charging state function. */ +/* */ +/* fntype Function */ +/* */ +/* This function implements the Charging state. */ +/* */ + +static ddi_bc_Status_t ddi_bc_Charging(void) +{ + + /* -------------------------------------------------------------------------- */ + /* This variable counts the number of times we've seen the charging status */ + /* bit cleared. */ + /* -------------------------------------------------------------------------- */ + + static int iStatusCount; + /* -------------------------------------------------------------------------- */ + /* The first order of business is to update alarms. */ + /* -------------------------------------------------------------------------- */ + + ddi_bc_RampUpdateAlarms(); + + /* -------------------------------------------------------------------------- */ + /* If we're not under an alarm, increment the state timer. */ + /* -------------------------------------------------------------------------- */ + + if (!ddi_bc_RampGetDieTempAlarm() && !ddi_bc_RampGetBatteryTempAlarm()) { + g_ddi_bc_u32StateTimer += + g_ddi_bc_Configuration.u32StateMachinePeriod; + } + /* Check if the power supply is still around. */ + + + if (!ddi_bc_hwPowerSupplyIsPresent()) { + + /* ---------------------------------------------------------------------- */ + /* If control arrives here, the power supply has been removed. Go back */ + /* and wait. */ + /* ---------------------------------------------------------------------- */ + + TransitionToWaitingToCharge(); + + /* ---------------------------------------------------------------------- */ + /* Return success. */ + /* ---------------------------------------------------------------------- */ + + return DDI_BC_STATUS_SUCCESS; + + } + /* -------------------------------------------------------------------------- */ + /* If control arrives here, we're still connected to a power supply. We need */ + /* to decide now if the battery is still charging, or if it's nearly full. */ + /* If it's still charging, we'll stay in this state. Otherwise, we'll move */ + /* to the Topping Off state. */ + /* */ + /* Most of the time, we decide that the battery is still charging simply by */ + /* checking if the the actual current flow is above the charging threshold */ + /* current (as indicated by the charge status bit). However, if we're */ + /* still ramping up to full charging current, the hardware may still be set */ + /* to deliver an amount that's less than the threshold. In that case, the */ + /* charging status bit would *definitely* show a low charging current, but */ + /* that doesn't mean the battery is ready for topping off. */ + /* */ + /* So, in summary, we will move to the Topping Off state if both of the */ + /* following are true: */ + /* */ + /* 1) The maximum current set in the hardware is greater than the charging */ + /* threshold. */ + /* -AND- */ + /* 2) The actual current flow is also higher than the threshold (as */ + /* indicated by the charge status bit). */ + /* */ + /* -------------------------------------------------------------------------- */ + + + + ddi_bc_hwSetCurrentThreshold(g_ddi_bc_Configuration. + u16ChargingThresholdCurrent); + + + { + uint16_t u16ActualProgrammedCurrent = ddi_bc_hwGetMaxCurrent(); + + /* ---------------------------------------------------------------------- */ + /* Get the Maximum current that we will ramp to. */ + /* ---------------------------------------------------------------------- */ + + /* ---------------------------------------------------------------------- */ + /* Not all possible values are expressible by the BATTCHRG_I bitfield. */ + /* The following coverts the max current value into the the closest hardware */ + /* expressible bitmask equivalent. Then, it converts this back to the actual */ + /* decimal current value that this bitmask represents. */ + /* ---------------------------------------------------------------------- */ + + uint16_t u16CurrentRampTarget = ddi_bc_RampGetTarget(); + + if (u16CurrentRampTarget > ddi_bc_RampGetLimit()) + u16CurrentRampTarget = ddi_bc_RampGetLimit(); + + /* ---------------------------------------------------------------------- */ + /* Not all possible values are expressible by the BATTCHRG_I bitfield. */ + /* The following coverts the max current value into the the closest hardware */ + /* expressible bitmask equivalent. Then, it converts this back to the actual */ + /* decimal current value that this bitmask represents. */ + /* ---------------------------------------------------------------------- */ + + u16CurrentRampTarget = + ddi_bc_hwExpressibleCurrent(u16CurrentRampTarget); + + /* ---------------------------------------------------------------------- */ + /* We want to wait before we check the charge status bit until the ramping */ + /* up is complete. Because the charge status bit is noisy, we want to */ + /* disregard it until the programmed charge currint in BATTCHRG_I is well */ + /* beyond the STOP_ILIMIT value. */ + /* ---------------------------------------------------------------------- */ + if ((u16ActualProgrammedCurrent >= u16CurrentRampTarget) && + !ddi_bc_hwGetChargeStatus()) { + uint8_t u8IlimitThresholdLimit; + /* ---------------------------------------------------------------------- */ + /* If control arrives here, the hardware flag is telling us that the */ + /* charging current has fallen below the threshold. We need to see this */ + /* happen twice consecutively before we believe it. Increment the count. */ + /* ---------------------------------------------------------------------- */ + + iStatusCount++; + + + u8IlimitThresholdLimit = 10; + + /* ---------------------------------------------------------------------- */ + /* How many times in a row have we seen this status bit low? */ + /* ---------------------------------------------------------------------- */ + + if (iStatusCount >= u8IlimitThresholdLimit) { + + /* + * If control arrives here, we've seen the + * CHRGSTS bit low too many times. This means + * it's time to move to the Topping Off state. + * First, reset the status count for the next + * time we're in this state. + */ + + iStatusCount = 0; + +#ifdef CONFIG_POWER_SUPPLY_DEBUG + u16ExternalBatteryPowerVoltageCheck = + ddi_bc_hwGetBatteryVoltage(); +#endif + + + + /* Move to the Topping Off state */ + + + TransitionToToppingOff(); + + /* ------------------------------------------------------------------ */ + /* Return success. */ + /* ------------------------------------------------------------------ */ + + return DDI_BC_STATUS_SUCCESS; + + } + + } else { + + /* ---------------------------------------------------------------------- */ + /* If control arrives here, the battery is still charging. Clear the */ + /* status count. */ + /* ---------------------------------------------------------------------- */ + + iStatusCount = 0; + + } + + } + + /* -------------------------------------------------------------------------- */ + /* Have we been in this state too long? */ + /* -------------------------------------------------------------------------- */ + + if (g_ddi_bc_u32StateTimer >= g_ddi_bc_Configuration.u32ChargingTimeout) { + + /* ---------------------------------------------------------------------- */ + /* If control arrives here, we've been here too long. */ + /* ---------------------------------------------------------------------- */ + + ddi_bc_gBrokenReason = DDI_BC_BROKEN_CHARGING_TIMEOUT; + + TransitionToBroken(); + + /* ---------------------------------------------------------------------- */ + /* Tell our caller the battery appears to be broken. */ + /* ---------------------------------------------------------------------- */ + + return DDI_BC_STATUS_BROKEN; + + } + /* -------------------------------------------------------------------------- */ + /* If control arrives here, we're staying in this state. Step the current */ + /* ramp. */ + /* -------------------------------------------------------------------------- */ + + ddi_bc_RampStep(g_ddi_bc_Configuration.u32StateMachinePeriod); + + /* -------------------------------------------------------------------------- */ + /* Return success. */ + /* -------------------------------------------------------------------------- */ + + return DDI_BC_STATUS_SUCCESS; + +} + + +/* */ +/* brief Topping Off state function. */ +/* */ +/* fntype Function */ +/* */ +/* This function implements the Topping Off state. */ +/* */ + +static ddi_bc_Status_t ddi_bc_ToppingOff(void) +{ + + /* -------------------------------------------------------------------------- */ + /* The first order of business is to update alarms. */ + + /* -------------------------------------------------------------------------- */ + + ddi_bc_RampUpdateAlarms(); + + /* -------------------------------------------------------------------------- */ + /* Increment the state timer. Notice that, unlike other states, we increment */ + /* the state timer whether or not we're under an alarm. */ + /* -------------------------------------------------------------------------- */ + + g_ddi_bc_u32StateTimer += g_ddi_bc_Configuration.u32StateMachinePeriod; + + /* -------------------------------------------------------------------------- */ + /* Check if the power supply is still around. */ + /* -------------------------------------------------------------------------- */ + + if (!ddi_bc_hwPowerSupplyIsPresent()) { + + /* ---------------------------------------------------------------------- */ + /* If control arrives here, the power supply has been removed. Go back */ + /* and wait. */ + /* --------------------------------------------------------------------- */ + + TransitionToWaitingToCharge(); + + /* ---------------------------------------------------------------------- */ + /* Return success. */ + /* ---------------------------------------------------------------------- */ + + return DDI_BC_STATUS_SUCCESS; + + } + + /* -------------------------------------------------------------------------- */ + /* Are we done topping off? */ + /* -------------------------------------------------------------------------- */ + if (g_ddi_bc_u32StateTimer >= g_ddi_bc_Configuration.u32TopOffPeriod) { + + /* ---------------------------------------------------------------------- */ + /* If control arrives here, we're done topping off. */ + /* ---------------------------------------------------------------------- */ + + TransitionToWaitingToCharge(); + + } + /* -------------------------------------------------------------------------- */ + /* If control arrives here, we're staying in this state. Step the current */ + /* ramp. */ + /* -------------------------------------------------------------------------- */ + + ddi_bc_RampStep(g_ddi_bc_Configuration.u32StateMachinePeriod); + + /* -------------------------------------------------------------------------- */ + /* Return success. */ + /* -------------------------------------------------------------------------- */ + + return DDI_BC_STATUS_SUCCESS; + +} + + +/* End of file */ + +/* @} */ diff --git a/drivers/power/mxs/ddi_bc_sm.h b/drivers/power/mxs/ddi_bc_sm.h new file mode 100644 index 000000000000..40bd4a494fb3 --- /dev/null +++ b/drivers/power/mxs/ddi_bc_sm.h @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + + +/* addtogroup ddi_bc */ +/* @{ */ +/* */ +/* Copyright (c) 2004-2005 SigmaTel, Inc. */ +/* */ +/* file ddi_bc_sm.h */ +/* brief Header file for the Battery Charger state machine. */ +/* date 06/2005 */ +/* */ +/* This file contains declarations for the Battery Charger state machine. */ + + +#ifndef _DDI_BC_SM_H +#define _DDI_BC_SM_H + + +/* Externs */ + + +/* The current state. */ + +extern ddi_bc_State_t g_ddi_bc_State; + +/* The state function table. */ + +extern ddi_bc_Status_t(*const (stateFunctionTable[])) (void); + + +/* End of file */ + +#endif /* _DDI_BC_H */ +/* @} */ diff --git a/drivers/power/mxs/ddi_power_battery.c b/drivers/power/mxs/ddi_power_battery.c new file mode 100644 index 000000000000..762f29bd784e --- /dev/null +++ b/drivers/power/mxs/ddi_power_battery.c @@ -0,0 +1,1908 @@ +/* + * Copyright (C) 2010 Freescale Semiconductor, Inc. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + + +/* addtogroup ddi_power */ +/* @{ */ +/* */ +/* Copyright(C) 2005 SigmaTel, Inc. */ +/* */ +/* file ddi_power_battery.c */ +/* brief Implementation file for the power driver battery charger. */ +/* */ + +/* Includes and external references */ + +#include +#include +#include +#include +#include /* cpu_relax */ +#include +#include +#include +#include +#include +#include +#include "ddi_bc_internal.h" + +/* brief Base voltage to start battery calculations for LiIon */ +#define BATT_BRWNOUT_LIION_BASE_MV 2800 +/* brief Constant to help with determining whether to round up or */ +/* not during calculation */ +#define BATT_BRWNOUT_LIION_CEILING_OFFSET_MV 39 +/* brief Number of mV to add if rounding up in LiIon mode */ +#define BATT_BRWNOUT_LIION_LEVEL_STEP_MV 40 +/* brief Constant value to be calculated by preprocessing */ +#define BATT_BRWNOUT_LIION_EQN_CONST \ + (BATT_BRWNOUT_LIION_BASE_MV - BATT_BRWNOUT_LIION_CEILING_OFFSET_MV) +/* brief Base voltage to start battery calculations for Alkaline/NiMH */ +#define BATT_BRWNOUT_ALKAL_BASE_MV 800 +/* brief Constant to help with determining whether to round up or */ +/* not during calculation */ +#define BATT_BRWNOUT_ALKAL_CEILING_OFFSET_MV 19 +/* brief Number of mV to add if rounding up in Alkaline/NiMH mode */ +#define BATT_BRWNOUT_ALKAL_LEVEL_STEP_MV 20 +/* brief Constant value to be calculated by preprocessing */ +#define BATT_BRWNOUT_ALKAL_EQN_CONST \ + (BATT_BRWNOUT_ALKAL_BASE_MV - BATT_BRWNOUT_ALKAL_CEILING_OFFSET_MV) + +#define GAIN_CORRECTION 1012 /* 1.012 */ + +#define VBUSVALID_THRESH_2_90V 0x0 +#define VBUSVALID_THRESH_4_00V 0x1 +#define VBUSVALID_THRESH_4_10V 0x2 +#define VBUSVALID_THRESH_4_20V 0x3 +#define VBUSVALID_THRESH_4_30V 0x4 +#define VBUSVALID_THRESH_4_40V 0x5 +#define VBUSVALID_THRESH_4_50V 0x6 +#define VBUSVALID_THRESH_4_60V 0x7 + +#define LINREG_OFFSET_STEP_BELOW 0x2 +#define BP_POWER_BATTMONITOR_BATT_VAL 16 +#define BP_POWER_CHARGE_BATTCHRG_I 0 +#define BP_POWER_CHARGE_STOP_ILIMIT 8 + +#define VDD4P2_ENABLED + +#define DDI_POWER_BATTERY_XFER_THRESHOLD_MV 3200 + + +#ifndef BATTERY_VOLTAGE_CMPTRIP100_THRESHOLD_MV +#define BATTERY_VOLTAGE_CMPTRIP100_THRESHOLD_MV 4000 +#endif + +#ifndef BATTERY_VOLTAGE_CMPTRIP105_THRESHOLD_MV +#define BATTERY_VOLTAGE_CMPTRIP105_THRESHOLD_MV 3800 +#endif + +/* #define DEBUG_IRQS */ + +/* to be re-enabled once FIQ functionality is added */ +#define DISABLE_VDDIO_BO_PROTECTION + +#ifdef CONFIG_ARCH_MX28 +#define BM_POWER_STS_VBUSVALID BM_POWER_STS_VBUSVALID0 +#endif + +/* Globals & Variables */ + + + +/* Select your 5V Detection method */ + +static ddi_power_5vDetection_t DetectionMethod = + DDI_POWER_5V_VDD5V_GT_VDDIO; +/* static ddi_power_5vDetection_t DetectionMethod = DDI_POWER_5V_VBUSVALID; */ + + +/* Code */ + + +#if 0 +static void dump_regs(void) +{ + printk("HW_POWER_CHARGE 0x%08x\n", __raw_readl(REGS_POWER_BASE + HW_POWER_CHARGE)); + printk("HW_POWER_STS 0x%08x\n", __raw_readl(REGS_POWER_BASE + HW_POWER_STS)); + printk("HW_POWER_BATTMONITOR 0x%08x\n", __raw_readl(REGS_POWER_BASE + HW_POWER_BATTMONITOR)); +} +#endif + +/* This array maps bit numbers to current increments, as used in the register */ +/* fields HW_POWER_CHARGE.STOP_ILIMIT and HW_POWER_CHARGE.BATTCHRG_I. */ +static const uint16_t currentPerBit[] = { 10, 20, 50, 100, 200, 400 }; + +uint16_t ddi_power_convert_current_to_setting(uint16_t u16Current) +{ + int i; + uint16_t u16Mask; + uint16_t u16Setting = 0; + + /* Scan across the bit field, adding in current increments. */ + u16Mask = (0x1 << 5); + + for (i = 5; (i >= 0) && (u16Current > 0); i--, u16Mask >>= 1) { + if (u16Current >= currentPerBit[i]) { + u16Current -= currentPerBit[i]; + u16Setting |= u16Mask; + } + } + + /* Return the result. */ + return u16Setting; +} + + +/* See hw_power.h for details. */ + +uint16_t ddi_power_convert_setting_to_current(uint16_t u16Setting) +{ + int i; + uint16_t u16Mask; + uint16_t u16Current = 0; + + /* Scan across the bit field, adding in current increments. */ + u16Mask = (0x1 << 5); + + for (i = 5; i >= 0; i--, u16Mask >>= 1) { + if (u16Setting & u16Mask) + u16Current += currentPerBit[i]; + } + + /* Return the result. */ + return u16Current; +} + +void ddi_power_Enable5vDetection(void) +{ + u32 val; + /* Disable hardware power down when 5V is inserted or removed */ + __raw_writel(BM_POWER_5VCTRL_PWDN_5VBRNOUT, + REGS_POWER_BASE + HW_POWER_5VCTRL_CLR); + + /* Enabling VBUSVALID hardware detection even if VDD5V_GT_VDDIO + * is the detection method being used for 5V status (hardware + * or software). This is in case any other drivers (such as + * USB) are specifically monitoring VBUSVALID status + */ + __raw_writel(BM_POWER_5VCTRL_VBUSVALID_5VDETECT, + REGS_POWER_BASE + HW_POWER_5VCTRL_SET); + + /* Set 5V detection threshold to 4.3V for VBUSVALID. */ + __raw_writel( + BF_POWER_5VCTRL_VBUSVALID_TRSH(VBUSVALID_THRESH_4_30V), + REGS_POWER_BASE + HW_POWER_5VCTRL_SET); + + /* gotta set LINREG_OFFSET to STEP_BELOW according to manual */ + val = __raw_readl(REGS_POWER_BASE + HW_POWER_VDDIOCTRL); + val &= ~(BM_POWER_VDDIOCTRL_LINREG_OFFSET); + val |= BF_POWER_VDDIOCTRL_LINREG_OFFSET(LINREG_OFFSET_STEP_BELOW); + __raw_writel(val, REGS_POWER_BASE + HW_POWER_VDDIOCTRL); + + val = __raw_readl(REGS_POWER_BASE + HW_POWER_VDDACTRL); + val &= ~(BM_POWER_VDDACTRL_LINREG_OFFSET); + val |= BF_POWER_VDDACTRL_LINREG_OFFSET(LINREG_OFFSET_STEP_BELOW); + __raw_writel(val, REGS_POWER_BASE + HW_POWER_VDDACTRL); + + val = __raw_readl(REGS_POWER_BASE + HW_POWER_VDDDCTRL); + val &= ~(BM_POWER_VDDDCTRL_LINREG_OFFSET); + val |= BF_POWER_VDDDCTRL_LINREG_OFFSET(LINREG_OFFSET_STEP_BELOW); + __raw_writel(val, REGS_POWER_BASE + HW_POWER_VDDDCTRL); + + /* Clear vbusvalid interrupt flag */ + __raw_writel(BM_POWER_CTRL_VBUSVALID_IRQ, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + __raw_writel(BM_POWER_CTRL_VDD5V_GT_VDDIO_IRQ, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + /* enable vbusvalid irq */ + + + /* enable 5V Detection interrupt vbusvalid irq */ + switch (DetectionMethod) { + case DDI_POWER_5V_VBUSVALID: + /* Check VBUSVALID for 5V present */ + __raw_writel(BM_POWER_CTRL_ENIRQ_VBUS_VALID, + REGS_POWER_BASE + HW_POWER_CTRL_SET); + break; + case DDI_POWER_5V_VDD5V_GT_VDDIO: + /* Check VDD5V_GT_VDDIO for 5V present */ + __raw_writel(BM_POWER_CTRL_ENIRQ_VDD5V_GT_VDDIO, + REGS_POWER_BASE + HW_POWER_CTRL_SET); + break; + } +} + +/* + * This function prepares the hardware for a 5V-to-battery handoff. It assumes + * the current configuration is using 5V as the power source. The 5V + * interrupt will be set up for a 5V removal. + */ +void ddi_power_enable_5v_to_battery_handoff(void) +{ + /* Clear vbusvalid interrupt flag */ + __raw_writel(BM_POWER_CTRL_VBUSVALID_IRQ, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + __raw_writel(BM_POWER_CTRL_VDD5V_GT_VDDIO_IRQ, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + + /* detect 5v unplug */ + __raw_writel(BM_POWER_CTRL_POLARITY_VBUSVALID, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + __raw_writel(BM_POWER_CTRL_POLARITY_VDD5V_GT_VDDIO, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + +#ifndef VDD4P2_ENABLED + /* Enable automatic transition to DCDC */ + __raw_writel(BM_POWER_5VCTRL_DCDC_XFER, + REGS_POWER_BASE + HW_POWER_5VCTRL_SET); +#endif +} + +/* + * This function will handle all the power rail transitions necesarry to power + * the chip from the battery when it was previously powered from the 5V power + * source. + */ +void ddi_power_execute_5v_to_battery_handoff(void) +{ + int val; +#ifdef VDD4P2_ENABLED + val = __raw_readl(REGS_POWER_BASE + HW_POWER_DCDC4P2); + val &= ~(BM_POWER_DCDC4P2_ENABLE_DCDC | BM_POWER_DCDC4P2_ENABLE_4P2); + __raw_writel(val, REGS_POWER_BASE + HW_POWER_DCDC4P2); + + __raw_writel(BM_POWER_5VCTRL_PWD_CHARGE_4P2, + REGS_POWER_BASE + HW_POWER_5VCTRL_SET); + + /* make VBUSVALID_TRSH 4400mV and set PWD_CHARGE_4P2 */ + __raw_writel(BM_POWER_5VCTRL_VBUSVALID_TRSH, + REGS_POWER_BASE + HW_POWER_5VCTRL_CLR); + + __raw_writel(BF_POWER_5VCTRL_VBUSVALID_TRSH(VBUSVALID_THRESH_4_40V), + REGS_POWER_BASE + HW_POWER_5VCTRL_SET); + +#else + /* VDDD has different configurations depending on the battery type */ + /* and battery level. */ + + /* For LiIon battery, we will use the DCDC to power VDDD. */ + /* Use LinReg offset for DCDC mode. */ + __raw_writel(BF_POWER_VDDDCTRL_LINREG_OFFSET(LINREG_OFFSET_STEP_BELOW), + HW_POWER_BASE + HW_POWER_VDDDCTRL_SET); + /* Turn on the VDDD DCDC output and turn off the VDDD LinReg output. */ + __raw_writel(BM_POWER_VDDDCTRL_DISABLE_FET, + HW_POWER_BASE + HW_POWER_VDDDCTRL_CLR); + + __raw_writel(BM_POWER_VDDDCTRL_ENABLE_LINREG, + HW_POWER_BASE + HW_POWER_VDDDCTRL_CLR); + /* Make sure stepping is enabled when using DCDC. */ + __raw_writel(BM_POWER_VDDDCTRL_DISABLE_STEPPING, + HW_POWER_BASE + HW_POWER_VDDDCTRL_CLR); + + /* Power VDDA and VDDIO from the DCDC. */ + + /* Use LinReg offset for DCDC mode. */ + __raw_writel(BF_POWER_VDDACTRL_LINREG_OFFSET(LINREG_OFFSET_STEP_BELOW), + HW_POWER_BASE + HW_POWER_VDDACTRL_SET); + /* Turn on the VDDA DCDC converter output and turn off LinReg output. */ + __raw_writel(BM_POWER_VDDACTRL_DISABLE_FET, + HW_POWER_BASE + HW_POWER_VDDACTRL_CLR); + __raw_writel(BM_POWER_VDDACTRL_ENABLE_LINREG, + HW_POWER_BASE + HW_POWER_VDDACTRL_CLR); + + /* Make sure stepping is enabled when using DCDC. */ + __raw_writel(BM_POWER_VDDACTRL_DISABLE_STEPPING, + HW_POWER_BASE + HW_POWER_VDDACTRL_CLR); + + /* Use LinReg offset for DCDC mode. */ + __raw_writel(BF_POWER_VDDIOCTRL_LINREG_OFFSET( + LINREG_OFFSET_STEP_BELOW + ), + HW_POWER_BASE + HW_POWER_VDDIOCTRL_SET); + + /* Turn on the VDDIO DCDC output and turn on the LinReg output.*/ + __raw_writel(BM_POWER_VDDIOCTRL_DISABLE_FET, + HW_POWER_BASE + HW_POWER_VDDIOCTRL_CLR); + + __raw_writel(BM_POWER_5VCTRL_ILIMIT_EQ_ZERO, + HW_POWER_BASE + HW_POWER_5VCTRL_CLR_CLR); + + /* Make sure stepping is enabled when using DCDC. */ + __raw_writel(BM_POWER_VDDIOCTRL_DISABLE_STEPPING, + HW_POWER_BASE + HW_POWER_VDDIOCTRL_CLR); +#endif + +} + +/* + * This function sets up battery-to-5V handoff. The power switch from + * battery to 5V is automatic. This funtion enables the 5V present detection + * such that the 5V interrupt can be generated if it is enabled. (The interrupt + * handler can inform software the 5V present event.) To deal with noise or + * a high current, this function enables DCDC1/2 based on the battery mode. + */ +void ddi_power_enable_battery_to_5v_handoff(void) +{ + /* Clear vbusvalid interrupt flag */ + __raw_writel(BM_POWER_CTRL_VBUSVALID_IRQ, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + __raw_writel(BM_POWER_CTRL_VDD5V_GT_VDDIO_IRQ, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + + /* detect 5v plug-in */ + __raw_writel(BM_POWER_CTRL_POLARITY_VBUSVALID, + REGS_POWER_BASE + HW_POWER_CTRL_SET); + __raw_writel(BM_POWER_CTRL_POLARITY_VDD5V_GT_VDDIO, + REGS_POWER_BASE + HW_POWER_CTRL_SET); + +#ifndef VDD4P2_ENABLED + /* Force current from 5V to be zero by disabling its entry source. */ + __raw_writel(BM_POWER_5VCTRL_ILIMIT_EQ_ZERO, + REGS_POWER_BASE + HW_POWER_5VCTRL_SET); +#endif + /* Allow DCDC be to active when 5V is present. */ + __raw_writel(BM_POWER_5VCTRL_ENABLE_DCDC, + REGS_POWER_BASE + HW_POWER_5VCTRL_SET); +} + +/* This function handles the transitions on each of theVDD5V_GT_VDDIO power + * rails necessary to power the chip from the 5V power supply when it was + * previously powered from the battery power supply. + */ +void ddi_power_execute_battery_to_5v_handoff(void) +{ + +#ifdef VDD4P2_ENABLED + ddi_power_Enable4p2(450); +#else + /* Disable the DCDC during 5V connections. */ + __raw_writel(BM_POWER_5VCTRL_ENABLE_DCDC, + HW_POWER_BAE + HW_POWER_5VCTRL_CLR); + + /* Power the VDDD/VDDA/VDDIO rail from the linear regulator. The DCDC */ + /* is ready to automatically power the chip when 5V is removed. */ + /* Use this configuration when powering from 5V */ + + /* Use LinReg offset for LinReg mode */ + __raw_writel(BF_POWER_VDDDCTRL_LINREG_OFFSET(LINREG_OFFSET_STEP_BELOW), + HW_POWER_BAE + HW_POWER_VDDDCTRL_SET); + + /* Turn on the VDDD LinReg and turn on the VDDD DCDC output. The */ + /* ENABLE_DCDC must be cleared to avoid LinReg and DCDC conflict. */ + __raw_writel(BM_POWER_VDDDCTRL_ENABLE_LINREG, + HW_POWER_BAE + HW_POWER_VDDDCTRL_SET); + __raw_writel(BM_POWER_VDDDCTRL_DISABLE_FET, + HW_POWER_BAE + HW_POWER_VDDDCTRL_CLR); + + /* Make sure stepping is disabled when using linear regulators */ + __raw_writel(BM_POWER_VDDDCTRL_DISABLE_STEPPING, + HW_POWER_BAE + HW_POWER_VDDDCTRL_SET); + + /* Use LinReg offset for LinReg mode */ + __raw_writel(BM_POWER_VDDACTRL_LINREG_OFFSET(LINREG_OFFSET_STEP_BELOW), + HW_POWER_BAE + HW_POWER_VDDACTRL_SET); + + + /* Turn on the VDDA LinReg output and prepare the DCDC for transfer. */ + /* ENABLE_DCDC must be clear to avoid DCDC and LinReg conflict. */ + stmp3xxx_set(BM_POWER_VDDACTRL_ENABLE_LINREG, + HW_POWER_BASE + HW_POWER_VDDACTRL_SET); + __raw_writel(BM_POWER_VDDACTRL_DISABLE_FET, + HW_POWER_BASE + HW_POWER_VDDACTRL_CLR); + + /* Make sure stepping is disabled when using linear regulators */ + __raw_writel(BM_POWER_VDDACTRL_DISABLE_STEPPING, + HW_POWER_BASE + HW_POWER_VDDACTRL_SET); + + /* Use LinReg offset for LinReg mode. */ + __raw_writel(BF_POWER_VDDIOCTRL_LINREG_OFFSET( + LINREG_OFFSET_STEP_BELOW), + HW_POWER_BASE + HW_POWER_VDDIOCTRL_SET); + + /* Turn on the VDDIO LinReg output and prepare the VDDIO DCDC output. */ + /* ENABLE_DCDC must be cleared to prevent DCDC and LinReg conflict. */ + __raw_writel(BM_POWER_VDDIOCTRL_DISABLE_FET, + HW_POWER_BASE + HW_POWER_VDDIOCTRL_CLR); + __raw_writel(BM_POWER_5VCTRL_ILIMIT_EQ_ZERO, + REGS_POWER_BASE + HW_POWER_5VCTRL_CLR); + + /* Make sure stepping is disabled when using DCDC. */ + __raw_writel(BM_POWER_VDDIOCTRL_DISABLE_STEPPING, + REGS_POWER_BASE + HW_POWER_VDDIOCTRL_SET); +#endif +} + + +void ddi_power_Start4p2Dcdc(bool battery_ready) +{ + uint32_t temp_reg, old_values; + bool vdda_pwdn = false, vddd_pwdn = false, vddio_pwdn = false; + +#ifndef CONFIG_ARCH_MX28 + /* set vbusvalid threshold to 2.9V because of errata */ + __raw_writel(BM_POWER_5VCTRL_VBUSVALID_TRSH, + REGS_POWER_BASE + HW_POWER_5VCTRL_CLR); +#endif + +#if 0 + if (battery_ready) + ddi_power_EnableBatteryIrq(); + else + enable_4p2_fiq_shutdown(); +#endif + + /* enable hardware shutdown on battery brownout */ + __raw_writel( + BM_POWER_BATTMONITOR_PWDN_BATTBRNOUT | + __raw_readl(REGS_POWER_BASE + HW_POWER_BATTMONITOR), + REGS_POWER_BASE + HW_POWER_BATTMONITOR); + + /* set VBUS DROOP threshold to 4.3V */ + __raw_writel(BM_POWER_5VCTRL_VBUSDROOP_TRSH, + REGS_POWER_BASE + HW_POWER_5VCTRL_CLR); + + /* turn of vbus valid detection. Part of errate + * workaround. */ + __raw_writel(BM_POWER_5VCTRL_PWRUP_VBUS_CMPS, + REGS_POWER_BASE + HW_POWER_5VCTRL_SET); + + __raw_writel(BM_POWER_5VCTRL_VBUSVALID_5VDETECT, + REGS_POWER_BASE + HW_POWER_5VCTRL_CLR); + + if (__raw_readl(REGS_POWER_BASE + HW_POWER_VDDIOCTRL) + & BM_POWER_VDDIOCTRL_PWDN_BRNOUT) + vddio_pwdn = true; + + if (__raw_readl(REGS_POWER_BASE + HW_POWER_VDDDCTRL) + & BM_POWER_VDDDCTRL_PWDN_BRNOUT) + vddd_pwdn = true; + + if (__raw_readl(REGS_POWER_BASE + HW_POWER_VDDACTRL) + & BM_POWER_VDDACTRL_PWDN_BRNOUT) + vdda_pwdn = true; + + __raw_writel(__raw_readl(REGS_POWER_BASE + HW_POWER_VDDACTRL) + & (~BM_POWER_VDDACTRL_PWDN_BRNOUT), + REGS_POWER_BASE + HW_POWER_VDDACTRL); + + __raw_writel(__raw_readl(REGS_POWER_BASE + HW_POWER_VDDDCTRL) + & (~BM_POWER_VDDDCTRL_PWDN_BRNOUT), + REGS_POWER_BASE + HW_POWER_VDDDCTRL); + + __raw_writel(__raw_readl(REGS_POWER_BASE + HW_POWER_VDDIOCTRL) + & (~BM_POWER_VDDIOCTRL_PWDN_BRNOUT), + REGS_POWER_BASE + HW_POWER_VDDIOCTRL); + + if ((__raw_readl(REGS_POWER_BASE + HW_POWER_STS) + & BM_POWER_STS_VDDIO_BO) == 0) + __raw_writel(BM_POWER_CTRL_VDDIO_BO_IRQ, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + + if ((__raw_readl(REGS_POWER_BASE + HW_POWER_STS) + & BM_POWER_STS_VDDD_BO) == 0) + __raw_writel(BM_POWER_CTRL_VDDD_BO_IRQ, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + + if ((__raw_readl(REGS_POWER_BASE + HW_POWER_STS) + & BM_POWER_STS_VDDA_BO) == 0) + __raw_writel(BM_POWER_CTRL_VDDA_BO_IRQ, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + + temp_reg = (BM_POWER_CTRL_ENIRQ_VDDD_BO | + BM_POWER_CTRL_ENIRQ_VDDA_BO | + BM_POWER_CTRL_ENIRQ_VDDIO_BO | + BM_POWER_CTRL_ENIRQ_VDD5V_DROOP | + BM_POWER_CTRL_ENIRQ_VBUS_VALID); + + /* save off old brownout enable values */ + old_values = __raw_readl(REGS_POWER_BASE + HW_POWER_CTRL) & + temp_reg; + + /* disable irqs affected by errata */ + __raw_writel(temp_reg, REGS_POWER_BASE + HW_POWER_CTRL_CLR); + + /* Enable DCDC from 4P2 */ + __raw_writel(__raw_readl(REGS_POWER_BASE + HW_POWER_DCDC4P2) | + BM_POWER_DCDC4P2_ENABLE_DCDC, + REGS_POWER_BASE + HW_POWER_DCDC4P2); + + /* give a delay to check for errate noise problem */ + mdelay(1); + + temp_reg = (BM_POWER_CTRL_VDDD_BO_IRQ | + BM_POWER_CTRL_VDDA_BO_IRQ | + BM_POWER_CTRL_VDDIO_BO_IRQ | + BM_POWER_CTRL_VDD5V_DROOP_IRQ | + BM_POWER_CTRL_VBUSVALID_IRQ); + + __raw_writel(temp_reg, REGS_POWER_BASE + HW_POWER_CTRL_CLR); + /* stay in this loop until the false brownout indciations + * no longer occur or until 5V actually goes away + */ + while ((__raw_readl(REGS_POWER_BASE + HW_POWER_CTRL) & temp_reg) && + !(__raw_readl(REGS_POWER_BASE + HW_POWER_CTRL) & + BM_POWER_CTRL_VDD5V_GT_VDDIO_IRQ)) { + __raw_writel(temp_reg, REGS_POWER_BASE + HW_POWER_CTRL_CLR); + + mdelay(1); + } + /* revert to previous enable irq values */ + __raw_writel(old_values, REGS_POWER_BASE + HW_POWER_CTRL_SET); + + if (vdda_pwdn) + __raw_writel(__raw_readl(REGS_POWER_BASE + HW_POWER_VDDACTRL) + | BM_POWER_VDDACTRL_PWDN_BRNOUT, + REGS_POWER_BASE + HW_POWER_VDDACTRL); + + if (vddd_pwdn) + __raw_writel(__raw_readl(REGS_POWER_BASE + HW_POWER_VDDDCTRL) + | BM_POWER_VDDDCTRL_PWDN_BRNOUT, + REGS_POWER_BASE + HW_POWER_VDDDCTRL); + + if (vddio_pwdn) + __raw_writel(__raw_readl(REGS_POWER_BASE + HW_POWER_VDDIOCTRL) + | BM_POWER_VDDIOCTRL_PWDN_BRNOUT, + REGS_POWER_BASE + HW_POWER_VDDIOCTRL); + + if (DetectionMethod == DDI_POWER_5V_VBUSVALID) + __raw_writel(BM_POWER_5VCTRL_VBUSVALID_5VDETECT, + REGS_POWER_BASE + HW_POWER_5VCTRL_SET); +} + + +/* set the optimal CMPTRIP for the best possible 5V + * disconnection handling but without drawing power + * from the power on a stable 4p2 rails (at 4.2V). + */ +void ddi_power_handle_cmptrip(void) +{ + enum ddi_power_5v_status pmu_5v_status; + uint32_t temp = __raw_readl(REGS_POWER_BASE + HW_POWER_DCDC4P2); + temp &= ~(BM_POWER_DCDC4P2_CMPTRIP); + + pmu_5v_status = ddi_power_GetPmu5vStatus(); + + /* CMPTRIP should remain at 31 when 5v is disconnected + * or 5v is connected but hasn't been handled yet + */ + if (pmu_5v_status != existing_5v_connection) + temp |= (31 << BP_POWER_DCDC4P2_CMPTRIP); + else if (ddi_power_GetBattery() > + BATTERY_VOLTAGE_CMPTRIP100_THRESHOLD_MV) + temp |= (1 << BP_POWER_DCDC4P2_CMPTRIP); + else if (ddi_power_GetBattery() > + BATTERY_VOLTAGE_CMPTRIP105_THRESHOLD_MV) + temp |= (24 << BP_POWER_DCDC4P2_CMPTRIP); + else + temp |= (31 << BP_POWER_DCDC4P2_CMPTRIP); + + + __raw_writel(temp, REGS_POWER_BASE + HW_POWER_DCDC4P2); +} + +void ddi_power_Init4p2Params(void) +{ + uint32_t temp; + + ddi_power_handle_cmptrip(); + + temp = __raw_readl(REGS_POWER_BASE + HW_POWER_DCDC4P2); + + /* DROPOUT CTRL to 10, TRG to 0 */ + temp &= ~(BM_POWER_DCDC4P2_TRG | BM_POWER_DCDC4P2_DROPOUT_CTRL); + temp |= (0xa << BP_POWER_DCDC4P2_DROPOUT_CTRL); + + __raw_writel(temp, REGS_POWER_BASE + HW_POWER_DCDC4P2); + + + temp = __raw_readl(REGS_POWER_BASE + HW_POWER_5VCTRL); + + /* HEADROOM_ADJ to 4, CHARGE_4P2_ILIMIT to 0 */ + temp &= ~(BM_POWER_5VCTRL_HEADROOM_ADJ | + BM_POWER_5VCTRL_CHARGE_4P2_ILIMIT); + temp |= (4 << BP_POWER_5VCTRL_HEADROOM_ADJ); + +} + +bool ddi_power_IsBattRdyForXfer(void) +{ + uint16_t u16BatteryVoltage = ddi_power_GetBattery(); + + if (u16BatteryVoltage > DDI_POWER_BATTERY_XFER_THRESHOLD_MV) + return true; + else + return false; +} + +void ddi_power_EnableVbusDroopIrq(void) +{ + + __raw_writel(BM_POWER_CTRL_VDD5V_DROOP_IRQ, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + + __raw_writel(BM_POWER_CTRL_ENIRQ_VDD5V_DROOP, + REGS_POWER_BASE + HW_POWER_CTRL_SET); + +} + + +void ddi_power_Enable4p2(uint16_t target_current_limit_ma) +{ + + uint16_t u16BatteryVoltage; + uint32_t temp_reg; + + ddi_power_Init4p2Params(); + /* disable 4p2 rail brownouts for now. (they + * should have already been off at this point) */ + __raw_writel(BM_POWER_CTRL_ENIRQ_DCDC4P2_BO, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + + u16BatteryVoltage = ddi_power_GetBattery(); + + if (ddi_power_IsBattRdyForXfer()) { + + /* PWD_CHARGE_4P2 should already be set but just in case... */ + __raw_writel(BM_POWER_5VCTRL_PWD_CHARGE_4P2, + REGS_POWER_BASE + HW_POWER_5VCTRL_SET); + + /* set CMPTRIP to DCDC_4P2 pin >= BATTERY pin */ + temp_reg = __raw_readl(REGS_POWER_BASE + HW_POWER_DCDC4P2); + temp_reg &= ~(BM_POWER_DCDC4P2_CMPTRIP); + temp_reg |= (31 << BP_POWER_DCDC4P2_CMPTRIP); + __raw_writel(temp_reg, REGS_POWER_BASE + HW_POWER_DCDC4P2); + + /* since we have a good battery, we can go ahead + * and turn on the Dcdcing from the 4p2 source. + * This is helpful in working around the chip + * errata. + */ + ddi_power_Start4p2Dcdc(true); + + /* Enable VbusDroopIrq to handle errata */ + + /* set vbus droop detection level to 4.3V */ + __raw_writel(BM_POWER_5VCTRL_VBUSDROOP_TRSH, + REGS_POWER_BASE + HW_POWER_5VCTRL_CLR); + + ddi_power_EnableVbusDroopIrq(); + /* now that the DCDC4P2 problems are cleared, + * turn on and ramp up the 4p2 regulator + */ + temp_reg = ddi_power_BringUp4p2Regulator( + target_current_limit_ma, true); + + /* if we still have our 5V connection, we can disable + * battery brownout interrupt. This is because the + * VDD5V DROOP IRQ handler will also shutdown if battery + * is browned out and it will enable the battery brownout + * and bring VBUSVALID_TRSH level back to a normal level + * which caused the hardware battery brownout shutdown + * to be enabled. The benefit of this is that device + * that have detachable batteries (or devices going through + * the assembly line and running this firmware to test + * with) can avoid shutting down if 5V is present and + * battery voltage goes away. + */ + if (!(__raw_readl(REGS_POWER_BASE + HW_POWER_CTRL) & + (BM_POWER_CTRL_VBUSVALID_IRQ | + BM_POWER_CTRL_VDD5V_DROOP_IRQ))) { + ddi_power_EnableBatteryBoInterrupt(false); + } + + + + printk(KERN_DEBUG "4P2 rail started. 5V current limit\ + set to %dmA\n", temp_reg); + + } else { + + printk(KERN_ERR "4P2 rail was attempted to be started \ + from a system\ + with a very low battery voltage. This is not\ + yet handled by the kernel driver, only by the\ + bootlets. Remaining on battery power.\n"); + + if ((__raw_readl(REGS_POWER_BASE + HW_POWER_5VCTRL) && + BM_POWER_5VCTRL_ENABLE_DCDC)) + ddi_power_EnableBatteryBoInterrupt(true); + +#if 0 + /* enable hardware shutdown (if 5v disconnected) + * on battery brownout */ + __raw_writel( + BM_POWER_BATTMONITOR_PWDN_BATTBRNOUT | + __raw_readl(REGS_POWER_BASE + HW_POWER_BATTMONITOR), + REGS_POWER_BASE + HW_POWER_BATTMONITOR); + + /* turn on and ramp up the 4p2 regulator */ + temp_reg = ddi_power_BringUp4p2Regulator( + target_current_limit_ma, false); + + Configure4p2FiqShutdown(); + + SetVbusValidThresh(0); +#endif + } + +} + +/* enable and ramp up 4p2 regulator */ +uint16_t ddi_power_BringUp4p2Regulator( + uint16_t target_current_limit_ma, + bool b4p2_dcdc_enabled) +{ + uint32_t temp_reg; + uint16_t charge_4p2_ilimit = 0; + + /* initial current limit to 0 */ + __raw_writel(BM_POWER_5VCTRL_CHARGE_4P2_ILIMIT, + REGS_POWER_BASE + HW_POWER_5VCTRL_CLR); + + __raw_writel(__raw_readl(REGS_POWER_BASE + HW_POWER_DCDC4P2) | + BM_POWER_DCDC4P2_ENABLE_4P2, + REGS_POWER_BASE + HW_POWER_DCDC4P2); + + /* set 4p2 target voltage to zero */ + temp_reg = __raw_readl(REGS_POWER_BASE + HW_POWER_DCDC4P2); + temp_reg &= (~BM_POWER_DCDC4P2_TRG); + __raw_writel(temp_reg, REGS_POWER_BASE + HW_POWER_DCDC4P2); + + /* Enable 4P2 regulator*/ + __raw_writel(BM_POWER_5VCTRL_PWD_CHARGE_4P2, + REGS_POWER_BASE + HW_POWER_5VCTRL_CLR); + + if (target_current_limit_ma > 780) + target_current_limit_ma = 780; + + ddi_power_Set4p2BoLevel(4150); + + /* possibly not necessary but recommended for unloaded + * 4p2 rail + */ + __raw_writel(BM_POWER_CHARGE_ENABLE_LOAD, + REGS_POWER_BASE + HW_POWER_CHARGE_SET); + + while (charge_4p2_ilimit < target_current_limit_ma) { + + if (__raw_readl(REGS_POWER_BASE + HW_POWER_CTRL) & + (BM_POWER_CTRL_VBUSVALID_IRQ | + BM_POWER_CTRL_VDD5V_DROOP_IRQ)) + break; + + + charge_4p2_ilimit += 100; + if (charge_4p2_ilimit > target_current_limit_ma) + charge_4p2_ilimit = target_current_limit_ma; + + ddi_power_set_4p2_ilimit(charge_4p2_ilimit); + + /* dcdc4p2 enable_dcdc must be enabled for + * 4p2 bo indication to function. If not enabled, + * skip using bo level detection + */ + if (!(b4p2_dcdc_enabled)) + msleep(1); + else if (__raw_readl(REGS_POWER_BASE + HW_POWER_STS) & + BM_POWER_STS_DCDC_4P2_BO) + msleep(1); + else { + charge_4p2_ilimit = target_current_limit_ma; + ddi_power_set_4p2_ilimit(charge_4p2_ilimit); + } + } + + ddi_power_Set4p2BoLevel(3600); + + __raw_writel(BM_POWER_CTRL_DCDC4P2_BO_IRQ, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + + /* rail should now be up and loaded. Extra + * internal load is not necessary. + */ + __raw_writel(BM_POWER_CHARGE_ENABLE_LOAD, + REGS_POWER_BASE + HW_POWER_CHARGE_CLR); + + return charge_4p2_ilimit; + +} + + +void ddi_power_Set4p2BoLevel(uint16_t bo_voltage_mv) +{ + uint16_t bo_reg_value; + uint32_t temp; + + if (bo_voltage_mv < 3600) + bo_voltage_mv = 3600; + else if (bo_voltage_mv > 4375) + bo_voltage_mv = 4375; + + bo_reg_value = (bo_voltage_mv - 3600) / 25; + + temp = __raw_readl(REGS_POWER_BASE + HW_POWER_DCDC4P2); + temp &= (~BM_POWER_DCDC4P2_BO); + temp |= (bo_reg_value << BP_POWER_DCDC4P2_BO); + __raw_writel(temp, REGS_POWER_BASE + HW_POWER_DCDC4P2); +} + + + +void ddi_power_init_handoff(void) +{ + int val; + /* The following settings give optimal power supply capability */ + + /* enable 5v presence detection */ + ddi_power_Enable5vDetection(); + + if (ddi_power_Get5vPresentFlag()) + /* It's 5V mode, enable 5V-to-battery handoff */ + ddi_power_enable_5v_to_battery_handoff(); + else + /* It's battery mode, enable battery-to-5V handoff */ + ddi_power_enable_battery_to_5v_handoff(); + + /* Finally enable the battery adjust */ + val = __raw_readl(REGS_POWER_BASE + HW_POWER_BATTMONITOR); + val |= BM_POWER_BATTMONITOR_EN_BATADJ; + __raw_writel(val, REGS_POWER_BASE + HW_POWER_BATTMONITOR); +} + + +void ddi_power_EnableBatteryInterrupt(bool enable) +{ + + __raw_writel(BM_POWER_CTRL_BATT_BO_IRQ, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + + __raw_writel(BM_POWER_CTRL_ENIRQBATT_BO, + REGS_POWER_BASE + HW_POWER_CTRL_SET); + +} + + +#define REGS_LRADC_BASE IO_ADDRESS(LRADC_PHYS_ADDR) + +int ddi_power_init_battery(void) +{ + + int ret = 0; + + if (!(__raw_readl(REGS_POWER_BASE + HW_POWER_5VCTRL) && + BM_POWER_5VCTRL_ENABLE_DCDC)) { + printk(KERN_ERR "WARNING: Power Supply not\ + initialized correctly by \ + pre-kernel bootlets. HW_POWER_5VCTRL \ + ENABLE_DCDC should already be set. Kernel \ + power driver behavior may not be reliable \n"); + ret = 1; + } + if ((__raw_readl(REGS_POWER_BASE + HW_POWER_BATTMONITOR) & + BM_POWER_BATTMONITOR_BATT_VAL) == 0) { + ret = 1; + printk(KERN_INFO "WARNING : No battery connected !\r\n"); + return ret; + } + + /* the following code to enable automatic battery measurement + * should have already been enabled in the boot prep files. Not + * sure if this is necessary or possibly susceptible to + * mis-coordination + */ + + + ret = !hw_lradc_present(BATTERY_VOLTAGE_CH); + + if (ret) { + printk(KERN_ERR "%s: hw_lradc_present failed\n", __func__); + return -ENODEV; + } else { + uint16_t wait_time = 0; + + hw_lradc_configure_channel(BATTERY_VOLTAGE_CH, 0 /* div2 */ , + 0 /* acc */ , + 0 /* num_samples */); + + /* Setup the trigger loop forever */ + hw_lradc_set_delay_trigger(LRADC_DELAY_TRIGGER_BATTERY, + 1 << BATTERY_VOLTAGE_CH, + 1 << LRADC_DELAY_TRIGGER_BATTERY, + 0, 200); + + /* Clear the accumulator & NUM_SAMPLES */ + __raw_writel(0xFFFFFFFF, + REGS_LRADC_BASE + HW_LRADC_CHn_CLR(BATTERY_VOLTAGE_CH)); + + /* clear previous "measurement performed" status */ + __raw_writel(1 << BATTERY_VOLTAGE_CH, + REGS_LRADC_BASE + HW_LRADC_CTRL1_CLR); + + /* set to LiIon scale factor */ + __raw_writel(BM_LRADC_CONVERSION_SCALE_FACTOR, + REGS_LRADC_BASE + HW_LRADC_CONVERSION_SET); + + /* kick off the trigger */ + hw_lradc_set_delay_trigger_kick( + LRADC_DELAY_TRIGGER_BATTERY, 1); + + + /* wait for 1st converstion to be complete before + * enabling automatic copy to power supply + * peripheral + */ + while (!(__raw_readl(REGS_LRADC_BASE + HW_LRADC_CTRL1) & + 1 << BATTERY_VOLTAGE_CH) && + (wait_time < 10)) { + wait_time++; + mdelay(1); + } + + __raw_writel(BM_LRADC_CONVERSION_AUTOMATIC, + REGS_LRADC_BASE + HW_LRADC_CONVERSION_SET); +#ifdef CONFIG_ARCH_MX28 + /* workaround for mx28 lradc result incorrect in the + first several ms */ + for (wait_time = 0; wait_time < 20; wait_time++) + if (ddi_bc_hwGetBatteryVoltage() < 1000) { + pr_info("ddi_bc_hwGetBatteryVoltage=%u\n", + ddi_bc_hwGetBatteryVoltage()); + mdelay(100); + } else + break; +#endif + } + +#ifndef VDD4P2_ENABLED + /* prepare handoff */ + ddi_power_init_handoff(); +#endif + return ret; +} + +/* + * Use the the lradc channel + * get the die temperature from on-chip sensor. + */ +uint16_t MeasureInternalDieTemperature(void) +{ + uint32_t ch8Value, ch9Value, lradc_irq_mask, channel; + + channel = g_ddi_bc_Configuration.u8BatteryTempChannel; + lradc_irq_mask = 1 << channel; + + /* power up internal tep sensor block */ + __raw_writel(BM_LRADC_CTRL2_TEMPSENSE_PWD, + REGS_LRADC_BASE + HW_LRADC_CTRL2_CLR); + + /* mux to the lradc 8th temp channel */ + __raw_writel((0xF << (4 * channel)), + REGS_LRADC_BASE + HW_LRADC_CTRL4_CLR); + __raw_writel((8 << (4 * channel)), + REGS_LRADC_BASE + HW_LRADC_CTRL4_SET); + + /* Clear the interrupt flag */ + __raw_writel(lradc_irq_mask, + REGS_LRADC_BASE + HW_LRADC_CTRL1_CLR); + __raw_writel(BF_LRADC_CTRL0_SCHEDULE(1 << channel), + REGS_LRADC_BASE + HW_LRADC_CTRL0_SET); + + /* Wait for conversion complete*/ + while (!(__raw_readl(REGS_LRADC_BASE + HW_LRADC_CTRL1) + & lradc_irq_mask)) + cpu_relax(); + + /* Clear the interrupt flag again */ + __raw_writel(lradc_irq_mask, + REGS_LRADC_BASE + HW_LRADC_CTRL1_CLR); + + /* read temperature value and clr lradc */ + ch8Value = __raw_readl(REGS_LRADC_BASE + + HW_LRADC_CHn(channel)) & BM_LRADC_CHn_VALUE; + + + __raw_writel(BM_LRADC_CHn_VALUE, + REGS_LRADC_BASE + HW_LRADC_CHn_CLR(channel)); + + /* mux to the lradc 9th temp channel */ + __raw_writel((0xF << (4 * channel)), + REGS_LRADC_BASE + HW_LRADC_CTRL4_CLR); + __raw_writel((9 << (4 * channel)), + REGS_LRADC_BASE + HW_LRADC_CTRL4_SET); + + /* Clear the interrupt flag */ + __raw_writel(lradc_irq_mask, + REGS_LRADC_BASE + HW_LRADC_CTRL1_CLR); + __raw_writel(BF_LRADC_CTRL0_SCHEDULE(1 << channel), + REGS_LRADC_BASE + HW_LRADC_CTRL0_SET); + /* Wait for conversion complete */ + while (!(__raw_readl(REGS_LRADC_BASE + HW_LRADC_CTRL1) + & lradc_irq_mask)) + cpu_relax(); + + /* Clear the interrupt flag */ + __raw_writel(lradc_irq_mask, + REGS_LRADC_BASE + HW_LRADC_CTRL1_CLR); + /* read temperature value */ + ch9Value = __raw_readl( + REGS_LRADC_BASE + HW_LRADC_CHn(channel)) + & BM_LRADC_CHn_VALUE; + + + __raw_writel(BM_LRADC_CHn_VALUE, + REGS_LRADC_BASE + HW_LRADC_CHn_CLR(channel)); + + /* power down temp sensor block */ + __raw_writel(BM_LRADC_CTRL2_TEMPSENSE_PWD, + REGS_LRADC_BASE + HW_LRADC_CTRL2_SET); + + + return (uint16_t)((ch9Value-ch8Value)*GAIN_CORRECTION/4000); +} + + + +/* Name: ddi_power_GetBatteryMode */ +/* */ +/* brief */ + +ddi_power_BatteryMode_t ddi_power_GetBatteryMode(void) +{ + return DDI_POWER_BATT_MODE_LIION; +} + + +/* Name: ddi_power_GetBatteryChargerEnabled */ +/* */ +/* brief */ + +bool ddi_power_GetBatteryChargerEnabled(void) +{ +#if 0 + return (__raw_readl(REGS_POWER_BASE + HW_POWER_STS) & BM_POWER_STS_BATT_CHRG_PRESENT) ? 1 : 0; +#endif + return 1; +} + + +/* */ +/* brief Report if the charger hardware power is on. */ +/* */ +/* fntype Function */ +/* */ +/* This function reports if the charger hardware power is on. */ +/* */ +/* retval Zero if the charger hardware is not powered. Non-zero otherwise. */ +/* */ +/* Note that the bit we're looking at is named PWD_BATTCHRG. The "PWD" */ +/* stands for "power down". Thus, when the bit is set, the battery charger */ +/* hardware is POWERED DOWN. */ + +bool ddi_power_GetChargerPowered(void) +{ + return (__raw_readl(REGS_POWER_BASE + HW_POWER_CHARGE) & BM_POWER_CHARGE_PWD_BATTCHRG) ? 0 : 1; +} + + +/* */ +/* brief Turn the charging hardware on or off. */ +/* */ +/* fntype Function */ +/* */ +/* This function turns the charging hardware on or off. */ +/* */ +/* param[in] on Indicates whether the charging hardware should be on or off. */ +/* */ +/* Note that the bit we're looking at is named PWD_BATTCHRG. The "PWD" */ +/* stands for "power down". Thus, when the bit is set, the battery charger */ +/* hardware is POWERED DOWN. */ + +void ddi_power_SetChargerPowered(bool bPowerOn) +{ + /* Hit the battery charge power switch. */ + if (bPowerOn) { + __raw_writel(BM_POWER_CHARGE_PWD_BATTCHRG, + REGS_POWER_BASE + HW_POWER_CHARGE_CLR); + __raw_writel(BM_POWER_5VCTRL_PWD_CHARGE_4P2, + REGS_POWER_BASE + HW_POWER_5VCTRL_CLR); + } else { + __raw_writel(BM_POWER_CHARGE_PWD_BATTCHRG, + REGS_POWER_BASE + HW_POWER_CHARGE_SET); +#ifndef VDD4P2_ENABLED + __raw_writel(BM_POWER_5VCTRL_PWD_CHARGE_4P2, + REGS_POWER_BASE + HW_POWER_5VCTRL_SET); +#endif + } + +/* #ifdef CONFIG_POWER_SUPPLY_DEBUG */ +#if 0 + printk("Battery charger: charger %s\n", bPowerOn ? "ON!" : "OFF"); + dump_regs(); +#endif +} + + +/* */ +/* brief Reports if the charging current has fallen below the threshold. */ +/* */ +/* fntype Function */ +/* */ +/* This function reports if the charging current that the battery is accepting */ +/* has fallen below the threshold. */ +/* */ +/* Note that this bit is regarded by the hardware guys as very slightly */ +/* unreliable. They recommend that you don't believe a value of zero until */ +/* you've sampled it twice. */ +/* */ +/* retval Zero if the battery is accepting less current than indicated by the */ +/* charging threshold. Non-zero otherwise. */ +/* */ + +int ddi_power_GetChargeStatus(void) +{ + return (__raw_readl(REGS_POWER_BASE + HW_POWER_STS) & BM_POWER_STS_CHRGSTS) ? 1 : 0; +} + + +/* Battery Voltage */ + + + +/* */ +/* brief Report the voltage across the battery. */ +/* */ +/* fntype Function */ +/* */ +/* This function reports the voltage across the battery. Should return a */ +/* value in range ~3000 - 4200 mV. */ +/* */ +/* retval The voltage across the battery, in mV. */ +/* */ + + +/* brief Constant value for 8mV steps used in battery translation */ +#define BATT_VOLTAGE_8_MV 8 + +uint16_t ddi_power_GetBattery(void) +{ + uint32_t u16BattVolt; + + /* Get the raw result of battery measurement */ + u16BattVolt = __raw_readl(REGS_POWER_BASE + HW_POWER_BATTMONITOR); + u16BattVolt &= BM_POWER_BATTMONITOR_BATT_VAL; + u16BattVolt >>= BP_POWER_BATTMONITOR_BATT_VAL; + + /* Adjust for 8-mV LSB resolution and return */ + u16BattVolt *= BATT_VOLTAGE_8_MV; + +/* #ifdef CONFIG_POWER_SUPPLY_DEBUG */ +#if 0 + printk("Battery charger: %u mV\n", u16BattVolt); +#endif + + return u16BattVolt; +} + +#if 0 + +/* */ +/* brief Report the voltage across the battery. */ +/* */ +/* fntype Function */ +/* */ +/* This function reports the voltage across the battery. */ +/* */ +/* retval The voltage across the battery, in mV. */ +/* */ + +uint16_t ddi_power_GetBatteryBrownout(void) +{ + uint32_t u16BatteryBrownoutLevel; + + /* Get battery brownout level */ + u16BatteryBrownoutLevel = __raw_readl(REGS_POWER_BASE + HW_POWER_BATTMONITOR); + u16BatteryBrownoutLevel &= BM_POWER_BATTMONITOR_BRWNOUT_LVL; + u16BatteryBrownoutLevel >>= BP_POWER_BATTMONITOR_BRWNOUT_LVL; + + /* Calculate battery brownout level */ + switch (ddi_power_GetBatteryMode()) { + case DDI_POWER_BATT_MODE_LIION: + u16BatteryBrownoutLevel *= BATT_BRWNOUT_LIION_LEVEL_STEP_MV; + u16BatteryBrownoutLevel += BATT_BRWNOUT_LIION_BASE_MV; + break; + case DDI_POWER_BATT_MODE_ALKALINE_NIMH: + u16BatteryBrownoutLevel *= BATT_BRWNOUT_ALKAL_LEVEL_STEP_MV; + u16BatteryBrownoutLevel += BATT_BRWNOUT_ALKAL_BASE_MV; + break; + default: + u16BatteryBrownoutLevel = 0; + break; + } + return u16BatteryBrownoutLevel; +} + + +/* */ +/* brief Set battery brownout level */ +/* */ +/* fntype Reentrant Function */ +/* */ +/* This function sets the battery brownout level in millivolt. It transforms the */ +/* input brownout value from millivolts to the hardware register bit field value */ +/* taking the ceiling value in the calculation. */ +/* */ +/* param[in] u16BattBrownout_mV Battery battery brownout level in mV */ +/* */ +/* return SUCCESS */ +/* */ + +int ddi_power_SetBatteryBrownout(uint16_t u16BattBrownout_mV) +{ + int16_t i16BrownoutLevel; + int ret = 0; + + /* Calculate battery brownout level */ + switch (ddi_power_GetBatteryMode()) { + case DDI_POWER_BATT_MODE_LIION: + i16BrownoutLevel = u16BattBrownout_mV - + BATT_BRWNOUT_LIION_EQN_CONST; + i16BrownoutLevel /= BATT_BRWNOUT_LIION_LEVEL_STEP_MV; + break; + case DDI_POWER_BATT_MODE_ALKALINE_NIMH: + i16BrownoutLevel = u16BattBrownout_mV - + BATT_BRWNOUT_ALKAL_EQN_CONST; + i16BrownoutLevel /= BATT_BRWNOUT_ALKAL_LEVEL_STEP_MV; + break; + default: + return -EINVAL; + } + + /* Do a check to make sure nothing went wrong. */ + if (i16BrownoutLevel <= 0x0f) { + /* Write the battery brownout level */ + __raw_writel( + BF_POWER_BATTMONITOR_BRWNOUT_LVL(i16BrownoutLevel), + REGS_POWER_BASE + HW_POWER_BATTMONITOR_SET); + } else + ret = -EINVAL; + + return ret; +} +#endif + + +/* Currents */ + + + + +/* Name: ddi_power_SetMaxBatteryChargeCurrent */ +/* */ +/* brief */ + +uint16_t ddi_power_SetMaxBatteryChargeCurrent(uint16_t u16MaxCur) +{ + uint32_t u16OldSetting; + uint32_t u16NewSetting; + uint32_t u16ToggleMask; + + /* Get the old setting. */ + u16OldSetting = (__raw_readl(REGS_POWER_BASE + HW_POWER_CHARGE) & BM_POWER_CHARGE_BATTCHRG_I) >> + BP_POWER_CHARGE_BATTCHRG_I; + + /* Convert the new threshold into a setting. */ + u16NewSetting = ddi_power_convert_current_to_setting(u16MaxCur); + + /* Compute the toggle mask. */ + u16ToggleMask = u16OldSetting ^ u16NewSetting; + + /* Write to the toggle register.*/ + __raw_writel(u16ToggleMask << BP_POWER_CHARGE_BATTCHRG_I, + REGS_POWER_BASE + HW_POWER_CHARGE_TOG); + + /* Tell the caller what current we're set at now. */ + return ddi_power_convert_setting_to_current(u16NewSetting); +} + + +/* Name: ddi_power_GetMaxBatteryChargeCurrent */ +/* */ +/* brief */ + +uint16_t ddi_power_GetMaxBatteryChargeCurrent(void) +{ + uint32_t u8Bits; + + /* Get the raw data from register */ + u8Bits = (__raw_readl(REGS_POWER_BASE + HW_POWER_CHARGE) & BM_POWER_CHARGE_BATTCHRG_I) >> + BP_POWER_CHARGE_BATTCHRG_I; + + /* Translate raw data to current (in mA) and return it */ + return ddi_power_convert_setting_to_current(u8Bits); +} + + +/* Name: ddi_power_GetMaxChargeCurrent */ +/* */ +/* brief */ + +uint16_t ddi_power_SetBatteryChargeCurrentThreshold(uint16_t u16Thresh) +{ + uint32_t u16OldSetting; + uint32_t u16NewSetting; + uint32_t u16ToggleMask; + + /* ------------------------------------------------------------------- */ + /* See ddi_power_SetMaxBatteryChargeCurrent for an explanation of */ + /* why we're using the toggle register here. */ + /* */ + /* Since this function doesn't have any major hardware effect, */ + /* we could use the usual macros for writing to this bit field. But, */ + /* for the sake of parallel construction and any potentially odd */ + /* effects on the status bit, we use the toggle register in the same */ + /* way as ddi_bc_hwSetMaxCurrent. */ + /* ------------------------------------------------------------------- */ + + /* ------------------------------------------------------------------- */ + /* The threshold hardware can't express as large a range as the max */ + /* current setting, but we can use the same functions as long as we */ + /* add an extra check here. */ + /* */ + /* Thresholds larger than 180mA can't be expressed. */ + /* ------------------------------------------------------------------- */ + + if (u16Thresh > 180) + u16Thresh = 180; + + + /* Create the mask */ + + + /* Get the old setting. */ + u16OldSetting = (__raw_readl(REGS_POWER_BASE + HW_POWER_CHARGE) & BM_POWER_CHARGE_STOP_ILIMIT) >> + BP_POWER_CHARGE_STOP_ILIMIT; + + /* Convert the new threshold into a setting. */ + u16NewSetting = ddi_power_convert_current_to_setting(u16Thresh); + + /* Compute the toggle mask. */ + u16ToggleMask = u16OldSetting ^ u16NewSetting; + + + /* Write to the register */ + + + /* Write to the toggle register. */ + __raw_writel(BF_POWER_CHARGE_STOP_ILIMIT(u16ToggleMask), + REGS_POWER_BASE + HW_POWER_CHARGE_TOG); + + /* Tell the caller what current we're set at now. */ + return ddi_power_convert_setting_to_current(u16NewSetting); +} + + +/* Name: ddi_power_GetBatteryChargeCurrentThreshold */ +/* */ +/* brief */ + +uint16_t ddi_power_GetBatteryChargeCurrentThreshold(void) +{ + uint32_t u16Threshold; + + u16Threshold = (__raw_readl(REGS_POWER_BASE + HW_POWER_CHARGE) & BM_POWER_CHARGE_STOP_ILIMIT) >> + BP_POWER_CHARGE_STOP_ILIMIT; + + return ddi_power_convert_setting_to_current(u16Threshold); +} + + +/* Conversion */ + + + +/* */ +/* brief Compute the actual current expressible in the hardware. */ +/* */ +/* fntype Function */ +/* */ +/* Given a desired current, this function computes the actual current */ +/* expressible in the hardware. */ +/* */ +/* Note that the hardware has a minimum resolution of 10mA and a maximum */ +/* expressible value of 780mA (see the data sheet for details). If the given */ +/* current cannot be expressed exactly, then the largest expressible smaller */ +/* value will be used. */ +/* */ +/* param[in] u16Current The current of interest. */ +/* */ +/* retval The corresponding current in mA. */ +/* */ + +uint16_t ddi_power_ExpressibleCurrent(uint16_t u16Current) +{ + return ddi_power_convert_setting_to_current( + ddi_power_convert_current_to_setting(u16Current)); +} + + +/* Name: ddi_power_Get5VPresent */ +/* */ +/* brief */ + + +bool ddi_power_Get5vPresentFlag(void) +{ + switch (DetectionMethod) { + case DDI_POWER_5V_VBUSVALID: + /* Check VBUSVALID for 5V present */ + return ((__raw_readl(REGS_POWER_BASE + HW_POWER_STS) & + BM_POWER_STS_VBUSVALID) != 0); + case DDI_POWER_5V_VDD5V_GT_VDDIO: + /* Check VDD5V_GT_VDDIO for 5V present */ + return ((__raw_readl(REGS_POWER_BASE + HW_POWER_STS) & + BM_POWER_STS_VDD5V_GT_VDDIO) != 0); + default: + break; + } + + return 0; +} + + + + +/* */ +/* brief Report on the die temperature. */ +/* */ +/* fntype Function */ +/* */ +/* This function reports on the die temperature. */ +/* */ +/* param[out] pLow The low end of the temperature range. */ +/* param[out] pHigh The high end of the temperature range. */ +/* */ + +/* Temperature constant */ +#define TEMP_READING_ERROR_MARGIN 5 +#define KELVIN_TO_CELSIUS_CONST 273 + +void ddi_power_GetDieTemp(int16_t *pLow, int16_t *pHigh) +{ + int16_t i16High, i16Low; + uint16_t u16Reading; + + /* Get the reading in Kelvins */ + u16Reading = MeasureInternalDieTemperature(); + + /* Adjust for error margin */ + i16High = u16Reading + TEMP_READING_ERROR_MARGIN; + i16Low = u16Reading - TEMP_READING_ERROR_MARGIN; + + /* Convert to Celsius */ + i16High -= KELVIN_TO_CELSIUS_CONST; + i16Low -= KELVIN_TO_CELSIUS_CONST; + +/* #ifdef CONFIG_POWER_SUPPLY_DEBUG */ +#if 0 + printk("Battery charger: Die temp %d to %d C\n", i16Low, i16High); +#endif + /* Return the results */ + *pHigh = i16High; + *pLow = i16Low; +} + + +/* */ +/* brief Checks to see if the DCDC has been manually enabled */ +/* */ +/* fntype Function */ +/* */ +/* retval true if DCDC is ON, false if DCDC is OFF. */ +/* */ + +bool ddi_power_IsDcdcOn(void) +{ + return (__raw_readl(REGS_POWER_BASE + HW_POWER_5VCTRL) & BM_POWER_5VCTRL_ENABLE_DCDC) ? 1 : 0; +} + + + +/* See hw_power.h for details. */ + +void ddi_power_SetPowerClkGate(bool bGate) +{ + /* Gate/Ungate the clock to the power block */ +#ifndef CONFIG_ARCH_MX28 + if (bGate) { + __raw_writel(BM_POWER_CTRL_CLKGATE, + REGS_POWER_BASE + HW_POWER_CTRL_SET); + } else { + __raw_writel(BM_POWER_CTRL_CLKGATE, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + } +#endif +} + + +/* See hw_power.h for details. */ + +bool ddi_power_GetPowerClkGate(void) +{ +#ifdef CONFIG_ARCH_MX28 + return 0; +#else + return (__raw_readl(REGS_POWER_BASE + HW_POWER_CTRL) & BM_POWER_CTRL_CLKGATE) ? 1 : 0; +#endif +} + + +enum ddi_power_5v_status ddi_power_GetPmu5vStatus(void) +{ + + if (DetectionMethod == DDI_POWER_5V_VDD5V_GT_VDDIO) { + + if (__raw_readl(REGS_POWER_BASE + HW_POWER_CTRL) & + BM_POWER_CTRL_POLARITY_VDD5V_GT_VDDIO) { + if ((__raw_readl(REGS_POWER_BASE + HW_POWER_CTRL) & + BM_POWER_CTRL_VDD5V_GT_VDDIO_IRQ) || + ddi_power_Get5vPresentFlag()) + return new_5v_connection; + else + return existing_5v_disconnection; + } else { + if ((__raw_readl(REGS_POWER_BASE + HW_POWER_CTRL) & + BM_POWER_CTRL_VDD5V_GT_VDDIO_IRQ) || + !ddi_power_Get5vPresentFlag() || + ddi_power_Get5vDroopFlag()) + return new_5v_disconnection; + else + return existing_5v_connection; + } + } else { + + if (__raw_readl(REGS_POWER_BASE + HW_POWER_CTRL) & + BM_POWER_CTRL_POLARITY_VBUSVALID) { + if ((__raw_readl(REGS_POWER_BASE + HW_POWER_CTRL) & + BM_POWER_CTRL_VBUSVALID_IRQ) || + ddi_power_Get5vPresentFlag()) + return new_5v_connection; + else + return existing_5v_disconnection; + } else { + if ((__raw_readl(REGS_POWER_BASE + HW_POWER_CTRL) & + BM_POWER_CTRL_VBUSVALID_IRQ) || + !ddi_power_Get5vPresentFlag() || + ddi_power_Get5vDroopFlag()) + return new_5v_disconnection; + else + return existing_5v_connection; + } + + } +} + +void ddi_power_disable_5v_connection_irq(void) +{ + + __raw_writel((BM_POWER_CTRL_ENIRQ_VBUS_VALID | + BM_POWER_CTRL_ENIRQ_VDD5V_GT_VDDIO), + REGS_POWER_BASE + HW_POWER_CTRL_CLR); +} + +void ddi_power_enable_5v_disconnect_detection(void) +{ + __raw_writel(BM_POWER_CTRL_POLARITY_VDD5V_GT_VDDIO | + BM_POWER_CTRL_POLARITY_VBUSVALID, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + + __raw_writel(BM_POWER_CTRL_VDD5V_GT_VDDIO_IRQ | + BM_POWER_CTRL_VBUSVALID_IRQ, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + + if (DetectionMethod == DDI_POWER_5V_VDD5V_GT_VDDIO) { + __raw_writel(BM_POWER_CTRL_ENIRQ_VDD5V_GT_VDDIO, + REGS_POWER_BASE + HW_POWER_CTRL_SET); + } else { + __raw_writel(BM_POWER_CTRL_ENIRQ_VBUS_VALID, + REGS_POWER_BASE + HW_POWER_CTRL_SET); + } +} + +void ddi_power_enable_5v_connect_detection(void) +{ + __raw_writel(BM_POWER_CTRL_POLARITY_VDD5V_GT_VDDIO | + BM_POWER_CTRL_POLARITY_VBUSVALID, + REGS_POWER_BASE + HW_POWER_CTRL_SET); + + __raw_writel(BM_POWER_CTRL_VDD5V_GT_VDDIO_IRQ | + BM_POWER_CTRL_VBUSVALID_IRQ, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + + if (DetectionMethod == DDI_POWER_5V_VDD5V_GT_VDDIO) { + __raw_writel(BM_POWER_CTRL_ENIRQ_VDD5V_GT_VDDIO, + REGS_POWER_BASE + HW_POWER_CTRL_SET); + } else { + __raw_writel(BM_POWER_CTRL_ENIRQ_VBUS_VALID, + REGS_POWER_BASE + HW_POWER_CTRL_SET); + } +} + +void ddi_power_EnableBatteryBoInterrupt(bool bEnable) +{ + if (bEnable) { + + __raw_writel(BM_POWER_CTRL_BATT_BO_IRQ, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + __raw_writel(BM_POWER_CTRL_ENIRQBATT_BO, + REGS_POWER_BASE + HW_POWER_CTRL_SET); + /* todo: make sure the battery brownout comparator + * is enabled in HW_POWER_BATTMONITOR + */ + } else { + __raw_writel(BM_POWER_CTRL_ENIRQBATT_BO, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + } +} + +void ddi_power_EnableDcdc4p2BoInterrupt(bool bEnable) +{ + if (bEnable) { + + __raw_writel(BM_POWER_CTRL_DCDC4P2_BO_IRQ, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + __raw_writel(BM_POWER_CTRL_ENIRQ_DCDC4P2_BO, + REGS_POWER_BASE + HW_POWER_CTRL_SET); + } else { + __raw_writel(BM_POWER_CTRL_ENIRQ_DCDC4P2_BO, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + } +} + +void ddi_power_EnableVdd5vDroopInterrupt(bool bEnable) +{ + if (bEnable) { + + __raw_writel(BM_POWER_CTRL_VDD5V_DROOP_IRQ, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + __raw_writel(BM_POWER_CTRL_ENIRQ_VDD5V_DROOP, + REGS_POWER_BASE + HW_POWER_CTRL_SET); + } else { + __raw_writel(BM_POWER_CTRL_ENIRQ_VDD5V_DROOP, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + } +} + + +void ddi_power_Enable5vDisconnectShutdown(bool bEnable) +{ + if (bEnable) { + __raw_writel(BM_POWER_5VCTRL_PWDN_5VBRNOUT, + REGS_POWER_BASE + HW_POWER_5VCTRL_SET); + } else { + __raw_writel(BM_POWER_5VCTRL_PWDN_5VBRNOUT, + REGS_POWER_BASE + HW_POWER_5VCTRL_CLR); + } +} + + +void ddi_power_enable_5v_to_battery_xfer(bool bEnable) +{ + if (bEnable) { + /* order matters */ + + /* we can enable this in in vbus droop or 4p2 fiq handler + * ddi_power_EnableBatteryBoInterrupt(true); + */ + ddi_power_Enable5vDisconnectShutdown(false); + } else { + /* order matters */ + ddi_power_Enable5vDisconnectShutdown(true); + ddi_power_EnableBatteryBoInterrupt(false); + } +} + + +void ddi_power_init_4p2_protection(void) +{ + /* set vbus droop detection level to 4.3V */ + __raw_writel(BM_POWER_5VCTRL_VBUSDROOP_TRSH, + REGS_POWER_BASE + HW_POWER_5VCTRL_CLR); + + /* VBUSDROOP THRESHOLD to 4.3V */ + __raw_writel(BM_POWER_5VCTRL_VBUSDROOP_TRSH, + REGS_POWER_BASE + HW_POWER_5VCTRL_CLR); + + ddi_power_EnableVbusDroopIrq(); + +#ifndef CONFIG_ARCH_MX28 + /* VBUSVALID THRESH = 2.9V */ + __raw_writel(BM_POWER_5VCTRL_VBUSVALID_TRSH, + REGS_POWER_BASE + HW_POWER_5VCTRL_CLR); +#endif + +} + +/* determine if all the bits are in a 'DCDC 4P2 Enabled' state. */ +bool ddi_power_check_4p2_bits(void) +{ + + + uint32_t temp; + + temp = __raw_readl(REGS_POWER_BASE + HW_POWER_5VCTRL) & + BM_POWER_5VCTRL_PWD_CHARGE_4P2; + + /* if PWD_CHARGE_4P2 = 1, 4p2 is disabled */ + if (temp) + return false; + + temp = __raw_readl(REGS_POWER_BASE + HW_POWER_DCDC4P2) & + BM_POWER_DCDC4P2_ENABLE_DCDC; + + if (!temp) + return false; + + temp = __raw_readl(REGS_POWER_BASE + HW_POWER_DCDC4P2) & + BM_POWER_DCDC4P2_ENABLE_4P2; + + if (temp) + return true; + else + return false; + +} + +uint16_t ddi_power_set_4p2_ilimit(uint16_t ilimit) +{ + uint32_t temp_reg; + + if (ilimit > 780) + ilimit = 780; + temp_reg = __raw_readl(REGS_POWER_BASE + HW_POWER_5VCTRL); + temp_reg &= (~BM_POWER_5VCTRL_CHARGE_4P2_ILIMIT); + temp_reg |= BF_POWER_5VCTRL_CHARGE_4P2_ILIMIT( + ddi_power_convert_current_to_setting( + ilimit)); + __raw_writel(temp_reg, REGS_POWER_BASE + HW_POWER_5VCTRL); + + return ilimit; +} + +void ddi_power_shutdown(void) +{ + __raw_writel(0x3e770001, REGS_POWER_BASE + HW_POWER_RESET); +} + +void ddi_power_handle_dcdc4p2_bo(void) +{ + ddi_power_EnableBatteryBoInterrupt(true); + ddi_power_EnableDcdc4p2BoInterrupt(false); +} + +void ddi_power_enable_vddio_interrupt(bool enable) +{ + if (enable) { + __raw_writel(BM_POWER_CTRL_VDDIO_BO_IRQ, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); +#ifndef DISABLE_VDDIO_BO_PROTECTION + __raw_writel(BM_POWER_CTRL_ENIRQ_VDDIO_BO, + REGS_POWER_BASE + HW_POWER_CTRL_SET); +#endif + } else { + __raw_writel(BM_POWER_CTRL_ENIRQ_VDDIO_BO, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + } + +} + + +void ddi_power_handle_vddio_brnout(void) +{ + if (ddi_power_GetPmu5vStatus() == new_5v_connection || + (ddi_power_GetPmu5vStatus() == new_5v_disconnection)) { + ddi_power_enable_vddio_interrupt(false); + } else { +#ifdef DEBUG_IRQS + ddi_power_enable_vddio_interrupt(false); + printk(KERN_ALERT "VDDIO BO TRIED TO SHUTDOWN!!!\n"); + return; +#else + ddi_power_shutdown(); +#endif + } +} + +void ddi_power_handle_vdd5v_droop(void) +{ + uint32_t temp; + + /* handle errata */ + temp = __raw_readl(REGS_POWER_BASE + HW_POWER_DCDC4P2); + temp |= (BF_POWER_DCDC4P2_CMPTRIP(31) | BM_POWER_DCDC4P2_TRG); + __raw_writel(temp, REGS_POWER_BASE + HW_POWER_DCDC4P2); + + + /* if battery is below brownout level, shutdown asap */ + if (__raw_readl(REGS_POWER_BASE + HW_POWER_STS) & BM_POWER_STS_BATT_BO) + ddi_power_shutdown(); + + /* due to 5v connect vddio bo chip bug, we need to + * disable vddio interrupts until we reset the 5v + * detection for 5v connect detect. We want to allow + * some debounce time before enabling connect detection. + */ + ddi_power_enable_vddio_interrupt(false); + + ddi_power_EnableBatteryBoInterrupt(true); + ddi_power_EnableDcdc4p2BoInterrupt(false); + ddi_power_EnableVdd5vDroopInterrupt(false); + +} + +void ddi_power_InitOutputBrownouts(void) +{ + uint32_t temp; + + __raw_writel(BM_POWER_CTRL_VDDD_BO_IRQ | + BM_POWER_CTRL_VDDA_BO_IRQ | + BM_POWER_CTRL_VDDIO_BO_IRQ, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + + __raw_writel(BM_POWER_CTRL_ENIRQ_VDDD_BO | + BM_POWER_CTRL_ENIRQ_VDDA_BO | + BM_POWER_CTRL_ENIRQ_VDDIO_BO, + REGS_POWER_BASE + HW_POWER_CTRL_SET); + + temp = __raw_readl(REGS_POWER_BASE + HW_POWER_VDDDCTRL); + temp &= ~BM_POWER_VDDDCTRL_PWDN_BRNOUT; + __raw_writel(temp, REGS_POWER_BASE + HW_POWER_VDDDCTRL); + + temp = __raw_readl(REGS_POWER_BASE + HW_POWER_VDDACTRL); + temp &= ~BM_POWER_VDDACTRL_PWDN_BRNOUT; + __raw_writel(temp, REGS_POWER_BASE + HW_POWER_VDDACTRL); + + temp = __raw_readl(REGS_POWER_BASE + HW_POWER_VDDIOCTRL); + temp &= ~BM_POWER_VDDIOCTRL_PWDN_BRNOUT; + __raw_writel(temp, REGS_POWER_BASE + HW_POWER_VDDIOCTRL); +} + +/* used for debugging purposes only */ +void ddi_power_disable_power_interrupts(void) +{ + __raw_writel(BM_POWER_CTRL_ENIRQ_DCDC4P2_BO | + BM_POWER_CTRL_ENIRQ_VDD5V_DROOP | + BM_POWER_CTRL_ENIRQ_PSWITCH | + BM_POWER_CTRL_ENIRQ_DC_OK | + BM_POWER_CTRL_ENIRQBATT_BO | + BM_POWER_CTRL_ENIRQ_VDDIO_BO | + BM_POWER_CTRL_ENIRQ_VDDA_BO | + BM_POWER_CTRL_ENIRQ_VDDD_BO | + BM_POWER_CTRL_ENIRQ_VBUS_VALID | + BM_POWER_CTRL_ENIRQ_VDD5V_GT_VDDIO, + REGS_POWER_BASE + HW_POWER_CTRL_CLR); + +} + +bool ddi_power_Get5vDroopFlag(void) +{ + if (__raw_readl(REGS_POWER_BASE + HW_POWER_STS) & + BM_POWER_STS_VDD5V_DROOP) + return true; + else + return false; +} + + +/* End of file */ + +/* @} */ diff --git a/drivers/power/mxs/ddi_power_battery.h b/drivers/power/mxs/ddi_power_battery.h new file mode 100644 index 000000000000..6a25569f25d3 --- /dev/null +++ b/drivers/power/mxs/ddi_power_battery.h @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/* brief Battery modes */ +typedef enum { + /* 37xx battery modes */ + /* brief LiIon battery powers the player */ + DDI_POWER_BATT_MODE_LIION = 0, + /* brief Alkaline/NiMH battery powers the player */ + DDI_POWER_BATT_MODE_ALKALINE_NIMH = 1, +} ddi_power_BatteryMode_t; + + +/* brief Possible 5V detection methods */ +typedef enum { + /* brief Use VBUSVALID comparator for detection */ + DDI_POWER_5V_VBUSVALID, + /* brief Use VDD5V_GT_VDDIO comparison for detection */ + DDI_POWER_5V_VDD5V_GT_VDDIO +} ddi_power_5vDetection_t; + + +enum ddi_power_5v_status { + new_5v_connection, + existing_5v_connection, + new_5v_disconnection, + existing_5v_disconnection, +} ; + + +uint16_t ddi_power_convert_current_to_setting(uint16_t u16Current); +uint16_t ddi_power_convert_setting_to_current(uint16_t u16Setting); +void ddi_power_enable_5v_to_battery_handoff(void); +void ddi_power_execute_5v_to_battery_handoff(void); +void ddi_power_enable_battery_to_5v_handoff(void); +void ddi_power_execute_battery_to_5v_handoff(void); +int ddi_power_init_battery(void); +ddi_power_BatteryMode_t ddi_power_GetBatteryMode(void); +bool ddi_power_GetBatteryChargerEnabled(void); +bool ddi_power_GetChargerPowered(void); +void ddi_power_SetChargerPowered(bool bPowerOn); +int ddi_power_GetChargeStatus(void); +uint16_t ddi_power_GetBattery(void); +uint16_t ddi_power_GetBatteryBrownout(void); +int ddi_power_SetBatteryBrownout(uint16_t u16BattBrownout_mV); +uint16_t ddi_power_SetMaxBatteryChargeCurrent(uint16_t u16MaxCur); +uint16_t ddi_power_GetMaxBatteryChargeCurrent(void); +uint16_t ddi_power_SetBatteryChargeCurrentThreshold(uint16_t u16Thresh); +uint16_t ddi_power_GetBatteryChargeCurrentThreshold(void); +uint16_t ddi_power_ExpressibleCurrent(uint16_t u16Current); +bool ddi_power_Get5vPresentFlag(void); +void ddi_power_GetDieTemp(int16_t *pLow, int16_t *pHigh); +bool ddi_power_IsDcdcOn(void); +void ddi_power_SetPowerClkGate(bool bGate); +bool ddi_power_GetPowerClkGate(void); +enum ddi_power_5v_status ddi_power_GetPmu5vStatus(void); +void ddi_power_EnableBatteryBoFiq(bool bEnable); +void ddi_power_disable_5v_connection_irq(void); +void ddi_power_enable_5v_disconnect_detection(void); +void ddi_power_enable_5v_connect_detection(void); +void ddi_power_Enable5vDisconnectShutdown(bool bEnable); +void ddi_power_enable_5v_to_battery_xfer(bool bEnable); +void ddi_power_init_4p2_protection(void); +bool ddi_power_check_4p2_bits(void); +void ddi_power_Start4p2Dcdc(bool battery_ready); +void ddi_power_Init4p2Params(void); +bool ddi_power_IsBattRdyForXfer(void); +void ddi_power_EnableVbusDroopIrq(void); +void ddi_power_Enable4p2(uint16_t target_current_limit_ma); +uint16_t ddi_power_BringUp4p2Regulator( + uint16_t target_current_limit_ma, + bool b4p2_dcdc_enabled); +void ddi_power_Set4p2BoLevel(uint16_t bo_voltage_mv); +void ddi_power_EnableBatteryBoInterrupt(bool bEnable); +void ddi_power_handle_cmptrip(void); +uint16_t ddi_power_set_4p2_ilimit(uint16_t ilimit); +void ddi_power_shutdown(void); +void ddi_power_handle_dcdc4p2_bo(void); +void ddi_power_enable_vddio_interrupt(bool enable); +void ddi_power_handle_vddio_brnout(void); +void ddi_power_EnableDcdc4p2BoInterrupt(bool bEnable); +void ddi_power_handle_vdd5v_droop(void); +void ddi_power_InitOutputBrownouts(void); +void ddi_power_disable_power_interrupts(void); +bool ddi_power_Get5vDroopFlag(void); diff --git a/drivers/power/mxs/fiq.S b/drivers/power/mxs/fiq.S new file mode 100644 index 000000000000..1ad380d07efd --- /dev/null +++ b/drivers/power/mxs/fiq.S @@ -0,0 +1,125 @@ +/* + * Copyright (C) 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + + +#include +#include +#include +#include +#include +#include +#include + + .align 5 + .globl power_fiq_start + .globl power_fiq_end + .globl power_fiq_count + .globl lock_vector_tlb + +power_fiq_start: + ldr r8,power_reg + ldr r9,[r8,#HW_POWER_CTRL ] + ldr r10,power_off + + @ when VDDIO_BO_IRQ, + @ disabled, handled in IRQ for now + @tst r9, #BM_POWER_CTRL_VDDIO_BO_IRQ + + + @ when BATT_BO_IRQ, VDDD_BO_IRQ, VDDA_BO_IRQ, power off chip + ldr r11,power_bo + tst r9, r11 + strne r10,[r8,#HW_POWER_RESET] + + @VDD5V_DROOP_IRQ + tst r9, #BM_POWER_CTRL_VDD5V_DROOP_IRQ + beq check_dcdc4p2 + + @ handle errata + ldr r10, [r8, #HW_POWER_DCDC4P2] + orr r10,r10,#(BM_POWER_DCDC4P2_TRG) + orr r10,r10,#(BF_POWER_DCDC4P2_CMPTRIP(31)) + str r10,[r8, #(HW_POWER_DCDC4P2)] + + @ if battery is below brownout level, shutdown asap + ldr r10, [r8, #HW_POWER_STS] + tst r10, #BM_POWER_STS_BATT_BO + ldr r10, power_off + strne r10, [r8, #HW_POWER_RESET] + + @ disable viddio irq + mov r11, #BM_POWER_CTRL_ENIRQ_VDDIO_BO + str r11, [r8, #HW_POWER_CTRL_CLR] + + @ enable battery BO irq + mov r11, #BM_POWER_CTRL_BATT_BO_IRQ + str r11, [r8, #HW_POWER_CTRL_CLR] + mov r11, #BM_POWER_CTRL_ENIRQBATT_BO + str r11, [r8, #HW_POWER_CTRL_SET] + + @ disable dcdc4p2 interrupt + mov r11, #BM_POWER_CTRL_ENIRQ_DCDC4P2_BO + str r11, [r8, #HW_POWER_CTRL_CLR] + + @ disable vdd5v_droop interrupt + mov r11, #BM_POWER_CTRL_ENIRQ_VDD5V_DROOP + str r11, [r8, #HW_POWER_CTRL_CLR] + +check_dcdc4p2: + @ when DCDC4P2_BO_IRQ, + tst r9, #BM_POWER_CTRL_DCDC4P2_BO_IRQ + + mov r11, #BM_POWER_CTRL_BATT_BO_IRQ + strne r11, [r8, #HW_POWER_CTRL_CLR] + + mov r11, #BM_POWER_CTRL_ENIRQBATT_BO + strne r11, [r8, #HW_POWER_CTRL_SET] + + mov r11, #BM_POWER_CTRL_ENIRQ_DCDC4P2_BO + strne r11, [r8, #HW_POWER_CTRL_CLR] + + + + @return from fiq + subs pc,lr, #4 + +power_reg: + .long IO_ADDRESS(POWER_PHYS_ADDR) +power_off: + .long 0x3e770001 +power_bo: + .long BM_POWER_CTRL_BATT_BO_IRQ | \ + BM_POWER_CTRL_VDDA_BO_IRQ | BM_POWER_CTRL_VDDD_BO_IRQ +power_fiq_count: + .long 0 +power_fiq_end: + +lock_vector_tlb: + + mov r1, r0 @ set r1 to the value of the address to be locked down + mcr p15,0,r1,c8,c7,1 @ invalidate TLB single entry to ensure that + @ LockAddr is not already in the TLB + mrc p15,0,r0,c10,c0,0 @ read the lockdown register + orr r0,r0,#1 @ set the preserve bit + mcr p15,0,r0,c10,c0,0 @ write to the lockdown register + ldr r1,[r1] @ TLB will miss, and entry will be loaded + mrc p15,0,r0,c10,c0,0 @ read the lockdown register (victim will have + @ incremented) + bic r0,r0,#1 @ clear preserve bit + mcr p15,0,r0,c10,c0,0 @ write to the lockdown registerADR r1,LockAddr + mov pc,lr @ diff --git a/drivers/power/mxs/linux.c b/drivers/power/mxs/linux.c new file mode 100644 index 000000000000..1c2dfc10f7ca --- /dev/null +++ b/drivers/power/mxs/linux.c @@ -0,0 +1,1182 @@ +/* + * Linux glue to MXS battery state machine. + * + * Author: Steve Longerbeam + * + * Copyright (C) 2008 EmbeddedAlley Solutions Inc. + * Copyright 2008-2010 Freescale Semiconductor, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, as + * published by the Free Software Foundation. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "ddi_bc_internal.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +enum application_5v_status{ + _5v_connected_verified, + _5v_connected_unverified, + _5v_disconnected_unverified, + _5v_disconnected_verified, +}; + +struct mxs_info { + struct device *dev; + struct regulator *regulator; + + struct power_supply bat; + struct power_supply ac; + struct power_supply usb; + + ddi_bc_Cfg_t *sm_cfg; + struct mutex sm_lock; + struct timer_list sm_timer; + struct work_struct sm_work; + struct resource *irq_vdd5v; + struct resource *irq_dcdc4p2_bo; + struct resource *irq_batt_brnout; + struct resource *irq_vddd_brnout; + struct resource *irq_vdda_brnout; + struct resource *irq_vddio_brnout; + struct resource *irq_vdd5v_droop; + int is_ac_online; + int source_protection_mode; + uint32_t sm_new_5v_connection_jiffies; + uint32_t sm_new_5v_disconnection_jiffies; + enum application_5v_status sm_5v_connection_status; + + + + +#define USB_ONLINE 0x01 +#define USB_REG_SET 0x02 +#define USB_SM_RESTART 0x04 +#define USB_SHUTDOWN 0x08 +#define USB_N_SEND 0x10 + int is_usb_online; +}; + +#define to_mxs_info(x) container_of((x), struct mxs_info, bat) + +#ifndef NON_USB_5V_SUPPLY_CURRENT_LIMIT_MA +#define NON_USB_5V_SUPPLY_CURRENT_LIMIT_MA 780 +#endif + +#ifndef POWERED_USB_5V_CURRENT_LIMIT_MA +#define POWERED_USB_5V_CURRENT_LIMIT_MA 450 +#endif + +#ifndef UNPOWERED_USB_5V_CURRENT_LIMIT_MA +#define UNPOWERED_USB_5V_CURRENT_LIMIT_MA 80 +#endif + +#ifndef _5V_DEBOUNCE_TIME_MS +#define _5V_DEBOUNCE_TIME_MS 500 +#endif + +#ifndef OS_SHUTDOWN_BATTERY_VOLTAGE_THRESHOLD_MV +#define OS_SHUTDOWN_BATTERY_VOLTAGE_THRESHOLD_MV 3350 +#endif + +#ifdef CONFIG_ARCH_MX23 +#define IRQ_DCDC4P2_BRNOUT IRQ_DCDC4P2_BO +#endif + +#define POWER_FIQ + +/* #define DEBUG_IRQS */ + +/* There is no direct way to detect wall power presence, so assume the AC + * power source is valid if 5V presents and USB device is disconnected. + * If USB device is connected then assume that AC is offline and USB power + * is online. + */ + + +#define is_ac_online() \ + (ddi_power_Get5vPresentFlag() ? (!fsl_is_usb_plugged()) : 0) +#define is_usb_online() \ + (ddi_power_Get5vPresentFlag() ? (!!fsl_is_usb_plugged()) : 0) + + + +void init_protection(struct mxs_info *info) +{ + enum ddi_power_5v_status pmu_5v_status; + uint16_t battery_voltage; + + pmu_5v_status = ddi_power_GetPmu5vStatus(); + battery_voltage = ddi_power_GetBattery(); + + /* InitializeFiqSystem(); */ + ddi_power_InitOutputBrownouts(); + + + /* if we start the kernel with 4p2 already started + * by the bootlets, we need to hand off from this + * state to the kernel 4p2 enabled state. + */ + if ((pmu_5v_status == existing_5v_connection) && + ddi_power_check_4p2_bits()) { + ddi_power_enable_5v_disconnect_detection(); + + /* includes VBUS DROOP workaround for errata */ + ddi_power_init_4p2_protection(); + + /* if we still have our 5V connection, we can disable + * battery brownout interrupt. This is because the + * VDD5V DROOP IRQ handler will also shutdown if battery + * is browned out and it will enable the battery brownout + * and bring VBUSVALID_TRSH level back to a normal level + * which caused the hardware battery brownout shutdown + * to be enabled. The benefit of this is that device + * that have detachable batteries (or devices going through + * the assembly line and running this firmware to test + * with) can avoid shutting down if 5V is present and + * battery voltage goes away. + */ + ddi_power_EnableBatteryBoInterrupt(false); + + info->sm_5v_connection_status = _5v_connected_verified; + } else { +#ifdef DEBUG_IRQS + if (battery_voltage < + OS_SHUTDOWN_BATTERY_VOLTAGE_THRESHOLD_MV) { + printk(KERN_CRIT "Polled battery voltage measurement is\ + less than %dmV. Kernel should be halted/\ + shutdown\n", + OS_SHUTDOWN_BATTERY_VOLTAGE_THRESHOLD_MV); + + return; + } +#endif + info->sm_5v_connection_status = _5v_disconnected_verified; + ddi_power_EnableBatteryBoInterrupt(true); + + } + + + /* all brownouts are now handled software fiqs. We + * can now disable the hardware protection mechanisms + * because leaving them on yields ~2kV ESD level + * versus ~4kV ESD levels when they are off. This + * difference is suspected to be cause by the fast + * falling edge pswitch functionality being tripped + * by ESD events. This functionality is disabled + * when PWD_OFF is disabled. + */ +#ifdef DISABLE_HARDWARE_PROTECTION_MECHANISMS + __raw_writel(BM_POWER_RESET_PWD_OFF, + HW_POWER_RESET_SET_ADDR); +#endif + + + + +} + + + +static void check_and_handle_5v_connection(struct mxs_info *info) +{ + + switch (ddi_power_GetPmu5vStatus()) { + + case new_5v_connection: + ddi_power_enable_5v_disconnect_detection(); + info->sm_5v_connection_status = _5v_connected_unverified; + + case existing_5v_connection: + if (info->sm_5v_connection_status != _5v_connected_verified) { + /* we allow some time to pass before considering + * the 5v connection to be ready to use. This + * will give the USB system time to enumerate + * (coordination with USB driver to be added + * in the future). + */ + + /* handle jiffies rollover case */ + if ((jiffies - info->sm_new_5v_connection_jiffies) + < 0) { + info->sm_new_5v_connection_jiffies = jiffies; + break; + } + + if ((jiffies_to_msecs(jiffies - + info->sm_new_5v_connection_jiffies)) > + _5V_DEBOUNCE_TIME_MS) { + info->sm_5v_connection_status = + _5v_connected_verified; + dev_dbg(info->dev, + "5v connection verified\n"); +#ifdef CONFIG_MXS_VBUS_CURRENT_DRAW + #ifdef CONFIG_USB_GADGET + /* if there is USB 2.0 current limitation requirement, + * waiting for USB enum done. + */ + if ((__raw_readl(REGS_POWER_BASE + HW_POWER_5VCTRL) + & BM_POWER_5VCTRL_CHARGE_4P2_ILIMIT) == + (0x20 << BP_POWER_5VCTRL_CHARGE_4P2_ILIMIT)) { + dev_info(info->dev, "waiting USB enum done...\r\n"); + } + while ((__raw_readl(REGS_POWER_BASE + HW_POWER_5VCTRL) + & BM_POWER_5VCTRL_CHARGE_4P2_ILIMIT) + == (0x20 << BP_POWER_5VCTRL_CHARGE_4P2_ILIMIT)) { + msleep(50); + } + #endif +#endif + ddi_power_Enable4p2(450); + + /* part of handling for errata. It is + * now "somewhat" safe to + * turn on vddio interrupts again + */ + ddi_power_enable_vddio_interrupt(true); + } + } + break; + + case new_5v_disconnection: + + ddi_bc_SetDisable(); + ddi_bc_SetCurrentLimit(0); + if (info->regulator) + regulator_set_current_limit(info->regulator, 0, 0); + info->is_usb_online = 0; + info->is_ac_online = 0; + + info->sm_5v_connection_status = _5v_disconnected_unverified; + + case existing_5v_disconnection: + + if (info->sm_5v_connection_status != + _5v_disconnected_verified) { + if ((jiffies - info->sm_new_5v_disconnection_jiffies) + < 0) { + info->sm_new_5v_connection_jiffies = jiffies; + break; + } + + if ((jiffies_to_msecs(jiffies - + info->sm_new_5v_disconnection_jiffies)) > + _5V_DEBOUNCE_TIME_MS) { + info->sm_5v_connection_status = + _5v_disconnected_verified; + ddi_power_execute_5v_to_battery_handoff(); + ddi_power_enable_5v_connect_detection(); + + /* part of handling for errata. + * It is now safe to + * turn on vddio interrupts again + */ + ddi_power_enable_vddio_interrupt(true); + dev_dbg(info->dev, + "5v disconnection handled\n"); + + __raw_writel(__raw_readl(REGS_POWER_BASE + + HW_POWER_5VCTRL) & + (~BM_POWER_5VCTRL_CHARGE_4P2_ILIMIT) + | (0x20 << BP_POWER_5VCTRL_CHARGE_4P2_ILIMIT), + REGS_POWER_BASE + HW_POWER_5VCTRL); + + } + } + + break; + } +} + + +static void handle_battery_voltage_changes(struct mxs_info *info) +{ +#if 0 + uint16_t battery_voltage; + + battery_voltage = ddi_power_GetBattery(); + + if (info->sm_5v_connection_status != _5v_connected_verified) { + if (battery_voltage < + OS_SHUTDOWN_BATTERY_VOLTAGE_THRESHOLD_MV) { + printk(KERN_CRIT "Polled battery voltage measurement is\ + less than %dmV. Shutting down the \ + system\n", + OS_SHUTDOWN_BATTERY_VOLTAGE_THRESHOLD_MV); + + shutdown_os(); + return; + } + } else +#endif + { + ddi_power_handle_cmptrip(); + + if (ddi_power_IsBattRdyForXfer()) + ddi_power_enable_5v_to_battery_xfer(true); + else + ddi_power_enable_5v_to_battery_xfer(false); + + } +} + + +/* + * Power properties + */ +static enum power_supply_property mxs_power_props[] = { + POWER_SUPPLY_PROP_ONLINE, +}; + +static int mxs_power_get_property(struct power_supply *psy, + enum power_supply_property psp, + union power_supply_propval *val) +{ + switch (psp) { + case POWER_SUPPLY_PROP_ONLINE: + if (psy->type == POWER_SUPPLY_TYPE_MAINS) + /* ac online */ + val->intval = is_ac_online(); + else + /* usb online */ + val->intval = is_usb_online(); + break; + default: + return -EINVAL; + } + + return 0; +} +/* + * Battery properties + */ +static enum power_supply_property mxs_bat_props[] = { + POWER_SUPPLY_PROP_STATUS, + POWER_SUPPLY_PROP_PRESENT, + POWER_SUPPLY_PROP_HEALTH, + POWER_SUPPLY_PROP_TECHNOLOGY, + POWER_SUPPLY_PROP_VOLTAGE_NOW, + POWER_SUPPLY_PROP_CURRENT_NOW, + POWER_SUPPLY_PROP_TEMP, +}; + +static int mxs_bat_get_property(struct power_supply *psy, + enum power_supply_property psp, + union power_supply_propval *val) +{ + struct mxs_info *info = to_mxs_info(psy); + ddi_bc_State_t state; + ddi_bc_BrokenReason_t reason; + int temp_alarm; + int16_t temp_lo, temp_hi; + + switch (psp) { + case POWER_SUPPLY_PROP_STATUS: + state = ddi_bc_GetState(); + switch (state) { + case DDI_BC_STATE_CONDITIONING: + case DDI_BC_STATE_CHARGING: + case DDI_BC_STATE_TOPPING_OFF: + val->intval = POWER_SUPPLY_STATUS_CHARGING; + break; + case DDI_BC_STATE_DISABLED: + val->intval = ddi_power_Get5vPresentFlag() ? + POWER_SUPPLY_STATUS_NOT_CHARGING : + POWER_SUPPLY_STATUS_DISCHARGING; + break; + default: + /* TODO: detect full */ + val->intval = POWER_SUPPLY_STATUS_NOT_CHARGING; + break; + } + break; + case POWER_SUPPLY_PROP_PRESENT: + /* is battery present */ + state = ddi_bc_GetState(); + switch (state) { + case DDI_BC_STATE_WAITING_TO_CHARGE: + case DDI_BC_STATE_DCDC_MODE_WAITING_TO_CHARGE: + case DDI_BC_STATE_CONDITIONING: + case DDI_BC_STATE_CHARGING: + case DDI_BC_STATE_TOPPING_OFF: + case DDI_BC_STATE_DISABLED: + val->intval = 1; + break; + case DDI_BC_STATE_BROKEN: + val->intval = !(ddi_bc_GetBrokenReason() == + DDI_BC_BROKEN_NO_BATTERY_DETECTED); + break; + default: + val->intval = 0; + break; + } + break; + case POWER_SUPPLY_PROP_HEALTH: + temp_alarm = ddi_bc_RampGetDieTempAlarm(); + if (temp_alarm) { + val->intval = POWER_SUPPLY_HEALTH_OVERHEAT; + } else { + state = ddi_bc_GetState(); + switch (state) { + case DDI_BC_STATE_BROKEN: + reason = ddi_bc_GetBrokenReason(); + val->intval = + (reason == DDI_BC_BROKEN_CHARGING_TIMEOUT) ? + POWER_SUPPLY_HEALTH_DEAD : + POWER_SUPPLY_HEALTH_UNSPEC_FAILURE; + break; + case DDI_BC_STATE_UNINITIALIZED: + val->intval = POWER_SUPPLY_HEALTH_UNKNOWN; + break; + default: + val->intval = POWER_SUPPLY_HEALTH_GOOD; + break; + } + } + break; + case POWER_SUPPLY_PROP_TECHNOLOGY: + val->intval = POWER_SUPPLY_TECHNOLOGY_LION; + break; + case POWER_SUPPLY_PROP_VOLTAGE_NOW: + /* uV */ + val->intval = ddi_power_GetBattery() * 1000; + break; + case POWER_SUPPLY_PROP_CURRENT_NOW: + /* uA */ + val->intval = ddi_power_GetMaxBatteryChargeCurrent() * 1000; + break; + case POWER_SUPPLY_PROP_TEMP: + mutex_lock(&info->sm_lock); + ddi_power_GetDieTemp(&temp_lo, &temp_hi); + mutex_unlock(&info->sm_lock); + val->intval = temp_lo + (temp_hi - temp_lo) / 2; + + break; + default: + return -EINVAL; + } + + return 0; +} + +static void state_machine_timer(unsigned long data) +{ + struct mxs_info *info = (struct mxs_info *)data; + ddi_bc_Cfg_t *cfg = info->sm_cfg; + int ret; + + /* schedule next call to state machine */ + mod_timer(&info->sm_timer, + jiffies + msecs_to_jiffies(cfg->u32StateMachinePeriod)); + + ret = schedule_work(&info->sm_work); + if (!ret) + dev_dbg(info->dev, "state machine failed to schedule\n"); + +} +/* + * Assumption: + * AC power can't be switched to USB w/o system reboot + * and vice-versa + */ +static void state_machine_work(struct work_struct *work) +{ + struct mxs_info *info = + container_of(work, struct mxs_info, sm_work); + + mutex_lock(&info->sm_lock); + + handle_battery_voltage_changes(info); + + check_and_handle_5v_connection(info); + + if ((info->sm_5v_connection_status != _5v_connected_verified) || + !(info->regulator)) { + mod_timer(&info->sm_timer, jiffies + msecs_to_jiffies(100)); + goto out; + } + + /* if we made it here, we have a verified 5v connection */ +#ifndef CONFIG_MXS_VBUS_CURRENT_DRAW + if (info->is_ac_online) + goto done; + + /* ac supply connected */ + dev_dbg(info->dev, "changed power connection to ac/5v.\n)"); + dev_dbg(info->dev, "5v current limit set to %u.\n", + NON_USB_5V_SUPPLY_CURRENT_LIMIT_MA); + + info->is_ac_online = 1; + info->is_usb_online = 0; + ddi_power_set_4p2_ilimit( + NON_USB_5V_SUPPLY_CURRENT_LIMIT_MA); + ddi_bc_SetCurrentLimit( + NON_USB_5V_SUPPLY_CURRENT_LIMIT_MA /*mA*/); + if (regulator_set_current_limit(info->regulator, + 0, + NON_USB_5V_SUPPLY_CURRENT_LIMIT_MA*1000)) { + dev_err(info->dev, "reg_set_current(%duA) failed\n", + NON_USB_5V_SUPPLY_CURRENT_LIMIT_MA*1000); + } + ddi_bc_SetEnable(); + goto done; +#else + + if (!is_usb_online()) + goto out; + + if (info->is_usb_online & USB_REG_SET) + goto done; + + info->is_ac_online = 0; + info->is_usb_online |= USB_ONLINE; + + + + if (!(info->is_usb_online & USB_N_SEND)) { + info->is_usb_online |= USB_N_SEND; + } + + + dev_dbg(info->dev, "%s: charge current set to %dmA\n", __func__, + POWERED_USB_5V_CURRENT_LIMIT_MA); + + if (regulator_set_current_limit(info->regulator, + 0, + POWERED_USB_5V_CURRENT_LIMIT_MA*1000)) { + dev_err(info->dev, "reg_set_current(%duA) failed\n", + POWERED_USB_5V_CURRENT_LIMIT_MA*1000); + } else { + ddi_bc_SetCurrentLimit(POWERED_USB_5V_CURRENT_LIMIT_MA/*mA*/); + ddi_bc_SetEnable(); + } + + if (info->is_usb_online & USB_SM_RESTART) { + info->is_usb_online &= ~USB_SM_RESTART; + ddi_bc_SetEnable(); + } + + info->is_usb_online |= USB_REG_SET; + +#endif + dev_dbg(info->dev, "changed power connection to usb/5v present\n"); + +done: + ddi_bc_StateMachine(); +out: + mutex_unlock(&info->sm_lock); +} + + + +static int bc_sm_restart(struct mxs_info *info) +{ + ddi_bc_Status_t bcret; + int ret = 0; + + mutex_lock(&info->sm_lock); + + /* ungate power clk */ + ddi_power_SetPowerClkGate(0); + + /* + * config battery charger state machine and move it to the Disabled + * state. This must be done before starting the state machine. + */ + bcret = ddi_bc_Init(info->sm_cfg); + if (bcret != DDI_BC_STATUS_SUCCESS) { + dev_err(info->dev, "battery charger init failed: %d\n", bcret); + ret = -EIO; + goto out; + } else { + + if (!info->regulator) { + info->regulator = regulator_get(NULL, "charger-1"); + if (!info->regulator || IS_ERR(info->regulator)) { + dev_err(info->dev, + "%s: failed to get regulator\n", __func__); + info->regulator = NULL; + } else { + regulator_set_current_limit( + info->regulator, 0, 0); + regulator_set_mode(info->regulator, + REGULATOR_MODE_FAST); + } + } + } + + + + /* schedule first call to state machine */ + mod_timer(&info->sm_timer, jiffies + 1); +out: + mutex_unlock(&info->sm_lock); + return ret; +} + +#ifndef POWER_FIQ + +static irqreturn_t mxs_irq_dcdc4p2_bo(int irq, void *cookie) +{ +#ifdef DEBUG_IRQS + struct mxs_info *info = (struct mxs_info *)cookie; + dev_info(info->dev, "dcdc4p2 brownout interrupt occurred\n"); + +#endif + ddi_power_handle_dcdc4p2_bo(); + return IRQ_HANDLED; +} + +static irqreturn_t mxs_irq_batt_brnout(int irq, void *cookie) +{ +#ifdef DEBUG_IRQS + struct mxs_info *info = (struct mxs_info *)cookie; + dev_info(info->dev, "battery brownout interrupt occurred\n"); + ddi_power_disable_power_interrupts(); +#else + ddi_power_shutdown(); +#endif + return IRQ_HANDLED; +} + + +static irqreturn_t mxs_irq_vddd_brnout(int irq, void *cookie) +{ +#ifdef DEBUG_IRQS + struct mxs_info *info = (struct mxs_info *)cookie; + dev_info(info->dev, "vddd brownout interrupt occurred\n"); + ddi_power_disable_power_interrupts(); +#else + ddi_power_shutdown(); +#endif + return IRQ_HANDLED; +} +static irqreturn_t mxs_irq_vdda_brnout(int irq, void *cookie) +{ +#ifdef DEBUG_IRQS + struct mxs_info *info = (struct mxs_info *)cookie; + dev_info(info->dev, "vdda brownout interrupt occurred\n"); + ddi_power_disable_power_interrupts(); +#else + ddi_power_shutdown(); +#endif + return IRQ_HANDLED; +} + +static irqreturn_t mxs_irq_vdd5v_droop(int irq, void *cookie) +{ +#ifdef DEBUG_IRQS + struct mxs_info *info = (struct mxs_info *)cookie; + dev_info(info->dev, "vdd5v droop interrupt occurred\n"); +#endif + ddi_power_handle_vdd5v_droop(); + + return IRQ_HANDLED; +} + +#endif /* if POWER_FIQ */ + +static irqreturn_t mxs_irq_vddio_brnout(int irq, void *cookie) +{ +#ifdef DEBUG_IRQS + struct mxs_info *info = (struct mxs_info *)cookie; + dev_info(info->dev, "vddio brownout interrupt occurred\n"); + ddi_power_disable_power_interrupts(); +#else + ddi_power_handle_vddio_brnout(); +#endif + return IRQ_HANDLED; +} + +static irqreturn_t mxs_irq_vdd5v(int irq, void *cookie) +{ + struct mxs_info *info = (struct mxs_info *)cookie; + + switch (ddi_power_GetPmu5vStatus()) { + + case new_5v_connection: + + ddi_power_disable_5v_connection_irq(); + dev_dbg(info->dev, "new 5v connection detected\n"); + info->sm_new_5v_connection_jiffies = jiffies; + mod_timer(&info->sm_timer, jiffies + 1); + break; + + case new_5v_disconnection: + + /* due to 5v connect vddio bo chip bug, we need to + * disable vddio interrupts until we reset the 5v + * detection for 5v connect detect. We want to allow + * some debounce time before enabling connect detection. + * This is handled in the vdd5v_droop interrupt for now. + */ + /* ddi_power_enable_vddio_interrupt(false); */ + + ddi_power_disable_5v_connection_irq(); + dev_dbg(info->dev, "new 5v disconnection detected\n"); + info->sm_new_5v_disconnection_jiffies = jiffies; + mod_timer(&info->sm_timer, jiffies + 1); + break; + + default: + + break; + + } + + return IRQ_HANDLED; +} + +static int mxs_bat_probe(struct platform_device *pdev) +{ + struct mxs_info *info; + int ret = 0; + + + /* enable usb device presence detection */ + fsl_enable_usb_plugindetect(); + + ret = ddi_power_init_battery(); + if (ret) { + printk(KERN_ERR "Aborting power driver initialization\n"); + return 1; + } + + + if (!pdev->dev.platform_data) { + printk(KERN_ERR "%s: missing platform data\n", __func__); + return -ENODEV; + } + + info = kzalloc(sizeof(*info), GFP_KERNEL); + if (!info) + return -ENOMEM; + + info->irq_vdd5v = platform_get_resource(pdev, IORESOURCE_IRQ, 0); + if (info->irq_vdd5v == NULL) { + printk(KERN_ERR "%s: failed to get irq resouce\n", __func__); + goto free_info; + } + + info->irq_vddio_brnout = platform_get_resource( + pdev, IORESOURCE_IRQ, 5); + if (info->irq_vddio_brnout == NULL) { + printk(KERN_ERR "%s: failed to get irq resouce\n", __func__); + goto free_info; + } + +#ifndef POWER_FIQ + info->irq_dcdc4p2_bo = platform_get_resource(pdev, IORESOURCE_IRQ, 1); + if (info->irq_dcdc4p2_bo == NULL) { + printk(KERN_ERR "%s: failed to get irq resouce\n", __func__); + goto free_info; + } + + info->irq_batt_brnout = platform_get_resource(pdev, IORESOURCE_IRQ, 2); + if (info->irq_batt_brnout == NULL) { + printk(KERN_ERR "%s: failed to get irq resouce\n", __func__); + goto free_info; + } + + info->irq_vddd_brnout = platform_get_resource(pdev, IORESOURCE_IRQ, 3); + if (info->irq_vddd_brnout == NULL) { + printk(KERN_ERR "%s: failed to get irq resouce\n", __func__); + goto free_info; + } + + info->irq_vdda_brnout = platform_get_resource(pdev, IORESOURCE_IRQ, 4); + if (info->irq_vdda_brnout == NULL) { + printk(KERN_ERR "%s: failed to get irq resouce\n", __func__); + goto free_info; + } + + + info->irq_vdd5v_droop = platform_get_resource(pdev, IORESOURCE_IRQ, 6); + if (info->irq_vdd5v_droop == NULL) { + printk(KERN_ERR "%s: failed to get irq resouce\n", __func__); + goto free_info; + } +#endif + + + platform_set_drvdata(pdev, info); + + info->dev = &pdev->dev; + info->sm_cfg = pdev->dev.platform_data; + + /* initialize bat power_supply struct */ + info->bat.name = "battery"; + info->bat.type = POWER_SUPPLY_TYPE_BATTERY; + info->bat.properties = mxs_bat_props; + info->bat.num_properties = ARRAY_SIZE(mxs_bat_props); + info->bat.get_property = mxs_bat_get_property; + + /* initialize ac power_supply struct */ + info->ac.name = "ac"; + info->ac.type = POWER_SUPPLY_TYPE_MAINS; + info->ac.properties = mxs_power_props; + info->ac.num_properties = ARRAY_SIZE(mxs_power_props); + info->ac.get_property = mxs_power_get_property; + + /* initialize usb power_supply struct */ + info->usb.name = "usb"; + info->usb.type = POWER_SUPPLY_TYPE_USB; + info->usb.properties = mxs_power_props; + info->usb.num_properties = ARRAY_SIZE(mxs_power_props); + info->usb.get_property = mxs_power_get_property; + + init_timer(&info->sm_timer); + info->sm_timer.data = (unsigned long)info; + info->sm_timer.function = state_machine_timer; + + mutex_init(&info->sm_lock); + INIT_WORK(&info->sm_work, state_machine_work); + + /* init LRADC channels to measure battery voltage and die temp */ + + __raw_writel(BM_POWER_5VCTRL_ENABLE_LINREG_ILIMIT, + REGS_POWER_BASE + HW_POWER_5VCTRL_CLR); + + ret = bc_sm_restart(info); + if (ret) + goto free_info; + + + ret = request_irq(info->irq_vdd5v->start, + mxs_irq_vdd5v, IRQF_DISABLED | IRQF_SHARED, + pdev->name, info); + if (ret) { + dev_err(info->dev, "failed to request irq\n"); + goto stop_sm; + } + + ret = request_irq(info->irq_vddio_brnout->start, + mxs_irq_vddio_brnout, IRQF_DISABLED, + pdev->name, info); + if (ret) { + dev_err(info->dev, "failed to request irq\n"); + goto stop_sm; + } + +#ifndef POWER_FIQ + ret = request_irq(info->irq_dcdc4p2_bo->start, + mxs_irq_dcdc4p2_bo, IRQF_DISABLED, + pdev->name, info); + if (ret) { + dev_err(info->dev, "failed to request irq\n"); + goto stop_sm; + } + + ret = request_irq(info->irq_batt_brnout->start, + mxs_irq_batt_brnout, IRQF_DISABLED, + pdev->name, info); + if (ret) { + dev_err(info->dev, "failed to request irq\n"); + goto stop_sm; + } + + ret = request_irq(info->irq_vddd_brnout->start, + mxs_irq_vddd_brnout, IRQF_DISABLED, + pdev->name, info); + if (ret) { + dev_err(info->dev, "failed to request irq\n"); + goto stop_sm; + } + + ret = request_irq(info->irq_vdda_brnout->start, + mxs_irq_vdda_brnout, IRQF_DISABLED, + pdev->name, info); + if (ret) { + dev_err(info->dev, "failed to request irq\n"); + goto stop_sm; + } + + + ret = request_irq(info->irq_vdd5v_droop->start, + mxs_irq_vdd5v_droop, IRQF_DISABLED, + pdev->name, info); + if (ret) { + dev_err(info->dev, "failed to request irq\n"); + goto stop_sm; + } +#endif + + ret = power_supply_register(&pdev->dev, &info->bat); + if (ret) { + dev_err(info->dev, "failed to register battery\n"); + goto free_irq; + } + + ret = power_supply_register(&pdev->dev, &info->ac); + if (ret) { + dev_err(info->dev, "failed to register ac power supply\n"); + goto unregister_bat; + } + + ret = power_supply_register(&pdev->dev, &info->usb); + if (ret) { + dev_err(info->dev, "failed to register usb power supply\n"); + goto unregister_ac; + } + + /* handoff protection handling from bootlets protection method + * to kernel protection method + */ + init_protection(info); + + + return 0; + +unregister_ac: + power_supply_unregister(&info->ac); +unregister_bat: + power_supply_unregister(&info->bat); +free_irq: + free_irq(info->irq_vdd5v->start, pdev); + free_irq(info->irq_vddio_brnout->start, pdev); +#ifndef POWER_FIQ + free_irq(info->irq_dcdc4p2_bo->start, pdev); + free_irq(info->irq_batt_brnout->start, pdev); + free_irq(info->irq_vddd_brnout->start, pdev); + free_irq(info->irq_vdda_brnout->start, pdev); + free_irq(info->irq_vdd5v_droop->start, pdev); +#endif + +stop_sm: + ddi_bc_ShutDown(); +free_info: + kfree(info); + return ret; +} + +static int mxs_bat_remove(struct platform_device *pdev) +{ + struct mxs_info *info = platform_get_drvdata(pdev); + + if (info->regulator) + regulator_put(info->regulator); + free_irq(info->irq_vdd5v->start, pdev); + free_irq(info->irq_vddio_brnout->start, pdev); +#ifndef POWER_FIQ + free_irq(info->irq_dcdc4p2_bo->start, pdev); + free_irq(info->irq_batt_brnout->start, pdev); + free_irq(info->irq_vddd_brnout->start, pdev); + free_irq(info->irq_vdda_brnout->start, pdev); + free_irq(info->irq_vdd5v_droop->start, pdev); +#endif + ddi_bc_ShutDown(); + power_supply_unregister(&info->usb); + power_supply_unregister(&info->ac); + power_supply_unregister(&info->bat); + return 0; +} + +static void mxs_bat_shutdown(struct platform_device *pdev) +{ + ddi_bc_ShutDown(); +} + + +#ifdef CONFIG_PM + +static int mxs_bat_suspend(struct platform_device *pdev, pm_message_t msg) +{ + struct mxs_info *info = platform_get_drvdata(pdev); + + mutex_lock(&info->sm_lock); + + /* enable USB 5v wake up so don't disable irq here*/ + + ddi_bc_SetDisable(); + /* cancel state machine timer */ + del_timer_sync(&info->sm_timer); + + mutex_unlock(&info->sm_lock); + return 0; +} + +static int mxs_bat_resume(struct platform_device *pdev) +{ + struct mxs_info *info = platform_get_drvdata(pdev); + ddi_bc_Cfg_t *cfg = info->sm_cfg; + + mutex_lock(&info->sm_lock); + + if (is_ac_online()) { + /* ac supply connected */ + dev_dbg(info->dev, "ac/5v present, enabling state machine\n"); + + info->is_ac_online = 1; + info->is_usb_online = 0; + ddi_bc_SetCurrentLimit( + NON_USB_5V_SUPPLY_CURRENT_LIMIT_MA /*mA*/); + ddi_bc_SetEnable(); + } else if (is_usb_online()) { + /* usb supply connected */ + dev_dbg(info->dev, "usb/5v present, enabling state machine\n"); + + info->is_ac_online = 0; + info->is_usb_online = 1; + ddi_bc_SetCurrentLimit(POWERED_USB_5V_CURRENT_LIMIT_MA /*mA*/); + ddi_bc_SetEnable(); + } else { + /* not powered */ + dev_dbg(info->dev, "%s: 5v not present\n", __func__); + + info->is_ac_online = 0; + info->is_usb_online = 0; + } + + /* enable 5v irq */ + __raw_writel(BM_POWER_CTRL_ENIRQ_VDD5V_GT_VDDIO, + REGS_POWER_BASE + HW_POWER_CTRL_SET); + + /* reschedule calls to state machine */ + mod_timer(&info->sm_timer, + jiffies + msecs_to_jiffies(cfg->u32StateMachinePeriod)); + + mutex_unlock(&info->sm_lock); + return 0; +} + +#else +#define mxs_bat_suspend NULL +#define mxs_bat_resume NULL +#endif + +static struct platform_driver mxs_batdrv = { + .probe = mxs_bat_probe, + .remove = mxs_bat_remove, + .shutdown = mxs_bat_shutdown, + .suspend = mxs_bat_suspend, + .resume = mxs_bat_resume, + .driver = { + .name = "mxs-battery", + .owner = THIS_MODULE, + }, +}; + +#ifdef POWER_FIQ +static int power_relinquish(void *data, int relinquish) +{ + return -1; +} + +static struct fiq_handler power_fiq = { + .name = "mxs-battery", + .fiq_op = power_relinquish +}; + +static struct pt_regs fiq_regs; +extern char power_fiq_start[], power_fiq_end[]; +extern void lock_vector_tlb(void *); +extern long power_fiq_count; +static struct proc_dir_entry *power_fiq_proc; +#endif + +static int __init mxs_bat_init(void) +{ + struct clk *cpu, *pll0; + +#ifdef POWER_FIQ + int ret; + ret = claim_fiq(&power_fiq); + if (ret) { + pr_err("Can't claim fiq"); + } else { + get_fiq_regs(&fiq_regs); + set_fiq_handler(power_fiq_start, power_fiq_end-power_fiq_start); + lock_vector_tlb((void *)0xffff0000); + lock_vector_tlb(REGS_POWER_BASE); + + /* disable interrupts to be configured as FIQs */ + disable_irq(IRQ_DCDC4P2_BRNOUT); + disable_irq(IRQ_BATT_BRNOUT); + disable_irq(IRQ_VDDD_BRNOUT); +#ifndef CONFIG_ARCH_MX28 + disable_irq(IRQ_VDD18_BRNOUT); +#endif + disable_irq(IRQ_VDD5V_DROOP); + + + /* Enable these interrupts as FIQs */ + mxs_set_irq_fiq(IRQ_DCDC4P2_BRNOUT, 1); + mxs_set_irq_fiq(IRQ_BATT_BRNOUT, 1); + mxs_set_irq_fiq(IRQ_VDDD_BRNOUT, 1); +#ifndef CONFIG_ARCH_MX28 + mxs_set_irq_fiq(IRQ_VDD18_BRNOUT, 1); +#endif + mxs_set_irq_fiq(IRQ_VDD5V_DROOP, 1); + + + /* enable FIQ functionality */ + mxs_enable_fiq_functionality(1); + + enable_irq(IRQ_DCDC4P2_BRNOUT); + enable_irq(IRQ_BATT_BRNOUT); + enable_irq(IRQ_VDDD_BRNOUT); +#ifndef CONFIG_ARCH_MX28 + enable_irq(IRQ_VDD18_BRNOUT); +#endif + enable_irq(IRQ_VDD5V_DROOP); + + } +#endif + +#ifdef CONFIG_MXS_VBUS_CURRENT_DRAW + if (((__raw_readl(REGS_POWER_BASE + HW_POWER_5VCTRL) & + BM_POWER_5VCTRL_CHARGE_4P2_ILIMIT) == 0x20000) + && ((__raw_readl(REGS_POWER_BASE + HW_POWER_5VCTRL) & + BM_POWER_5VCTRL_PWD_CHARGE_4P2) == 0)) { +#ifdef CONFIG_USB_GADGET + printk(KERN_INFO "USB GADGET exist,wait USB enum done...\r\n"); + while (((__raw_readl(REGS_POWER_BASE + HW_POWER_5VCTRL) + & BM_POWER_5VCTRL_CHARGE_4P2_ILIMIT) == 0x20000) && + ((__raw_readl(REGS_POWER_BASE + HW_POWER_5VCTRL) & + BM_POWER_5VCTRL_PWD_CHARGE_4P2) == 0)) + ; +#else + printk(KERN_INFO "USB GADGET not exist,\ + release current limit and let CPU clock up...\r\n"); +#endif + } + cpu = clk_get(NULL, "cpu"); + pll0 = clk_get(NULL, "ref_cpu"); + clk_set_parent(cpu, pll0); +#endif + return platform_driver_register(&mxs_batdrv); +} + +static void __exit mxs_bat_exit(void) +{ + platform_driver_unregister(&mxs_batdrv); +} +#ifdef CONFIG_MXS_VBUS_CURRENT_DRAW + fs_initcall(mxs_bat_init); +#else + module_init(mxs_bat_init); +#endif +module_exit(mxs_bat_exit); + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Steve Longerbeam "); +MODULE_DESCRIPTION("Linux glue to MXS battery state machine"); diff --git a/drivers/regulator/Kconfig b/drivers/regulator/Kconfig index 04f2e085116a..90c47a684de4 100644 --- a/drivers/regulator/Kconfig +++ b/drivers/regulator/Kconfig @@ -201,5 +201,30 @@ config REGULATOR_88PM8607 help This driver supports 88PM8607 voltage regulator chips. +config REGULATOR_MC13892 + tristate "MC13892 Regulator Support" + depends on MXC_PMIC_MC13892 + default y + +config REGULATOR_MC34704 + tristate "MC34704 Regulator Support" + depends on MXC_PMIC_MC34704 + default y + +config REGULATOR_MXS + tristate "MXS Regulator Support" + depends on ARCH_MXS + default y + +config REGULATOR_MC9S08DZ60 + tristate "mc9s08dz60 Regulator Support" + depends on MXC_PMIC_MC9S08DZ60 + default y + +config REGULATOR_MAX17135 + tristate "Maxim MAX17135 Regulator Support" + depends on REGULATOR + default n + endif diff --git a/drivers/regulator/Makefile b/drivers/regulator/Makefile index 4e7feece22d5..724460635476 100644 --- a/drivers/regulator/Makefile +++ b/drivers/regulator/Makefile @@ -2,7 +2,6 @@ # Makefile for regulator drivers. # - obj-$(CONFIG_REGULATOR) += core.o obj-$(CONFIG_REGULATOR_FIXED_VOLTAGE) += fixed.o obj-$(CONFIG_REGULATOR_VIRTUAL_CONSUMER) += virtual.o @@ -32,4 +31,13 @@ obj-$(CONFIG_REGULATOR_TPS65023) += tps65023-regulator.o obj-$(CONFIG_REGULATOR_TPS6507X) += tps6507x-regulator.o obj-$(CONFIG_REGULATOR_88PM8607) += 88pm8607.o +obj-$(CONFIG_REGULATOR_MAX17135) += max17135-regulator.o + +obj-$(CONFIG_REGULATOR_MC13892) += reg-mc13892.o +obj-$(CONFIG_REGULATOR_MC34704) += reg-mc34704.o +obj-$(CONFIG_REGULATOR_STMP3XXX) += stmp3xxx.o +obj-$(CONFIG_REGULATOR_MXS) += mxs-regulator.o + +obj-$(CONFIG_REGULATOR_MC9S08DZ60) += reg-mc9s08dz60.o + ccflags-$(CONFIG_REGULATOR_DEBUG) += -DDEBUG diff --git a/drivers/regulator/core.c b/drivers/regulator/core.c index 2248087b9be2..af6ebc027884 100644 --- a/drivers/regulator/core.c +++ b/drivers/regulator/core.c @@ -1108,6 +1108,11 @@ static struct regulator *_regulator_get(struct device *dev, const char *id, goto found; } } + list_for_each_entry(rdev, ®ulator_list, list) { + if (strcmp(rdev->desc->name, id) == 0) { + goto found; + } + } #ifdef CONFIG_REGULATOR_DUMMY if (!devname) diff --git a/drivers/regulator/max17135-regulator.c b/drivers/regulator/max17135-regulator.c new file mode 100644 index 000000000000..3fdec795fbeb --- /dev/null +++ b/drivers/regulator/max17135-regulator.c @@ -0,0 +1,736 @@ +/* + * Copyright (C) 2010 Freescale Semiconductor, Inc. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Define this as 1 when using a Rev 1 MAX17135 part. These parts have + * some limitations, including an inability to turn on the PMIC via I2C. + */ +#define MAX17135_REV 1 + +/* + * PMIC Register Addresses + */ +enum { + REG_MAX17135_EXT_TEMP = 0x0, + REG_MAX17135_CONFIG, + REG_MAX17135_INT_TEMP = 0x4, + REG_MAX17135_STATUS, + REG_MAX17135_PRODUCT_REV, + REG_MAX17135_PRODUCT_ID, + REG_MAX17135_DVR, + REG_MAX17135_ENABLE, + REG_MAX17135_FAULT, /*0x0A*/ + REG_MAX17135_HVINP, + REG_MAX17135_PRGM_CTRL, + REG_MAX17135_TIMING1 = 0x10, /* Timing regs base address is 0x10 */ + REG_MAX17135_TIMING2, + REG_MAX17135_TIMING3, + REG_MAX17135_TIMING4, + REG_MAX17135_TIMING5, + REG_MAX17135_TIMING6, + REG_MAX17135_TIMING7, + REG_MAX17135_TIMING8, +}; +#define MAX17135_REG_NUM 21 +#define MAX17135_MAX_REGISTER 0xFF + +/* + * Bitfield macros that use rely on bitfield width/shift information. + */ +#define BITFMASK(field) (((1U << (field ## _WID)) - 1) << (field ## _LSH)) +#define BITFVAL(field, val) ((val) << (field ## _LSH)) +#define BITFEXT(var, bit) ((var & BITFMASK(bit)) >> (bit ## _LSH)) + +/* + * Shift and width values for each register bitfield + */ +#define EXT_TEMP_LSH 7 +#define EXT_TEMP_WID 9 + +#define THERMAL_SHUTDOWN_LSH 0 +#define THERMAL_SHUTDOWN_WID 1 + +#define INT_TEMP_LSH 7 +#define INT_TEMP_WID 9 + +#define STAT_BUSY_LSH 0 +#define STAT_BUSY_WID 1 +#define STAT_OPEN_LSH 1 +#define STAT_OPEN_WID 1 +#define STAT_SHRT_LSH 2 +#define STAT_SHRT_WID 1 + +#define PROD_REV_LSH 0 +#define PROD_REV_WID 8 + +#define PROD_ID_LSH 0 +#define PROD_ID_WID 8 + +#define DVR_LSH 0 +#define DVR_WID 8 + +#define ENABLE_LSH 0 +#define ENABLE_WID 1 +#define VCOM_ENABLE_LSH 1 +#define VCOM_ENABLE_WID 1 + +#define FAULT_FBPG_LSH 0 +#define FAULT_FBPG_WID 1 +#define FAULT_HVINP_LSH 1 +#define FAULT_HVINP_WID 1 +#define FAULT_HVINN_LSH 2 +#define FAULT_HVINN_WID 1 +#define FAULT_FBNG_LSH 3 +#define FAULT_FBNG_WID 1 +#define FAULT_HVINPSC_LSH 4 +#define FAULT_HVINPSC_WID 1 +#define FAULT_HVINNSC_LSH 5 +#define FAULT_HVINNSC_WID 1 +#define FAULT_OT_LSH 6 +#define FAULT_OT_WID 1 +#define FAULT_POK_LSH 7 +#define FAULT_POK_WID 1 + +#define HVINP_LSH 0 +#define HVINP_WID 4 + +#define CTRL_DVR_LSH 0 +#define CTRL_DVR_WID 1 +#define CTRL_TIMING_LSH 1 +#define CTRL_TIMING_WID 1 + +#define TIMING1_LSH 0 +#define TIMING1_WID 8 +#define TIMING2_LSH 0 +#define TIMING2_WID 8 +#define TIMING3_LSH 0 +#define TIMING3_WID 8 +#define TIMING4_LSH 0 +#define TIMING4_WID 8 +#define TIMING5_LSH 0 +#define TIMING5_WID 8 +#define TIMING6_LSH 0 +#define TIMING6_WID 8 +#define TIMING7_LSH 0 +#define TIMING7_WID 8 +#define TIMING8_LSH 0 +#define TIMING8_WID 8 + +/* + * Regulator definitions + * *_MIN_uV - minimum microvolt for regulator + * *_MAX_uV - maximum microvolt for regulator + * *_STEP_uV - microvolts between regulator output levels + * *_MIN_VAL - minimum register field value for regulator + * *_MAX_VAL - maximum register field value for regulator + */ +#define MAX17135_HVINP_MIN_uV 5000000 +#define MAX17135_HVINP_MAX_uV 20000000 +#define MAX17135_HVINP_STEP_uV 1000000 +#define MAX17135_HVINP_MIN_VAL 0 +#define MAX17135_HVINP_MAX_VAL 1 + +#define MAX17135_HVINN_MIN_uV 5000000 +#define MAX17135_HVINN_MAX_uV 20000000 +#define MAX17135_HVINN_STEP_uV 1000000 +#define MAX17135_HVINN_MIN_VAL 0 +#define MAX17135_HVINN_MAX_VAL 1 + +#define MAX17135_GVDD_MIN_uV 5000000 +#define MAX17135_GVDD_MAX_uV 20000000 +#define MAX17135_GVDD_STEP_uV 1000000 +#define MAX17135_GVDD_MIN_VAL 0 +#define MAX17135_GVDD_MAX_VAL 1 + +#define MAX17135_GVEE_MIN_uV 5000000 +#define MAX17135_GVEE_MAX_uV 20000000 +#define MAX17135_GVEE_STEP_uV 1000000 +#define MAX17135_GVEE_MIN_VAL 0 +#define MAX17135_GVEE_MAX_VAL 1 + +#if (MAX17135_REV == 1) +#define MAX17135_VCOM_MIN_uV -4325000 +#define MAX17135_VCOM_MAX_uV -500000 +#define MAX17135_VCOM_STEP_uV 15000 +#define MAX17135_VCOM_MIN_VAL 0 +#define MAX17135_VCOM_MAX_VAL 255 +/* Required due to discrepancy between + * observed VCOM programming and + * what is suggested in the spec. + */ +#define MAX17135_VCOM_FUDGE_FACTOR 330000 +#else +#define MAX17135_VCOM_MIN_uV -3050000 +#define MAX17135_VCOM_MAX_uV -500000 +#define MAX17135_VCOM_STEP_uV 10000 +#define MAX17135_VCOM_MIN_VAL 0 +#define MAX17135_VCOM_MAX_VAL 255 +#define MAX17135_VCOM_FUDGE_FACTOR 330000 +#endif + +#define MAX17135_VCOM_VOLTAGE_DEFAULT -1250000 + +#define MAX17135_VNEG_MIN_uV 5000000 +#define MAX17135_VNEG_MAX_uV 20000000 +#define MAX17135_VNEG_STEP_uV 1000000 +#define MAX17135_VNEG_MIN_VAL 0 +#define MAX17135_VNEG_MAX_VAL 1 + +#define MAX17135_VPOS_MIN_uV 5000000 +#define MAX17135_VPOS_MAX_uV 20000000 +#define MAX17135_VPOS_STEP_uV 1000000 +#define MAX17135_VPOS_MIN_VAL 0 +#define MAX17135_VPOS_MAX_VAL 1 + +struct max17135 { + /* chip revision */ + int rev; + + struct device *dev; + + /* Platform connection */ + struct i2c_client *i2c_client; + + /* Client devices */ + struct platform_device *pdev[MAX17135_REG_NUM]; + + /* GPIOs */ + int gpio_pmic_pwrgood; + int gpio_pmic_vcom_ctrl; + int gpio_pmic_wakeup; + int gpio_pmic_intr; + + bool vcom_setup; + + int max_wait; +}; + +/* + * Regulator operations + */ +static int max17135_hvinp_set_voltage(struct regulator_dev *reg, + int minuV, int uV) +{ + unsigned int reg_val; + unsigned int fld_val; + struct max17135 *max17135 = rdev_get_drvdata(reg); + struct i2c_client *client = max17135->i2c_client; + + if ((uV >= MAX17135_HVINP_MIN_uV) && + (uV <= MAX17135_HVINP_MAX_uV)) + fld_val = (uV - MAX17135_HVINP_MIN_uV) / + MAX17135_HVINP_STEP_uV; + else + return -EINVAL; + + reg_val = i2c_smbus_read_byte_data(client, REG_MAX17135_HVINP); + + reg_val &= ~BITFMASK(HVINP); + reg_val |= BITFVAL(HVINP, fld_val); /* shift to correct bit */ + + return i2c_smbus_write_byte_data(client, REG_MAX17135_HVINP, reg_val); +} + +static int max17135_hvinp_get_voltage(struct regulator_dev *reg) +{ + unsigned int reg_val; + unsigned int fld_val; + int volt; + struct max17135 *max17135 = rdev_get_drvdata(reg); + struct i2c_client *client = max17135->i2c_client; + + reg_val = i2c_smbus_read_byte_data(client, REG_MAX17135_HVINP); + + fld_val = (reg_val & BITFMASK(HVINP)) >> HVINP_LSH; + + if ((fld_val >= MAX17135_HVINP_MIN_VAL) && + (fld_val <= MAX17135_HVINP_MAX_VAL)) { + volt = (fld_val * MAX17135_HVINP_STEP_uV) + + MAX17135_HVINP_MIN_uV; + } else { + printk(KERN_ERR "MAX17135: HVINP voltage is out of range\n"); + volt = 0; + } + return volt; +} + +static int max17135_hvinp_enable(struct regulator_dev *reg) +{ + return 0; +} + +static int max17135_hvinp_disable(struct regulator_dev *reg) +{ + return 0; +} + +/* Convert uV to the VCOM register bitfield setting */ +static inline int vcom_uV_to_rs(int uV) +{ + return (MAX17135_VCOM_MAX_uV - uV) / MAX17135_VCOM_STEP_uV; +} + +/* Convert the VCOM register bitfield setting to uV */ +static inline int vcom_rs_to_uV(int rs) +{ + return MAX17135_VCOM_MAX_uV - (MAX17135_VCOM_STEP_uV * rs); +} + +static int max17135_vcom_set_voltage(struct regulator_dev *reg, + int minuV, int uV) +{ + struct max17135 *max17135 = rdev_get_drvdata(reg); + struct i2c_client *client = max17135->i2c_client; + unsigned int reg_val; + int vcom_read; + + if ((uV < MAX17135_VCOM_MIN_uV) || (uV > MAX17135_VCOM_MAX_uV)) + return -EINVAL; + + reg_val = i2c_smbus_read_byte_data(client, REG_MAX17135_DVR); + + /* + * Only program VCOM if it is not set to the desired value. + * Programming VCOM excessively degrades ability to keep + * DVR register value persistent. + */ + vcom_read = vcom_rs_to_uV(reg_val) - MAX17135_VCOM_FUDGE_FACTOR; + if (vcom_read != MAX17135_VCOM_VOLTAGE_DEFAULT) { + reg_val &= ~BITFMASK(DVR); + reg_val |= BITFVAL(DVR, + vcom_uV_to_rs(uV + MAX17135_VCOM_FUDGE_FACTOR)); + i2c_smbus_write_byte_data(client, REG_MAX17135_DVR, reg_val); + + reg_val = BITFVAL(CTRL_DVR, true); /* shift to correct bit */ + return i2c_smbus_write_byte_data(client, + REG_MAX17135_PRGM_CTRL, reg_val); + } +} + +static int max17135_vcom_get_voltage(struct regulator_dev *reg) +{ + struct max17135 *max17135 = rdev_get_drvdata(reg); + struct i2c_client *client = max17135->i2c_client; + unsigned int reg_val; + + reg_val = i2c_smbus_read_byte_data(client, REG_MAX17135_DVR); + return vcom_rs_to_uV(BITFEXT(reg_val, DVR)); +} + +static int max17135_vcom_enable(struct regulator_dev *reg) +{ + struct max17135 *max17135 = rdev_get_drvdata(reg); + + /* + * Check to see if we need to set the VCOM voltage. + * Should only be done one time. And, we can + * only change vcom voltage if we have been enabled. + */ + if (!max17135->vcom_setup + && gpio_get_value(max17135->gpio_pmic_pwrgood)) { + max17135_vcom_set_voltage(reg, + MAX17135_VCOM_VOLTAGE_DEFAULT, + MAX17135_VCOM_VOLTAGE_DEFAULT); + max17135->vcom_setup = true; + } + + /* enable VCOM regulator output */ +#if (MAX17135_REV == 1) + gpio_set_value(max17135->gpio_pmic_vcom_ctrl, 1); +#else + struct i2c_client *client = max17135->i2c_client; + + reg_val = i2c_smbus_read_byte_data(client, REG_MAX17135_ENABLE); + reg_val &= ~BITFMASK(VCOM_ENABLE); + reg_val |= BITFVAL(VCOM_ENABLE, 1); /* shift to correct bit */ + i2c_smbus_write_byte_data(client, REG_MAX17135_ENABLE, reg_val); +#endif + return 0; +} + +static int max17135_vcom_disable(struct regulator_dev *reg) +{ + struct max17135 *max17135 = rdev_get_drvdata(reg); +#if (MAX17135_REV == 1) + gpio_set_value(max17135->gpio_pmic_vcom_ctrl, 0); +#else + struct i2c_client *client = max17135->i2c_client; + unsigned int reg_val; + + reg_val = i2c_smbus_read_byte_data(client, REG_MAX17135_ENABLE); + reg_val &= ~BITFMASK(VCOM_ENABLE); + i2c_smbus_write_byte_data(client, REG_MAX17135_ENABLE, reg_val); +#endif + return 0; +} + +static int max17135_wait_power_good(struct max17135 *max17135) +{ + int i; + + for (i = 0; i < max17135->max_wait * 3; i++) { + if (gpio_get_value(max17135->gpio_pmic_pwrgood)) + return 0; + + msleep(1); + } + return -ETIMEDOUT; +} + +static int max17135_display_enable(struct regulator_dev *reg) +{ + struct max17135 *max17135 = rdev_get_drvdata(reg); +#if (MAX17135_REV == 1) + gpio_set_value(max17135->gpio_pmic_wakeup, 1); +#else + struct i2c_client *client = max17135->i2c_client; + unsigned int reg_val; + + reg_val = i2c_smbus_read_byte_data(client, REG_MAX17135_ENABLE); + reg_val &= ~BITFMASK(ENABLE); + reg_val |= BITFVAL(ENABLE, 1); + i2c_smbus_write_byte_data(client, REG_MAX17135_ENABLE, reg_val); +#endif + + return max17135_wait_power_good(max17135); +} + +static int max17135_display_disable(struct regulator_dev *reg) +{ + struct max17135 *max17135 = rdev_get_drvdata(reg); +#if (MAX17135_REV == 1) + gpio_set_value(max17135->gpio_pmic_wakeup, 0); +#else + struct i2c_client *client = max17135->i2c_client; + unsigned int reg_val; + + reg_val = i2c_smbus_read_byte_data(client, REG_MAX17135_ENABLE); + reg_val &= ~BITFMASK(ENABLE); + i2c_smbus_write_byte_data(client, REG_MAX17135_ENABLE, reg_val); + msleep(PMIC_DISABLE__V3P3_DESERT/1000); +#endif + return 0; +} + +static int max17135_display_is_enabled(struct regulator_dev *reg) +{ + struct max17135 *max17135 = rdev_get_drvdata(reg); + int gpio = gpio_get_value(max17135->gpio_pmic_wakeup); + + if (gpio == 0) + return 0; + else + return 1; +} + +/* + * Regulator operations + */ + +static struct regulator_ops max17135_display_ops = { + .enable = max17135_display_enable, + .disable = max17135_display_disable, + .is_enabled = max17135_display_is_enabled, +}; + +static struct regulator_ops max17135_gvdd_ops = { +}; + +static struct regulator_ops max17135_gvee_ops = { +}; + +static struct regulator_ops max17135_hvinn_ops = { +}; + +static struct regulator_ops max17135_hvinp_ops = { + .enable = max17135_hvinp_enable, + .disable = max17135_hvinp_disable, + .get_voltage = max17135_hvinp_get_voltage, + .set_voltage = max17135_hvinp_set_voltage, +}; + +static struct regulator_ops max17135_vcom_ops = { + .enable = max17135_vcom_enable, + .disable = max17135_vcom_disable, + .get_voltage = max17135_vcom_get_voltage, + .set_voltage = max17135_vcom_set_voltage, +}; + +static struct regulator_ops max17135_vneg_ops = { +}; + +static struct regulator_ops max17135_vpos_ops = { +}; + +/* + * Regulator descriptors + */ +static struct regulator_desc max17135_reg[MAX17135_NUM_REGULATORS] = { +{ + .name = "DISPLAY", + .id = MAX17135_DISPLAY, + .ops = &max17135_display_ops, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE, +}, +{ + .name = "GVDD", + .id = MAX17135_GVDD, + .ops = &max17135_gvdd_ops, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE, +}, +{ + .name = "GVEE", + .id = MAX17135_GVEE, + .ops = &max17135_gvee_ops, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE, +}, +{ + .name = "HVINN", + .id = MAX17135_HVINN, + .ops = &max17135_hvinn_ops, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE, +}, +{ + .name = "HVINP", + .id = MAX17135_HVINP, + .ops = &max17135_hvinp_ops, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE, +}, +{ + .name = "VCOM", + .id = MAX17135_VCOM, + .ops = &max17135_vcom_ops, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE, +}, +{ + .name = "VNEG", + .id = MAX17135_VNEG, + .ops = &max17135_vneg_ops, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE, +}, +{ + .name = "VPOS", + .id = MAX17135_VPOS, + .ops = &max17135_vpos_ops, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE, +}, +}; + +/* + * Regulator init/probing/exit functions + */ +static int max17135_regulator_probe(struct platform_device *pdev) +{ + struct regulator_dev *rdev; + + rdev = regulator_register(&max17135_reg[pdev->id], &pdev->dev, + pdev->dev.platform_data, + dev_get_drvdata(&pdev->dev)); + + if (IS_ERR(rdev)) { + dev_err(&pdev->dev, "failed to register %s\n", + max17135_reg[pdev->id].name); + return PTR_ERR(rdev); + } + + return 0; +} + +static int max17135_regulator_remove(struct platform_device *pdev) +{ + struct regulator_dev *rdev = platform_get_drvdata(pdev); + regulator_unregister(rdev); + return 0; +} + +static struct platform_driver max17135_regulator_driver = { + .probe = max17135_regulator_probe, + .remove = max17135_regulator_remove, + .driver = { + .name = "max17135-reg", + }, +}; + +static int max17135_register_regulator(struct max17135 *max17135, int reg, + struct regulator_init_data *initdata) +{ + struct platform_device *pdev; + int ret; + + struct i2c_client *client = max17135->i2c_client; + /* If we can't find PMIC via I2C, we should not register regulators */ + if (i2c_smbus_read_byte_data(client, + REG_MAX17135_PRODUCT_REV >= 0)) { + dev_err(max17135->dev, + "Max17135 PMIC not found!\n"); + return -ENXIO; + } + + if (max17135->pdev[reg]) + return -EBUSY; + + pdev = platform_device_alloc("max17135-reg", reg); + if (!pdev) + return -ENOMEM; + + max17135->pdev[reg] = pdev; + + initdata->driver_data = max17135; + + pdev->dev.platform_data = initdata; + pdev->dev.parent = max17135->dev; + platform_set_drvdata(pdev, max17135); + + ret = platform_device_add(pdev); + + if (ret != 0) { + dev_err(max17135->dev, + "Failed to register regulator %d: %d\n", + reg, ret); + platform_device_del(pdev); + max17135->pdev[reg] = NULL; + } + + return ret; +} + +static int max17135_i2c_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + int i; + struct max17135 *max17135; + struct max17135_platform_data *pdata = client->dev.platform_data; + int ret = 0; + + if (!pdata || !pdata->regulator_init) + return -ENODEV; + + /* Create the PMIC data structure */ + max17135 = kzalloc(sizeof(struct max17135), GFP_KERNEL); + if (max17135 == NULL) { + kfree(client); + return -ENOMEM; + } + + /* Initialize the PMIC data structure */ + i2c_set_clientdata(client, max17135); + max17135->dev = &client->dev; + max17135->i2c_client = client; + + max17135->gpio_pmic_pwrgood = pdata->gpio_pmic_pwrgood; + max17135->gpio_pmic_vcom_ctrl = pdata->gpio_pmic_vcom_ctrl; + max17135->gpio_pmic_wakeup = pdata->gpio_pmic_wakeup; + max17135->gpio_pmic_intr = pdata->gpio_pmic_intr; + + max17135->vcom_setup = false; + + ret = platform_driver_register(&max17135_regulator_driver); + if (ret < 0) + goto err; + + for (i = 0; i <= MAX17135_VPOS; i++) { + ret = max17135_register_regulator(max17135, i, &pdata->regulator_init[i]); + if (ret != 0) { + dev_err(max17135->dev, "Platform init() failed: %d\n", + ret); + goto err; + } + } + + max17135->max_wait = pdata->vpos_pwrup + pdata->vneg_pwrup + + pdata->gvdd_pwrup + pdata->gvee_pwrup; + + /* Initialize the PMIC device */ + dev_info(&client->dev, "PMIC MAX17135 for eInk display\n"); + + return ret; +err: + kfree(max17135); + + return ret; +} + + +static int max17135_i2c_remove(struct i2c_client *i2c) +{ + struct max17135 *max17135 = i2c_get_clientdata(i2c); + int i; + + for (i = 0; i < ARRAY_SIZE(max17135->pdev); i++) + platform_device_unregister(max17135->pdev[i]); + + platform_driver_unregister(&max17135_regulator_driver); + + kfree(max17135); + + return 0; +} + +static const struct i2c_device_id max17135_i2c_id[] = { + { "max17135", 0 }, + { } +}; +MODULE_DEVICE_TABLE(i2c, max17135_i2c_id); + + +static struct i2c_driver max17135_i2c_driver = { + .driver = { + .name = "max17135", + .owner = THIS_MODULE, + }, + .probe = max17135_i2c_probe, + .remove = max17135_i2c_remove, + .id_table = max17135_i2c_id, +}; + +static int __init max17135_init(void) +{ + return i2c_add_driver(&max17135_i2c_driver); +} +module_init(max17135_init); + +static void __exit max17135_exit(void) +{ + i2c_del_driver(&max17135_i2c_driver); +} +module_exit(max17135_exit); + +/* Module information */ +MODULE_DESCRIPTION("MAX17135 regulator driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/regulator/mxs-regulator.c b/drivers/regulator/mxs-regulator.c new file mode 100644 index 000000000000..34930776a90c --- /dev/null +++ b/drivers/regulator/mxs-regulator.c @@ -0,0 +1,302 @@ +/* + * Freescale STMP378X voltage regulators + * + * Embedded Alley Solutions, Inc + * + * Copyright (C) 2010 Freescale Semiconductor, Inc. + * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static int mxs_set_voltage(struct regulator_dev *reg, int MiniV, int uv) +{ + struct mxs_regulator *mxs_reg = rdev_get_drvdata(reg); + + if (mxs_reg->rdata->set_voltage) + return mxs_reg->rdata->set_voltage(mxs_reg, uv); + else + return -ENOTSUPP; +} + + +static int mxs_get_voltage(struct regulator_dev *reg) +{ + struct mxs_regulator *mxs_reg = rdev_get_drvdata(reg); + + if (mxs_reg->rdata->get_voltage) + return mxs_reg->rdata->get_voltage(mxs_reg); + else + return -ENOTSUPP; +} + +static int mxs_set_current(struct regulator_dev *reg, int min_uA, int uA) +{ + struct mxs_regulator *mxs_reg = rdev_get_drvdata(reg); + + if (mxs_reg->rdata->set_current) + return mxs_reg->rdata->set_current(mxs_reg, uA); + else + return -ENOTSUPP; +} + +static int mxs_get_current(struct regulator_dev *reg) +{ + struct mxs_regulator *mxs_reg = rdev_get_drvdata(reg); + + if (mxs_reg->rdata->get_current) + return mxs_reg->rdata->get_current(mxs_reg); + else + return -ENOTSUPP; +} + +static int mxs_enable(struct regulator_dev *reg) +{ + struct mxs_regulator *mxs_reg = rdev_get_drvdata(reg); + + return mxs_reg->rdata->enable(mxs_reg); +} + +static int mxs_disable(struct regulator_dev *reg) +{ + struct mxs_regulator *mxs_reg = rdev_get_drvdata(reg); + + return mxs_reg->rdata->disable(mxs_reg); +} + +static int mxs_is_enabled(struct regulator_dev *reg) +{ + struct mxs_regulator *mxs_reg = rdev_get_drvdata(reg); + + return mxs_reg->rdata->is_enabled(mxs_reg); +} + +static int mxs_set_mode(struct regulator_dev *reg, unsigned int mode) +{ + struct mxs_regulator *mxs_reg = rdev_get_drvdata(reg); + + return mxs_reg->rdata->set_mode(mxs_reg, mode); +} + +static unsigned int mxs_get_mode(struct regulator_dev *reg) +{ + struct mxs_regulator *mxs_reg = rdev_get_drvdata(reg); + + return mxs_reg->rdata->get_mode(mxs_reg); +} + +static unsigned int mxs_get_optimum_mode(struct regulator_dev *reg, + int input_uV, int output_uV, int load_uA) +{ + struct mxs_regulator *mxs_reg = rdev_get_drvdata(reg); + + if (mxs_reg->rdata->get_optimum_mode) + return mxs_reg->rdata->get_optimum_mode(mxs_reg, input_uV, + output_uV, load_uA); + else + return -ENOTSUPP; +} + +static struct regulator_ops mxs_rops = { + .set_voltage = mxs_set_voltage, + .get_voltage = mxs_get_voltage, + .set_current_limit = mxs_set_current, + .get_current_limit = mxs_get_current, + .enable = mxs_enable, + .disable = mxs_disable, + .is_enabled = mxs_is_enabled, + .set_mode = mxs_set_mode, + .get_mode = mxs_get_mode, + .get_optimum_mode = mxs_get_optimum_mode, +}; + +static struct regulator_desc mxs_reg_desc[] = { + { + .name = "vddd", + .id = MXS_VDDD, + .ops = &mxs_rops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "vdda", + .id = MXS_VDDA, + .ops = &mxs_rops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "vddio", + .id = MXS_VDDIO, + .ops = &mxs_rops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "vddd_bo", + .id = MXS_VDDDBO, + .ops = &mxs_rops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "overall_current", + .id = MXS_OVERALL_CUR, + .ops = &mxs_rops, + .irq = 0, + .type = REGULATOR_CURRENT, + .owner = THIS_MODULE + }, +}; + +static int reg_callback(struct notifier_block *self, + unsigned long event, void *data) +{ + unsigned long flags; + struct mxs_regulator *sreg = + container_of(self, struct mxs_regulator , nb); + + switch (event) { + case MXS_REG5V_IS_USB: + spin_lock_irqsave(&sreg->lock, flags); + sreg->rdata->max_current = 500000; + spin_unlock_irqrestore(&sreg->lock, flags); + break; + case MXS_REG5V_NOT_USB: + spin_lock_irqsave(&sreg->lock, flags); + sreg->rdata->max_current = 0x7fffffff; + spin_unlock_irqrestore(&sreg->lock, flags); + break; + } + + return 0; +} + +int mxs_regulator_probe(struct platform_device *pdev) +{ + struct regulator_desc *rdesc; + struct regulator_dev *rdev; + struct mxs_regulator *sreg; + struct regulator_init_data *initdata; + + sreg = platform_get_drvdata(pdev); + initdata = pdev->dev.platform_data; + sreg->cur_current = 0; + sreg->next_current = 0; + sreg->cur_voltage = 0; + + init_waitqueue_head(&sreg->wait_q); + spin_lock_init(&sreg->lock); + + if (pdev->id > MXS_OVERALL_CUR) { + rdesc = kzalloc(sizeof(struct regulator_desc), GFP_KERNEL); + memcpy(rdesc, &mxs_reg_desc[MXS_OVERALL_CUR], + sizeof(struct regulator_desc)); + rdesc->name = kstrdup(sreg->rdata->name, GFP_KERNEL); + } else + rdesc = &mxs_reg_desc[pdev->id]; + + pr_debug("probing regulator %s %s %d\n", + sreg->rdata->name, + rdesc->name, + pdev->id); + + /* register regulator */ + rdev = regulator_register(rdesc, &pdev->dev, + initdata, sreg); + + if (IS_ERR(rdev)) { + dev_err(&pdev->dev, "failed to register %s\n", + rdesc->name); + return PTR_ERR(rdev); + } + + if (sreg->rdata->max_current) { + struct regulator *regu; + regu = regulator_get(NULL, sreg->rdata->name); + sreg->nb.notifier_call = reg_callback; + regulator_register_notifier(regu, &sreg->nb); + } + + return 0; +} + + +int mxs_regulator_remove(struct platform_device *pdev) +{ + struct regulator_dev *rdev = platform_get_drvdata(pdev); + + regulator_unregister(rdev); + + return 0; + +} + +int mxs_register_regulator( + struct mxs_regulator *reg_data, int reg, + struct regulator_init_data *initdata) +{ + struct platform_device *pdev; + int ret; + + pdev = platform_device_alloc("mxs_reg", reg); + if (!pdev) + return -ENOMEM; + + pdev->dev.platform_data = initdata; + + platform_set_drvdata(pdev, reg_data); + ret = platform_device_add(pdev); + + if (ret != 0) { + pr_debug("Failed to register regulator %d: %d\n", + reg, ret); + platform_device_del(pdev); + } + pr_debug("register regulator %s, %d: %d\n", + reg_data->rdata->name, reg, ret); + + return ret; +} +EXPORT_SYMBOL_GPL(mxs_register_regulator); + +struct platform_driver mxs_reg = { + .driver = { + .name = "mxs_reg", + }, + .probe = mxs_regulator_probe, + .remove = mxs_regulator_remove, +}; + +int mxs_regulator_init(void) +{ + return platform_driver_register(&mxs_reg); +} + +void mxs_regulator_exit(void) +{ + platform_driver_unregister(&mxs_reg); +} + +postcore_initcall(mxs_regulator_init); +module_exit(mxs_regulator_exit); diff --git a/drivers/regulator/reg-mc13783.c b/drivers/regulator/reg-mc13783.c new file mode 100644 index 000000000000..da20907ba087 --- /dev/null +++ b/drivers/regulator/reg-mc13783.c @@ -0,0 +1,2662 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Convenience conversion. + * Here atm, maybe there is somewhere better for this. + */ +#define mV_to_uV(mV) (mV * 1000) +#define uV_to_mV(uV) (uV / 1000) +#define V_to_uV(V) (mV_to_uV(V * 1000)) +#define uV_to_V(uV) (uV_to_mV(uV) / 1000) + +/*! + * @enum regulator_voltage_sw + * @brief PMIC regulator SW output voltage. + */ +enum { + SW_0_9V = 0, /*!< 0.900 V */ + SW_0_925V, /*!< 0.925 V */ + SW_0_95V, /*!< 0.950 V */ + SW_0_975V, /*!< 0.975 V */ + SW_1V, /*!< 1.000 V */ + SW_1_025V, /*!< 1.025 V */ + SW_1_05V, /*!< 1.050 V */ + SW_1_075V, /*!< 1.075 V */ + SW_1_1V, /*!< 1.100 V */ + SW_1_125V, /*!< 1.125 V */ + SW_1_15V, /*!< 1.150 V */ + SW_1_175V, /*!< 1.175 V */ + SW_1_2V, /*!< 1.200 V */ + SW_1_225V, /*!< 1.225 V */ + SW_1_25V, /*!< 1.250 V */ + SW_1_275V, /*!< 1.275 V */ + SW_1_3V, /*!< 1.300 V */ + SW_1_325V, /*!< 1.325 V */ + SW_1_35V, /*!< 1.350 V */ + SW_1_375V, /*!< 1.375 V */ + SW_1_4V, /*!< 1.400 V */ + SW_1_425V, /*!< 1.425 V */ + SW_1_45V, /*!< 1.450 V */ + SW_1_475V, /*!< 1.475 V */ + SW_1_5V, /*!< 1.500 V */ + SW_1_525V, /*!< 1.525 V */ + SW_1_55V, /*!< 1.550 V */ + SW_1_575V, /*!< 1.575 V */ + SW_1_6V, /*!< 1.600 V */ + SW_1_625V, /*!< 1.625 V */ + SW_1_65V, /*!< 1.650 V */ + SW_1_675V, /*!< 1.675 V */ + SW_1_7V, /*!< 1.700 V */ + SW_1_8V = 36, /*!< 1.800 V */ + SW_1_85V = 40, /*!< 1.850 V */ + SW_2V = 44, /*!< 2_000 V */ + SW_2_1V = 48, /*!< 2_100 V */ + SW_2_2V = 52, /*!< 2_200 V */ +} regulator_voltage_sw; + +/*! + * @enum regulator_voltage_violo + * @brief PMIC regulator VIOLO output voltage. + */ +enum { + VIOLO_1_2V = 0, /*!< 1.2 V */ + VIOLO_1_3V, /*!< 1.3 V */ + VIOLO_1_5V, /*!< 1.5 V */ + VIOLO_1_8V, /*!< 1.8 V */ +} regulator_voltage_violo; + +/*! + * @enum regulator_voltage_vdig + * @brief PMIC regulator VDIG output voltage. + */ +enum { + VDIG_1_2V = 0, /*!< 1.2 V */ + VDIG_1_3V, /*!< 1.3 V */ + VDIG_1_5V, /*!< 1.5 V */ + VDIG_1_8V, /*!< 1.8 V */ +} regulator_voltage_vdig; + +/*! + * @enum regulator_voltage_vgen + * @brief PMIC regulator VGEN output voltage. + */ +enum { + VGEN_1_2V = 0, /*!< 1.2 V */ + VGEN_1_3V, /*!< 1.3 V */ + VGEN_1_5V, /*!< 1.5 V */ + VGEN_1_8V, /*!< 1.8 V */ + VGEN_1_1V, /*!< 1.1 V */ + VGEN_2V, /*!< 2 V */ + VGEN_2_775V, /*!< 2.775 V */ + VGEN_2_4V, /*!< 2.4 V */ +} regulator_voltage_vgen; + +/*! + * @enum regulator_voltage_vrfdig + * @brief PMIC regulator VRFDIG output voltage. + */ +enum { + VRFDIG_1_2V = 0, /*!< 1.2 V */ + VRFDIG_1_5V, /*!< 1.5 V */ + VRFDIG_1_8V, /*!< 1.8 V */ + VRFDIG_1_875V, /*!< 1.875 V */ +} regulator_voltage_vrfdig; + +/*! + * @enum regulator_voltage_vrfref + * @brief PMIC regulator VRFREF output voltage. + */ +enum { + VRFREF_2_475V = 0, /*!< 2.475 V */ + VRFREF_2_6V, /*!< 2.600 V */ + VRFREF_2_7V, /*!< 2.700 V */ + VRFREF_2_775V, /*!< 2.775 V */ +} regulator_voltage_vrfref; + +/*! + * @enum regulator_voltage_vrfcp + * @brief PMIC regulator VRFCP output voltage. + */ +enum { + VRFCP_2_7V = 0, /*!< 2.700 V */ + VRFCP_2_775V, /*!< 2.775 V */ +} regulator_voltage_vrfcp; + +/*! + * @enum regulator_voltage_vsim + * @brief PMIC linear regulator VSIM output voltage. + */ +enum { + VSIM_1_8V = 0, /*!< 1.8 V */ + VSIM_2_9V, /*!< 2.90 V */ + VSIM_3V = 1, /*!< 3 V */ +} regulator_voltage_vsim; + +/*! + * @enum regulator_voltage_vesim + * @brief PMIC regulator VESIM output voltage. + */ +enum { + VESIM_1_8V = 0, /*!< 1.80 V */ + VESIM_2_9V, /*!< 2.90 V */ +} regulator_voltage_vesim; + +/*! + * @enum regulator_voltage_vcam + * @brief PMIC regulator VCAM output voltage. + */ +enum { + VCAM_1_5V = 0, /*!< 1.50 V */ + VCAM_1_8V, /*!< 1.80 V */ + VCAM_2_5V, /*!< 2.50 V */ + VCAM_2_55V, /*!< 2.55 V */ + VCAM_2_6V, /*!< 2.60 V */ + VCAM_2_75V, /*!< 2.75 V */ + VCAM_2_8V, /*!< 2.80 V */ + VCAM_3V, /*!< 3.00 V */ +} regulator_voltage_vcam; + +/*! + * @enum regulator_voltage_vvib + * @brief PMIC linear regulator V_VIB output voltage. + */ +enum { + VVIB_1_3V = 0, /*!< 1.30 V */ + VVIB_1_8V, /*!< 1.80 V */ + VVIB_2V, /*!< 2 V */ + VVIB_3V, /*!< 3 V */ +} regulator_voltage_vvib; + +/*! + * @enum regulator_voltage_vmmc + * @brief MC13783 PMIC regulator VMMC output voltage. + */ +enum { + VMMC_1_6V = 0, /*!< 1.60 V */ + VMMC_1_8V, /*!< 1.80 V */ + VMMC_2V, /*!< 2.00 V */ + VMMC_2_6V, /*!< 2.60 V */ + VMMC_2_7V, /*!< 2.70 V */ + VMMC_2_8V, /*!< 2.80 V */ + VMMC_2_9V, /*!< 2.90 V */ + VMMC_3V, /*!< 3.00 V */ +} regulator_voltage_vmmc; + +/*! + * @enum regulator_voltage_vrf + * @brief PMIC regulator VRF output voltage. + */ +enum { + VRF_1_5V = 0, /*!< 1.500 V */ + VRF_1_875V, /*!< 1.875 V */ + VRF_2_7V, /*!< 2.700 V */ + VRF_2_775V, /*!< 2.775 V */ +} regulator_voltage_vrf; + +/*! + * @enum regulator_voltage_sw3 + * @brief PMIC Switch mode regulator SW3 output voltages. + */ +enum { + SW3_5V = 0, /*!< 5.0 V */ + SW3_5_5V = 3, /*!< 5.5 V */ +} regulator_voltage_sw3; + +/*! + * The \b TPmicDVSTransitionSpeed enum defines the rate with which the + * voltage transition occurs. + */ +enum { + ESysDependent, + E25mVEach4us, + E25mVEach8us, + E25mvEach16us +} DVS_transition_speed; + +/* + * Reg Regulator Mode 0 + */ +#define VAUDIO_EN_LSH 0 +#define VAUDIO_EN_WID 1 +#define VAUDIO_EN_ENABLE 1 +#define VAUDIO_EN_DISABLE 0 +#define VIOHI_EN_LSH 3 +#define VIOHI_EN_WID 1 +#define VIOHI_EN_ENABLE 1 +#define VIOHI_EN_DISABLE 0 +#define VIOLO_EN_LSH 6 +#define VIOLO_EN_WID 1 +#define VIOLO_EN_ENABLE 1 +#define VIOLO_EN_DISABLE 0 +#define VDIG_EN_LSH 9 +#define VDIG_EN_WID 1 +#define VDIG_EN_ENABLE 1 +#define VDIG_EN_DISABLE 0 +#define VGEN_EN_LSH 12 +#define VGEN_EN_WID 1 +#define VGEN_EN_ENABLE 1 +#define VGEN_EN_DISABLE 0 +#define VRFDIG_EN_LSH 15 +#define VRFDIG_EN_WID 1 +#define VRFDIG_EN_ENABLE 1 +#define VRFDIG_EN_DISABLE 0 +#define VRFREF_EN_LSH 18 +#define VRFREF_EN_WID 1 +#define VRFREF_EN_ENABLE 1 +#define VRFREF_EN_DISABLE 0 +#define VRFCP_EN_LSH 21 +#define VRFCP_EN_WID 1 +#define VRFCP_EN_ENABLE 1 +#define VRFCP_EN_DISABLE 0 + +/* + * Reg Regulator Mode 1 + */ +#define VSIM_EN_LSH 0 +#define VSIM_EN_WID 1 +#define VSIM_EN_ENABLE 1 +#define VSIM_EN_DISABLE 0 +#define VESIM_EN_LSH 3 +#define VESIM_EN_WID 1 +#define VESIM_EN_ENABLE 1 +#define VESIM_EN_DISABLE 0 +#define VCAM_EN_LSH 6 +#define VCAM_EN_WID 1 +#define VCAM_EN_ENABLE 1 +#define VCAM_EN_DISABLE 0 +#define VRFBG_EN_LSH 9 +#define VRFBG_EN_WID 1 +#define VRFBG_EN_ENABLE 1 +#define VRFBG_EN_DISABLE 0 +#define VVIB_EN_LSH 11 +#define VVIB_EN_WID 1 +#define VVIB_EN_ENABLE 1 +#define VVIB_EN_DISABLE 0 +#define VRF1_EN_LSH 12 +#define VRF1_EN_WID 1 +#define VRF1_EN_ENABLE 1 +#define VRF1_EN_DISABLE 0 +#define VRF2_EN_LSH 15 +#define VRF2_EN_WID 1 +#define VRF2_EN_ENABLE 1 +#define VRF2_EN_DISABLE 0 +#define VMMC1_EN_LSH 18 +#define VMMC1_EN_WID 1 +#define VMMC1_EN_ENABLE 1 +#define VMMC1_EN_DISABLE 0 +#define VMMC2_EN_LSH 21 +#define VMMC2_EN_WID 1 +#define VMMC2_EN_ENABLE 1 +#define VMMC2_EN_DISABLE 0 + +/* + * Reg Regulator Setting 0 + */ +#define VIOLO_LSH 2 +#define VIOLO_WID 2 +#define VDIG_LSH 4 +#define VDIG_WID 2 +#define VGEN_LSH 6 +#define VGEN_WID 3 +#define VRFDIG_LSH 9 +#define VRFDIG_WID 2 +#define VRFREF_LSH 11 +#define VRFREF_WID 2 +#define VRFCP_LSH 13 +#define VRFCP_WID 1 +#define VSIM_LSH 14 +#define VSIM_WID 1 +#define VESIM_LSH 15 +#define VESIM_WID 1 +#define VCAM_LSH 16 +#define VCAM_WID 3 + +/* + * Reg Regulator Setting 1 + */ +#define VVIB_LSH 0 +#define VVIB_WID 2 +#define VRF1_LSH 2 +#define VRF1_WID 2 +#define VRF2_LSH 4 +#define VRF2_WID 2 +#define VMMC1_LSH 6 +#define VMMC1_WID 3 +#define VMMC2_LSH 9 +#define VMMC2_WID 3 + +/* + * Reg Switcher 0 + */ +#define SW1A_LSH 0 +#define SW1A_WID 6 +#define SW1A_DVS_LSH 6 +#define SW1A_DVS_WID 6 +#define SW1A_STDBY_LSH 12 +#define SW1A_STDBY_WID 6 + +/* + * Reg Switcher 1 + */ +#define SW1B_LSH 0 +#define SW1B_WID 6 +#define SW1B_DVS_LSH 6 +#define SW1B_DVS_WID 6 +#define SW1B_STDBY_LSH 12 +#define SW1B_STDBY_WID 6 + +/* + * Reg Switcher 2 + */ +#define SW2A_LSH 0 +#define SW2A_WID 6 +#define SW2A_DVS_LSH 6 +#define SW2A_DVS_WID 6 +#define SW2A_STDBY_LSH 12 +#define SW2A_STDBY_WID 6 + +/* + * Reg Switcher 3 + */ +#define SW2B_LSH 0 +#define SW2B_WID 6 +#define SW2B_DVS_LSH 6 +#define SW2B_DVS_WID 6 +#define SW2B_STDBY_LSH 12 +#define SW2B_STDBY_WID 6 + +/* + * Reg Switcher 4 + */ +#define SW1A_MODE_LSH 0 +#define SW1A_MODE_WID 2 +#define SW1A_STBY_MODE_LSH 2 +#define SW1A_STBY_MODE_WID 2 +#define SW1A_DVS_SPEED_LSH 6 +#define SW1A_DVS_SPEED_WID 2 +#define SW1B_MODE_LSH 10 +#define SW1B_MODE_WID 2 +#define SW1B_STBY_MODE_LSH 12 +#define SW1B_STBY_MODE_WID 2 +#define SW1B_DVS_SPEED_LSH 14 +#define SW1B_DVS_SPEED_WID 2 + +/* + * Reg Switcher 5 + */ +#define SW2A_MODE_LSH 0 +#define SW2A_MODE_WID 2 +#define SW2A_STBY_MODE_LSH 2 +#define SW2A_STBY_MODE_WID 2 +#define SW2A_DVS_SPEED_LSH 6 +#define SW2A_DVS_SPEED_WID 2 +#define SW2B_MODE_LSH 10 +#define SW2B_MODE_WID 2 +#define SW2B_STBY_MODE_LSH 12 +#define SW2B_STBY_MODE_WID 2 +#define SW2B_DVS_SPEED_LSH 14 +#define SW2B_DVS_SPEED_WID 2 +#define SW3_LSH 18 +#define SW3_WID 2 +#define SW3_EN_LSH 20 +#define SW3_EN_WID 2 +#define SW3_EN_ENABLE 1 +#define SW3_EN_DISABLE 0 + +/* + * Reg Regulator Misc. + */ +#define GPO1_EN_LSH 6 +#define GPO1_EN_WID 1 +#define GPO1_EN_ENABLE 1 +#define GPO1_EN_DISABLE 0 +#define GPO2_EN_LSH 8 +#define GPO2_EN_WID 1 +#define GPO2_EN_ENABLE 1 +#define GPO2_EN_DISABLE 0 +#define GPO3_EN_LSH 10 +#define GPO3_EN_WID 1 +#define GPO3_EN_ENABLE 1 +#define GPO3_EN_DISABLE 0 +#define GPO4_EN_LSH 12 +#define GPO4_EN_WID 1 +#define GPO4_EN_ENABLE 1 +#define GPO4_EN_DISABLE 0 + +/* + * Switcher mode configuration + */ +#define SW_MODE_SYNC_RECT_EN 0 +#define SW_MODE_PULSE_NO_SKIP_EN 1 +#define SW_MODE_PULSE_SKIP_EN 2 +#define SW_MODE_LOW_POWER_EN 3 + +#define dvs_speed E25mvEach16us + +static int mc13783_vaudio_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VAUDIO_EN, VAUDIO_EN_ENABLE); + register_mask = BITFMASK(VAUDIO_EN); + register1 = REG_REGULATOR_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vaudio_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VAUDIO_EN, VAUDIO_EN_DISABLE); + register_mask = BITFMASK(VAUDIO_EN); + register1 = REG_REGULATOR_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_viohi_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VIOHI_EN, VIOHI_EN_ENABLE); + register_mask = BITFMASK(VIOHI_EN); + register1 = REG_REGULATOR_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_viohi_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VIOHI_EN, VIOHI_EN_DISABLE); + register_mask = BITFMASK(VIOHI_EN); + register1 = REG_REGULATOR_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_violo_set_voltage(struct regulator_dev *reg, + int minuV, int uV) +{ + unsigned int register_val = 0, register_mask = 0, register1 = 0; + int voltage, mV = uV / 1000; + + if ((mV >= 1200) && (mV < 1300)) + voltage = VIOLO_1_2V; + else if ((mV >= 1300) && (mV < 1500)) + voltage = VIOLO_1_3V; + else if ((mV >= 1500) && (mV < 1800)) + voltage = VIOLO_1_5V; + else + voltage = VIOLO_1_8V; + + register_val = BITFVAL(VIOLO, voltage); + register_mask = BITFMASK(VIOLO); + register1 = REG_REGULATOR_SETTING_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_violo_get_voltage(struct regulator_dev *reg) +{ + unsigned int register_val = 0; + int voltage = 0, mV = 0; + + CHECK_ERROR(pmic_read_reg(REG_REGULATOR_SETTING_0, + ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, VIOLO); + + switch (voltage) { + case VIOLO_1_2V: + mV = 1200; + break; + case VIOLO_1_3V: + mV = 1300; + break; + case VIOLO_1_5V: + mV = 1500; + break; + case VIOLO_1_8V: + mV = 1800; + break; + default: + return -EINVAL; + } + + return mV * 1000; +} + +static int mc13783_violo_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VIOLO_EN, VIOLO_EN_ENABLE); + register_mask = BITFMASK(VIOLO_EN); + register1 = REG_REGULATOR_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_violo_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VIOLO_EN, VIOLO_EN_DISABLE); + register_mask = BITFMASK(VIOLO_EN); + register1 = REG_REGULATOR_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vdig_set_voltage(struct regulator_dev *reg, + int minuV, int uV) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int voltage, mV = uV / 1000; + + if ((mV >= 1200) && (mV < 1300)) + voltage = VDIG_1_2V; + else if ((mV >= 1300) && (mV < 1500)) + voltage = VDIG_1_3V; + else if ((mV >= 1500) && (mV < 1800)) + voltage = VDIG_1_5V; + else + voltage = VDIG_1_8V; + + register_val = BITFVAL(VDIG, voltage); + register_mask = BITFMASK(VDIG); + register1 = REG_REGULATOR_SETTING_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vdig_get_voltage(struct regulator_dev *reg) +{ + unsigned int register_val = 0; + int voltage = 0, mV = 0; + + CHECK_ERROR(pmic_read_reg(REG_REGULATOR_SETTING_0, + ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, VDIG); + + switch (voltage) { + case VDIG_1_2V: + mV = 1200; + break; + case VDIG_1_3V: + mV = 1300; + break; + case VDIG_1_5V: + mV = 1500; + break; + case VDIG_1_8V: + mV = 1800; + break; + default: + return -EINVAL; + } + + return mV * 1000; +} + +static int mc13783_vdig_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VDIG_EN, VDIG_EN_ENABLE); + register_mask = BITFMASK(VDIG_EN); + register1 = REG_REGULATOR_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vdig_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VDIG_EN, VDIG_EN_DISABLE); + register_mask = BITFMASK(VDIG_EN); + register1 = REG_REGULATOR_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vgen_set_voltage(struct regulator_dev *reg, + int minuV, int uV) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int voltage, mV = uV / 1000; + int vgenid = rdev_get_id(reg); + + printk(KERN_INFO "VGEN ID is %d\n", vgenid); + + if ((mV >= 1100) && (mV < 1200)) + voltage = VGEN_1_1V; + else if ((mV >= 1200) && (mV < 1300)) + voltage = VGEN_1_2V; + else if ((mV >= 1300) && (mV < 1500)) + voltage = VGEN_1_3V; + else if ((mV >= 1500) && (mV < 1800)) + voltage = VGEN_1_5V; + else if ((mV >= 1800) && (mV < 2000)) + voltage = VGEN_1_8V; + else if ((mV >= 2000) && (mV < 2400)) + voltage = VGEN_2V; + else if ((mV >= 2400) && (mV < 2775)) + voltage = VGEN_2_4V; + else + voltage = VGEN_2_775V; + + register_val = BITFVAL(VGEN, voltage); + register_mask = BITFMASK(VGEN); + register1 = REG_REGULATOR_SETTING_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vgen_get_voltage(struct regulator_dev *reg) +{ + unsigned int register_val = 0; + int voltage = 0, mV = 0; + + CHECK_ERROR(pmic_read_reg(REG_REGULATOR_SETTING_0, + ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, VGEN); + + switch (voltage) { + case VGEN_1_2V: + mV = 1200; + break; + case VGEN_1_3V: + mV = 1300; + break; + case VGEN_1_5V: + mV = 1500; + break; + case VGEN_1_8V: + mV = 1800; + break; + case VGEN_1_1V: + mV = 1100; + break; + case VGEN_2V: + mV = 2000; + break; + case VGEN_2_775V: + mV = 2775; + break; + case VGEN_2_4V: + mV = 2400; + break; + default: + return -EINVAL; + } + + return mV * 1000; +} + +static int mc13783_vgen_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VGEN_EN, VGEN_EN_ENABLE); + register_mask = BITFMASK(VGEN_EN); + register1 = REG_REGULATOR_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vgen_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VGEN_EN, VGEN_EN_DISABLE); + register_mask = BITFMASK(VGEN_EN); + register1 = REG_REGULATOR_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vrfdig_set_voltage(struct regulator_dev *reg, + int minuV, int uV) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int voltage, mV = uV / 1000; + + if ((mV >= 1200) && (mV < 1500)) + voltage = VRFDIG_1_2V; + else if ((mV >= 1500) && (mV < 1300)) + voltage = VRFDIG_1_5V; + else if ((mV >= 1800) && (mV < 1875)) + voltage = VRFDIG_1_8V; + else + voltage = VRFDIG_1_875V; + + register_val = BITFVAL(VRFDIG, voltage); + register_mask = BITFMASK(VRFDIG); + register1 = REG_REGULATOR_SETTING_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vrfdig_get_voltage(struct regulator_dev *reg) +{ + unsigned int register_val = 0; + int voltage = 0, mV = 0; + + CHECK_ERROR(pmic_read_reg(REG_REGULATOR_SETTING_0, + ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, VRFDIG); + + switch (voltage) { + case VRFDIG_1_2V: + mV = 1200; + break; + case VRFDIG_1_5V: + mV = 1500; + break; + case VRFDIG_1_8V: + mV = 1800; + break; + case VRFDIG_1_875V: + mV = 1875; + break; + default: + return -EINVAL; + } + + return mV * 1000; +} + +static int mc13783_vrfdig_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VRFDIG_EN, VRFDIG_EN_ENABLE); + register_mask = BITFMASK(VRFDIG_EN); + register1 = REG_REGULATOR_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vrfdig_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VRFDIG_EN, VRFDIG_EN_DISABLE); + register_mask = BITFMASK(VRFDIG_EN); + register1 = REG_REGULATOR_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vrfref_set_voltage(struct regulator_dev *reg, + int minuV, int uV) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int voltage, mV = uV / 1000; + + if ((mV >= 2475) && (mV < 2600)) + voltage = VRFREF_2_475V; + else if ((mV >= 2600) && (mV < 2700)) + voltage = VRFREF_2_6V; + else if ((mV >= 2700) && (mV < 2775)) + voltage = VRFREF_2_7V; + else + voltage = VRFREF_2_775V; + + register_val = BITFVAL(VRFREF, voltage); + register_mask = BITFMASK(VRFREF); + register1 = REG_REGULATOR_SETTING_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vrfref_get_voltage(struct regulator_dev *reg) +{ + unsigned int register_val = 0; + int voltage = 0, mV = 0; + + CHECK_ERROR(pmic_read_reg(REG_REGULATOR_SETTING_0, + ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, VRFREF); + + switch (voltage) { + case VRFREF_2_475V: + mV = 2475; + break; + case VRFREF_2_6V: + mV = 2600; + break; + case VRFREF_2_7V: + mV = 2700; + break; + case VRFREF_2_775V: + mV = 2775; + break; + default: + return -EINVAL; + } + + return mV * 1000; +} + +static int mc13783_vrfref_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VRFREF_EN, VRFREF_EN_ENABLE); + register_mask = BITFMASK(VRFREF_EN); + register1 = REG_REGULATOR_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vrfref_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VRFREF_EN, VRFREF_EN_DISABLE); + register_mask = BITFMASK(VRFREF_EN); + register1 = REG_REGULATOR_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vrfcp_set_voltage(struct regulator_dev *reg, + int minuV, int uV) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int voltage, mV = uV / 1000; + + if ((mV >= 2700) && (mV < 2775)) + voltage = VRFCP_2_7V; + else + voltage = VRFCP_2_775V; + + register_val = BITFVAL(VRFCP, voltage); + register_mask = BITFMASK(VRFCP); + register1 = REG_REGULATOR_SETTING_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vrfcp_get_voltage(struct regulator_dev *reg) +{ + unsigned int register_val = 0; + int voltage = 0, mV = 0; + + CHECK_ERROR(pmic_read_reg(REG_REGULATOR_SETTING_0, + ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, VRFCP); + + switch (voltage) { + case VRFCP_2_7V: + mV = 2700; + break; + case VRFCP_2_775V: + mV = 2775; + break; + default: + return -EINVAL; + } + + return mV * 1000; +} + +static int mc13783_vrfcp_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VRFCP_EN, VRFCP_EN_ENABLE); + register_mask = BITFMASK(VRFCP_EN); + register1 = REG_REGULATOR_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vrfcp_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VRFCP_EN, VRFCP_EN_DISABLE); + register_mask = BITFMASK(VRFCP_EN); + register1 = REG_REGULATOR_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vsim_set_voltage(struct regulator_dev *reg, + int minuV, int uV) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int voltage, mV = uV / 1000; + + if ((mV >= 1800) && (mV < 2900)) + voltage = VSIM_1_8V; + else + voltage = VSIM_2_9V; + + register_val = BITFVAL(VSIM, voltage); + register_mask = BITFMASK(VSIM); + register1 = REG_REGULATOR_SETTING_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vsim_get_voltage(struct regulator_dev *reg) +{ + unsigned int register_val = 0; + int voltage = 0, mV = 0; + + CHECK_ERROR(pmic_read_reg(REG_REGULATOR_SETTING_0, + ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, VSIM); + + switch (voltage) { + case VSIM_1_8V: + mV = 1800; + break; + case VSIM_2_9V: + mV = 1900; + break; + default: + return -EINVAL; + } + + return mV * 1000; +} + +static int mc13783_vsim_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VSIM_EN, VSIM_EN_ENABLE); + register_mask = BITFMASK(VSIM_EN); + register1 = REG_REGULATOR_MODE_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vsim_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VSIM_EN, VSIM_EN_DISABLE); + register_mask = BITFMASK(VSIM_EN); + register1 = REG_REGULATOR_MODE_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vesim_set_voltage(struct regulator_dev *reg, + int minuV, int uV) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int voltage, mV = uV / 1000; + + if ((mV >= 1800) && (mV < 2900)) + voltage = VESIM_1_8V; + else + voltage = VESIM_2_9V; + + register_val = BITFVAL(VESIM, voltage); + register_mask = BITFMASK(VESIM); + register1 = REG_REGULATOR_SETTING_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vesim_get_voltage(struct regulator_dev *reg) +{ + unsigned int register_val = 0; + int voltage = 0, mV = 0; + + CHECK_ERROR(pmic_read_reg(REG_REGULATOR_SETTING_0, + ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, VESIM); + + switch (voltage) { + case VESIM_1_8V: + mV = 1800; + break; + case VESIM_2_9V: + mV = 1900; + break; + default: + return -EINVAL; + } + + return mV * 1000; +} + +static int mc13783_vesim_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VESIM_EN, VESIM_EN_ENABLE); + register_mask = BITFMASK(VESIM_EN); + register1 = REG_REGULATOR_MODE_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vesim_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VESIM_EN, VESIM_EN_DISABLE); + register_mask = BITFMASK(VESIM_EN); + register1 = REG_REGULATOR_MODE_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vcam_set_voltage(struct regulator_dev *reg, + int minuV, int uV) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int voltage, mV = uV / 1000; + + if ((mV >= 1500) && (mV < 1800)) + voltage = VCAM_1_5V; + else if ((mV >= 1800) && (mV < 2500)) + voltage = VCAM_1_8V; + else if ((mV >= 2500) && (mV < 2550)) + voltage = VCAM_2_5V; + else if ((mV >= 2550) && (mV < 2600)) + voltage = VCAM_2_55V; + if ((mV >= 2600) && (mV < 2750)) + voltage = VCAM_2_6V; + else if ((mV >= 2750) && (mV < 2800)) + voltage = VCAM_2_75V; + else if ((mV >= 2800) && (mV < 3000)) + voltage = VCAM_2_8V; + else + voltage = VCAM_3V; + + register_val = BITFVAL(VCAM, voltage); + register_mask = BITFMASK(VCAM); + register1 = REG_REGULATOR_SETTING_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vcam_get_voltage(struct regulator_dev *reg) +{ + unsigned int register_val = 0; + int voltage = 0, mV = 0; + + CHECK_ERROR(pmic_read_reg(REG_REGULATOR_SETTING_0, + ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, VCAM); + + switch (voltage) { + case VCAM_1_5V: + mV = 1500; + break; + case VCAM_1_8V: + mV = 1800; + break; + case VCAM_2_5V: + mV = 2500; + break; + case VCAM_2_55V: + mV = 2550; + break; + case VCAM_2_6V: + mV = 2600; + break; + case VCAM_2_75V: + mV = 2750; + break; + case VCAM_2_8V: + mV = 2800; + break; + case VCAM_3V: + mV = 3000; + break; + default: + return -EINVAL; + } + + return mV * 1000; +} + +static int mc13783_vcam_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VCAM_EN, VCAM_EN_ENABLE); + register_mask = BITFMASK(VCAM_EN); + register1 = REG_REGULATOR_MODE_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vcam_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VCAM_EN, VCAM_EN_DISABLE); + register_mask = BITFMASK(VCAM_EN); + register1 = REG_REGULATOR_MODE_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vvib_set_voltage(struct regulator_dev *reg, + int minuV, int uV) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int voltage, mV = uV / 1000; + + if ((mV >= 1300) && (mV < 1800)) + voltage = VVIB_1_3V; + else if ((mV >= 1800) && (mV < 2000)) + voltage = VVIB_1_8V; + else if ((mV >= 2000) && (mV < 3000)) + voltage = VVIB_2V; + else + voltage = VVIB_3V; + + register_val = BITFVAL(VVIB, voltage); + register_mask = BITFMASK(VVIB); + register1 = REG_REGULATOR_SETTING_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vvib_get_voltage(struct regulator_dev *reg) +{ + unsigned int register_val = 0; + int voltage = 0, mV = 0; + + CHECK_ERROR(pmic_read_reg(REG_REGULATOR_SETTING_1, + ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, VVIB); + + switch (voltage) { + case VVIB_1_3V: + mV = 1300; + break; + case VVIB_1_8V: + mV = 1800; + break; + case VVIB_2V: + mV = 2000; + break; + case VVIB_3V: + mV = 3000; + break; + default: + return -EINVAL; + } + + return mV * 1000; +} + +static int mc13783_vvib_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VVIB_EN, VVIB_EN_ENABLE); + register_mask = BITFMASK(VVIB_EN); + register1 = REG_REGULATOR_MODE_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vvib_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VVIB_EN, VVIB_EN_DISABLE); + register_mask = BITFMASK(VVIB_EN); + register1 = REG_REGULATOR_MODE_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vrf_set_voltage(struct regulator_dev *reg, int minuV, int uV) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int voltage, rf = rdev_get_id(reg), mV = uV / 1000; + + if ((mV >= 1500) && (mV < 1875)) + voltage = VRF_1_5V; + else if ((mV >= 1875) && (mV < 2700)) + voltage = VRF_1_875V; + else if ((mV >= 2700) && (mV < 2775)) + voltage = VRF_2_7V; + else + voltage = VRF_2_775V; + + switch (rf) { + case MC13783_VRF1: + register_val = BITFVAL(VRF1, voltage); + register_mask = BITFMASK(VRF1); + break; + case MC13783_VRF2: + register_val = BITFVAL(VRF2, voltage); + register_mask = BITFMASK(VRF2); + break; + default: + return -EINVAL; + } + + register1 = REG_REGULATOR_SETTING_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vrf_get_voltage(struct regulator_dev *reg) +{ + unsigned int register_val = 0; + int voltage = 0, rf = rdev_get_id(reg), mV = 0; + + CHECK_ERROR(pmic_read_reg(REG_REGULATOR_SETTING_1, + ®ister_val, PMIC_ALL_BITS)); + + switch (rf) { + case MC13783_VRF1: + voltage = BITFEXT(register_val, VRF1); + break; + case MC13783_VRF2: + voltage = BITFEXT(register_val, VRF2); + break; + default: + return -EINVAL; + }; + + switch (voltage) { + case VRF_1_5V: + mV = 1500; + break; + case VRF_1_875V: + mV = 1875; + break; + case VRF_2_7V: + mV = 2700; + break; + case VRF_2_775V: + mV = 2775; + break; + default: + return -EINVAL; + } + + return mV * 1000; +} + +static int mc13783_vrf_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int vrf = rdev_get_id(reg); + + switch (vrf) { + case MC13783_VRF1: + register_val = BITFVAL(VRF1_EN, VRF1_EN_ENABLE); + register_mask = BITFMASK(VRF1_EN); + break; + case MC13783_VRF2: + register_val = BITFVAL(VRF2_EN, VRF2_EN_ENABLE); + register_mask = BITFMASK(VRF2_EN); + break; + default: + return -EINVAL; + }; + + register1 = REG_REGULATOR_MODE_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vrf_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int vrf = rdev_get_id(reg); + + switch (vrf) { + case MC13783_VRF1: + register_val = BITFVAL(VRF1_EN, VRF1_EN_DISABLE); + register_mask = BITFMASK(VRF1_EN); + break; + case MC13783_VRF2: + register_val = BITFVAL(VRF2_EN, VRF2_EN_DISABLE); + register_mask = BITFMASK(VRF2_EN); + break; + default: + return -EINVAL; + }; + + register1 = REG_REGULATOR_MODE_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vmmc_set_voltage(struct regulator_dev *reg, + int minuV, int uV) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int voltage, mmc = rdev_get_id(reg), mV = uV / 1000; + + printk(KERN_INFO "VMMC ID is %d\n", mmc); + + if ((mV >= 1600) && (mV < 1800)) + voltage = VMMC_1_6V; + else if ((mV >= 1800) && (mV < 2000)) + voltage = VMMC_1_8V; + else if ((mV >= 2000) && (mV < 2600)) + voltage = VMMC_2V; + else if ((mV >= 2600) && (mV < 2700)) + voltage = VMMC_2_6V; + else if ((mV >= 2700) && (mV < 2800)) + voltage = VMMC_2_7V; + else if ((mV >= 2800) && (mV < 2900)) + voltage = VMMC_2_8V; + else if ((mV >= 2900) && (mV < 3000)) + voltage = VMMC_2_9V; + else + voltage = VMMC_3V; + + switch (mmc) { + case MC13783_VMMC1: + register_val = BITFVAL(VMMC1, voltage); + register_mask = BITFMASK(VMMC1); + break; + case MC13783_VMMC2: + register_val = BITFVAL(VMMC2, voltage); + register_mask = BITFMASK(VMMC2); + break; + default: + return -EINVAL; + } + + register1 = REG_REGULATOR_SETTING_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vmmc_get_voltage(struct regulator_dev *reg) +{ + unsigned int register_val = 0; + int voltage = 0, mmc = rdev_get_id(reg), mV = 0; + + CHECK_ERROR(pmic_read_reg(REG_REGULATOR_SETTING_1, + ®ister_val, PMIC_ALL_BITS)); + + switch (mmc) { + case MC13783_VMMC1: + voltage = BITFEXT(register_val, VMMC1); + break; + case MC13783_VMMC2: + voltage = BITFEXT(register_val, VMMC2); + break; + default: + return -EINVAL; + } + + switch (voltage) { + case VMMC_1_6V: + mV = 1600; + break; + case VMMC_1_8V: + mV = 1800; + break; + case VMMC_2V: + mV = 2000; + break; + case VMMC_2_6V: + mV = 2600; + break; + case VMMC_2_7V: + mV = 2700; + break; + case VMMC_2_8V: + mV = 2800; + break; + case VMMC_2_9V: + mV = 2900; + break; + case VMMC_3V: + mV = 3000; + break; + default: + return -EINVAL; + } + + return mV * 1000; +} + +static int mc13783_vmmc_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int vmmc = rdev_get_id(reg); + + switch (vmmc) { + case MC13783_VMMC1: + register_val = BITFVAL(VMMC1_EN, VMMC1_EN_ENABLE); + register_mask = BITFMASK(VMMC1_EN); + break; + case MC13783_VMMC2: + register_val = BITFVAL(VMMC2_EN, VMMC2_EN_ENABLE); + register_mask = BITFMASK(VMMC2_EN); + break; + default: + return -EINVAL; + }; + + register1 = REG_REGULATOR_MODE_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_vmmc_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int vmmc = rdev_get_id(reg); + + switch (vmmc) { + case MC13783_VMMC1: + register_val = BITFVAL(VMMC1_EN, VMMC1_EN_DISABLE); + register_mask = BITFMASK(VMMC1_EN); + break; + case MC13783_VMMC2: + register_val = BITFVAL(VMMC2_EN, VMMC2_EN_DISABLE); + register_mask = BITFMASK(VMMC2_EN); + break; + default: + return -EINVAL; + }; + + register1 = REG_REGULATOR_MODE_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_gpo_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int gpo = rdev_get_id(reg); + + switch (gpo) { + case MC13783_GPO1: + register_val = BITFVAL(GPO1_EN, GPO1_EN_ENABLE); + register_mask = BITFMASK(GPO1_EN); + break; + case MC13783_GPO2: + register_val = BITFVAL(GPO2_EN, GPO2_EN_ENABLE); + register_mask = BITFMASK(GPO2_EN); + break; + case MC13783_GPO3: + register_val = BITFVAL(GPO3_EN, GPO3_EN_ENABLE); + register_mask = BITFMASK(GPO3_EN); + break; + case MC13783_GPO4: + register_val = BITFVAL(GPO4_EN, GPO4_EN_ENABLE); + register_mask = BITFMASK(GPO4_EN); + break; + default: + return -EINVAL; + }; + + register1 = REG_POWER_MISCELLANEOUS; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_gpo_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int gpo = rdev_get_id(reg); + + switch (gpo) { + case MC13783_GPO1: + register_val = BITFVAL(GPO1_EN, GPO1_EN_DISABLE); + register_mask = BITFMASK(GPO1_EN); + break; + case MC13783_GPO2: + register_val = BITFVAL(GPO2_EN, GPO2_EN_DISABLE); + register_mask = BITFMASK(GPO2_EN); + break; + case MC13783_GPO3: + register_val = BITFVAL(GPO3_EN, GPO3_EN_DISABLE); + register_mask = BITFMASK(GPO3_EN); + break; + case MC13783_GPO4: + register_val = BITFVAL(GPO4_EN, GPO4_EN_DISABLE); + register_mask = BITFMASK(GPO4_EN); + break; + default: + return -EINVAL; + }; + + register1 = REG_POWER_MISCELLANEOUS; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_sw3_set_voltage(struct regulator_dev *reg, int minuV, int uV) +{ + unsigned int register_val = 0, register_mask = 0, register1 = 0; + int voltage, mV = uV / 1000; + + if ((mV >= 5000) && (mV < 5500)) + voltage = SW3_5V; + else + voltage = SW3_5_5V; + + register_val = BITFVAL(SW3, voltage); + register_mask = BITFMASK(SW3); + register1 = REG_SWITCHERS_5; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_sw3_get_voltage(struct regulator_dev *reg) +{ + unsigned int register_val = 0; + int voltage = 0, mV = 0; + + CHECK_ERROR(pmic_read_reg(REG_SWITCHERS_5, + ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, SW3); + + if (voltage == SW3_5_5V) + mV = 5500; + else + mV = 5000; + + return mV * 1000; +} + +static int mc13783_sw3_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(SW3_EN, SW3_EN_ENABLE); + register_mask = BITFMASK(SW3_EN); + register1 = REG_SWITCHERS_5; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_sw3_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(SW3_EN, SW3_EN_DISABLE); + register_mask = BITFMASK(SW3_EN); + register1 = REG_SWITCHERS_5; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_sw_set_normal_voltage(struct regulator_dev *reg, + int minuV, int uV) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1 = 0; + int voltage, sw = rdev_get_id(reg), mV = uV / 1000; + + if ((mV >= 900) && (mV < 925)) + voltage = SW_0_9V; + else if ((mV >= 925) && (mV < 950)) + voltage = SW_0_925V; + else if ((mV >= 950) && (mV < 975)) + voltage = SW_0_95V; + else if ((mV >= 975) && (mV < 1000)) + voltage = SW_0_975V; + else if ((mV >= 1000) && (mV < 1025)) + voltage = SW_1V; + else if ((mV >= 1025) && (mV < 1050)) + voltage = SW_1_025V; + else if ((mV >= 1050) && (mV < 1075)) + voltage = SW_1_05V; + else if ((mV >= 1075) && (mV < 1100)) + voltage = SW_1_075V; + else if ((mV >= 1100) && (mV < 1125)) + voltage = SW_1_1V; + else if ((mV >= 1125) && (mV < 1150)) + voltage = SW_1_125V; + else if ((mV >= 1150) && (mV < 1175)) + voltage = SW_1_15V; + else if ((mV >= 1175) && (mV < 1200)) + voltage = SW_1_175V; + else if ((mV >= 1200) && (mV < 1225)) + voltage = SW_1_2V; + else if ((mV >= 1225) && (mV < 1250)) + voltage = SW_1_225V; + else if ((mV >= 1250) && (mV < 1275)) + voltage = SW_1_25V; + else if ((mV >= 1275) && (mV < 1300)) + voltage = SW_1_275V; + else if ((mV >= 1300) && (mV < 1325)) + voltage = SW_1_3V; + else if ((mV >= 1325) && (mV < 1350)) + voltage = SW_1_325V; + else if ((mV >= 1350) && (mV < 1375)) + voltage = SW_1_35V; + else if ((mV >= 1375) && (mV < 1400)) + voltage = SW_1_375V; + else if ((mV >= 1400) && (mV < 1425)) + voltage = SW_1_4V; + else if ((mV >= 1425) && (mV < 1450)) + voltage = SW_1_425V; + else if ((mV >= 1450) && (mV < 1475)) + voltage = SW_1_45V; + else if ((mV >= 1475) && (mV < 1500)) + voltage = SW_1_475V; + else if ((mV >= 1500) && (mV < 1525)) + voltage = SW_1_5V; + else if ((mV >= 1525) && (mV < 1550)) + voltage = SW_1_525V; + else if ((mV >= 1550) && (mV < 1575)) + voltage = SW_1_55V; + else if ((mV >= 1575) && (mV < 1600)) + voltage = SW_1_575V; + else if ((mV >= 1600) && (mV < 1625)) + voltage = SW_1_6V; + else if ((mV >= 1625) && (mV < 1650)) + voltage = SW_1_625V; + else if ((mV >= 1650) && (mV < 1675)) + voltage = SW_1_65V; + else if ((mV >= 1675) && (mV < 1700)) + voltage = SW_1_675V; + else if ((mV >= 1700) && (mV < 1800)) + voltage = SW_1_7V; + else if ((mV >= 1800) && (mV < 1850)) + voltage = SW_1_8V; + else if ((mV >= 1850) && (mV < 2000)) + voltage = SW_1_85V; + else if ((mV >= 2000) && (mV < 2100)) + voltage = SW_2V; + else if ((mV >= 2100) && (mV < 2200)) + voltage = SW_2_1V; + else + voltage = SW_2_2V; + + switch (sw) { + case MC13783_SW1A: + register1 = REG_SWITCHERS_0; + register_val = BITFVAL(SW1A, voltage); + register_mask = BITFMASK(SW1A); + break; + case MC13783_SW1B: + register1 = REG_SWITCHERS_1; + register_val = BITFVAL(SW1B, voltage); + register_mask = BITFMASK(SW1B); + break; + case MC13783_SW2A: + register1 = REG_SWITCHERS_2; + register_val = BITFVAL(SW2A, voltage); + register_mask = BITFMASK(SW2A); + break; + case MC13783_SW2B: + register1 = REG_SWITCHERS_3; + register_val = BITFVAL(SW2B, voltage); + register_mask = BITFMASK(SW2B); + break; + default: + return -EINVAL; + } + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_sw_get_normal_voltage(struct regulator_dev *reg) +{ + unsigned int register_val = 0; + int voltage = 0, mV = 0, sw = rdev_get_id(reg); + + switch (sw) { + case MC13783_SW1A: + CHECK_ERROR(pmic_read_reg(REG_SWITCHERS_0, + ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, SW1A); + break; + case MC13783_SW1B: + CHECK_ERROR(pmic_read_reg(REG_SWITCHERS_1, + ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, SW1B); + break; + case MC13783_SW2A: + CHECK_ERROR(pmic_read_reg(REG_SWITCHERS_2, + ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, SW2A); + break; + case MC13783_SW2B: + CHECK_ERROR(pmic_read_reg(REG_SWITCHERS_3, + ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, SW2B); + break; + default: + return -EINVAL; + } + + switch (voltage) { + case SW_0_9V: + mV = 900; + break; + case SW_0_925V: + mV = 925; + break; + case SW_0_95V: + mV = 950; + break; + case SW_0_975V: + mV = 975; + break; + case SW_1V: + mV = 1000; + break; + case SW_1_025V: + mV = 1025; + break; + case SW_1_05V: + mV = 1050; + break; + case SW_1_075V: + mV = 1075; + break; + case SW_1_1V: + mV = 1100; + break; + case SW_1_125V: + mV = 1125; + break; + case SW_1_15V: + mV = 1150; + break; + case SW_1_175V: + mV = 1175; + break; + case SW_1_2V: + mV = 1200; + break; + case SW_1_225V: + mV = 1225; + break; + case SW_1_25V: + mV = 1250; + break; + case SW_1_275V: + mV = 1275; + break; + case SW_1_3V: + mV = 1300; + break; + case SW_1_325V: + mV = 1325; + break; + case SW_1_35V: + mV = 1350; + break; + case SW_1_375V: + mV = 1375; + break; + case SW_1_4V: + mV = 1400; + break; + case SW_1_425V: + mV = 1425; + break; + case SW_1_45V: + mV = 1450; + break; + case SW_1_475V: + mV = 1475; + break; + case SW_1_5V: + mV = 1500; + break; + case SW_1_525V: + mV = 1525; + break; + case SW_1_55V: + mV = 1550; + break; + case SW_1_575V: + mV = 1575; + break; + case SW_1_6V: + mV = 1600; + break; + case SW_1_625V: + mV = 1625; + break; + case SW_1_65V: + mV = 1650; + break; + case SW_1_675V: + mV = 1675; + break; + case SW_1_7V: + mV = 1700; + break; + case SW_1_8V: + mV = 1800; + break; + case SW_1_85V: + mV = 1850; + break; + case SW_2V: + mV = 2000; + break; + case SW_2_1V: + mV = 2100; + break; + case SW_2_2V: + mV = 2200; + break; + default: + return -EINVAL; + } + + return mV * 1000; +} + +static int mc13783_sw_normal_enable(struct regulator_dev *reg) +{ + return 0; +} + +static int mc13783_sw_normal_disable(struct regulator_dev *reg) +{ + return 0; +} + +static int mc13783_sw_stby_enable(struct regulator_dev *reg) +{ + return 0; +} + +static int mc13783_sw_stby_disable(struct regulator_dev *reg) +{ + return 0; +} + +static int mc13783_sw_set_stby_voltage(struct regulator_dev *reg, int uV) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1 = 0; + int voltage, sw = rdev_get_id(reg), mV = uV / 1000; + + if ((mV >= 900) && (mV < 925)) + voltage = SW_0_9V; + else if ((mV >= 925) && (mV < 950)) + voltage = SW_0_925V; + else if ((mV >= 950) && (mV < 975)) + voltage = SW_0_95V; + else if ((mV >= 975) && (mV < 1000)) + voltage = SW_0_975V; + else if ((mV >= 1000) && (mV < 1025)) + voltage = SW_1V; + else if ((mV >= 1025) && (mV < 1050)) + voltage = SW_1_025V; + else if ((mV >= 1050) && (mV < 1075)) + voltage = SW_1_05V; + else if ((mV >= 1075) && (mV < 1100)) + voltage = SW_1_075V; + else if ((mV >= 1100) && (mV < 1125)) + voltage = SW_1_1V; + else if ((mV >= 1125) && (mV < 1150)) + voltage = SW_1_125V; + else if ((mV >= 1150) && (mV < 1175)) + voltage = SW_1_15V; + else if ((mV >= 1175) && (mV < 1200)) + voltage = SW_1_175V; + else if ((mV >= 1200) && (mV < 1225)) + voltage = SW_1_2V; + else if ((mV >= 1225) && (mV < 1250)) + voltage = SW_1_225V; + else if ((mV >= 1250) && (mV < 1275)) + voltage = SW_1_25V; + else if ((mV >= 1275) && (mV < 1300)) + voltage = SW_1_275V; + else if ((mV >= 1300) && (mV < 1325)) + voltage = SW_1_3V; + else if ((mV >= 1325) && (mV < 1350)) + voltage = SW_1_325V; + else if ((mV >= 1350) && (mV < 1375)) + voltage = SW_1_35V; + else if ((mV >= 1375) && (mV < 1400)) + voltage = SW_1_375V; + else if ((mV >= 1400) && (mV < 1425)) + voltage = SW_1_4V; + else if ((mV >= 1425) && (mV < 1450)) + voltage = SW_1_425V; + else if ((mV >= 1450) && (mV < 1475)) + voltage = SW_1_45V; + else if ((mV >= 1475) && (mV < 1500)) + voltage = SW_1_475V; + else if ((mV >= 1500) && (mV < 1525)) + voltage = SW_1_5V; + else if ((mV >= 1525) && (mV < 1550)) + voltage = SW_1_525V; + else if ((mV >= 1550) && (mV < 1575)) + voltage = SW_1_55V; + else if ((mV >= 1575) && (mV < 1600)) + voltage = SW_1_575V; + else if ((mV >= 1600) && (mV < 1625)) + voltage = SW_1_6V; + else if ((mV >= 1625) && (mV < 1650)) + voltage = SW_1_625V; + else if ((mV >= 1650) && (mV < 1675)) + voltage = SW_1_65V; + else if ((mV >= 1675) && (mV < 1700)) + voltage = SW_1_675V; + else if ((mV >= 1700) && (mV < 1800)) + voltage = SW_1_7V; + else if ((mV >= 1800) && (mV < 1850)) + voltage = SW_1_8V; + else if ((mV >= 1850) && (mV < 2000)) + voltage = SW_1_85V; + else if ((mV >= 2000) && (mV < 2100)) + voltage = SW_2V; + else if ((mV >= 2100) && (mV < 2200)) + voltage = SW_2_1V; + else + voltage = SW_2_2V; + + switch (sw) { + case MC13783_SW1A: + register1 = REG_SWITCHERS_0; + register_val = BITFVAL(SW1A_STDBY, voltage); + register_mask = BITFMASK(SW1A_STDBY); + break; + case MC13783_SW1B: + register1 = REG_SWITCHERS_1; + register_val = BITFVAL(SW1B_STDBY, voltage); + register_mask = BITFMASK(SW1B_STDBY); + break; + case MC13783_SW2A: + register1 = REG_SWITCHERS_2; + register_val = BITFVAL(SW2A_STDBY, voltage); + register_mask = BITFMASK(SW2A_STDBY); + break; + case MC13783_SW2B: + register1 = REG_SWITCHERS_3; + register_val = BITFVAL(SW2B_STDBY, voltage); + register_mask = BITFMASK(SW2B_STDBY); + break; + default: + return -EINVAL; + } + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13783_sw_set_normal_mode(struct regulator_dev *reg, + unsigned int mode) +{ + unsigned int reg_val = 0, reg_mask = 0; + unsigned int register1 = 0; + unsigned int l_mode; + int sw = rdev_get_id(reg); + + switch (mode) { + case REGULATOR_MODE_FAST: + /* SYNC RECT mode */ + l_mode = SW_MODE_SYNC_RECT_EN; + break; + case REGULATOR_MODE_NORMAL: + /* PULSE SKIP mode */ + l_mode = SW_MODE_PULSE_SKIP_EN; + break; + case REGULATOR_MODE_IDLE: + /* LOW POWER mode */ + l_mode = SW_MODE_LOW_POWER_EN; + break; + case REGULATOR_MODE_STANDBY: + /* NO PULSE SKIP mode */ + l_mode = SW_MODE_PULSE_NO_SKIP_EN; + break; + default: + return -EINVAL; + } + + switch (sw) { + case MC13783_SW1A: + reg_val = BITFVAL(SW1A_MODE, l_mode); + reg_mask = BITFMASK(SW1A_MODE); + register1 = REG_SWITCHERS_4; + break; + case MC13783_SW1B: + reg_val = BITFVAL(SW1B_MODE, l_mode); + reg_mask = BITFMASK(SW1B_MODE); + register1 = REG_SWITCHERS_4; + break; + case MC13783_SW2A: + reg_val = BITFVAL(SW2A_MODE, l_mode); + reg_mask = BITFMASK(SW2A_MODE); + register1 = REG_SWITCHERS_5; + break; + case MC13783_SW2B: + reg_val = BITFVAL(SW2B_MODE, l_mode); + reg_mask = BITFMASK(SW2B_MODE); + register1 = REG_SWITCHERS_5; + break; + default: + return -EINVAL; + } + + return pmic_write_reg(register1, reg_val, reg_mask); +} + +static unsigned int mc13783_sw_get_normal_mode(struct regulator_dev *reg) +{ + unsigned int reg_val = 0, reg_mask = 0; + unsigned int register1 = 0; + unsigned int l_mode = 0; + int sw = rdev_get_id(reg); + int ret = 0; + + switch (sw) { + case MC13783_SW1A: + reg_mask = BITFMASK(SW1A_MODE); + register1 = REG_SWITCHERS_4; + break; + case MC13783_SW1B: + reg_mask = BITFMASK(SW1B_MODE); + register1 = REG_SWITCHERS_4; + break; + case MC13783_SW2A: + reg_mask = BITFMASK(SW2A_MODE); + register1 = REG_SWITCHERS_5; + break; + case MC13783_SW2B: + reg_mask = BITFMASK(SW2B_MODE); + register1 = REG_SWITCHERS_5; + break; + default: + return -EINVAL; + } + + ret = pmic_read_reg(register1, ®_val, reg_mask); + if (ret != 0) + return ret; + + switch (sw) { + case MC13783_SW1A: + l_mode = BITFEXT(reg_val, SW1A_MODE); + break; + case MC13783_SW1B: + l_mode = BITFEXT(reg_val, SW1B_MODE); + break; + case MC13783_SW2A: + l_mode = BITFEXT(reg_val, SW2A_MODE); + break; + case MC13783_SW2B: + l_mode = BITFEXT(reg_val, SW2B_MODE); + break; + default: + return -EINVAL; + } + + if (l_mode == SW_MODE_SYNC_RECT_EN) { + return REGULATOR_MODE_FAST; + } else if (l_mode == SW_MODE_PULSE_NO_SKIP_EN) { + return REGULATOR_MODE_STANDBY; + } else if (l_mode == SW_MODE_PULSE_SKIP_EN) { + return REGULATOR_MODE_NORMAL; + } else if (l_mode == SW_MODE_LOW_POWER_EN) { + return REGULATOR_MODE_IDLE; + } else { + return -EINVAL; + } +} + +static int mc13783_sw_set_stby_mode(struct regulator_dev *reg, + unsigned int mode) +{ + unsigned int reg_val = 0, reg_mask = 0; + unsigned int register1 = 0; + unsigned int l_mode; + int sw = rdev_get_id(reg); + + switch (mode) { + case REGULATOR_MODE_FAST: + /* SYNC RECT mode */ + l_mode = SW_MODE_SYNC_RECT_EN; + break; + case REGULATOR_MODE_NORMAL: + /* PULSE SKIP mode */ + l_mode = SW_MODE_PULSE_SKIP_EN; + break; + case REGULATOR_MODE_IDLE: + /* LOW POWER mode */ + l_mode = SW_MODE_LOW_POWER_EN; + break; + case REGULATOR_MODE_STANDBY: + /* NO PULSE SKIP mode */ + l_mode = SW_MODE_PULSE_NO_SKIP_EN; + break; + default: + return -EINVAL; + } + + switch (sw) { + case MC13783_SW1A: + reg_val = BITFVAL(SW1A_STBY_MODE, l_mode); + reg_mask = BITFMASK(SW1A_STBY_MODE); + register1 = REG_SWITCHERS_4; + break; + case MC13783_SW1B: + reg_val = BITFVAL(SW1B_STBY_MODE, l_mode); + reg_mask = BITFMASK(SW1B_STBY_MODE); + register1 = REG_SWITCHERS_4; + break; + case MC13783_SW2A: + reg_val = BITFVAL(SW2A_STBY_MODE, l_mode); + reg_mask = BITFMASK(SW2A_STBY_MODE); + register1 = REG_SWITCHERS_5; + break; + case MC13783_SW2B: + reg_val = BITFVAL(SW2B_STBY_MODE, l_mode); + reg_mask = BITFMASK(SW2B_STBY_MODE); + register1 = REG_SWITCHERS_5; + break; + default: + return -EINVAL; + } + + return pmic_write_reg(register1, reg_val, reg_mask); +} + +static struct regulator_ops mc13783_vaudio_ops = { + .enable = mc13783_vaudio_enable, + .disable = mc13783_vaudio_disable, +}; + +static struct regulator_ops mc13783_viohi_ops = { + .enable = mc13783_viohi_enable, + .disable = mc13783_viohi_disable, +}; + +static struct regulator_ops mc13783_violo_ops = { + .set_voltage = mc13783_violo_set_voltage, + .get_voltage = mc13783_violo_get_voltage, + .enable = mc13783_violo_enable, + .disable = mc13783_violo_disable, +}; + +static struct regulator_ops mc13783_vdig_ops = { + .set_voltage = mc13783_vdig_set_voltage, + .get_voltage = mc13783_vdig_get_voltage, + .enable = mc13783_vdig_enable, + .disable = mc13783_vdig_disable, +}; + +static struct regulator_ops mc13783_vgen_ops = { + .set_voltage = mc13783_vgen_set_voltage, + .get_voltage = mc13783_vgen_get_voltage, + .enable = mc13783_vgen_enable, + .disable = mc13783_vgen_disable, +}; + +static struct regulator_ops mc13783_vrfdig_ops = { + .set_voltage = mc13783_vrfdig_set_voltage, + .get_voltage = mc13783_vrfdig_get_voltage, + .enable = mc13783_vrfdig_enable, + .disable = mc13783_vrfdig_disable, +}; + +static struct regulator_ops mc13783_vrfref_ops = { + .set_voltage = mc13783_vrfref_set_voltage, + .get_voltage = mc13783_vrfref_get_voltage, + .enable = mc13783_vrfref_enable, + .disable = mc13783_vrfref_disable, +}; + +static struct regulator_ops mc13783_vrfcp_ops = { + .set_voltage = mc13783_vrfcp_set_voltage, + .get_voltage = mc13783_vrfcp_get_voltage, + .enable = mc13783_vrfcp_enable, + .disable = mc13783_vrfcp_disable, +}; + +static struct regulator_ops mc13783_vsim_ops = { + .set_voltage = mc13783_vsim_set_voltage, + .get_voltage = mc13783_vsim_get_voltage, + .enable = mc13783_vsim_enable, + .disable = mc13783_vsim_disable, +}; + +static struct regulator_ops mc13783_vesim_ops = { + .set_voltage = mc13783_vesim_set_voltage, + .get_voltage = mc13783_vesim_get_voltage, + .enable = mc13783_vesim_enable, + .disable = mc13783_vesim_disable, +}; + +static struct regulator_ops mc13783_vcam_ops = { + .set_voltage = mc13783_vcam_set_voltage, + .get_voltage = mc13783_vcam_get_voltage, + .enable = mc13783_vcam_enable, + .disable = mc13783_vcam_disable, +}; + +static struct regulator_ops mc13783_vvib_ops = { + .set_voltage = mc13783_vvib_set_voltage, + .get_voltage = mc13783_vvib_get_voltage, + .enable = mc13783_vvib_enable, + .disable = mc13783_vvib_disable, +}; + +static struct regulator_ops mc13783_vrf_ops = { + .set_voltage = mc13783_vrf_set_voltage, + .get_voltage = mc13783_vrf_get_voltage, + .enable = mc13783_vrf_enable, + .disable = mc13783_vrf_disable, +}; + +static struct regulator_ops mc13783_vmmc_ops = { + .set_voltage = mc13783_vmmc_set_voltage, + .get_voltage = mc13783_vmmc_get_voltage, + .enable = mc13783_vmmc_enable, + .disable = mc13783_vmmc_disable, +}; + +static struct regulator_ops mc13783_gpo_ops = { + .enable = mc13783_gpo_enable, + .disable = mc13783_gpo_disable, +}; + +static struct regulator_ops mc13783_sw3_ops = { + .set_voltage = mc13783_sw3_set_voltage, + .get_voltage = mc13783_sw3_get_voltage, + .enable = mc13783_sw3_enable, + .disable = mc13783_sw3_disable, +}; + +static struct regulator_ops mc13783_sw1_ops = { + .set_voltage = mc13783_sw_set_normal_voltage, + .get_voltage = mc13783_sw_get_normal_voltage, + .get_mode = mc13783_sw_get_normal_mode, + .set_mode = mc13783_sw_set_normal_mode, + .set_suspend_voltage = mc13783_sw_set_stby_voltage, + .set_suspend_enable = mc13783_sw_stby_enable, + .set_suspend_disable = mc13783_sw_stby_disable, + .set_suspend_mode = mc13783_sw_set_stby_mode, +}; + +static struct regulator_ops mc13783_sw_normal_ops = { + .set_voltage = mc13783_sw_set_normal_voltage, + .get_voltage = mc13783_sw_get_normal_voltage, + .get_mode = mc13783_sw_get_normal_mode, + .set_mode = mc13783_sw_set_normal_mode, + .enable = mc13783_sw_normal_enable, + .disable = mc13783_sw_normal_disable, +}; + +static struct regulator_desc reg_mc13783[] = { + { + .name = "SW1A", + .id = MC13783_SW1A, + .ops = &mc13783_sw1_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "SW1B", + .id = MC13783_SW1B, + .ops = &mc13783_sw_normal_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "SW2A", + .id = MC13783_SW2A, + .ops = &mc13783_sw_normal_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "SW2B", + .id = MC13783_SW2B, + .ops = &mc13783_sw_normal_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "SW3", + .id = MC13783_SW3, + .ops = &mc13783_sw3_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VAUDIO", + .id = MC13783_VAUDIO, + .ops = &mc13783_vaudio_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VIOHI", + .id = MC13783_VIOHI, + .ops = &mc13783_viohi_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VIOLO", + .id = MC13783_VIOLO, + .ops = &mc13783_violo_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VDIG", + .id = MC13783_VDIG, + .ops = &mc13783_vdig_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VGEN", + .id = MC13783_VGEN, + .ops = &mc13783_vgen_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VRFDIG", + .id = MC13783_VRFDIG, + .ops = &mc13783_vrfdig_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VRFREF", + .id = MC13783_VRFREF, + .ops = &mc13783_vrfref_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VRFCP", + .id = MC13783_VRFCP, + .ops = &mc13783_vrfcp_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VSIM", + .id = MC13783_VSIM, + .ops = &mc13783_vsim_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VESIM", + .id = MC13783_VESIM, + .ops = &mc13783_vesim_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VCAM", + .id = MC13783_VCAM, + .ops = &mc13783_vcam_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VRFBG", + .id = MC13783_VRFBG, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VVIB", + .id = MC13783_VVIB, + .ops = &mc13783_vvib_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VRF1", + .id = MC13783_VRF1, + .ops = &mc13783_vrf_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VRF2", + .id = MC13783_VRF2, + .ops = &mc13783_vrf_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VMMC1", + .id = MC13783_VMMC1, + .ops = &mc13783_vmmc_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VMMC2", + .id = MC13783_VMMC2, + .ops = &mc13783_vmmc_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "GPO1", + .id = MC13783_GPO1, + .ops = &mc13783_gpo_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "GPO2", + .id = MC13783_GPO2, + .ops = &mc13783_gpo_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "GPO3", + .id = MC13783_GPO3, + .ops = &mc13783_gpo_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "GPO4", + .id = MC13783_GPO4, + .ops = &mc13783_gpo_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, +}; + +/* + * Init and Exit + */ + +static int reg_mc13783_probe(struct platform_device *pdev) +{ + struct regulator_dev *rdev; + + /* register regulator */ + rdev = regulator_register(®_mc13783[pdev->id], &pdev->dev, + pdev->dev.platform_data, + dev_get_drvdata(&pdev->dev)); + if (IS_ERR(rdev)) { + dev_err(&pdev->dev, "failed to register %s\n", + reg_mc13783[pdev->id].name); + return PTR_ERR(rdev); + } + platform_set_drvdata(pdev, rdev); + + return 0; +} + +static int mc13783_regulator_remove(struct platform_device *pdev) +{ + struct regulator_dev *rdev = platform_get_drvdata(pdev); + + regulator_unregister(rdev); + + return 0; +} + +int mc13783_register_regulator(struct mc13783 *mc13783, int reg, + struct regulator_init_data *initdata) +{ + struct platform_device *pdev; + int ret; + + if (mc13783->pmic.pdev[reg]) + return -EBUSY; + + pdev = platform_device_alloc("mc13783-regulatr", reg); + if (!pdev) + return -ENOMEM; + + mc13783->pmic.pdev[reg] = pdev; + + initdata->driver_data = mc13783; + + pdev->dev.platform_data = initdata; + pdev->dev.parent = mc13783->dev; + ret = platform_device_add(pdev); + + if (ret != 0) { + dev_err(mc13783->dev, "Failed to register regulator %d: %d\n", + reg, ret); + platform_device_del(pdev); + mc13783->pmic.pdev[reg] = NULL; + } + + return ret; +} +EXPORT_SYMBOL_GPL(mc13783_register_regulator); + +static struct platform_driver mc13783_regulator_driver = { + .probe = reg_mc13783_probe, + .remove = mc13783_regulator_remove, + .driver = { + .name = "mc13783-regulatr", + /* o left out due to string length */ + }, +}; + +static int __init mc13783_regulator_subsys_init(void) +{ + return platform_driver_register(&mc13783_regulator_driver); +} +subsys_initcall(mc13783_regulator_subsys_init); + +static void __exit mc13783_regulator_exit(void) +{ + platform_driver_unregister(&mc13783_regulator_driver); +} +module_exit(mc13783_regulator_exit); + + +/* Module information */ +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MC13783 Regulator driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/regulator/reg-mc13892.c b/drivers/regulator/reg-mc13892.c new file mode 100644 index 000000000000..f6803f8ba837 --- /dev/null +++ b/drivers/regulator/reg-mc13892.c @@ -0,0 +1,1850 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Convenience conversion. + * Here atm, maybe there is somewhere better for this. + */ +#define mV_to_uV(mV) (mV * 1000) +#define uV_to_mV(uV) (uV / 1000) +#define V_to_uV(V) (mV_to_uV(V * 1000)) +#define uV_to_V(uV) (uV_to_mV(uV) / 1000) + +enum { + VDIG_1_05V = 0, + VDIG_1_25V, + VDIG_1_65V, + VDIG_1_80V, +} regulator_voltage_vdig; + +enum { + VPLL_1_05V = 0, + VPLL_1_25V, + VPLL_1_65V, + VPLL_1_80V, +} regulator_voltage_vpll; + +enum { + VGEN1_1_2V = 0, + VGEN1_1_5V, + VGEN1_2_775V, + VGEN1_3_15V, +} regulator_voltage_vgen1; + +enum { + VGEN2_1_2V = 0, + VGEN2_1_5V, + VGEN2_1_6V, + VGEN2_1_8V, + VGEN2_2_7V, + VGEN2_2_8V, + VGEN2_3_0V, + VGEN2_3_15V, +} regulator_voltage_vgen2; + +enum { + VGEN3_1_8V = 0, + VGEN3_2_9V, +} regulator_voltage_vgen3; + +enum { + VSD_1_8V = 0, + VSD_2_0V, + VSD_2_6V, + VSD_2_7V, + VSD_2_8V, + VSD_2_9V, + VSD_3_0V, + VSD_3_15V, +} regulator_voltage_vsd; + +enum { + VCAM_2_5V, + VCAM_2_6V, + VCAM_2_75V, + VCAM_3_0V, +} regulator_voltage_vcam; + +enum { + VAUDIO_2_3V, + VAUDIO_2_5V, + VAUDIO_2_775V, + VAUDIO_3V, +} regulator_voltage_vaudio; + +enum { + VUSB2_2_4V, + VUSB2_2_6V, + VUSB2_2_7V, + VUSB2_2_775V, +} regulator_voltage_vusb2; + +enum { + VVIDEO_2_7V, + VVIDEO_2_775V, + VVIDEO_2_5V, + VVIDEO_2_6V, +} regulator_voltage_vvideo; + +#define VAUDIO_LSH 4 +#define VAUDIO_WID 2 +#define VAUDIO_EN_LSH 15 +#define VAUDIO_EN_WID 1 +#define VAUDIO_EN_ENABLE 1 +#define VAUDIO_EN_DISABLE 0 + +#define VUSB2_LSH 11 +#define VUSB2_WID 2 +#define VUSB2_EN_LSH 18 +#define VUSB2_EN_WID 1 +#define VUSB2_EN_ENABLE 1 +#define VUSB2_EN_DISABLE 0 + +#define VVIDEO_LSH 2 +#define VVIDEO_WID 2 +#define VVIDEO_EN_LSH 12 +#define VVIDEO_EN_WID 1 +#define VVIDEO_EN_ENABLE 1 +#define VVIDEO_EN_DISABLE 0 + +#define SWBST_EN_LSH 20 +#define SWBST_EN_WID 1 +#define SWBST_EN_ENABLE 1 +#define SWBST_EN_DISABLE 0 + +#define VIOHI_EN_LSH 3 +#define VIOHI_EN_WID 1 +#define VIOHI_EN_ENABLE 1 +#define VIOHI_EN_DISABLE 0 + +#define VDIG_LSH 4 +#define VDIG_WID 2 +#define VDIG_EN_LSH 9 +#define VDIG_EN_WID 1 +#define VDIG_EN_ENABLE 1 +#define VDIG_EN_DISABLE 0 + +#define VPLL_LSH 9 +#define VPLL_WID 2 +#define VPLL_EN_LSH 15 +#define VPLL_EN_WID 1 +#define VPLL_EN_ENABLE 1 +#define VPLL_EN_DISABLE 0 + +#define VGEN1_LSH 0 +#define VGEN1_WID 2 +#define VGEN1_EN_LSH 0 +#define VGEN1_EN_WID 1 +#define VGEN1_EN_ENABLE 1 +#define VGEN1_EN_DISABLE 0 + +#define VGEN2_LSH 6 +#define VGEN2_WID 3 +#define VGEN2_EN_LSH 12 +#define VGEN2_EN_WID 1 +#define VGEN2_EN_ENABLE 1 +#define VGEN2_EN_DISABLE 0 + +#define VGEN3_LSH 14 +#define VGEN3_WID 1 +#define VGEN3_EN_LSH 0 +#define VGEN3_EN_WID 1 +#define VGEN3_EN_ENABLE 1 +#define VGEN3_EN_DISABLE 0 + +#define VSD_LSH 6 +#define VSD_WID 3 +#define VSD_EN_LSH 18 +#define VSD_EN_WID 1 +#define VSD_EN_ENABLE 1 +#define VSD_EN_DISABLE 0 + +#define VCAM_LSH 16 +#define VCAM_WID 2 +#define VCAM_EN_LSH 6 +#define VCAM_EN_WID 1 +#define VCAM_EN_ENABLE 1 +#define VCAM_EN_DISABLE 0 +#define VCAM_CONFIG_LSH 9 +#define VCAM_CONFIG_WID 1 +#define VCAM_CONFIG_EXT 1 +#define VCAM_CONFIG_INT 0 + +#define SW1_LSH 0 +#define SW1_WID 5 +#define SW1_DVS_LSH 5 +#define SW1_DVS_WID 5 +#define SW1_STDBY_LSH 10 +#define SW1_STDBY_WID 5 + +#define SW2_LSH 0 +#define SW2_WID 5 +#define SW2_DVS_LSH 5 +#define SW2_DVS_WID 5 +#define SW2_STDBY_LSH 10 +#define SW2_STDBY_WID 5 + +#define SW3_LSH 0 +#define SW3_WID 5 +#define SW3_STDBY_LSH 10 +#define SW3_STDBY_WID 5 + +#define SW4_LSH 0 +#define SW4_WID 5 +#define SW4_STDBY_LSH 10 +#define SW4_STDBY_WID 5 + +#define VUSB_EN_LSH 3 +#define VUSB_EN_WID 1 +#define VUSB_EN_ENABLE 1 +#define VUSB_EN_DISABLE 0 + +#define GPO1_EN_LSH 6 +#define GPO1_EN_WID 1 +#define GPO1_EN_ENABLE 1 +#define GPO1_EN_DISABLE 0 + +#define GPO2_EN_LSH 8 +#define GPO2_EN_WID 1 +#define GPO2_EN_ENABLE 1 +#define GPO2_EN_DISABLE 0 + +#define GPO3_EN_LSH 10 +#define GPO3_EN_WID 1 +#define GPO3_EN_ENABLE 1 +#define GPO3_EN_DISABLE 0 + +#define GPO4_EN_LSH 12 +#define GPO4_EN_WID 1 +#define GPO4_EN_ENABLE 1 +#define GPO4_EN_DISABLE 0 + +#define GPO4_ADIN_LSH 21 +#define GPO4_ADIN_WID 1 +#define GPO4_ADIN_ENABLE 1 +#define GPO4_ADIN_DISABLE 0 + +#define PWGT1SPI_EN_LSH 15 +#define PWGT1SPI_EN_WID 1 +#define PWGT1SPI_EN_ENABLE 0 +#define PWGT1SPI_EN_DISABLE 1 + +#define PWGT2SPI_EN_LSH 16 +#define PWGT2SPI_EN_WID 1 +#define PWGT2SPI_EN_ENABLE 0 +#define PWGT2SPI_EN_DISABLE 1 + +#define SWXHI_LSH 23 +#define SWXHI_WID 1 +#define SWXHI_ON 1 +#define SWXHI_OFF 0 + +static int mc13892_get_sw_hi_bit(int sw) +{ + unsigned int register_val = 0; + unsigned int reg = 0; + + switch (sw) { + case MC13892_SW1: + reg = REG_SW_0; + break; + case MC13892_SW2: + reg = REG_SW_1; + break; + case MC13892_SW3: + reg = REG_SW_2; + break; + case MC13892_SW4: + reg = REG_SW_3; + break; + default: + return -EINVAL; + } + + CHECK_ERROR(pmic_read_reg(reg, ®ister_val, PMIC_ALL_BITS)); + return (register_val & 0x800000) >> SWXHI_LSH; +} + +static int mc13892_get_voltage_value(int *hi, int mV) +{ + int voltage; + + if (mV < 600) + mV = 600; + if (mV > 1850) + mV = 1850; + + if (mV > 1375) + *hi = 1; + if (mV < 1100) + *hi = 0; + + if (*hi == 0) + voltage = (mV - 600) / 25; + else + voltage = (mV - 1100) / 25; + + return voltage; +} + +static int mc13892_get_voltage_mV(int hi, int voltage) +{ + int mV; + + if (hi == 0) + mV = voltage * 25 + 600; + else + mV = voltage * 25 + 1100; + + return mV; +} + +static int mc13892_sw_set_voltage(struct regulator_dev *reg, int MiniV, int uV) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1 = 0; + int voltage; + int sw = rdev_get_id(reg); + int mV = uV / 1000; + int hi; + + hi = mc13892_get_sw_hi_bit(sw); + voltage = mc13892_get_voltage_value(&hi, mV); + + switch (sw) { + case MC13892_SW1: + register1 = REG_SW_0; + register_val = BITFVAL(SW1, voltage); + register_mask = BITFMASK(SW1); + break; + case MC13892_SW2: + register1 = REG_SW_1; + register_val = BITFVAL(SW2, voltage); + register_mask = BITFMASK(SW2); + break; + case MC13892_SW3: + register1 = REG_SW_2; + register_val = BITFVAL(SW3, voltage); + register_mask = BITFMASK(SW3); + break; + case MC13892_SW4: + register1 = REG_SW_3; + register_val = BITFVAL(SW4, voltage); + register_mask = BITFMASK(SW4); + break; + default: + return -EINVAL; + } + + register_val |= (hi << SWXHI_LSH); + register_mask |= (1 << SWXHI_LSH); + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_sw_get_voltage(struct regulator_dev *reg) +{ + unsigned int register_val = 0; + int voltage = 0; + int mV = 0; + int sw = rdev_get_id(reg); + int hi; + + switch (sw) { + case MC13892_SW1: + CHECK_ERROR(pmic_read_reg(REG_SW_0, + ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, SW1); + break; + case MC13892_SW2: + CHECK_ERROR(pmic_read_reg(REG_SW_1, + ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, SW2); + break; + case MC13892_SW3: + CHECK_ERROR(pmic_read_reg(REG_SW_2, + ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, SW3); + break; + case MC13892_SW4: + CHECK_ERROR(pmic_read_reg(REG_SW_3, + ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, SW4); + break; + default: + return -EINVAL; + } + + hi = mc13892_get_sw_hi_bit(sw); + mV = mc13892_get_voltage_mV(hi, voltage); + + return mV * 1000; +} + +static int mc13892_sw_stby_enable(struct regulator_dev *reg) +{ + return 0; +} + +static int mc13892_sw_stby_disable(struct regulator_dev *reg) +{ + return 0; +} + +static int mc13892_sw_stby_set_mode(struct regulator_dev *reg, unsigned int mode) +{ + return 0; +} + +static int mc13892_sw_stby_set_voltage(struct regulator_dev *reg, int uV) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1 = 0; + int voltage, mV = uV / 1000, hi; + int sw = rdev_get_id(reg); + + hi = mc13892_get_sw_hi_bit(sw); + voltage = mc13892_get_voltage_value(&hi, mV); + + switch (sw) { + case MC13892_SW1: + register1 = REG_SW_0; + register_val = BITFVAL(SW1_STDBY, voltage); + register_mask = BITFMASK(SW1_STDBY); + break; + case MC13892_SW2: + register1 = REG_SW_1; + register_val = BITFVAL(SW2_STDBY, voltage); + register_mask = BITFMASK(SW2_STDBY); + break; + case MC13892_SW3: + register1 = REG_SW_2; + register_val = BITFVAL(SW3_STDBY, voltage); + register_mask = BITFMASK(SW3_STDBY); + break; + case MC13892_SW4: + register1 = REG_SW_3; + register_val = BITFVAL(SW4_STDBY, voltage); + register_mask = BITFMASK(SW4_STDBY); + break; + default: + return -EINVAL; + } + + register_val |= (hi << SWXHI_LSH); + register_mask |= (1 << SWXHI_LSH); + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_swbst_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(SWBST_EN, SWBST_EN_ENABLE); + register_mask = BITFMASK(SWBST_EN); + register1 = REG_SW_5; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_swbst_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(SWBST_EN, SWBST_EN_DISABLE); + register_mask = BITFMASK(SWBST_EN); + register1 = REG_SW_5; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_viohi_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VIOHI_EN, VIOHI_EN_ENABLE); + register_mask = BITFMASK(VIOHI_EN); + register1 = REG_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_viohi_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VIOHI_EN, VIOHI_EN_DISABLE); + register_mask = BITFMASK(VIOHI_EN); + register1 = REG_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vusb_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VUSB_EN, VUSB_EN_ENABLE); + register_mask = BITFMASK(VUSB_EN); + register1 = REG_USB1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vusb_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VUSB_EN, VUSB_EN_DISABLE); + register_mask = BITFMASK(VUSB_EN); + register1 = REG_USB1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vdig_set_voltage(struct regulator_dev *reg, + int minuV, int uV) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int voltage, mV = uV / 1000; + + if ((mV >= 1050) && (mV < 1250)) + voltage = VDIG_1_05V; + else if ((mV >= 1250) && (mV < 1650)) + voltage = VDIG_1_25V; + else if ((mV >= 1650) && (mV < 1800)) + voltage = VDIG_1_65V; + else + voltage = VDIG_1_80V; + + register_val = BITFVAL(VDIG, voltage); + register_mask = BITFMASK(VDIG); + register1 = REG_SETTING_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vdig_get_voltage(struct regulator_dev *reg) +{ + unsigned int register_val = 0; + int voltage = 0, mV = 0; + + CHECK_ERROR(pmic_read_reg(REG_SETTING_0, ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, VDIG); + + switch (voltage) { + case VDIG_1_05V: + mV = 1050; + break; + case VDIG_1_25V: + mV = 1250; + break; + case VDIG_1_65V: + mV = 1650; + break; + case VDIG_1_80V: + mV = 1800; + break; + default: + return -EINVAL; + } + + return mV * 1000; +} + +static int mc13892_vdig_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VDIG_EN, VDIG_EN_ENABLE); + register_mask = BITFMASK(VDIG_EN); + register1 = REG_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vdig_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VDIG_EN, VDIG_EN_DISABLE); + register_mask = BITFMASK(VDIG_EN); + register1 = REG_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vpll_set_voltage(struct regulator_dev *reg, + int minuV, int uV) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int voltage, mV = uV / 1000; + + if ((mV >= 1050) && (mV < 1250)) + voltage = VPLL_1_05V; + else if ((mV >= 1250) && (mV < 1650)) + voltage = VPLL_1_25V; + else if ((mV >= 1650) && (mV < 1800)) + voltage = VPLL_1_65V; + else + voltage = VPLL_1_80V; + + register_val = BITFVAL(VPLL, voltage); + register_mask = BITFMASK(VPLL); + register1 = REG_SETTING_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vpll_get_voltage(struct regulator_dev *reg) +{ + unsigned int register_val = 0; + int voltage = 0, mV = 0; + + CHECK_ERROR(pmic_read_reg(REG_SETTING_0, ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, VPLL); + + switch (voltage) { + case VPLL_1_05V: + mV = 1050; + break; + case VPLL_1_25V: + mV = 1250; + break; + case VPLL_1_65V: + mV = 1650; + break; + case VPLL_1_80V: + mV = 1800; + break; + default: + return -EINVAL; + } + + return mV * 1000; +} + +static int mc13892_vpll_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VPLL_EN, VPLL_EN_ENABLE); + register_mask = BITFMASK(VPLL_EN); + register1 = REG_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vpll_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VPLL_EN, VPLL_EN_DISABLE); + register_mask = BITFMASK(VPLL_EN); + register1 = REG_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vaudio_set_voltage(struct regulator_dev *reg, + int minuV, int uV) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int voltage, mV = uV / 1000; + + if ((mV >= 2300) && (mV < 2500)) + voltage = VAUDIO_2_3V; + else if ((mV >= 2500) && (mV < 2775)) + voltage = VAUDIO_2_5V; + else if ((mV >= 2775) && (mV < 3000)) + voltage = VAUDIO_2_775V; + else + voltage = VAUDIO_3V; + + register_val = BITFVAL(VAUDIO, voltage); + register_mask = BITFMASK(VAUDIO); + register1 = REG_SETTING_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vaudio_get_voltage(struct regulator_dev *reg) +{ + unsigned int register_val = 0; + int voltage = 0, mV = 0; + + CHECK_ERROR(pmic_read_reg(REG_SETTING_1, ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, VAUDIO); + + switch (voltage) { + case VAUDIO_2_3V: + mV = 2300; + break; + case VAUDIO_2_5V: + mV = 2500; + break; + case VAUDIO_2_775V: + mV = 2775; + break; + case VAUDIO_3V: + mV = 3000; + break; + default: + return -EINVAL; + } + + return mV * 1000; +} + +static int mc13892_vaudio_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VAUDIO_EN, VAUDIO_EN_ENABLE); + register_mask = BITFMASK(VAUDIO_EN); + register1 = REG_MODE_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vaudio_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VAUDIO_EN, VAUDIO_EN_DISABLE); + register_mask = BITFMASK(VAUDIO_EN); + register1 = REG_MODE_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vusb2_set_voltage(struct regulator_dev *reg, + int minuV, int uV) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int voltage, mV = uV / 1000; + + if ((mV >= 2400) && (mV < 2600)) + voltage = VUSB2_2_4V; + else if ((mV >= 2600) && (mV < 2700)) + voltage = VUSB2_2_6V; + else if ((mV >= 2700) && (mV < 2775)) + voltage = VUSB2_2_7V; + else + voltage = VUSB2_2_775V; + + register_val = BITFVAL(VUSB2, voltage); + register_mask = BITFMASK(VUSB2); + register1 = REG_SETTING_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vusb2_get_voltage(struct regulator_dev *reg) +{ + unsigned int register_val = 0; + int voltage = 0, mV = 0; + + CHECK_ERROR(pmic_read_reg(REG_SETTING_0, ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, VUSB2); + + switch (voltage) { + case VUSB2_2_4V: + mV = 2400; + break; + case VUSB2_2_6V: + mV = 2600; + break; + case VUSB2_2_7V: + mV = 2700; + break; + case VUSB2_2_775V: + mV = 2775; + break; + default: + return -EINVAL; + } + + return mV * 1000; +} + +static int mc13892_vusb2_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VUSB2_EN, VUSB2_EN_ENABLE); + register_mask = BITFMASK(VUSB2_EN); + register1 = REG_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vusb2_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VUSB2_EN, VUSB2_EN_DISABLE); + register_mask = BITFMASK(VUSB2_EN); + register1 = REG_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vvideo_set_voltage(struct regulator_dev *reg, + int minuV, int uV) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int voltage, mV = uV / 1000; + + if ((mV >= 2500) && (mV < 2600)) + voltage = VVIDEO_2_5V; + else if ((mV >= 2600) && (mV < 2700)) + voltage = VVIDEO_2_6V; + else if ((mV >= 2700) && (mV < 2775)) + voltage = VVIDEO_2_7V; + else + voltage = VVIDEO_2_775V; + + register_val = BITFVAL(VVIDEO, voltage); + register_mask = BITFMASK(VVIDEO); + register1 = REG_SETTING_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vvideo_get_voltage(struct regulator_dev *reg) +{ + unsigned int register_val = 0; + int voltage = 0, mV = 0; + + CHECK_ERROR(pmic_read_reg(REG_SETTING_1, ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, VVIDEO); + + switch (voltage) { + case VVIDEO_2_5V: + mV = 2500; + break; + case VVIDEO_2_6V: + mV = 2600; + break; + case VVIDEO_2_7V: + mV = 2700; + break; + case VVIDEO_2_775V: + mV = 2775; + break; + default: + return -EINVAL; + } + + return mV * 1000; +} + +static int mc13892_vvideo_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VVIDEO_EN, VVIDEO_EN_ENABLE); + register_mask = BITFMASK(VVIDEO_EN); + register1 = REG_MODE_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vvideo_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VVIDEO_EN, VVIDEO_EN_DISABLE); + register_mask = BITFMASK(VVIDEO_EN); + register1 = REG_MODE_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vsd_set_voltage(struct regulator_dev *reg, + int minuV, int uV) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int voltage, mV = uV / 1000; + + if ((mV >= 1800) && (mV < 2000)) + voltage = VSD_1_8V; + else if ((mV >= 2000) && (mV < 2600)) + voltage = VSD_2_0V; + else if ((mV >= 2600) && (mV < 2700)) + voltage = VSD_2_6V; + else if ((mV >= 2700) && (mV < 2800)) + voltage = VSD_2_7V; + else if ((mV >= 2800) && (mV < 2900)) + voltage = VSD_2_8V; + else if ((mV >= 2900) && (mV < 3000)) + voltage = VSD_2_9V; + else if ((mV >= 3000) && (mV < 3150)) + voltage = VSD_3_0V; + else + voltage = VSD_3_15V; + + register_val = BITFVAL(VSD, voltage); + register_mask = BITFMASK(VSD); + register1 = REG_SETTING_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vsd_get_voltage(struct regulator_dev *reg) +{ + unsigned int register_val = 0; + int voltage = 0, mV = 0; + + CHECK_ERROR(pmic_read_reg(REG_SETTING_1, ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, VSD); + + switch (voltage) { + case VSD_1_8V: + mV = 1800; + break; + case VSD_2_0V: + mV = 2000; + break; + case VSD_2_6V: + mV = 2600; + break; + case VSD_2_7V: + mV = 2700; + break; + case VSD_2_8V: + mV = 2800; + break; + case VSD_2_9V: + mV = 2900; + break; + case VSD_3_0V: + mV = 3000; + break; + case VSD_3_15V: + mV = 3150; + break; + default: + return -EINVAL; + } + + return mV * 1000; +} + +static int mc13892_vsd_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VSD_EN, VSD_EN_ENABLE); + register_mask = BITFMASK(VSD_EN); + register1 = REG_MODE_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vsd_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VSD_EN, VSD_EN_DISABLE); + register_mask = BITFMASK(VSD_EN); + register1 = REG_MODE_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vcam_set_voltage(struct regulator_dev *reg, + int minuV, int uV) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int voltage, mV = uV / 1000; + + if ((mV >= 2500) && (mV < 2600)) + voltage = VCAM_2_5V; + else if ((mV >= 2600) && (mV < 2750)) + voltage = VCAM_2_6V; + else if ((mV >= 2750) && (mV < 3000)) + voltage = VCAM_2_75V; + else + voltage = VCAM_3_0V; + + register_val = BITFVAL(VCAM, voltage); + register_mask = BITFMASK(VCAM); + register1 = REG_SETTING_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vcam_get_voltage(struct regulator_dev *reg) +{ + unsigned int register_val = 0; + int voltage = 0, mV = 0; + + CHECK_ERROR(pmic_read_reg(REG_SETTING_0, ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, VCAM); + + switch (voltage) { + case VCAM_2_5V: + mV = 2500; + break; + case VCAM_2_6V: + mV = 2600; + break; + case VCAM_2_75V: + mV = 2750; + break; + case VCAM_3_0V: + mV = 3000; + break; + default: + return -EINVAL; + } + + return mV * 1000; +} + +static int mc13892_vcam_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VCAM_EN, VCAM_EN_ENABLE); + register_mask = BITFMASK(VCAM_EN); + register1 = REG_MODE_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vcam_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VCAM_EN, VCAM_EN_DISABLE); + register_mask = BITFMASK(VCAM_EN); + register1 = REG_MODE_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vcam_set_mode(struct regulator_dev *reg, unsigned int mode) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + switch (mode) { + case REGULATOR_MODE_FAST: + register_val = BITFVAL(VCAM_CONFIG, VCAM_CONFIG_EXT); + break; + case REGULATOR_MODE_NORMAL: + register_val = BITFVAL(VCAM_CONFIG, VCAM_CONFIG_INT); + break; + default: + return -EINVAL; + } + register_mask = BITFMASK(VCAM_CONFIG); + register1 = REG_MODE_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +unsigned int mc13892_vcam_get_mode(struct regulator_dev *reg) +{ + unsigned int register_val = 0; + int config = 0, mode = VCAM_CONFIG_INT; + + CHECK_ERROR(pmic_read_reg(REG_MODE_1, ®ister_val, PMIC_ALL_BITS)); + config = BITFEXT(register_val, VCAM_CONFIG); + + switch (config) { + case VCAM_CONFIG_EXT: + mode = REGULATOR_MODE_FAST; + break; + case VCAM_CONFIG_INT: + mode = REGULATOR_MODE_NORMAL; + break; + default: + return -EINVAL; + } + return mode; +} + +static int mc13892_vgen1_set_voltage(struct regulator_dev *reg, + int minuV, int uV) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int voltage, mV = uV / 1000; + + if ((mV >= 1200) && (mV < 1500)) + voltage = VGEN1_1_2V; + else if ((mV >= 1500) && (mV < 2775)) + voltage = VGEN1_1_5V; + else if ((mV >= 2775) && (mV < 3150)) + voltage = VGEN1_2_775V; + else + voltage = VGEN1_3_15V; + + register_val = BITFVAL(VGEN1, voltage); + register_mask = BITFMASK(VGEN1); + register1 = REG_SETTING_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vgen1_get_voltage(struct regulator_dev *reg) +{ + unsigned int register_val = 0; + int voltage = 0, mV = 0; + + CHECK_ERROR(pmic_read_reg(REG_SETTING_0, ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, VGEN1); + + switch (voltage) { + case VGEN1_1_2V: + mV = 1200; + break; + case VGEN1_1_5V: + mV = 1500; + break; + case VGEN1_2_775V: + mV = 2775; + break; + case VGEN1_3_15V: + mV = 3150; + break; + default: + return -EINVAL; + } + + return mV * 1000; +} + +static int mc13892_vgen1_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VGEN1_EN, VGEN1_EN_ENABLE); + register_mask = BITFMASK(VGEN1_EN); + register1 = REG_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vgen1_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VGEN1_EN, VGEN1_EN_DISABLE); + register_mask = BITFMASK(VGEN1_EN); + register1 = REG_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vgen2_set_voltage(struct regulator_dev *reg, + int minuV, int uV) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int voltage, mV = uV / 1000; + + if ((mV >= 1200) && (mV < 1500)) + voltage = VGEN2_1_2V; + else if ((mV >= 1500) && (mV < 1600)) + voltage = VGEN2_1_5V; + else if ((mV >= 1600) && (mV < 1800)) + voltage = VGEN2_1_6V; + else if ((mV >= 1800) && (mV < 2700)) + voltage = VGEN2_1_8V; + else if ((mV >= 2700) && (mV < 2800)) + voltage = VGEN2_2_7V; + else if ((mV >= 2800) && (mV < 3000)) + voltage = VGEN2_2_8V; + else if ((mV >= 3000) && (mV < 3150)) + voltage = VGEN2_3_0V; + else + voltage = VGEN2_3_15V; + + register_val = BITFVAL(VGEN2, voltage); + register_mask = BITFMASK(VGEN2); + register1 = REG_SETTING_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vgen2_get_voltage(struct regulator_dev *reg) +{ + unsigned int register_val = 0; + int voltage = 0, mV = 0; + + CHECK_ERROR(pmic_read_reg(REG_SETTING_0, ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, VGEN2); + + switch (voltage) { + case VGEN2_1_2V: + mV = 1200; + break; + case VGEN2_1_5V: + mV = 1500; + break; + case VGEN2_1_6V: + mV = 1600; + break; + case VGEN2_1_8V: + mV = 1800; + break; + case VGEN2_2_7V: + mV = 2700; + break; + case VGEN2_2_8V: + mV = 2800; + break; + case VGEN2_3_0V: + mV = 3000; + break; + case VGEN2_3_15V: + mV = 3150; + break; + default: + return -EINVAL; + } + + return mV * 1000; +} + +static int mc13892_vgen2_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VGEN2_EN, VGEN2_EN_ENABLE); + register_mask = BITFMASK(VGEN2_EN); + register1 = REG_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vgen2_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VGEN2_EN, VGEN2_EN_DISABLE); + register_mask = BITFMASK(VGEN2_EN); + register1 = REG_MODE_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vgen3_set_voltage(struct regulator_dev *reg, + int minuV, int uV) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int voltage, mV = uV / 1000; + + if ((mV >= 1800) && (mV < 2900)) + voltage = VGEN3_1_8V; + else + voltage = VGEN3_2_9V; + + register_val = BITFVAL(VGEN3, voltage); + register_mask = BITFMASK(VGEN3); + register1 = REG_SETTING_0; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vgen3_get_voltage(struct regulator_dev *reg) +{ + unsigned int register_val = 0; + int voltage = 0, mV = 0; + + CHECK_ERROR(pmic_read_reg(REG_SETTING_0, ®ister_val, PMIC_ALL_BITS)); + voltage = BITFEXT(register_val, VGEN3); + + switch (voltage) { + case VGEN3_1_8V: + mV = 1800; + break; + case VGEN3_2_9V: + mV = 2900; + break; + default: + return -EINVAL; + } + + return mV * 1000; +} + +static int mc13892_vgen3_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VGEN3_EN, VGEN3_EN_ENABLE); + register_mask = BITFMASK(VGEN3_EN); + register1 = REG_MODE_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_vgen3_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + + register_val = BITFVAL(VGEN3_EN, VGEN3_EN_DISABLE); + register_mask = BITFMASK(VGEN3_EN); + register1 = REG_MODE_1; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_gpo_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int gpo = rdev_get_id(reg); + + switch (gpo) { + case MC13892_GPO1: + register_val = BITFVAL(GPO1_EN, GPO1_EN_ENABLE); + register_mask = BITFMASK(GPO1_EN); + break; + case MC13892_GPO2: + register_val = BITFVAL(GPO2_EN, GPO2_EN_ENABLE); + register_mask = BITFMASK(GPO2_EN); + break; + case MC13892_GPO3: + register_val = BITFVAL(GPO3_EN, GPO3_EN_ENABLE); + register_mask = BITFMASK(GPO3_EN); + break; + case MC13892_GPO4: + register_val = BITFVAL(GPO4_EN, GPO4_EN_ENABLE) + + BITFVAL(GPO4_ADIN, GPO4_ADIN_DISABLE); + register_mask = BITFMASK(GPO4_EN) + BITFMASK(GPO4_ADIN); + break; + default: + return -EINVAL; + }; + + register1 = REG_POWER_MISC; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_gpo_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int gpo = rdev_get_id(reg); + + switch (gpo) { + case MC13892_GPO1: + register_val = BITFVAL(GPO1_EN, GPO1_EN_DISABLE); + register_mask = BITFMASK(GPO1_EN); + break; + case MC13892_GPO2: + register_val = BITFVAL(GPO2_EN, GPO2_EN_DISABLE); + register_mask = BITFMASK(GPO2_EN); + break; + case MC13892_GPO3: + register_val = BITFVAL(GPO3_EN, GPO3_EN_DISABLE); + register_mask = BITFMASK(GPO3_EN); + break; + case MC13892_GPO4: + register_val = BITFVAL(GPO4_EN, GPO4_EN_DISABLE); + register_mask = BITFMASK(GPO4_EN); + break; + default: + return -EINVAL; + }; + + register1 = REG_POWER_MISC; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_power_gating_enable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int gpo = rdev_get_id(reg); + + switch (gpo) { + case MC13892_PWGT1: + register_val = BITFVAL(PWGT1SPI_EN, PWGT1SPI_EN_ENABLE); + register_mask = BITFMASK(PWGT1SPI_EN); + break; + case MC13892_PWGT2: + register_val = BITFVAL(PWGT2SPI_EN, PWGT2SPI_EN_ENABLE); + register_mask = BITFMASK(PWGT2SPI_EN); + break; + default: + return -EINVAL; + }; + + register1 = REG_POWER_MISC; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static int mc13892_power_gating_disable(struct regulator_dev *reg) +{ + unsigned int register_val = 0, register_mask = 0; + unsigned int register1; + int gpo = rdev_get_id(reg); + + switch (gpo) { + case MC13892_PWGT1: + register_val = BITFVAL(PWGT1SPI_EN, PWGT1SPI_EN_DISABLE); + register_mask = BITFMASK(PWGT1SPI_EN); + break; + case MC13892_PWGT2: + register_val = BITFVAL(PWGT2SPI_EN, PWGT2SPI_EN_DISABLE); + register_mask = BITFMASK(PWGT2SPI_EN); + break; + default: + return -EINVAL; + }; + + register1 = REG_POWER_MISC; + + return pmic_write_reg(register1, register_val, register_mask); +} + +static struct regulator_ops mc13892_sw_ops = { + .enable = mc13892_sw_stby_enable, + .disable = mc13892_sw_stby_disable, + .set_voltage = mc13892_sw_set_voltage, + .get_voltage = mc13892_sw_get_voltage, + .set_suspend_voltage = mc13892_sw_stby_set_voltage, + .set_suspend_enable = mc13892_sw_stby_enable, + .set_suspend_disable = mc13892_sw_stby_disable, + .set_suspend_mode = mc13892_sw_stby_set_mode, +}; + +static struct regulator_ops mc13892_swbst_ops = { + .enable = mc13892_swbst_enable, + .disable = mc13892_swbst_disable, +}; + +static struct regulator_ops mc13892_viohi_ops = { + .enable = mc13892_viohi_enable, + .disable = mc13892_viohi_disable, +}; + +static struct regulator_ops mc13892_vusb_ops = { + .enable = mc13892_vusb_enable, + .disable = mc13892_vusb_disable, +}; + +static struct regulator_ops mc13892_vdig_ops = { + .set_voltage = mc13892_vdig_set_voltage, + .get_voltage = mc13892_vdig_get_voltage, + .enable = mc13892_vdig_enable, + .disable = mc13892_vdig_disable, +}; + +static struct regulator_ops mc13892_vpll_ops = { + .set_voltage = mc13892_vpll_set_voltage, + .get_voltage = mc13892_vpll_get_voltage, + .enable = mc13892_vpll_enable, + .disable = mc13892_vpll_disable, +}; + +static struct regulator_ops mc13892_vusb2_ops = { + .set_voltage = mc13892_vusb2_set_voltage, + .get_voltage = mc13892_vusb2_get_voltage, + .enable = mc13892_vusb2_enable, + .disable = mc13892_vusb2_disable, +}; + +static struct regulator_ops mc13892_vvideo_ops = { + .set_voltage = mc13892_vvideo_set_voltage, + .get_voltage = mc13892_vvideo_get_voltage, + .enable = mc13892_vvideo_enable, + .disable = mc13892_vvideo_disable, +}; + +static struct regulator_ops mc13892_vaudio_ops = { + .set_voltage = mc13892_vaudio_set_voltage, + .get_voltage = mc13892_vaudio_get_voltage, + .enable = mc13892_vaudio_enable, + .disable = mc13892_vaudio_disable, +}; + +static struct regulator_ops mc13892_vsd_ops = { + .set_voltage = mc13892_vsd_set_voltage, + .get_voltage = mc13892_vsd_get_voltage, + .enable = mc13892_vsd_enable, + .disable = mc13892_vsd_disable, +}; + +static struct regulator_ops mc13892_vcam_ops = { + .set_voltage = mc13892_vcam_set_voltage, + .get_voltage = mc13892_vcam_get_voltage, + .enable = mc13892_vcam_enable, + .disable = mc13892_vcam_disable, + .set_mode = mc13892_vcam_set_mode, + .get_mode = mc13892_vcam_get_mode, +}; + +static struct regulator_ops mc13892_vgen1_ops = { + .set_voltage = mc13892_vgen1_set_voltage, + .get_voltage = mc13892_vgen1_get_voltage, + .enable = mc13892_vgen1_enable, + .disable = mc13892_vgen1_disable, +}; + +static struct regulator_ops mc13892_vgen2_ops = { + .set_voltage = mc13892_vgen2_set_voltage, + .get_voltage = mc13892_vgen2_get_voltage, + .enable = mc13892_vgen2_enable, + .disable = mc13892_vgen2_disable, +}; + +static struct regulator_ops mc13892_vgen3_ops = { + .set_voltage = mc13892_vgen3_set_voltage, + .get_voltage = mc13892_vgen3_get_voltage, + .enable = mc13892_vgen3_enable, + .disable = mc13892_vgen3_disable, +}; + +static struct regulator_ops mc13892_gpo_ops = { + .enable = mc13892_gpo_enable, + .disable = mc13892_gpo_disable, +}; + +static struct regulator_ops mc13892_power_gating_ops = { + .enable = mc13892_power_gating_enable, + .disable = mc13892_power_gating_disable, + +}; + +static struct regulator_desc mc13892_reg[] = { + { + .name = "SW1", + .id = MC13892_SW1, + .ops = &mc13892_sw_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "SW2", + .id = MC13892_SW2, + .ops = &mc13892_sw_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "SW3", + .id = MC13892_SW3, + .ops = &mc13892_sw_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "SW4", + .id = MC13892_SW4, + .ops = &mc13892_sw_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "SWBST", + .id = MC13892_SWBST, + .ops = &mc13892_swbst_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VIOHI", + .id = MC13892_VIOHI, + .ops = &mc13892_viohi_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VPLL", + .id = MC13892_VPLL, + .ops = &mc13892_vpll_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VDIG", + .id = MC13892_VDIG, + .ops = &mc13892_vdig_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VSD", + .id = MC13892_VSD, + .ops = &mc13892_vsd_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VUSB2", + .id = MC13892_VUSB2, + .ops = &mc13892_vusb2_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VVIDEO", + .id = MC13892_VVIDEO, + .ops = &mc13892_vvideo_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VAUDIO", + .id = MC13892_VAUDIO, + .ops = &mc13892_vaudio_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VCAM", + .id = MC13892_VCAM, + .ops = &mc13892_vcam_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VGEN1", + .id = MC13892_VGEN1, + .ops = &mc13892_vgen1_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VGEN2", + .id = MC13892_VGEN2, + .ops = &mc13892_vgen2_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VGEN3", + .id = MC13892_VGEN3, + .ops = &mc13892_vgen3_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "VUSB", + .id = MC13892_VUSB, + .ops = &mc13892_vusb_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "GPO1", + .id = MC13892_GPO1, + .ops = &mc13892_gpo_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "GPO2", + .id = MC13892_GPO2, + .ops = &mc13892_gpo_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "GPO3", + .id = MC13892_GPO3, + .ops = &mc13892_gpo_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "GPO4", + .id = MC13892_GPO4, + .ops = &mc13892_gpo_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "PWGT1", + .id = MC13892_PWGT1, + .ops = &mc13892_power_gating_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "PWGT2", + .id = MC13892_PWGT2, + .ops = &mc13892_power_gating_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, +}; + +static int mc13892_regulator_probe(struct platform_device *pdev) +{ + struct regulator_dev *rdev; + + /* register regulator */ + rdev = regulator_register(&mc13892_reg[pdev->id], &pdev->dev, + pdev->dev.platform_data, + dev_get_drvdata(&pdev->dev)); + if (IS_ERR(rdev)) { + dev_err(&pdev->dev, "failed to register %s\n", + mc13892_reg[pdev->id].name); + return PTR_ERR(rdev); + } + + return 0; +} + + +static int mc13892_regulator_remove(struct platform_device *pdev) +{ + struct regulator_dev *rdev = platform_get_drvdata(pdev); + + regulator_unregister(rdev); + + return 0; +} + +int mc13892_register_regulator(struct mc13892 *mc13892, int reg, + struct regulator_init_data *initdata) +{ + struct platform_device *pdev; + int ret; + + if (mc13892->pmic.pdev[reg]) + return -EBUSY; + + pdev = platform_device_alloc("mc13892-regulatr", reg); + if (!pdev) + return -ENOMEM; + + mc13892->pmic.pdev[reg] = pdev; + + initdata->driver_data = mc13892; + + pdev->dev.platform_data = initdata; + pdev->dev.parent = mc13892->dev; + platform_set_drvdata(pdev, mc13892); + ret = platform_device_add(pdev); + + if (ret != 0) { + dev_err(mc13892->dev, "Failed to register regulator %d: %d\n", + reg, ret); + platform_device_del(pdev); + mc13892->pmic.pdev[reg] = NULL; + } + + return ret; +} +EXPORT_SYMBOL_GPL(mc13892_register_regulator); + +static struct platform_driver mc13892_regulator_driver = { + .probe = mc13892_regulator_probe, + .remove = mc13892_regulator_remove, + .driver = { + .name = "mc13892-regulatr", + }, +}; + +static int __init mc13892_regulator_init(void) +{ + return platform_driver_register(&mc13892_regulator_driver); +} +subsys_initcall(mc13892_regulator_init); + +static void __exit mc13892_regulator_exit(void) +{ + platform_driver_unregister(&mc13892_regulator_driver); +} +module_exit(mc13892_regulator_exit); + + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MC13892 Regulator driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/regulator/reg-mc34704.c b/drivers/regulator/reg-mc34704.c new file mode 100644 index 000000000000..ed134074fba3 --- /dev/null +++ b/drivers/regulator/reg-mc34704.c @@ -0,0 +1,289 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MC34704_ONOFFA 0x8 +#define MC34704_ONOFFC 0x4 +#define MC34704_ONOFFD 0x2 +#define MC34704_ONOFFE 0x1 + +/* Private data for MC34704 regulators */ + +struct reg_mc34704_priv { + short enable; /* enable bit, if available */ + short v_default; /* default regulator voltage in mV */ + int dvs_min; /* minimum voltage change in units of 2.5% */ + int dvs_max; /* maximum voltage change in units of 2.5% */ + char i2c_dvs; /* i2c DVS register number */ + char i2c_stat; /* i2c status register number */ +}; +struct reg_mc34704_priv mc34704_reg_priv[] = { + { + .v_default = REG1_V_MV, + .dvs_min = REG1_DVS_MIN_PCT / 2.5, + .dvs_max = REG1_DVS_MAX_PCT / 2.5, + .i2c_dvs = 0x4, + .i2c_stat = 0x5, + .enable = MC34704_ONOFFA, + }, + { + .v_default = REG2_V_MV, + .dvs_min = REG2_DVS_MIN_PCT / 2.5, + .dvs_max = REG2_DVS_MAX_PCT / 2.5, + .i2c_dvs = 0x6, + .i2c_stat = 0x7, + }, + { + .v_default = REG3_V_MV, + .dvs_min = REG3_DVS_MIN_PCT / 2.5, + .dvs_max = REG3_DVS_MAX_PCT / 2.5, + .i2c_dvs = 0x8, + .i2c_stat = 0x9, + }, + { + .v_default = REG4_V_MV, + .dvs_min = REG4_DVS_MIN_PCT / 2.5, + .dvs_max = REG4_DVS_MAX_PCT / 2.5, + .i2c_dvs = 0xA, + .i2c_stat = 0xB, + }, + { + .v_default = REG5_V_MV, + .dvs_min = REG5_DVS_MIN_PCT / 2.5, + .dvs_max = REG5_DVS_MAX_PCT / 2.5, + .i2c_dvs = 0xC, + .i2c_stat = 0xE, + .enable = MC34704_ONOFFE, + }, +}; + +static int mc34704_set_voltage(struct regulator_dev *reg, int MiniV, int uV) +{ + struct reg_mc34704_priv *priv = rdev_get_drvdata(reg); + int mV = uV / 1000; + int dV = mV - priv->v_default; + + /* compute dynamic voltage scaling value */ + int dvs = 1000 * dV / priv->v_default / 25; + + /* clip to regulator limits */ + if (dvs > priv->dvs_max) + dvs = priv->dvs_max; + if (dvs < priv->dvs_min) + dvs = priv->dvs_min; + + return pmic_write_reg(priv->i2c_dvs, dvs << 1, 0x1E); +} + +static int mc34704_get_voltage(struct regulator_dev *reg) +{ + int mV; + struct reg_mc34704_priv *priv = rdev_get_drvdata(reg); + int val, dvs; + + CHECK_ERROR(pmic_read_reg(priv->i2c_dvs, &val, 0xF)); + + dvs = (val >> 1) & 0xF; + + /* dvs is 4-bit 2's complement; sign-extend it */ + if (dvs & 8) + dvs |= -1 & ~0xF; + + /* Regulator voltage is adjusted by (dvs * 2.5%) */ + mV = priv->v_default * (1000 + 25 * dvs) / 1000; + + return 1000 * mV; +} + +static int mc34704_enable_reg(struct regulator_dev *reg) +{ + struct reg_mc34704_priv *priv = rdev_get_drvdata(reg); + + if (priv->enable) + return pmic_write_reg(REG_MC34704_GENERAL2, -1, priv->enable); + + return PMIC_ERROR; +} + +static int mc34704_disable_reg(struct regulator_dev *reg) +{ + struct reg_mc34704_priv *priv = rdev_get_drvdata(reg); + + if (priv->enable) + return pmic_write_reg(REG_MC34704_GENERAL2, 0, priv->enable); + + return PMIC_ERROR; +} + +static int mc34704_is_reg_enabled(struct regulator_dev *reg) +{ + struct reg_mc34704_priv *priv = rdev_get_drvdata(reg); + int val; + + if (priv->enable) { + CHECK_ERROR(pmic_read_reg(REG_MC34704_GENERAL2, &val, + priv->enable)); + return val ? 1 : 0; + } else { + return PMIC_ERROR; + } +} + +static struct regulator_ops mc34704_full_ops = { + .set_voltage = mc34704_set_voltage, + .get_voltage = mc34704_get_voltage, + .enable = mc34704_enable_reg, + .disable = mc34704_disable_reg, + .is_enabled = mc34704_is_reg_enabled, +}; + +static struct regulator_ops mc34704_partial_ops = { + .set_voltage = mc34704_set_voltage, + .get_voltage = mc34704_get_voltage, +}; + +static struct regulator_desc reg_mc34704[] = { + { + .name = "REG1_BKLT", + .id = MC34704_BKLT, + .ops = &mc34704_full_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE}, + { + .name = "REG2_CPU", + .id = MC34704_CPU, + .ops = &mc34704_partial_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE}, + { + .name = "REG3_CORE", + .id = MC34704_CORE, + .ops = &mc34704_partial_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE}, + { + .name = "REG4_DDR", + .id = MC34704_DDR, + .ops = &mc34704_partial_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE}, + { + .name = "REG5_PERS", + .id = MC34704_PERS, + .ops = &mc34704_full_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE}, +}; + +static int mc34704_regulator_probe(struct platform_device *pdev) +{ + struct regulator_dev *rdev; + + /* register regulator */ + rdev = regulator_register(®_mc34704[pdev->id], &pdev->dev, + pdev->dev.platform_data, + (void *)&mc34704_reg_priv[pdev->id]); + if (IS_ERR(rdev)) { + dev_err(&pdev->dev, "failed to register %s\n", + reg_mc34704[pdev->id].name); + return PTR_ERR(rdev); + } + + return 0; +} + +static int mc34704_regulator_remove(struct platform_device *pdev) +{ + struct regulator_dev *rdev = platform_get_drvdata(pdev); + + regulator_unregister(rdev); + + return 0; +} + +int mc34704_register_regulator(struct mc34704 *mc34704, int reg, + struct regulator_init_data *initdata) +{ + struct platform_device *pdev; + int ret; + + if (mc34704->pmic.pdev[reg]) + return -EBUSY; + + pdev = platform_device_alloc("mc34704-regulatr", reg); + if (!pdev) + return -ENOMEM; + + mc34704->pmic.pdev[reg] = pdev; + + initdata->driver_data = mc34704; + + pdev->dev.platform_data = initdata; + pdev->dev.driver_data = &mc34704_reg_priv[reg]; + pdev->dev.parent = mc34704->dev; + platform_set_drvdata(pdev, mc34704); + ret = platform_device_add(pdev); + + if (ret != 0) { + dev_err(mc34704->dev, "Failed to register regulator %d: %d\n", + reg, ret); + platform_device_del(pdev); + mc34704->pmic.pdev[reg] = NULL; + } + + return ret; +} +EXPORT_SYMBOL_GPL(mc34704_register_regulator); + +static struct platform_driver mc34704_regulator_driver = { + .probe = mc34704_regulator_probe, + .remove = mc34704_regulator_remove, + .driver = { + .name = "mc34704-regulatr", + }, +}; + +static int __init mc34704_regulator_init(void) +{ + return platform_driver_register(&mc34704_regulator_driver); +} +subsys_initcall(mc34704_regulator_init); + +static void __exit mc34704_regulator_exit(void) +{ + platform_driver_unregister(&mc34704_regulator_driver); +} +module_exit(mc34704_regulator_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MC34704 Regulator Driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/regulator/reg-mc9s08dz60.c b/drivers/regulator/reg-mc9s08dz60.c new file mode 100644 index 000000000000..f2748e99fd80 --- /dev/null +++ b/drivers/regulator/reg-mc9s08dz60.c @@ -0,0 +1,236 @@ +/* + * Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* lcd */ +static int mc9s08dz60_lcd_enable(struct regulator_dev *reg) +{ + return pmic_gpio_set_bit_val(MCU_GPIO_REG_GPIO_CONTROL_1, 6, 1); +} + +static int mc9s08dz60_lcd_disable(struct regulator_dev *reg) +{ + return pmic_gpio_set_bit_val(MCU_GPIO_REG_GPIO_CONTROL_1, 6, 0); +} + +static struct regulator_ops mc9s08dz60_lcd_ops = { + .enable = mc9s08dz60_lcd_enable, + .disable = mc9s08dz60_lcd_disable, +}; + +/* wifi */ +static int mc9s08dz60_wifi_enable(struct regulator_dev *reg) +{ + return pmic_gpio_set_bit_val(MCU_GPIO_REG_GPIO_CONTROL_1, 5, 1); +} + +static int mc9s08dz60_wifi_disable(struct regulator_dev *reg) +{ + return pmic_gpio_set_bit_val(MCU_GPIO_REG_GPIO_CONTROL_1, 5, 0); +} + +static struct regulator_ops mc9s08dz60_wifi_ops = { + .enable = mc9s08dz60_wifi_enable, + .disable = mc9s08dz60_wifi_disable, +}; + +/* hdd */ +static int mc9s08dz60_hdd_enable(struct regulator_dev *reg) +{ + return pmic_gpio_set_bit_val(MCU_GPIO_REG_GPIO_CONTROL_1, 4, 1); +} + +static int mc9s08dz60_hdd_disable(struct regulator_dev *reg) +{ + return pmic_gpio_set_bit_val(MCU_GPIO_REG_GPIO_CONTROL_1, 4, 0); +} + +static struct regulator_ops mc9s08dz60_hdd_ops = { + .enable = mc9s08dz60_hdd_enable, + .disable = mc9s08dz60_hdd_disable, +}; + +/* gps */ +static int mc9s08dz60_gps_enable(struct regulator_dev *reg) +{ + return pmic_gpio_set_bit_val(MCU_GPIO_REG_GPIO_CONTROL_2, 0, 1); +} + +static int mc9s08dz60_gps_disable(struct regulator_dev *reg) +{ + return pmic_gpio_set_bit_val(MCU_GPIO_REG_GPIO_CONTROL_2, 0, 0); +} + +static struct regulator_ops mc9s08dz60_gps_ops = { + .enable = mc9s08dz60_gps_enable, + .disable = mc9s08dz60_gps_disable, +}; + +/* speaker */ +static int mc9s08dz60_speaker_enable(struct regulator_dev *reg) +{ + return pmic_gpio_set_bit_val(MCU_GPIO_REG_GPIO_CONTROL_1, 0, 1); +} + +static int mc9s08dz60_speaker_disable(struct regulator_dev *reg) +{ + return pmic_gpio_set_bit_val(MCU_GPIO_REG_GPIO_CONTROL_1, 0, 0); +} + +static struct regulator_ops mc9s08dz60_speaker_ops = { + .enable = mc9s08dz60_speaker_enable, + .disable = mc9s08dz60_speaker_disable, +}; + +static struct regulator_desc mc9s08dz60_reg[] = { + { + .name = "LCD", + .id = MC9S08DZ60_LCD, + .ops = &mc9s08dz60_lcd_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "WIFI", + .id = MC9S08DZ60_WIFI, + .ops = &mc9s08dz60_wifi_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "HDD", + .id = MC9S08DZ60_HDD, + .ops = &mc9s08dz60_hdd_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "GPS", + .id = MC9S08DZ60_GPS, + .ops = &mc9s08dz60_gps_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + { + .name = "SPKR", + .id = MC9S08DZ60_SPKR, + .ops = &mc9s08dz60_speaker_ops, + .irq = 0, + .type = REGULATOR_VOLTAGE, + .owner = THIS_MODULE + }, + +}; + +static int mc9s08dz60_regulator_probe(struct platform_device *pdev) +{ + struct regulator_dev *rdev; + + /* register regulator */ + rdev = regulator_register(&mc9s08dz60_reg[pdev->id], &pdev->dev, + pdev->dev.platform_data, + dev_get_drvdata(&pdev->dev)); + if (IS_ERR(rdev)) { + dev_err(&pdev->dev, "failed to register %s\n", + mc9s08dz60_reg[pdev->id].name); + return PTR_ERR(rdev); + } + + return 0; +} + + +static int mc9s08dz60_regulator_remove(struct platform_device *pdev) +{ + struct regulator_dev *rdev = platform_get_drvdata(pdev); + + regulator_unregister(rdev); + + return 0; +} + +int mc9s08dz60_register_regulator(struct mc9s08dz60 *mc9s08dz60, int reg, + struct regulator_init_data *initdata) +{ + struct platform_device *pdev; + int ret; + + if (mc9s08dz60->pmic.pdev[reg]) + return -EBUSY; + + pdev = platform_device_alloc("mc9s08dz60-regu", reg); + if (!pdev) + return -ENOMEM; + + mc9s08dz60->pmic.pdev[reg] = pdev; + + initdata->driver_data = mc9s08dz60; + + pdev->dev.platform_data = initdata; + pdev->dev.parent = mc9s08dz60->dev; + platform_set_drvdata(pdev, mc9s08dz60); + ret = platform_device_add(pdev); + + if (ret != 0) { + dev_err(mc9s08dz60->dev, + "Failed to register regulator %d: %d\n", + reg, ret); + platform_device_del(pdev); + mc9s08dz60->pmic.pdev[reg] = NULL; + } + + return ret; +} +EXPORT_SYMBOL_GPL(mc9s08dz60_register_regulator); + +static struct platform_driver mc9s08dz60_regulator_driver = { + .probe = mc9s08dz60_regulator_probe, + .remove = mc9s08dz60_regulator_remove, + .driver = { + .name = "mc9s08dz60-regu", + }, +}; + +static int __init mc9s08dz60_regulator_init(void) +{ + return platform_driver_register(&mc9s08dz60_regulator_driver); +} +subsys_initcall(mc9s08dz60_regulator_init); + +static void __exit mc9s08dz60_regulator_exit(void) +{ + platform_driver_unregister(&mc9s08dz60_regulator_driver); +} +module_exit(mc9s08dz60_regulator_exit); + + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MC9S08DZ60 Regulator driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/rtc/Kconfig b/drivers/rtc/Kconfig index 10ba12c8c5e0..76d846a7039e 100644 --- a/drivers/rtc/Kconfig +++ b/drivers/rtc/Kconfig @@ -818,6 +818,52 @@ config RTC_DRV_PXA This RTC driver uses PXA RTC registers available since pxa27x series (RDxR, RYxR) instead of legacy RCNR, RTAR. +config RTC_MXC + tristate "Freescale MXC Real Time Clock" + depends on ARCH_MXC + depends on RTC_CLASS + help + Support for Freescale RTC MXC + +config RTC_DRV_MXC_V2 + tristate "Freescale MXC Secure Real Time Clock" + depends on ARCH_MXC + depends on RTC_CLASS + help + Support for Freescale SRTC MXC + +config RTC_DRV_IMXDI + tristate "Freescale IMX DryIce Real Time Clock" + depends on ARCH_MXC + depends on RTC_CLASS + help + Support for Freescale IMX DryIce RTC + +config RTC_MC13892 + tristate "Freescale MC13892 Real Time Clock" + depends on ARCH_MXC && MXC_PMIC_MC13892 + depends on RTC_CLASS + help + Support for Freescale MC13892 RTC + +config RTC_DRV_STMP3XXX + tristate "Sigmatel STMP3xxx series SoC RTC" + depends on ARCH_STMP3XXX && RTC_CLASS + help + Say Y here to get support for the real-time clock peripheral + on Sigmatel STMP3xxx series SoCs (tested on STMP3700). + + This driver can also be build as a module. If so, the module + will be called rtc-stmp3xxx. + +config RTC_DRV_MXS + tristate "Freescale MXS series SoC RTC" + depends on ARCH_MXS && RTC_CLASS + help + Say Y here to get support for the real-time clock peripheral + on Freescale MXS series SoCs + This driver can also be build as a module. If so, the module + will be called rtc-mxs. config RTC_DRV_SUN4V bool "SUN4V Hypervisor RTC" diff --git a/drivers/rtc/Makefile b/drivers/rtc/Makefile index 5adbba7cf89c..6d06d258419e 100644 --- a/drivers/rtc/Makefile +++ b/drivers/rtc/Makefile @@ -94,3 +94,8 @@ obj-$(CONFIG_RTC_DRV_VR41XX) += rtc-vr41xx.o obj-$(CONFIG_RTC_DRV_WM831X) += rtc-wm831x.o obj-$(CONFIG_RTC_DRV_WM8350) += rtc-wm8350.o obj-$(CONFIG_RTC_DRV_X1205) += rtc-x1205.o +obj-$(CONFIG_RTC_MXC) += rtc-mxc.o +obj-$(CONFIG_RTC_DRV_MXC_V2) += rtc-mxc_v2.o +obj-$(CONFIG_RTC_DRV_IMXDI) += rtc-imxdi.o +obj-$(CONFIG_RTC_MC13892) += rtc-mc13892.o +obj-$(CONFIG_RTC_DRV_MXS) += rtc-mxs.o diff --git a/drivers/rtc/rtc-imxdi.c b/drivers/rtc/rtc-imxdi.c new file mode 100644 index 000000000000..599c525a9f66 --- /dev/null +++ b/drivers/rtc/rtc-imxdi.c @@ -0,0 +1,581 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/* based on rtc-mc13892.c */ + +/* + * This driver uses the 47-bit 32 kHz counter in the Freescale DryIce block + * to implement a Linux RTC. Times and alarms are truncated to seconds. + * Since the RTC framework performs API locking via rtc->ops_lock the + * only simultaneous accesses we need to deal with is updating DryIce + * registers while servicing an alarm. + * + * Note that reading the DSR (DryIce Status Register) automatically clears + * the WCF (Write Complete Flag). All DryIce writes are synchronized to the + * LP (Low Power) domain and set the WCF upon completion. Writes to the + * DIER (DryIce Interrupt Enable Register) are the only exception. These + * occur at normal bus speeds and do not set WCF. Periodic interrupts are + * not supported by the hardware. + */ + +/* #define DEBUG */ +/* #define DI_DEBUG_REGIO */ + +#include +#include +#include +#include +#include +#include +#include +#include + +/* DryIce Register Definitions */ + +#define DTCMR 0x00 /* Time Counter MSB Reg */ +#define DTCLR 0x04 /* Time Counter LSB Reg */ + +#define DCAMR 0x08 /* Clock Alarm MSB Reg */ +#define DCALR 0x0c /* Clock Alarm LSB Reg */ +#define DCAMR_UNSET 0xFFFFFFFF /* doomsday - 1 sec */ + +#define DCR 0x10 /* Control Reg */ +#define DCR_TCE (1 << 3) /* Time Counter Enable */ + +#define DSR 0x14 /* Status Reg */ +#define DSR_WBF (1 << 10) /* Write Busy Flag */ +#define DSR_WNF (1 << 9) /* Write Next Flag */ +#define DSR_WCF (1 << 8) /* Write Complete Flag */ +#define DSR_WEF (1 << 7) /* Write Error Flag */ +#define DSR_CAF (1 << 4) /* Clock Alarm Flag */ +#define DSR_NVF (1 << 1) /* Non-Valid Flag */ +#define DSR_SVF (1 << 0) /* Security Violation Flag */ + +#define DIER 0x18 /* Interrupt Enable Reg */ +#define DIER_WNIE (1 << 9) /* Write Next Interrupt Enable */ +#define DIER_WCIE (1 << 8) /* Write Complete Interrupt Enable */ +#define DIER_WEIE (1 << 7) /* Write Error Interrupt Enable */ +#define DIER_CAIE (1 << 4) /* Clock Alarm Interrupt Enable */ + +#ifndef DI_DEBUG_REGIO +/* dryice read register */ +#define di_read(pdata, reg) __raw_readl((pdata)->ioaddr + (reg)) + +/* dryice write register */ +#define di_write(pdata, val, reg) __raw_writel((val), (pdata)->ioaddr + (reg)) +#else +/* dryice read register - debug version */ +static inline u32 di_read(struct rtc_drv_data *pdata, int reg) +{ + u32 val = __raw_readl(pdata->ioaddr + reg); + pr_info("di_read(0x%02x) = 0x%08x\n", reg, val); + return val; +} + +/* dryice write register - debug version */ +static inline void di_write(struct rtc_drv_data *pdata, u32 val, int reg) +{ + printk(KERN_INFO "di_write(0x%08x, 0x%02x)\n", val, reg); + __raw_writel(val, pdata->ioaddr + reg); +} +#endif + +/* + * dryice write register with wait and error handling. + * all registers, except for DIER, should use this method. + */ +#define di_write_wait_err(pdata, val, reg, rc, label) \ + do { \ + if (di_write_wait((pdata), (val), (reg))) { \ + rc = -EIO; \ + goto label; \ + } \ + } while (0) + +struct rtc_drv_data { + struct platform_device *pdev; /* pointer to platform dev */ + struct rtc_device *rtc; /* pointer to rtc struct */ + unsigned long baseaddr; /* physical bass address */ + void __iomem *ioaddr; /* virtual base address */ + int size; /* size of register region */ + int irq; /* dryice normal irq */ + struct clk *clk; /* dryice clock control */ + u32 dsr; /* copy of dsr reg from isr */ + spinlock_t irq_lock; /* irq resource lock */ + wait_queue_head_t write_wait; /* write-complete queue */ + struct mutex write_mutex; /* force reg writes to be sequential */ + struct work_struct work; /* schedule alarm work */ +}; + +/* + * enable a dryice interrupt + */ +static inline void di_int_enable(struct rtc_drv_data *pdata, u32 intr) +{ + unsigned long flags; + + spin_lock_irqsave(&pdata->irq_lock, flags); + di_write(pdata, di_read(pdata, DIER) | intr, DIER); + spin_unlock_irqrestore(&pdata->irq_lock, flags); +} + +/* + * disable a dryice interrupt + */ +static inline void di_int_disable(struct rtc_drv_data *pdata, u32 intr) +{ + unsigned long flags; + + spin_lock_irqsave(&pdata->irq_lock, flags); + di_write(pdata, di_read(pdata, DIER) & ~intr, DIER); + spin_unlock_irqrestore(&pdata->irq_lock, flags); +} + +/* + * This function attempts to clear the dryice write-error flag. + * + * A dryice write error is similar to a bus fault and should not occur in + * normal operation. Clearing the flag requires another write, so the root + * cause of the problem may need to be fixed before the flag can be cleared. + */ +static void clear_write_error(struct rtc_drv_data *pdata) +{ + int cnt; + + dev_warn(&pdata->pdev->dev, "WARNING: Register write error!\n"); + + for (;;) { + /* clear the write error flag */ + di_write(pdata, DSR_WEF, DSR); + + /* wait for it to take effect */ + for (cnt = 0; cnt < 100; cnt++) { + if ((di_read(pdata, DSR) & DSR_WEF) == 0) + return; + udelay(10); + } + dev_err(&pdata->pdev->dev, + "ERROR: Cannot clear write-error flag!\n"); + } +} + +/* + * Write a dryice register and wait until it completes. + * + * This function uses interrupts to determine when the + * write has completed. + */ +static int di_write_wait(struct rtc_drv_data *pdata, u32 val, int reg) +{ + int ret; + int rc = 0; + + /* serialize register writes */ + mutex_lock(&pdata->write_mutex); + + /* enable the write-complete interrupt */ + di_int_enable(pdata, DIER_WCIE); + + pdata->dsr = 0; + + /* do the register write */ + di_write(pdata, val, reg); + + /* wait for the write to finish */ + ret = wait_event_interruptible_timeout(pdata->write_wait, + pdata->dsr & (DSR_WCF | DSR_WEF), + 1 * HZ); + if (ret == 0) + dev_warn(&pdata->pdev->dev, "Write-wait timeout\n"); + + /* check for write error */ + if (pdata->dsr & DSR_WEF) { + clear_write_error(pdata); + rc = -EIO; + } + mutex_unlock(&pdata->write_mutex); + return rc; +} + +/* + * rtc device ioctl + * + * The rtc framework handles the basic rtc ioctls on behalf + * of the driver by calling the functions registered in the + * rtc_ops structure. + */ +static int dryice_rtc_ioctl(struct device *dev, unsigned int cmd, + unsigned long arg) +{ + struct rtc_drv_data *pdata = dev_get_drvdata(dev); + + dev_dbg(dev, "%s(0x%x)\n", __func__, cmd); + switch (cmd) { + case RTC_AIE_OFF: /* alarm disable */ + di_int_disable(pdata, DIER_CAIE); + return 0; + + case RTC_AIE_ON: /* alarm enable */ + di_int_enable(pdata, DIER_CAIE); + return 0; + } + return -ENOIOCTLCMD; +} + +/* + * read the seconds portion of the current time from the dryice time counter + */ +static int dryice_rtc_read_time(struct device *dev, struct rtc_time *tm) +{ + struct rtc_drv_data *pdata = dev_get_drvdata(dev); + unsigned long now; + + dev_dbg(dev, "%s\n", __func__); + now = di_read(pdata, DTCMR); + rtc_time_to_tm(now, tm); + + return 0; +} + +/* + * set the seconds portion of dryice time counter and clear the + * fractional part. + */ +static int dryice_rtc_set_time(struct device *dev, struct rtc_time *tm) +{ + struct rtc_drv_data *pdata = dev_get_drvdata(dev); + unsigned long now; + int rc; + + dev_dbg(dev, "%s\n", __func__); + rc = rtc_tm_to_time(tm, &now); + if (rc == 0) { + /* zero the fractional part first */ + di_write_wait_err(pdata, 0, DTCLR, rc, err); + di_write_wait_err(pdata, now, DTCMR, rc, err); + } +err: + return rc; +} + +/* + * read the seconds portion of the alarm register. + * the fractional part of the alarm register is always zero. + */ +static int dryice_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alarm) +{ + struct rtc_drv_data *pdata = dev_get_drvdata(dev); + u32 dcamr; + + dev_dbg(dev, "%s\n", __func__); + dcamr = di_read(pdata, DCAMR); + rtc_time_to_tm(dcamr, &alarm->time); + + /* alarm is enabled if the interrupt is enabled */ + alarm->enabled = (di_read(pdata, DIER) & DIER_CAIE) != 0; + + /* don't allow the DSR read to mess up DSR_WCF */ + mutex_lock(&pdata->write_mutex); + + /* alarm is pending if the alarm flag is set */ + alarm->pending = (di_read(pdata, DSR) & DSR_CAF) != 0; + + mutex_unlock(&pdata->write_mutex); + + return 0; +} + +/* + * set the seconds portion of dryice alarm register + */ +static int dryice_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alarm) +{ + struct rtc_drv_data *pdata = dev_get_drvdata(dev); + unsigned long now; + unsigned long alarm_time; + int rc; + + dev_dbg(dev, "%s\n", __func__); + rc = rtc_tm_to_time(&alarm->time, &alarm_time); + if (rc) + return rc; + + /* don't allow setting alarm in the past */ + now = di_read(pdata, DTCMR); + if (alarm_time < now) + return -EINVAL; + + /* write the new alarm time */ + di_write_wait_err(pdata, (u32)alarm_time, DCAMR, rc, err); + + if (alarm->enabled) + di_int_enable(pdata, DIER_CAIE); /* enable alarm intr */ + else + di_int_disable(pdata, DIER_CAIE); /* disable alarm intr */ +err: + return rc; +} + +static struct rtc_class_ops dryice_rtc_ops = { + .ioctl = dryice_rtc_ioctl, + .read_time = dryice_rtc_read_time, + .set_time = dryice_rtc_set_time, + .read_alarm = dryice_rtc_read_alarm, + .set_alarm = dryice_rtc_set_alarm, +}; + +/* + * dryice "normal" interrupt handler + */ +static irqreturn_t dryice_norm_irq(int irq, void *dev_id) +{ + struct rtc_drv_data *pdata = dev_id; + u32 dsr, dier; + irqreturn_t rc = IRQ_NONE; + + dier = di_read(pdata, DIER); + + /* handle write complete and write error cases */ + if ((dier & DIER_WCIE)) { + /*If the write wait queue is empty then there is no pending + operations. It means the interrupt is for DryIce -Security. + IRQ must be returned as none.*/ + if (list_empty_careful(&pdata->write_wait.task_list)) + return rc; + + /* DSR_WCF clears itself on DSR read */ + dsr = di_read(pdata, DSR); + if ((dsr & (DSR_WCF | DSR_WEF))) { + /* mask the interrupt */ + di_int_disable(pdata, DIER_WCIE); + + /* save the dsr value for the wait queue */ + pdata->dsr |= dsr; + + wake_up_interruptible(&pdata->write_wait); + rc = IRQ_HANDLED; + } + } + + /* handle the alarm case */ + if ((dier & DIER_CAIE)) { + /* DSR_WCF clears itself on DSR read */ + dsr = di_read(pdata, DSR); + if (dsr & DSR_CAF) { + /* mask the interrupt */ + di_int_disable(pdata, DIER_CAIE); + + /* finish alarm in user context */ + schedule_work(&pdata->work); + rc = IRQ_HANDLED; + } + } + return rc; +} + +/* + * post the alarm event from user context so it can sleep + * on the write completion. + */ +static void dryice_work(struct work_struct *work) +{ + struct rtc_drv_data *pdata = container_of(work, struct rtc_drv_data, + work); + int rc; + + /* dismiss the interrupt (ignore error) */ + di_write_wait_err(pdata, DSR_CAF, DSR, rc, err); +err: + /* + * pass the alarm event to the rtc framework. note that + * rtc_update_irq expects to be called with interrupts off. + */ + local_irq_disable(); + rtc_update_irq(pdata->rtc, 1, RTC_AF | RTC_IRQF); + local_irq_enable(); +} + +/* + * probe for dryice rtc device + */ +static int dryice_rtc_probe(struct platform_device *pdev) +{ + struct rtc_device *rtc; + struct resource *res; + struct rtc_drv_data *pdata = NULL; + void __iomem *ioaddr = NULL; + int rc = 0; + + dev_dbg(&pdev->dev, "%s\n", __func__); + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!res) + return -ENODEV; + + pdata = kzalloc(sizeof(*pdata), GFP_KERNEL); + if (!pdata) + return -ENOMEM; + + pdata->pdev = pdev; + pdata->irq = -1; + pdata->size = res->end - res->start + 1; + + if (!request_mem_region(res->start, pdata->size, pdev->name)) { + rc = -EBUSY; + goto err; + } + pdata->baseaddr = res->start; + ioaddr = ioremap(pdata->baseaddr, pdata->size); + if (!ioaddr) { + rc = -ENOMEM; + goto err; + } + pdata->ioaddr = ioaddr; + pdata->irq = platform_get_irq(pdev, 0); + + init_waitqueue_head(&pdata->write_wait); + + INIT_WORK(&pdata->work, dryice_work); + + mutex_init(&pdata->write_mutex); + + pdata->clk = clk_get(NULL, "dryice_clk"); + clk_enable(pdata->clk); + + if (pdata->irq >= 0) { + if (request_irq(pdata->irq, dryice_norm_irq, IRQF_SHARED, + pdev->name, pdata) < 0) { + dev_warn(&pdev->dev, "interrupt not available.\n"); + pdata->irq = -1; + goto err; + } + } + + /* + * Initialize dryice hardware + */ + + /* put dryice into valid state */ + if (di_read(pdata, DSR) & DSR_NVF) + di_write_wait_err(pdata, DSR_NVF | DSR_SVF, DSR, rc, err); + + /* mask alarm interrupt */ + di_int_disable(pdata, DIER_CAIE); + + /* initialize alarm */ + di_write_wait_err(pdata, DCAMR_UNSET, DCAMR, rc, err); + di_write_wait_err(pdata, 0, DCALR, rc, err); + + /* clear alarm flag */ + if (di_read(pdata, DSR) & DSR_CAF) + di_write_wait_err(pdata, DSR_CAF, DSR, rc, err); + + /* the timer won't count if it has never been written to */ + if (!di_read(pdata, DTCMR)) + di_write_wait_err(pdata, 0, DTCMR, rc, err); + + /* start keeping time */ + if (!(di_read(pdata, DCR) & DCR_TCE)) + di_write_wait_err(pdata, di_read(pdata, DCR) | DCR_TCE, DCR, + rc, err); + + rtc = rtc_device_register(pdev->name, &pdev->dev, + &dryice_rtc_ops, THIS_MODULE); + if (IS_ERR(rtc)) { + rc = PTR_ERR(rtc); + goto err; + } + pdata->rtc = rtc; + platform_set_drvdata(pdev, pdata); + + return 0; +err: + if (pdata->rtc) + rtc_device_unregister(pdata->rtc); + + if (pdata->irq >= 0) + free_irq(pdata->irq, pdata); + + if (pdata->clk) { + clk_disable(pdata->clk); + clk_put(pdata->clk); + } + + if (pdata->ioaddr) + iounmap(pdata->ioaddr); + + if (pdata->baseaddr) + release_mem_region(pdata->baseaddr, pdata->size); + + kfree(pdata); + + return rc; +} + +static int __exit dryice_rtc_remove(struct platform_device *pdev) +{ + struct rtc_drv_data *pdata = platform_get_drvdata(pdev); + + flush_scheduled_work(); + + if (pdata->rtc) + rtc_device_unregister(pdata->rtc); + + /* mask alarm interrupt */ + di_int_disable(pdata, DIER_CAIE); + + if (pdata->irq >= 0) + free_irq(pdata->irq, pdata); + + if (pdata->clk) { + clk_disable(pdata->clk); + clk_put(pdata->clk); + } + + if (pdata->ioaddr) + iounmap(pdata->ioaddr); + + if (pdata->baseaddr) + release_mem_region(pdata->baseaddr, pdata->size); + + kfree(pdata); + + return 0; +} + +static struct platform_driver dryice_rtc_driver = { + .driver = { + .name = "imxdi_rtc", + .owner = THIS_MODULE, + }, + .probe = dryice_rtc_probe, + .remove = __exit_p(dryice_rtc_remove), +}; + +static int __init dryice_rtc_init(void) +{ + pr_info("IMXDI Realtime Clock Driver (RTC)\n"); + return platform_driver_register(&dryice_rtc_driver); +} + +static void __exit dryice_rtc_exit(void) +{ + platform_driver_unregister(&dryice_rtc_driver); +} + +module_init(dryice_rtc_init); +module_exit(dryice_rtc_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("IMXDI Realtime Clock Driver (RTC)"); +MODULE_LICENSE("GPL"); diff --git a/drivers/rtc/rtc-mc13892.c b/drivers/rtc/rtc-mc13892.c new file mode 100644 index 000000000000..8abe1ba02bc0 --- /dev/null +++ b/drivers/rtc/rtc-mc13892.c @@ -0,0 +1,257 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include + +#include +#include + +#define RTC_TIME_LSH 0 +#define RTC_DAY_LSH 0 +#define RTCALARM_TIME_LSH 0 +#define RTCALARM_DAY_LSH 0 + +#define RTC_TIME_WID 17 +#define RTC_DAY_WID 15 +#define RTCALARM_TIME_WID 17 +#define RTCALARM_DAY_WID 15 + +static unsigned long rtc_status; + +static int mxc_rtc_open(struct device *dev) +{ + if (test_and_set_bit(1, &rtc_status)) + return -EBUSY; + return 0; +} + +static void mxc_rtc_release(struct device *dev) +{ + clear_bit(1, &rtc_status); +} + +static int mxc_rtc_ioctl(struct device *dev, unsigned int cmd, + unsigned long arg) +{ + switch (cmd) { + case RTC_AIE_OFF: + pr_debug("alarm off\n"); + CHECK_ERROR(pmic_write_reg(REG_RTC_ALARM, 0x100000, 0x100000)); + return 0; + case RTC_AIE_ON: + pr_debug("alarm on\n"); + CHECK_ERROR(pmic_write_reg(REG_RTC_ALARM, 0, 0x100000)); + return 0; + } + + return -ENOIOCTLCMD; +} + +static int mxc_rtc_read_time(struct device *dev, struct rtc_time *tm) +{ + unsigned int tod_reg_val = 0; + unsigned int day_reg_val = 0, day_reg_val2; + unsigned int mask, value; + unsigned long time; + + do { + mask = BITFMASK(RTC_DAY); + CHECK_ERROR(pmic_read_reg(REG_RTC_DAY, &value, mask)); + day_reg_val = BITFEXT(value, RTC_DAY); + + mask = BITFMASK(RTC_TIME); + CHECK_ERROR(pmic_read_reg(REG_RTC_TIME, &value, mask)); + tod_reg_val = BITFEXT(value, RTC_TIME); + + mask = BITFMASK(RTC_DAY); + CHECK_ERROR(pmic_read_reg(REG_RTC_DAY, &value, mask)); + day_reg_val2 = BITFEXT(value, RTC_DAY); + } while (day_reg_val != day_reg_val2); + + time = (unsigned long)((unsigned long)(tod_reg_val & + 0x0001FFFF) + + (unsigned long)(day_reg_val * 86400)); + + rtc_time_to_tm(time, tm); + + return 0; +} + +static int mxc_rtc_set_time(struct device *dev, struct rtc_time *tm) +{ + unsigned int tod_reg_val = 0; + unsigned int day_reg_val, day_reg_val2 = 0; + unsigned int mask, value; + unsigned long time; + + if (rtc_valid_tm(tm)) + return -1; + + rtc_tm_to_time(tm, &time); + + tod_reg_val = time % 86400; + day_reg_val = time / 86400; + + do { + mask = BITFMASK(RTC_DAY); + value = BITFVAL(RTC_DAY, day_reg_val); + CHECK_ERROR(pmic_write_reg(REG_RTC_DAY, value, mask)); + + mask = BITFMASK(RTC_TIME); + value = BITFVAL(RTC_TIME, tod_reg_val); + CHECK_ERROR(pmic_write_reg(REG_RTC_TIME, value, mask)); + + mask = BITFMASK(RTC_DAY); + CHECK_ERROR(pmic_read_reg(REG_RTC_DAY, &value, mask)); + day_reg_val2 = BITFEXT(value, RTC_DAY); + } while (day_reg_val != day_reg_val2); + + return 0; +} + +static int mxc_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alrm) +{ + unsigned int tod_reg_val = 0; + unsigned int day_reg_val = 0; + unsigned int mask, value; + unsigned long time; + + mask = BITFMASK(RTCALARM_TIME); + CHECK_ERROR(pmic_read_reg(REG_RTC_ALARM, &value, mask)); + tod_reg_val = BITFEXT(value, RTCALARM_TIME); + + mask = BITFMASK(RTCALARM_DAY); + CHECK_ERROR(pmic_read_reg(REG_RTC_DAY_ALARM, &value, mask)); + day_reg_val = BITFEXT(value, RTCALARM_DAY); + + time = (unsigned long)((unsigned long)(tod_reg_val & + 0x0001FFFF) + + (unsigned long)(day_reg_val * 86400)); + rtc_time_to_tm(time, &(alrm->time)); + + return 0; +} + +static int mxc_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alrm) +{ + unsigned int tod_reg_val = 0; + unsigned int day_reg_val = 0; + unsigned int mask, value; + unsigned long time; + + if (rtc_valid_tm(&alrm->time)) + return -1; + + rtc_tm_to_time(&alrm->time, &time); + + tod_reg_val = time % 86400; + day_reg_val = time / 86400; + + mask = BITFMASK(RTCALARM_TIME); + value = BITFVAL(RTCALARM_TIME, tod_reg_val); + CHECK_ERROR(pmic_write_reg(REG_RTC_ALARM, value, mask)); + + mask = BITFMASK(RTCALARM_DAY); + value = BITFVAL(RTCALARM_DAY, day_reg_val); + CHECK_ERROR(pmic_write_reg(REG_RTC_DAY_ALARM, value, mask)); + + return 0; +} + +struct rtc_drv_data { + struct rtc_device *rtc; + pmic_event_callback_t event; +}; + +static struct rtc_class_ops mxc_rtc_ops = { + .open = mxc_rtc_open, + .release = mxc_rtc_release, + .ioctl = mxc_rtc_ioctl, + .read_time = mxc_rtc_read_time, + .set_time = mxc_rtc_set_time, + .read_alarm = mxc_rtc_read_alarm, + .set_alarm = mxc_rtc_set_alarm, +}; + +static void mxc_rtc_alarm_int(void *data) +{ + struct rtc_drv_data *pdata = data; + + rtc_update_irq(pdata->rtc, 1, RTC_AF | RTC_IRQF); +} + +static int mxc_rtc_probe(struct platform_device *pdev) +{ + struct rtc_drv_data *pdata = NULL; + + printk(KERN_INFO "mc13892 rtc probe start\n"); + + pdata = kzalloc(sizeof(*pdata), GFP_KERNEL); + + if (!pdata) + return -ENOMEM; + + pdata->event.func = mxc_rtc_alarm_int; + pdata->event.param = pdata; + CHECK_ERROR(pmic_event_subscribe(EVENT_TODAI, pdata->event)); + + device_init_wakeup(&pdev->dev, 1); + pdata->rtc = rtc_device_register(pdev->name, &pdev->dev, + &mxc_rtc_ops, THIS_MODULE); + + platform_set_drvdata(pdev, pdata); + if (IS_ERR(pdata->rtc)) + return -1; + + printk(KERN_INFO "mc13892 rtc probe succeed\n"); + return 0; +} + +static int __exit mxc_rtc_remove(struct platform_device *pdev) +{ + struct rtc_drv_data *pdata = platform_get_drvdata(pdev); + + rtc_device_unregister(pdata->rtc); + CHECK_ERROR(pmic_event_unsubscribe(EVENT_TODAI, pdata->event)); + + return 0; +} + +static struct platform_driver mxc_rtc_driver = { + .driver = { + .name = "pmic_rtc", + }, + .probe = mxc_rtc_probe, + .remove = __exit_p(mxc_rtc_remove), +}; + +static int __init mxc_rtc_init(void) +{ + return platform_driver_register(&mxc_rtc_driver); +} + +static void __exit mxc_rtc_exit(void) +{ + platform_driver_unregister(&mxc_rtc_driver); + +} + +module_init(mxc_rtc_init); +module_exit(mxc_rtc_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MC13892 Realtime Clock Driver (RTC)"); +MODULE_LICENSE("GPL"); diff --git a/drivers/rtc/rtc-mxc.c b/drivers/rtc/rtc-mxc.c index 25ec921db07c..850be4842d4f 100644 --- a/drivers/rtc/rtc-mxc.c +++ b/drivers/rtc/rtc-mxc.c @@ -1,5 +1,5 @@ /* - * Copyright 2004-2008 Freescale Semiconductor, Inc. All Rights Reserved. + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. * * The code contained herein is licensed under the GNU General Public * License. You may obtain a copy of the GNU General Public License @@ -17,8 +17,6 @@ #include #include -#include - #define RTC_INPUT_CLK_32768HZ (0x00 << 5) #define RTC_INPUT_CLK_32000HZ (0x01 << 5) #define RTC_INPUT_CLK_38400HZ (0x02 << 5) diff --git a/drivers/rtc/rtc-mxc_v2.c b/drivers/rtc/rtc-mxc_v2.c new file mode 100644 index 000000000000..61e3265cc413 --- /dev/null +++ b/drivers/rtc/rtc-mxc_v2.c @@ -0,0 +1,766 @@ +/* + * Copyright (C) 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +/* + * Implementation based on rtc-ds1553.c + */ + +/*! + * @defgroup RTC Real Time Clock (RTC) Driver + */ +/*! + * @file rtc-mxc_v2.c + * @brief Real Time Clock interface + * + * This file contains Real Time Clock interface for Linux. + * + * @ingroup RTC + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SRTC_LPSCLR_LLPSC_LSH 17 /* start bit for LSB time value */ + +#define SRTC_LPPDR_INIT 0x41736166 /* init for glitch detect */ + +#define SRTC_LPCR_SWR_LP (1 << 0) /* lp software reset */ +#define SRTC_LPCR_EN_LP (1 << 3) /* lp enable */ +#define SRTC_LPCR_WAE (1 << 4) /* lp wakeup alarm enable */ +#define SRTC_LPCR_SAE (1 << 5) /* lp security alarm enable */ +#define SRTC_LPCR_SI (1 << 6) /* lp security interrupt enable */ +#define SRTC_LPCR_ALP (1 << 7) /* lp alarm flag */ +#define SRTC_LPCR_LTC (1 << 8) /* lp lock time counter */ +#define SRTC_LPCR_LMC (1 << 9) /* lp lock monotonic counter */ +#define SRTC_LPCR_SV (1 << 10) /* lp security violation */ +#define SRTC_LPCR_NSA (1 << 11) /* lp non secure access */ +#define SRTC_LPCR_NVEIE (1 << 12) /* lp non valid state exit int en */ +#define SRTC_LPCR_IEIE (1 << 13) /* lp init state exit int enable */ +#define SRTC_LPCR_NVE (1 << 14) /* lp non valid state exit bit */ +#define SRTC_LPCR_IE (1 << 15) /* lp init state exit bit */ + +#define SRTC_LPCR_ALL_INT_EN (SRTC_LPCR_WAE | SRTC_LPCR_SAE | \ + SRTC_LPCR_SI | SRTC_LPCR_ALP | \ + SRTC_LPCR_NVEIE | SRTC_LPCR_IEIE) + +#define SRTC_LPSR_TRI (1 << 0) /* lp time read invalidate */ +#define SRTC_LPSR_PGD (1 << 1) /* lp power supply glitc detected */ +#define SRTC_LPSR_CTD (1 << 2) /* lp clock tampering detected */ +#define SRTC_LPSR_ALP (1 << 3) /* lp alarm flag */ +#define SRTC_LPSR_MR (1 << 4) /* lp monotonic counter rollover */ +#define SRTC_LPSR_TR (1 << 5) /* lp time rollover */ +#define SRTC_LPSR_EAD (1 << 6) /* lp external alarm detected */ +#define SRTC_LPSR_IT0 (1 << 7) /* lp IIM throttle */ +#define SRTC_LPSR_IT1 (1 << 8) +#define SRTC_LPSR_IT2 (1 << 9) +#define SRTC_LPSR_SM0 (1 << 10) /* lp security mode */ +#define SRTC_LPSR_SM1 (1 << 11) +#define SRTC_LPSR_STATE_LP0 (1 << 12) /* lp state */ +#define SRTC_LPSR_STATE_LP1 (1 << 13) +#define SRTC_LPSR_NVES (1 << 14) /* lp non-valid state exit status */ +#define SRTC_LPSR_IES (1 << 15) /* lp init state exit status */ + +#define MAX_PIE_NUM 15 +#define MAX_PIE_FREQ 32768 +#define MIN_PIE_FREQ 1 + +#define SRTC_PI0 (1 << 0) +#define SRTC_PI1 (1 << 1) +#define SRTC_PI2 (1 << 2) +#define SRTC_PI3 (1 << 3) +#define SRTC_PI4 (1 << 4) +#define SRTC_PI5 (1 << 5) +#define SRTC_PI6 (1 << 6) +#define SRTC_PI7 (1 << 7) +#define SRTC_PI8 (1 << 8) +#define SRTC_PI9 (1 << 9) +#define SRTC_PI10 (1 << 10) +#define SRTC_PI11 (1 << 11) +#define SRTC_PI12 (1 << 12) +#define SRTC_PI13 (1 << 13) +#define SRTC_PI14 (1 << 14) +#define SRTC_PI15 (1 << 15) + +#define PIT_ALL_ON (SRTC_PI1 | SRTC_PI2 | SRTC_PI3 | \ + SRTC_PI4 | SRTC_PI5 | SRTC_PI6 | SRTC_PI7 | \ + SRTC_PI8 | SRTC_PI9 | SRTC_PI10 | SRTC_PI11 | \ + SRTC_PI12 | SRTC_PI13 | SRTC_PI14 | SRTC_PI15) + +#define SRTC_SWR_HP (1 << 0) /* hp software reset */ +#define SRTC_EN_HP (1 << 3) /* hp enable */ +#define SRTC_TS (1 << 4) /* time syncronize hp with lp */ + +#define SRTC_IE_AHP (1 << 16) /* Alarm HP Interrupt Enable bit */ +#define SRTC_IE_WDHP (1 << 18) /* Write Done HP Interrupt Enable bit */ +#define SRTC_IE_WDLP (1 << 19) /* Write Done LP Interrupt Enable bit */ + +#define SRTC_ISR_AHP (1 << 16) /* interrupt status: alarm hp */ +#define SRTC_ISR_WDHP (1 << 18) /* interrupt status: write done hp */ +#define SRTC_ISR_WDLP (1 << 19) /* interrupt status: write done lp */ +#define SRTC_ISR_WPHP (1 << 20) /* interrupt status: write pending hp */ +#define SRTC_ISR_WPLP (1 << 21) /* interrupt status: write pending lp */ + +#define SRTC_LPSCMR 0x00 /* LP Secure Counter MSB Reg */ +#define SRTC_LPSCLR 0x04 /* LP Secure Counter LSB Reg */ +#define SRTC_LPSAR 0x08 /* LP Secure Alarm Reg */ +#define SRTC_LPSMCR 0x0C /* LP Secure Monotonic Counter Reg */ +#define SRTC_LPCR 0x10 /* LP Control Reg */ +#define SRTC_LPSR 0x14 /* LP Status Reg */ +#define SRTC_LPPDR 0x18 /* LP Power Supply Glitch Detector Reg */ +#define SRTC_LPGR 0x1C /* LP General Purpose Reg */ +#define SRTC_HPCMR 0x20 /* HP Counter MSB Reg */ +#define SRTC_HPCLR 0x24 /* HP Counter LSB Reg */ +#define SRTC_HPAMR 0x28 /* HP Alarm MSB Reg */ +#define SRTC_HPALR 0x2C /* HP Alarm LSB Reg */ +#define SRTC_HPCR 0x30 /* HP Control Reg */ +#define SRTC_HPISR 0x34 /* HP Interrupt Status Reg */ +#define SRTC_HPIENR 0x38 /* HP Interrupt Enable Reg */ + +#define SRTC_SECMODE_MASK 0x3 /* the mask of SRTC security mode */ +#define SRTC_SECMODE_LOW 0x0 /* Low Security */ +#define SRTC_SECMODE_MED 0x1 /* Medium Security */ +#define SRTC_SECMODE_HIGH 0x2 /* High Security */ +#define SRTC_SECMODE_RESERVED 0x3 /* Reserved */ + +struct rtc_drv_data { + struct rtc_device *rtc; + void __iomem *ioaddr; + unsigned long baseaddr; + int irq; + struct clk *clk; + bool irq_enable; +}; + + +/* completion event for implementing RTC_WAIT_FOR_TIME_SET ioctl */ +DECLARE_COMPLETION(srtc_completion); +/* global to save difference of 47-bit counter value */ +static int64_t time_diff; + +/*! + * @defgroup RTC Real Time Clock (RTC) Driver + */ +/*! + * @file rtc-mxc.c + * @brief Real Time Clock interface + * + * This file contains Real Time Clock interface for Linux. + * + * @ingroup RTC + */ + +static unsigned long rtc_status; + +static DEFINE_SPINLOCK(rtc_lock); + +/*! + * This function does write synchronization for writes to the lp srtc block. + * To take care of the asynchronous CKIL clock, all writes from the IP domain + * will be synchronized to the CKIL domain. + */ +static inline void rtc_write_sync_lp(void __iomem *ioaddr) +{ + unsigned int i, count; + /* Wait for 3 CKIL cycles */ + for (i = 0; i < 3; i++) { + count = __raw_readl(ioaddr + SRTC_LPSCLR); + while + ((__raw_readl(ioaddr + SRTC_LPSCLR)) == count); + } +} + +/*! + * This function updates the RTC alarm registers and then clears all the + * interrupt status bits. + * + * @param alrm the new alarm value to be updated in the RTC + * + * @return 0 if successful; non-zero otherwise. + */ +static int rtc_update_alarm(struct device *dev, struct rtc_time *alrm) +{ + struct rtc_drv_data *pdata = dev_get_drvdata(dev); + void __iomem *ioaddr = pdata->ioaddr; + struct rtc_time alarm_tm, now_tm; + unsigned long now, time; + int ret; + + now = __raw_readl(ioaddr + SRTC_LPSCMR); + rtc_time_to_tm(now, &now_tm); + + alarm_tm.tm_year = now_tm.tm_year; + alarm_tm.tm_mon = now_tm.tm_mon; + alarm_tm.tm_mday = now_tm.tm_mday; + + alarm_tm.tm_hour = alrm->tm_hour; + alarm_tm.tm_min = alrm->tm_min; + alarm_tm.tm_sec = alrm->tm_sec; + + rtc_tm_to_time(&now_tm, &now); + rtc_tm_to_time(&alarm_tm, &time); + + if (time < now) { + time += 60 * 60 * 24; + rtc_time_to_tm(time, &alarm_tm); + } + ret = rtc_tm_to_time(&alarm_tm, &time); + + __raw_writel(time, ioaddr + SRTC_LPSAR); + + /* clear alarm interrupt status bit */ + __raw_writel(SRTC_LPSR_ALP, ioaddr + SRTC_LPSR); + + return ret; +} + +/*! + * This function is the RTC interrupt service routine. + * + * @param irq RTC IRQ number + * @param dev_id device ID which is not used + * + * @return IRQ_HANDLED as defined in the include/linux/interrupt.h file. + */ +static irqreturn_t mxc_rtc_interrupt(int irq, void *dev_id) +{ + struct platform_device *pdev = dev_id; + struct rtc_drv_data *pdata = platform_get_drvdata(pdev); + void __iomem *ioaddr = pdata->ioaddr; + u32 lp_status, lp_cr; + u32 events = 0; + + clk_enable(pdata->clk); + lp_status = __raw_readl(ioaddr + SRTC_LPSR); + lp_cr = __raw_readl(ioaddr + SRTC_LPCR); + + /* update irq data & counter */ + if (lp_status & SRTC_LPSR_ALP) { + if (lp_cr & SRTC_LPCR_ALP) + events |= (RTC_AF | RTC_IRQF); + + /* disable further lp alarm interrupts */ + lp_cr &= ~(SRTC_LPCR_ALP | SRTC_LPCR_WAE); + } + + /* Update interrupt enables */ + __raw_writel(lp_cr, ioaddr + SRTC_LPCR); + + /* If no interrupts are enabled, turn off interrupts in kernel */ + if (((lp_cr & SRTC_LPCR_ALL_INT_EN) == 0) && (pdata->irq_enable)) { + disable_irq_nosync(pdata->irq); + pdata->irq_enable = false; + } + + /* clear interrupt status */ + __raw_writel(lp_status, ioaddr + SRTC_LPSR); + clk_disable(pdata->clk); + + rtc_update_irq(pdata->rtc, 1, events); + return IRQ_HANDLED; +} + +/*! + * This function is used to open the RTC driver. + * + * @return 0 if successful; non-zero otherwise. + */ +static int mxc_rtc_open(struct device *dev) +{ + struct rtc_drv_data *pdata = dev_get_drvdata(dev); + clk_enable(pdata->clk); + + if (test_and_set_bit(1, &rtc_status)) + return -EBUSY; + return 0; +} + +/*! + * clear all interrupts and release the IRQ + */ +static void mxc_rtc_release(struct device *dev) +{ + struct rtc_drv_data *pdata = dev_get_drvdata(dev); + + clk_disable(pdata->clk); + + rtc_status = 0; +} + +/*! + * This function is used to support some ioctl calls directly. + * Other ioctl calls are supported indirectly through the + * arm/common/rtctime.c file. + * + * @param cmd ioctl command as defined in include/linux/rtc.h + * @param arg value for the ioctl command + * + * @return 0 if successful or negative value otherwise. + */ +static int mxc_rtc_ioctl(struct device *dev, unsigned int cmd, + unsigned long arg) +{ + struct rtc_drv_data *pdata = dev_get_drvdata(dev); + void __iomem *ioaddr = pdata->ioaddr; + unsigned long lock_flags = 0; + u32 lp_cr; + u64 time_47bit; + int retVal; + + switch (cmd) { + case RTC_AIE_OFF: + spin_lock_irqsave(&rtc_lock, lock_flags); + lp_cr = __raw_readl(ioaddr + SRTC_LPCR); + lp_cr &= ~(SRTC_LPCR_ALP | SRTC_LPCR_WAE); + if (((lp_cr & SRTC_LPCR_ALL_INT_EN) == 0) + && (pdata->irq_enable)) { + disable_irq(pdata->irq); + pdata->irq_enable = false; + } + __raw_writel(lp_cr, ioaddr + SRTC_LPCR); + spin_unlock_irqrestore(&rtc_lock, lock_flags); + return 0; + + case RTC_AIE_ON: + spin_lock_irqsave(&rtc_lock, lock_flags); + if (!pdata->irq_enable) { + enable_irq(pdata->irq); + pdata->irq_enable = true; + } + lp_cr = __raw_readl(ioaddr + SRTC_LPCR); + lp_cr |= SRTC_LPCR_ALP | SRTC_LPCR_WAE; + __raw_writel(lp_cr, ioaddr + SRTC_LPCR); + spin_unlock_irqrestore(&rtc_lock, lock_flags); + return 0; + + case RTC_READ_TIME_47BIT: + time_47bit = (((u64) __raw_readl(ioaddr + SRTC_LPSCMR)) << 32 | + ((u64) __raw_readl(ioaddr + SRTC_LPSCLR))); + time_47bit >>= SRTC_LPSCLR_LLPSC_LSH; + + if (arg && copy_to_user((u64 *) arg, &time_47bit, sizeof(u64))) + return -EFAULT; + + return 0; + + case RTC_WAIT_TIME_SET: + + /* don't block without releasing mutex first */ + mutex_unlock(&pdata->rtc->ops_lock); + + /* sleep until awakened by SRTC driver when LPSCMR is changed */ + wait_for_completion(&srtc_completion); + + /* relock mutex because rtc_dev_ioctl will unlock again */ + retVal = mutex_lock_interruptible(&pdata->rtc->ops_lock); + + /* copy the new time difference = new time - previous time + * to the user param. The difference is a signed value */ + if (arg && copy_to_user((int64_t *) arg, &time_diff, + sizeof(int64_t))) + return -EFAULT; + + return retVal; + + } + + return -ENOIOCTLCMD; +} + +/*! + * This function reads the current RTC time into tm in Gregorian date. + * + * @param tm contains the RTC time value upon return + * + * @return 0 if successful; non-zero otherwise. + */ +static int mxc_rtc_read_time(struct device *dev, struct rtc_time *tm) +{ + struct rtc_drv_data *pdata = dev_get_drvdata(dev); + void __iomem *ioaddr = pdata->ioaddr; + + rtc_time_to_tm(__raw_readl(ioaddr + SRTC_LPSCMR), tm); + return 0; +} + +/*! + * This function sets the internal RTC time based on tm in Gregorian date. + * + * @param tm the time value to be set in the RTC + * + * @return 0 if successful; non-zero otherwise. + */ +static int mxc_rtc_set_time(struct device *dev, struct rtc_time *tm) +{ + struct rtc_drv_data *pdata = dev_get_drvdata(dev); + void __iomem *ioaddr = pdata->ioaddr; + unsigned long time; + u64 old_time_47bit, new_time_47bit; + int ret; + ret = rtc_tm_to_time(tm, &time); + if (ret != 0) + return ret; + + old_time_47bit = (((u64) __raw_readl(ioaddr + SRTC_LPSCMR)) << 32 | + ((u64) __raw_readl(ioaddr + SRTC_LPSCLR))); + old_time_47bit >>= SRTC_LPSCLR_LLPSC_LSH; + + __raw_writel(time, ioaddr + SRTC_LPSCMR); + rtc_write_sync_lp(ioaddr); + + new_time_47bit = (((u64) __raw_readl(ioaddr + SRTC_LPSCMR)) << 32 | + ((u64) __raw_readl(ioaddr + SRTC_LPSCLR))); + new_time_47bit >>= SRTC_LPSCLR_LLPSC_LSH; + + /* update the difference between previous time and new time */ + time_diff = new_time_47bit - old_time_47bit; + + /* signal all waiting threads that time changed */ + complete_all(&srtc_completion); + /* reinitialize completion variable */ + INIT_COMPLETION(srtc_completion); + + return 0; +} + +/*! + * This function reads the current alarm value into the passed in \b alrm + * argument. It updates the \b alrm's pending field value based on the whether + * an alarm interrupt occurs or not. + * + * @param alrm contains the RTC alarm value upon return + * + * @return 0 if successful; non-zero otherwise. + */ +static int mxc_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alrm) +{ + struct rtc_drv_data *pdata = dev_get_drvdata(dev); + void __iomem *ioaddr = pdata->ioaddr; + + rtc_time_to_tm(__raw_readl(ioaddr + SRTC_LPSAR), &alrm->time); + alrm->pending = + ((__raw_readl(ioaddr + SRTC_LPSR) & SRTC_LPSR_ALP) != 0) ? 1 : 0; + + return 0; +} + +/*! + * This function sets the RTC alarm based on passed in alrm. + * + * @param alrm the alarm value to be set in the RTC + * + * @return 0 if successful; non-zero otherwise. + */ +static int mxc_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alrm) +{ + struct rtc_drv_data *pdata = dev_get_drvdata(dev); + void __iomem *ioaddr = pdata->ioaddr; + unsigned long lock_flags = 0; + u32 lp_cr; + int ret; + + if (rtc_valid_tm(&alrm->time)) { + if (alrm->time.tm_sec > 59 || + alrm->time.tm_hour > 23 || alrm->time.tm_min > 59) { + return -EINVAL; + } + } + + spin_lock_irqsave(&rtc_lock, lock_flags); + lp_cr = __raw_readl(ioaddr + SRTC_LPCR); + + ret = rtc_update_alarm(dev, &alrm->time); + if (ret) + goto out; + + if (alrm->enabled) + lp_cr |= (SRTC_LPCR_ALP | SRTC_LPCR_WAE); + else + lp_cr &= ~(SRTC_LPCR_ALP | SRTC_LPCR_WAE); + + if (lp_cr & SRTC_LPCR_ALL_INT_EN) { + if (!pdata->irq_enable) { + enable_irq(pdata->irq); + pdata->irq_enable = true; + } + } else { + if (pdata->irq_enable) { + disable_irq(pdata->irq); + pdata->irq_enable = false; + } + } + + __raw_writel(lp_cr, ioaddr + SRTC_LPCR); + +out: + spin_unlock_irqrestore(&rtc_lock, lock_flags); + rtc_write_sync_lp(ioaddr); + return ret; +} + +/*! + * This function is used to provide the content for the /proc/driver/rtc + * file. + * + * @param seq buffer to hold the information that the driver wants to write + * + * @return The number of bytes written into the rtc file. + */ +static int mxc_rtc_proc(struct device *dev, struct seq_file *seq) +{ + struct rtc_drv_data *pdata = dev_get_drvdata(dev); + void __iomem *ioaddr = pdata->ioaddr; + + clk_enable(pdata->clk); + seq_printf(seq, "alarm_IRQ\t: %s\n", + (((__raw_readl(ioaddr + SRTC_LPCR)) & SRTC_LPCR_ALP) != + 0) ? "yes" : "no"); + clk_disable(pdata->clk); + + return 0; +} + +/*! + * The RTC driver structure + */ +static struct rtc_class_ops mxc_rtc_ops = { + .open = mxc_rtc_open, + .release = mxc_rtc_release, + .ioctl = mxc_rtc_ioctl, + .read_time = mxc_rtc_read_time, + .set_time = mxc_rtc_set_time, + .read_alarm = mxc_rtc_read_alarm, + .set_alarm = mxc_rtc_set_alarm, + .proc = mxc_rtc_proc, +}; + +/*! MXC RTC Power management control */ +static int mxc_rtc_probe(struct platform_device *pdev) +{ + struct clk *clk; + struct timespec tv; + struct resource *res; + struct rtc_device *rtc; + struct rtc_drv_data *pdata = NULL; + struct mxc_srtc_platform_data *plat_data = NULL; + void __iomem *ioaddr; + void __iomem *srtc_secmode_addr; + int ret = 0; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!res) + return -ENODEV; + + pdata = kzalloc(sizeof(*pdata), GFP_KERNEL); + if (!pdata) + return -ENOMEM; + + pdata->clk = clk_get(&pdev->dev, "rtc_clk"); + clk_enable(pdata->clk); + pdata->baseaddr = res->start; + pdata->ioaddr = ioremap(pdata->baseaddr, 0x40); + ioaddr = pdata->ioaddr; + + /* Configure and enable the RTC */ + pdata->irq = platform_get_irq(pdev, 0); + if (pdata->irq >= 0) { + if (request_irq(pdata->irq, mxc_rtc_interrupt, IRQF_SHARED, + pdev->name, pdev) < 0) { + dev_warn(&pdev->dev, "interrupt not available.\n"); + pdata->irq = -1; + } else { + disable_irq(pdata->irq); + pdata->irq_enable = false; + } + } + + clk = clk_get(NULL, "rtc_clk"); + if (clk_get_rate(clk) != 32768) { + printk(KERN_ALERT "rtc clock is not valid"); + ret = -EINVAL; + clk_put(clk); + goto err_out; + } + clk_put(clk); + + /* initialize glitch detect */ + __raw_writel(SRTC_LPPDR_INIT, ioaddr + SRTC_LPPDR); + udelay(100); + + /* clear lp interrupt status */ + __raw_writel(0xFFFFFFFF, ioaddr + SRTC_LPSR); + udelay(100); + + plat_data = (struct mxc_srtc_platform_data *)pdev->dev.platform_data; + + /* move out of init state */ + __raw_writel((SRTC_LPCR_IE | SRTC_LPCR_NSA), + ioaddr + SRTC_LPCR); + + udelay(100); + + while ((__raw_readl(ioaddr + SRTC_LPSR) & SRTC_LPSR_IES) == 0) + ; + + /* move out of non-valid state */ + __raw_writel((SRTC_LPCR_IE | SRTC_LPCR_NVE | SRTC_LPCR_NSA | + SRTC_LPCR_EN_LP), ioaddr + SRTC_LPCR); + + udelay(100); + + while ((__raw_readl(ioaddr + SRTC_LPSR) & SRTC_LPSR_NVES) == 0) + ; + + __raw_writel(0xFFFFFFFF, ioaddr + SRTC_LPSR); + udelay(100); + + rtc = rtc_device_register(pdev->name, &pdev->dev, + &mxc_rtc_ops, THIS_MODULE); + if (IS_ERR(rtc)) { + ret = PTR_ERR(rtc); + goto err_out; + } + + pdata->rtc = rtc; + platform_set_drvdata(pdev, pdata); + + tv.tv_nsec = 0; + tv.tv_sec = __raw_readl(ioaddr + SRTC_LPSCMR); + + /* By default, devices should wakeup if they can */ + /* So srtc is set as "should wakeup" as it can */ + device_init_wakeup(&pdev->dev, 1); + + clk_disable(pdata->clk); + + return ret; + +err_out: + clk_disable(pdata->clk); + iounmap(ioaddr); + if (pdata->irq >= 0) + free_irq(pdata->irq, pdev); + kfree(pdata); + return ret; +} + +static int __exit mxc_rtc_remove(struct platform_device *pdev) +{ + struct rtc_drv_data *pdata = platform_get_drvdata(pdev); + rtc_device_unregister(pdata->rtc); + if (pdata->irq >= 0) + free_irq(pdata->irq, pdev); + + clk_disable(pdata->clk); + clk_put(pdata->clk); + kfree(pdata); + return 0; +} + +/*! + * This function is called to save the system time delta relative to + * the MXC RTC when enterring a low power state. This time delta is + * then used on resume to adjust the system time to account for time + * loss while suspended. + * + * @param pdev not used + * @param state Power state to enter. + * + * @return The function always returns 0. + */ +static int mxc_rtc_suspend(struct platform_device *pdev, pm_message_t state) +{ + struct rtc_drv_data *pdata = platform_get_drvdata(pdev); + + if (device_may_wakeup(&pdev->dev)) { + enable_irq_wake(pdata->irq); + } else { + if (pdata->irq_enable) + disable_irq(pdata->irq); + } + + return 0; +} + +/*! + * This function is called to correct the system time based on the + * current MXC RTC time relative to the time delta saved during + * suspend. + * + * @param pdev not used + * + * @return The function always returns 0. + */ +static int mxc_rtc_resume(struct platform_device *pdev) +{ + struct rtc_drv_data *pdata = platform_get_drvdata(pdev); + + if (device_may_wakeup(&pdev->dev)) { + disable_irq_wake(pdata->irq); + } else { + if (pdata->irq_enable) + enable_irq(pdata->irq); + } + + return 0; +} + +/*! + * Contains pointers to the power management callback functions. + */ +static struct platform_driver mxc_rtc_driver = { + .driver = { + .name = "mxc_rtc", + }, + .probe = mxc_rtc_probe, + .remove = __exit_p(mxc_rtc_remove), + .suspend = mxc_rtc_suspend, + .resume = mxc_rtc_resume, +}; + +/*! + * This function creates the /proc/driver/rtc file and registers the device RTC + * in the /dev/misc directory. It also reads the RTC value from external source + * and setup the internal RTC properly. + * + * @return -1 if RTC is failed to initialize; 0 is successful. + */ +static int __init mxc_rtc_init(void) +{ + return platform_driver_register(&mxc_rtc_driver); +} + +/*! + * This function removes the /proc/driver/rtc file and un-registers the + * device RTC from the /dev/misc directory. + */ +static void __exit mxc_rtc_exit(void) +{ + platform_driver_unregister(&mxc_rtc_driver); + +} + +module_init(mxc_rtc_init); +module_exit(mxc_rtc_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("Realtime Clock Driver (RTC)"); +MODULE_LICENSE("GPL"); diff --git a/drivers/rtc/rtc-mxs.c b/drivers/rtc/rtc-mxs.c new file mode 100644 index 000000000000..4ed5b40f7b8b --- /dev/null +++ b/drivers/rtc/rtc-mxs.c @@ -0,0 +1,320 @@ +/* + * Freescale STMP37XX/STMP378X Real Time Clock driver + * + * Copyright (c) 2007 Sigmatel, Inc. + * Peter Hartley, + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. + * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +struct mxs_rtc_data { + struct rtc_device *rtc; + unsigned int base; + int irq_alarm; + int irq_sample; + unsigned irq_count; +}; + +/* Time read/write */ +static int mxs_rtc_gettime(struct device *pdev, struct rtc_time *rtc_tm) +{ + struct mxs_rtc_data *rtc_data = dev_get_drvdata(pdev); + + while (__raw_readl(rtc_data->base + HW_RTC_STAT) & + BF_RTC_STAT_STALE_REGS(0x80)) + cpu_relax(); + + rtc_time_to_tm(__raw_readl(rtc_data->base + HW_RTC_SECONDS), rtc_tm); + return 0; +} + +static int mxs_rtc_settime(struct device *pdev, struct rtc_time *rtc_tm) +{ + unsigned long t; + int rc = rtc_tm_to_time(rtc_tm, &t); + struct mxs_rtc_data *rtc_data = dev_get_drvdata(pdev); + + if (rc == 0) { + __raw_writel(t, rtc_data->base + HW_RTC_SECONDS); + + /* The datasheet doesn't say which way round the + * NEW_REGS/STALE_REGS bitfields go. In fact it's 0x1=P0, + * 0x2=P1, .., 0x20=P5, 0x40=ALARM, 0x80=SECONDS, + */ + while (__raw_readl(rtc_data->base + HW_RTC_STAT) & + BF_RTC_STAT_NEW_REGS(0x80)) + cpu_relax(); + } + return rc; +} + +static irqreturn_t mxs_rtc_interrupt(int irq, void *dev_id) +{ + struct mxs_rtc_data *rtc_data = dev_get_drvdata(dev_id); + u32 status; + u32 events = 0; + + status = __raw_readl(rtc_data->base + HW_RTC_CTRL) & + (BM_RTC_CTRL_ALARM_IRQ | BM_RTC_CTRL_ONEMSEC_IRQ); + if (status & BM_RTC_CTRL_ALARM_IRQ) { + __raw_writel(BM_RTC_CTRL_ALARM_IRQ, + rtc_data->base + HW_RTC_CTRL_CLR); + events |= RTC_AF | RTC_IRQF; + } + if (status & BM_RTC_CTRL_ONEMSEC_IRQ) { + __raw_writel(BM_RTC_CTRL_ONEMSEC_IRQ, + rtc_data->base + HW_RTC_CTRL_CLR); + if (++rtc_data->irq_count % 1000 == 0) { + events |= RTC_UF | RTC_IRQF; + rtc_data->irq_count = 0; + } + } + + if (events) + rtc_update_irq(rtc_data->rtc, 1, events); + + return IRQ_HANDLED; +} + +static int mxs_rtc_open(struct device *pdev) +{ + int r; + struct mxs_rtc_data *rtc_data = dev_get_drvdata(pdev); + + r = request_irq(rtc_data->irq_alarm, mxs_rtc_interrupt, + IRQF_DISABLED, "RTC alarm", pdev); + if (r) { + dev_err(pdev, "Cannot claim IRQ%d\n", rtc_data->irq_alarm); + goto fail_1; + } + r = request_irq(rtc_data->irq_sample, mxs_rtc_interrupt, + IRQF_DISABLED, "RTC tick", pdev); + if (r) { + dev_err(pdev, "Cannot claim IRQ%d\n", rtc_data->irq_sample); + goto fail_2; + } + + return 0; +fail_2: + free_irq(rtc_data->irq_alarm, pdev); +fail_1: + return r; +} + +static void mxs_rtc_release(struct device *pdev) +{ + struct mxs_rtc_data *rtc_data = dev_get_drvdata(pdev); + + __raw_writel(BM_RTC_CTRL_ALARM_IRQ_EN | BM_RTC_CTRL_ONEMSEC_IRQ_EN, + rtc_data->base + HW_RTC_CTRL_CLR); + free_irq(rtc_data->irq_alarm, pdev); + free_irq(rtc_data->irq_sample, pdev); +} + +static int mxs_rtc_ioctl(struct device *pdev, unsigned int cmd, + unsigned long arg) +{ + struct mxs_rtc_data *rtc_data = dev_get_drvdata(pdev); + + switch (cmd) { + case RTC_AIE_OFF: + __raw_writel(BM_RTC_PERSISTENT0_ALARM_EN | + BM_RTC_PERSISTENT0_ALARM_WAKE_EN, + rtc_data->base + HW_RTC_PERSISTENT0_CLR); + __raw_writel(BM_RTC_CTRL_ALARM_IRQ_EN, + rtc_data->base + HW_RTC_CTRL_CLR); + break; + case RTC_AIE_ON: + __raw_writel(BM_RTC_PERSISTENT0_ALARM_EN | + BM_RTC_PERSISTENT0_ALARM_WAKE_EN, + rtc_data->base + HW_RTC_PERSISTENT0_SET); + + __raw_writel(BM_RTC_CTRL_ALARM_IRQ_EN, + rtc_data->base + HW_RTC_CTRL_SET); + break; + case RTC_UIE_ON: + rtc_data->irq_count = 0; + __raw_writel(BM_RTC_CTRL_ONEMSEC_IRQ_EN, + rtc_data->base + HW_RTC_CTRL_SET); + break; + case RTC_UIE_OFF: + __raw_writel(BM_RTC_CTRL_ONEMSEC_IRQ_EN, + rtc_data->base + HW_RTC_CTRL_CLR); + break; + default: + return -ENOIOCTLCMD; + } + + return 0; +} +static int mxs_rtc_read_alarm(struct device *pdev, struct rtc_wkalrm *alm) +{ + u32 t; + struct mxs_rtc_data *rtc_data = dev_get_drvdata(pdev); + + t = __raw_readl(rtc_data->base + HW_RTC_ALARM); + rtc_time_to_tm(t, &alm->time); + return 0; +} + +static int mxs_rtc_set_alarm(struct device *pdev, struct rtc_wkalrm *alm) +{ + unsigned long t; + struct mxs_rtc_data *rtc_data = dev_get_drvdata(pdev); + + rtc_tm_to_time(&alm->time, &t); + __raw_writel(t, rtc_data->base + HW_RTC_ALARM); + return 0; +} + +static struct rtc_class_ops mxs_rtc_ops = { + .open = mxs_rtc_open, + .release = mxs_rtc_release, + .ioctl = mxs_rtc_ioctl, + .read_time = mxs_rtc_gettime, + .set_time = mxs_rtc_settime, + .read_alarm = mxs_rtc_read_alarm, + .set_alarm = mxs_rtc_set_alarm, +}; + +static int mxs_rtc_probe(struct platform_device *pdev) +{ + u32 hwversion; + u32 rtc_stat; + struct resource *res; + struct mxs_rtc_data *rtc_data; + + rtc_data = kzalloc(sizeof(*rtc_data), GFP_KERNEL); + + if (!rtc_data) + return -ENOMEM; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (res == NULL) { + kfree(rtc_data); + return -ENODEV; + } + rtc_data->base = (unsigned int)IO_ADDRESS(res->start); + + res = platform_get_resource(pdev, IORESOURCE_IRQ, 0); + if (res == NULL) { + kfree(rtc_data); + return -ENODEV; + } + rtc_data->irq_alarm = res->start; + + res = platform_get_resource(pdev, IORESOURCE_IRQ, 1); + if (res == NULL) { + kfree(rtc_data); + return -ENODEV; + } + rtc_data->irq_sample = res->start; + + __raw_writel(BM_RTC_PERSISTENT0_ALARM_EN | + BM_RTC_PERSISTENT0_ALARM_WAKE_EN | + BM_RTC_PERSISTENT0_ALARM_WAKE, + rtc_data->base + HW_RTC_PERSISTENT0_CLR); + + hwversion = __raw_readl(rtc_data->base + HW_RTC_VERSION); + rtc_stat = __raw_readl(rtc_data->base + HW_RTC_STAT); + printk(KERN_INFO "MXS RTC driver v1.0 hardware v%u.%u.%u\n", + (hwversion >> 24), + (hwversion >> 16) & 0xFF, + hwversion & 0xFFFF); + + rtc_data->rtc = rtc_device_register(pdev->name, &pdev->dev, + &mxs_rtc_ops, THIS_MODULE); + if (IS_ERR(rtc_data->rtc)) { + kfree(rtc_data); + return PTR_ERR(rtc_data->rtc); + } + + platform_set_drvdata(pdev, rtc_data); + + return 0; +} + +static int mxs_rtc_remove(struct platform_device *dev) +{ + struct mxs_rtc_data *rtc_data = platform_get_drvdata(dev); + + if (rtc_data) { + rtc_device_unregister(rtc_data->rtc); + kfree(rtc_data); + } + + return 0; +} + +#ifdef CONFIG_PM +static int mxs_rtc_suspend(struct platform_device *dev, pm_message_t state) +{ + return 0; +} + +static int mxs_rtc_resume(struct platform_device *dev) +{ + struct mxs_rtc_data *rtc_data = platform_get_drvdata(dev); + + __raw_writel(BM_RTC_PERSISTENT0_ALARM_EN | + BM_RTC_PERSISTENT0_ALARM_WAKE_EN | + BM_RTC_PERSISTENT0_ALARM_WAKE, + rtc_data->base + HW_RTC_PERSISTENT0_CLR); + return 0; +} +#else +#define mxs_rtc_suspend NULL +#define mxs_rtc_resume NULL +#endif + +static struct platform_driver mxs_rtcdrv = { + .probe = mxs_rtc_probe, + .remove = mxs_rtc_remove, + .suspend = mxs_rtc_suspend, + .resume = mxs_rtc_resume, + .driver = { + .name = "mxs-rtc", + .owner = THIS_MODULE, + }, +}; + +static int __init mxs_rtc_init(void) +{ + return platform_driver_register(&mxs_rtcdrv); +} + +static void __exit mxs_rtc_exit(void) +{ + platform_driver_unregister(&mxs_rtcdrv); +} + +module_init(mxs_rtc_init); +module_exit(mxs_rtc_exit); + +MODULE_DESCRIPTION("MXS RTC Driver"); +MODULE_AUTHOR("dmitry pervushin "); +MODULE_LICENSE("GPL"); diff --git a/drivers/serial/Kconfig b/drivers/serial/Kconfig index 8b23165bc5dc..17cbbd3e9408 100644 --- a/drivers/serial/Kconfig +++ b/drivers/serial/Kconfig @@ -304,6 +304,110 @@ config SERIAL_AMBA_PL010_CONSOLE your boot loader (lilo or loadlin) about how to pass options to the kernel at boot time.) +config SERIAL_MXC + tristate "MXC Internal serial port support" + depends on ARCH_MXC + select SERIAL_CORE + help + This selects the Freescale Semiconductor MXC Internal UART driver. + If unsure, say N. + +config SERIAL_MXC_CONSOLE + bool "Support for console on a MXC/MX27/MX21 Internal serial port" + depends on SERIAL_MXC=y + select SERIAL_CORE_CONSOLE + help + Say Y here if you wish to use an MXC Internal UART as the system + console (the system console is the device which receives all kernel + messages and warnings and which allows logins in single user mode). + + Even if you say Y here, the currently visible framebuffer console + (/dev/tty0) will still be used as the system console by default, but + you can alter that using a kernel command line option such as + "console=ttymxc". (Try "man bootparam" or see the documentation of + your boot loader (lilo or loadlin) about how to pass options to the + kernel at boot time.) + +config SERIAL_STMP_DBG + tristate "STMP debug serial port support" + depends on ARCH_STMP3XXX + select SERIAL_CORE + help + Driver for Sigmatel 36XX/37XX internal debug serial port + +config SERIAL_STMP_DBG_CONSOLE + bool "Support for console on STMP37XX DBG serial port" + depends on SERIAL_STMP_DBG=y + select SERIAL_CORE_CONSOLE + ---help--- + Say Y here if you wish to use the STMP36XX/37XX debug serial port as the + system console (the system console is the device which receives all + kernel messages and warnings and which allows logins in single user + mode). + + Even if you say Y here, the currently visible framebuffer console + (/dev/tty0) will still be used as the system console by default, but + you can alter that using a kernel command line option such as + "console=ttyAM0". (Try "man bootparam" or see the documentation of + your boot loader (lilo or loadlin) about how to pass options to the + kernel at boot time.) + +config SERIAL_STMP_APP + tristate "STMP app serial port support" + depends on ARCH_STMP3XXX + select SERIAL_CORE + help + Driver for Sigmatel 36XX/37XX internal application serial port + +config SERIAL_MXS_DUART + tristate "i.MXS debug serial port support" + depends on ARCH_MXS + select SERIAL_CORE + help + Driver for Freescale i.MXS internal debug serial port + +config SERIAL_MXS_AUART + tristate "i.MXS Application serial port support" + depends on ARCH_MXS + select SERIAL_CORE + help + Driver for Freescale i.MXS internal application serial port + +config SERIAL_MXS_AUART_CONSOLE + bool "Support for console on i.MXS application serial port" + depends on SERIAL_MXS_AUART=y + select SERIAL_CORE_CONSOLE + ---help--- + Say Y here if you wish to use the i.MXS app serial port as the + system console (the system console is the device which receives all + kernel messages and warnings and which allows logins in single user + mode). + + Even if you say Y here, the currently visible framebuffer console + (/dev/tty0) will still be used as the system console by default, but + you can alter that using a kernel command line option such as + "console=ttySP1". (Try "man bootparam" or see the documentation of + your boot loader (lilo or loadlin) about how to pass options to the + kernel at boot time.) + + +config SERIAL_MXS_DUART_CONSOLE + bool "Support for console on i.MXS debug serial port" + depends on SERIAL_MXS_DUART=y + select SERIAL_CORE_CONSOLE + ---help--- + Say Y here if you wish to use the i.MXS debug serial port as the + system console (the system console is the device which receives all + kernel messages and warnings and which allows logins in single user + mode). + + Even if you say Y here, the currently visible framebuffer console + (/dev/tty0) will still be used as the system console by default, but + you can alter that using a kernel command line option such as + "console=ttyAM0". (Try "man bootparam" or see the documentation of + your boot loader (lilo or loadlin) about how to pass options to the + kernel at boot time.) + config SERIAL_AMBA_PL011 tristate "ARM AMBA PL011 serial port support" depends on ARM_AMBA diff --git a/drivers/serial/Makefile b/drivers/serial/Makefile index 208a85572c32..2ed31d54c6c6 100644 --- a/drivers/serial/Makefile +++ b/drivers/serial/Makefile @@ -75,6 +75,10 @@ obj-$(CONFIG_SERIAL_ATMEL) += atmel_serial.o obj-$(CONFIG_SERIAL_UARTLITE) += uartlite.o obj-$(CONFIG_SERIAL_MSM) += msm_serial.o obj-$(CONFIG_SERIAL_NETX) += netx-serial.o +obj-$(CONFIG_SERIAL_MXC) += mxc_uart.o +obj-$(CONFIG_SERIAL_MXC_CONSOLE) += mxc_uart_early.o +obj-$(CONFIG_SERIAL_MXS_DUART) += mxs-duart.o +obj-$(CONFIG_SERIAL_MXS_AUART) += mxs-auart.o obj-$(CONFIG_SERIAL_OF_PLATFORM) += of_serial.o obj-$(CONFIG_SERIAL_OF_PLATFORM_NWPSERIAL) += nwpserial.o obj-$(CONFIG_SERIAL_KS8695) += serial_ks8695.o diff --git a/drivers/serial/mxc_uart.c b/drivers/serial/mxc_uart.c new file mode 100644 index 000000000000..55f7660ef364 --- /dev/null +++ b/drivers/serial/mxc_uart.c @@ -0,0 +1,1954 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file drivers/serial/mxc_uart.c + * + * @brief Driver for the Freescale Semiconductor MXC serial ports based on + * drivers/char/serial.c, by Linus Torvalds, Theodore Ts'o. + * + * @ingroup UART + */ + +/* + * Include Files + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(CONFIG_SERIAL_MXC_CONSOLE) && defined(CONFIG_MAGIC_SYSRQ) +#define SUPPORT_SYSRQ +#endif +#define SERIAL_MXC_MAJOR 207 +#define SERIAL_MXC_MINOR 16 +#define MXC_ISR_PASS_LIMIT 256 +#define UART_CREAD_BIT 256 + +#define MXC_UART_NR 8 + +/* IRDA minimum pulse duration in micro seconds */ +#define MIN_PULSE_DUR 2 +/* + * Transmit DMA buffer size is set to 1024 bytes, this is limited + * by UART_XMIT_SIZE. + */ +#define TXDMA_BUFF_SIZE UART_XMIT_SIZE +/* + * Receive DMA sub-buffer size + */ +#define RXDMA_BUFF_SIZE 128 + +/*! + * This structure is used to store the information for DMA data transfer. + */ +typedef struct { + /*! + * Holds the read channel number. + */ + int rd_channel; + /*! + * Holds the write channel number. + */ + int wr_channel; + /*! + * UART Transmit Event ID + */ + int tx_event_id; + /*! + * UART Receive Event ID + */ + int rx_event_id; + /*! + * DMA Transmit tasklet + */ + struct tasklet_struct dma_tx_tasklet; + /*! + * Flag indicates if the channel is in use + */ + int dma_txchnl_inuse; +} dma_info; + +/*! + * This is used to indicate if we want echo cancellation in the Irda mode. + */ +static int echo_cancel; +extern void gpio_uart_active(int port, int no_irda); +extern void gpio_uart_inactive(int port, int no_irda); +extern void config_uartdma_event(int port); + +static uart_mxc_port *mxc_ports[MXC_UART_NR]; + +/*! + * This array holds the DMA channel information for each MXC UART + */ +static dma_info dma_list[MXC_UART_NR]; + +/*! + * This function is called by the core driver to stop UART transmission. + * This might be due to the TTY layer indicating that the user wants to stop + * transmission. + * + * @param port the port structure for the UART passed in by the core + * driver + */ +static void mxcuart_stop_tx(struct uart_port *port) +{ + uart_mxc_port *umxc = (uart_mxc_port *) port; + volatile unsigned int cr1; + + cr1 = readl(port->membase + MXC_UARTUCR1); + /* Disable Transmitter rdy interrupt */ + if (umxc->dma_enabled == 1) { + cr1 &= ~MXC_UARTUCR1_TXDMAEN; + } else { + cr1 &= ~MXC_UARTUCR1_TRDYEN; + } + writel(cr1, port->membase + MXC_UARTUCR1); +} + +/*! + * DMA Transmit tasklet method is scheduled on completion of a DMA transmit + * to send out any more data that is available in the UART xmit buffer. + * + * @param arg driver private data + */ +static void dma_tx_do_tasklet(unsigned long arg) +{ + uart_mxc_port *umxc = (uart_mxc_port *) arg; + struct circ_buf *xmit = &umxc->port.state->xmit; + mxc_dma_requestbuf_t writechnl_request; + int tx_num; + unsigned long flags; + + spin_lock_irqsave(&umxc->port.lock, flags); + tx_num = uart_circ_chars_pending(xmit); + if (tx_num > 0) { + if (xmit->tail > xmit->head) { + memcpy(umxc->tx_buf, xmit->buf + xmit->tail, + UART_XMIT_SIZE - xmit->tail); + memcpy(umxc->tx_buf + (UART_XMIT_SIZE - xmit->tail), + xmit->buf, xmit->head); + } else { + memcpy(umxc->tx_buf, xmit->buf + xmit->tail, tx_num); + } + umxc->tx_handle = dma_map_single(umxc->port.dev, umxc->tx_buf, + TXDMA_BUFF_SIZE, + DMA_TO_DEVICE); + + writechnl_request.dst_addr = umxc->port.mapbase + MXC_UARTUTXD; + writechnl_request.src_addr = umxc->tx_handle; + writechnl_request.num_of_bytes = tx_num; + + if ((mxc_dma_config(dma_list[umxc->port.line].wr_channel, + &writechnl_request, 1, + MXC_DMA_MODE_WRITE)) == 0) { + mxc_dma_enable(dma_list[umxc->port.line].wr_channel); + } + } else { + /* No more data available in the xmit queue, clear the flag */ + dma_list[umxc->port.line].dma_txchnl_inuse = 0; + } + spin_unlock_irqrestore(&umxc->port.lock, flags); +} + +/*! + * DMA Write callback is called by the SDMA controller after it has sent out all + * the data from the user buffer. This function updates the xmit buffer pointers. + * + * @param arg driver private data + * @param error any DMA error + * @param count amount of data that was transferred + */ +static void mxcuart_dma_writecallback(void *arg, int error, unsigned int count) +{ + uart_mxc_port *umxc = arg; + struct circ_buf *xmit = &umxc->port.state->xmit; + int tx_num; + + if (error != MXC_DMA_TRANSFER_ERROR) { + tx_num = count; + umxc->port.icount.tx += tx_num; + xmit->tail = (xmit->tail + tx_num) & (UART_XMIT_SIZE - 1); + } + + dma_unmap_single(umxc->port.dev, umxc->tx_handle, TXDMA_BUFF_SIZE, + DMA_TO_DEVICE); + tx_num = uart_circ_chars_pending(xmit); + /* Schedule a tasklet to send out the pending characters */ + if (tx_num > 0) { + tasklet_schedule(&dma_list[umxc->port.line].dma_tx_tasklet); + } else { + dma_list[umxc->port.line].dma_txchnl_inuse = 0; + } + if (tx_num < WAKEUP_CHARS) { + uart_write_wakeup(&umxc->port); + } +} + +/*! + * This function is called by the core driver to start transmitting characters. + * This function enables the transmit interrupts. + * + * @param port the port structure for the UART passed in by the core + * driver + */ +static void mxcuart_start_tx(struct uart_port *port) +{ + uart_mxc_port *umxc = (uart_mxc_port *) port; + struct circ_buf *xmit = &umxc->port.state->xmit; + volatile unsigned int cr1; + mxc_dma_requestbuf_t writechnl_request; + int tx_num; + + cr1 = readl(port->membase + MXC_UARTUCR1); + /* Enable Transmitter rdy interrupt */ + if (umxc->dma_enabled == 1) { + /* + * If the channel is in use then return immediately and use + * the dma_tx tasklet to transfer queued data when current DMA + * transfer is complete + */ + if (dma_list[umxc->port.line].dma_txchnl_inuse == 1) { + return; + } + tx_num = uart_circ_chars_pending(xmit); + if (tx_num > 0) { + dma_list[umxc->port.line].dma_txchnl_inuse = 1; + if (xmit->tail > xmit->head) { + memcpy(umxc->tx_buf, xmit->buf + xmit->tail, + UART_XMIT_SIZE - xmit->tail); + memcpy(umxc->tx_buf + + (UART_XMIT_SIZE - xmit->tail), xmit->buf, + xmit->head); + } else { + memcpy(umxc->tx_buf, xmit->buf + xmit->tail, + tx_num); + } + umxc->tx_handle = + dma_map_single(umxc->port.dev, umxc->tx_buf, + TXDMA_BUFF_SIZE, DMA_TO_DEVICE); + + writechnl_request.dst_addr = + umxc->port.mapbase + MXC_UARTUTXD; + writechnl_request.src_addr = umxc->tx_handle; + writechnl_request.num_of_bytes = tx_num; + if ((mxc_dma_config + (dma_list[umxc->port.line].wr_channel, + &writechnl_request, 1, + MXC_DMA_MODE_WRITE)) == 0) { + mxc_dma_enable(dma_list[umxc->port.line]. + wr_channel); + } + cr1 |= MXC_UARTUCR1_TXDMAEN; + } + } else { + cr1 |= MXC_UARTUCR1_TRDYEN; + } + writel(cr1, port->membase + MXC_UARTUCR1); +} + +/*! + * This function is called by the core driver to stop receiving characters; the + * port is in the process of being closed. + * + * @param port the port structure for the UART passed in by the core driver + */ +static void mxcuart_stop_rx(struct uart_port *port) +{ + uart_mxc_port *umxc = (uart_mxc_port *) port; + volatile unsigned int cr1; + + cr1 = readl(port->membase + MXC_UARTUCR1); + if (umxc->dma_enabled == 1) { + cr1 &= ~MXC_UARTUCR1_RXDMAEN; + } else { + cr1 &= ~MXC_UARTUCR1_RRDYEN; + } + writel(cr1, port->membase + MXC_UARTUCR1); +} + +/*! + * This function is called by the core driver to enable the modem status + * interrupts. If the port is configured to be in DTE mode then it enables the + * DCDDELT and RIDELT interrupts in addition to the DTRDEN interrupt. The RTSDEN + * interrupt is enabled only for interrupt-driven hardware flow control. + * + * @param port the port structure for the UART passed in by the core driver + */ +static void mxcuart_enable_ms(struct uart_port *port) +{ + uart_mxc_port *umxc = (uart_mxc_port *) port; + volatile unsigned int cr1, cr3; + + /* + * RTS interrupt is enabled only if we are using interrupt-driven + * software controlled hardware flow control + */ + if (umxc->hardware_flow == 0) { + cr1 = readl(umxc->port.membase + MXC_UARTUCR1); + cr1 |= MXC_UARTUCR1_RTSDEN; + writel(cr1, umxc->port.membase + MXC_UARTUCR1); + } + cr3 = readl(umxc->port.membase + MXC_UARTUCR3); + cr3 |= MXC_UARTUCR3_DTRDEN; + if (umxc->mode == MODE_DTE) { + cr3 |= MXC_UARTUCR3_DCD | MXC_UARTUCR3_RI; + } + writel(cr3, umxc->port.membase + MXC_UARTUCR3); +} + +/*! + * This function is called from the interrupt service routine if the status bit + * indicates that the receive fifo data level is above the set threshold. The + * function reads the character and queues them into the TTY layers read + * buffer. The function also looks for break characters, parity and framing + * errors in the received character and sets the appropriate flag in the TTY + * receive buffer. + * + * @param umxc the MXC UART port structure, this includes the \b uart_port + * structure and other members that are specific to MXC UARTs + */ +static void mxcuart_rx_chars(uart_mxc_port *umxc) +{ + volatile unsigned int ch, sr2; + unsigned int status, flag, max_count = 256; + + sr2 = readl(umxc->port.membase + MXC_UARTUSR2); + while (((sr2 & MXC_UARTUSR2_RDR) == 1) && (max_count-- > 0)) { + ch = readl(umxc->port.membase + MXC_UARTURXD); + + flag = TTY_NORMAL; + status = ch | UART_CREAD_BIT; + ch &= 0xFF; /* Clear the upper bits */ + umxc->port.icount.rx++; + + /* + * Check to see if there is an error in the received + * character. Perform the appropriate actions based on the + * error bit that was set. + */ + if (status & MXC_UARTURXD_ERR) { + if (status & MXC_UARTURXD_BRK) { + /* + * Clear the frame and parity error bits + * as these always get set on receiving a + * break character + */ + status &= ~(MXC_UARTURXD_FRMERR | + MXC_UARTURXD_PRERR); + umxc->port.icount.brk++; + if (uart_handle_break(&umxc->port)) { + goto ignore_char; + } + } else if (status & MXC_UARTURXD_FRMERR) { + umxc->port.icount.frame++; + } else if (status & MXC_UARTURXD_PRERR) { + umxc->port.icount.parity++; + } + if (status & MXC_UARTURXD_OVRRUN) { + umxc->port.icount.overrun++; + } + + status &= umxc->port.read_status_mask; + + if (status & MXC_UARTURXD_BRK) { + flag = TTY_BREAK; + } else if (status & MXC_UARTURXD_FRMERR) { + flag = TTY_FRAME; + } else if (status & MXC_UARTURXD_PRERR) { + flag = TTY_PARITY; + } + } + + if (uart_handle_sysrq_char(&umxc->port, ch)) { + goto ignore_char; + } + + uart_insert_char(&umxc->port, status, MXC_UARTURXD_OVRRUN, ch, + flag); + ignore_char: + sr2 = readl(umxc->port.membase + MXC_UARTUSR2); + } + tty_flip_buffer_push(umxc->port.state->port.tty); +} + +/*! + * This function is called from the interrupt service routine if the status bit + * indicates that the transmit fifo is emptied below its set threshold and + * requires data. The function pulls characters from the TTY layers write + * buffer and writes it out to the UART transmit fifo. + * + * @param umxc the MXC UART port structure, this includes the \b uart_port + * structure and other members that are specific to MXC UARTs + */ +static void mxcuart_tx_chars(uart_mxc_port *umxc) +{ + struct circ_buf *xmit = &umxc->port.state->xmit; + int count; + + /* + * Transmit the XON/XOFF character if required + */ + if (umxc->port.x_char) { + writel(umxc->port.x_char, umxc->port.membase + MXC_UARTUTXD); + umxc->port.icount.tx++; + umxc->port.x_char = 0; + return; + } + + /* + * Check to see if there is any data to be sent and that the + * port has not been currently stopped by anything. + */ + if (uart_circ_empty(xmit) || uart_tx_stopped(&umxc->port)) { + mxcuart_stop_tx(&umxc->port); + return; + } + + count = umxc->port.fifosize - umxc->tx_threshold; + do { + writel(xmit->buf[xmit->tail], + umxc->port.membase + MXC_UARTUTXD); + xmit->tail = (xmit->tail + 1) & (UART_XMIT_SIZE - 1); + umxc->port.icount.tx++; + if (uart_circ_empty(xmit)) { + break; + } + } while (--count > 0); + + /* + * Check to see if we have flushed enough characters to ask for more + * to be sent to us, if so, we notify the user space that we can + * accept more data + */ + if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS) { + uart_write_wakeup(&umxc->port); + } + + if (uart_circ_empty(xmit)) { + mxcuart_stop_tx(&umxc->port); + } +} + +/*! + * This function is called from the interrupt service routine if there is a + * change in the modem signals. This function handles these signal changes and + * also clears the appropriate status register bits. + * + * @param umxc the MXC UART port structure, this includes the \b uart_port + * structure and other members that are specific to MXC UARTs + * @param sr1 contents of status register 1 + * @param sr2 contents of status register 2 + */ +static void mxcuart_modem_status(uart_mxc_port *umxc, unsigned int sr1, + unsigned int sr2) +{ + if (umxc->mode == MODE_DTE) { + if (sr2 & MXC_UARTUSR2_DCDDELT) { + uart_handle_dcd_change(&umxc->port, + !(sr2 & MXC_UARTUSR2_DCDIN)); + } + if (sr2 & MXC_UARTUSR2_RIDELT) { + umxc->port.icount.rng++; + } + } + if (sr1 & MXC_UARTUSR1_DTRD) { + umxc->port.icount.dsr++; + } + if ((umxc->hardware_flow == 0) && (sr1 & MXC_UARTUSR1_RTSD)) { + uart_handle_cts_change(&umxc->port, sr1 & MXC_UARTUSR1_RTSS); + } + + wake_up_interruptible(&umxc->port.state->port.delta_msr_wait); +} + +/*! + * Interrupt service routine registered to handle the muxed ANDed interrupts. + * This routine is registered only in the case where the UART interrupts are + * muxed. + * + * @param irq the interrupt number + * @param dev_id driver private data + * + * @return The function returns \b IRQ_RETVAL(1) if interrupt was handled, + * returns \b IRQ_RETVAL(0) if the interrupt was not handled. + * \b IRQ_RETVAL is defined in \b include/linux/interrupt.h. + */ +static irqreturn_t mxcuart_int(int irq, void *dev_id) +{ + uart_mxc_port *umxc = dev_id; + volatile unsigned int sr1, sr2, cr1, cr; + unsigned int pass_counter = MXC_ISR_PASS_LIMIT; + unsigned int term_cond = 0; + int handled = 0; + + sr1 = readl(umxc->port.membase + MXC_UARTUSR1); + sr2 = readl(umxc->port.membase + MXC_UARTUSR2); + cr1 = readl(umxc->port.membase + MXC_UARTUCR1); + + do { + /* Clear the bits that triggered the interrupt */ + writel(sr1, umxc->port.membase + MXC_UARTUSR1); + writel(sr2, umxc->port.membase + MXC_UARTUSR2); + /* + * Read if there is data available + */ + if (sr2 & MXC_UARTUSR2_RDR) { + mxcuart_rx_chars(umxc); + } + + if ((sr1 & (MXC_UARTUSR1_RTSD | MXC_UARTUSR1_DTRD)) || + (sr2 & (MXC_UARTUSR2_DCDDELT | MXC_UARTUSR2_RIDELT))) { + mxcuart_modem_status(umxc, sr1, sr2); + } + + /* + * Send data if there is data to be sent + */ + if ((cr1 & MXC_UARTUCR1_TRDYEN) && (sr1 & MXC_UARTUSR1_TRDY)) { + /* Echo cancellation for IRDA Transmit chars */ + if (umxc->ir_mode == IRDA && echo_cancel) { + /* Disable the receiver */ + cr = readl(umxc->port.membase + MXC_UARTUCR2); + cr &= ~MXC_UARTUCR2_RXEN; + writel(cr, umxc->port.membase + MXC_UARTUCR2); + /* Enable Transmit complete intr to reenable RX */ + cr = readl(umxc->port.membase + MXC_UARTUCR4); + cr |= MXC_UARTUCR4_TCEN; + writel(cr, umxc->port.membase + MXC_UARTUCR4); + } + mxcuart_tx_chars(umxc); + } + + if (pass_counter-- == 0) { + break; + } + + sr1 = readl(umxc->port.membase + MXC_UARTUSR1); + sr2 = readl(umxc->port.membase + MXC_UARTUSR2); + + /* Is the transmit complete to reenable the receiver? */ + if (umxc->ir_mode == IRDA && echo_cancel) { + if (sr2 & MXC_UARTUSR2_TXDC) { + cr = readl(umxc->port.membase + MXC_UARTUCR2); + cr |= MXC_UARTUCR2_RXEN; + writel(cr, umxc->port.membase + MXC_UARTUCR2); + /* Disable the Transmit complete interrupt bit */ + cr = readl(umxc->port.membase + MXC_UARTUCR4); + cr &= ~MXC_UARTUCR4_TCEN; + writel(cr, umxc->port.membase + MXC_UARTUCR4); + } + } + + /* + * If there is no data to send or receive and if there is no + * change in the modem status signals then quit the routine + */ + term_cond = sr1 & (MXC_UARTUSR1_RTSD | MXC_UARTUSR1_DTRD); + term_cond |= sr2 & (MXC_UARTUSR2_RDR | MXC_UARTUSR2_DCDDELT); + term_cond |= !(sr2 & MXC_UARTUSR2_TXFE); + } while (term_cond > 0); + + handled = 1; + return IRQ_RETVAL(handled); +} + +/*! + * Interrupt service routine registered to handle the transmit interrupts. This + * routine is registered only in the case where the UART interrupts are not + * muxed. + * + * @param irq the interrupt number + * @param dev_id driver private data + * + * @return The function returns \b IRQ_RETVAL(1) if interrupt was handled, + * returns \b IRQ_RETVAL(0) if the interrupt was not handled. + * \b IRQ_RETVAL is defined in include/linux/interrupt.h. + */ +static irqreturn_t mxcuart_tx_int(int irq, void *dev_id) +{ + uart_mxc_port *umxc = dev_id; + int handled = 0; + volatile unsigned int sr2, cr; + + /* Echo cancellation for IRDA Transmit chars */ + if (umxc->ir_mode == IRDA && echo_cancel) { + /* Disable the receiver */ + cr = readl(umxc->port.membase + MXC_UARTUCR2); + cr &= ~MXC_UARTUCR2_RXEN; + writel(cr, umxc->port.membase + MXC_UARTUCR2); + /* Enable Transmit complete to reenable receiver */ + cr = readl(umxc->port.membase + MXC_UARTUCR4); + cr |= MXC_UARTUCR4_TCEN; + writel(cr, umxc->port.membase + MXC_UARTUCR4); + } + + mxcuart_tx_chars(umxc); + + /* Is the transmit complete to reenable the receiver? */ + if (umxc->ir_mode == IRDA && echo_cancel) { + sr2 = readl(umxc->port.membase + MXC_UARTUSR2); + if (sr2 & MXC_UARTUSR2_TXDC) { + cr = readl(umxc->port.membase + MXC_UARTUCR2); + cr |= MXC_UARTUCR2_RXEN; + writel(cr, umxc->port.membase + MXC_UARTUCR2); + /* Disable the Transmit complete interrupt bit */ + cr = readl(umxc->port.membase + MXC_UARTUCR4); + cr &= ~MXC_UARTUCR4_TCEN; + writel(cr, umxc->port.membase + MXC_UARTUCR4); + } + } + + handled = 1; + + return IRQ_RETVAL(handled); +} + +/*! + * Interrupt service routine registered to handle the receive interrupts. This + * routine is registered only in the case where the UART interrupts are not + * muxed. + * + * @param irq the interrupt number + * @param dev_id driver private data + * + * @return The function returns \b IRQ_RETVAL(1) if interrupt was handled, + * returns \b IRQ_RETVAL(0) if the interrupt was not handled. + * \b IRQ_RETVAL is defined in include/linux/interrupt.h. + */ +static irqreturn_t mxcuart_rx_int(int irq, void *dev_id) +{ + uart_mxc_port *umxc = dev_id; + int handled = 0; + + /* Clear the aging timer bit */ + writel(MXC_UARTUSR1_AGTIM, umxc->port.membase + MXC_UARTUSR1); + mxcuart_rx_chars(umxc); + handled = 1; + + return IRQ_RETVAL(handled); +} + +/*! + * Interrupt service routine registered to handle the master interrupts. This + * routine is registered only in the case where the UART interrupts are not + * muxed. + * + * @param irq the interrupt number + * @param dev_id driver private data + * + * @return The function returns \b IRQ_RETVAL(1) if interrupt was handled, + * returns \b IRQ_RETVAL(0) if the interrupt was not handled. + * \b IRQ_RETVAL is defined in include/linux/interrupt.h. + */ +static irqreturn_t mxcuart_mint_int(int irq, void *dev_id) +{ + uart_mxc_port *umxc = dev_id; + int handled = 0; + volatile unsigned int sr1, sr2; + + sr1 = readl(umxc->port.membase + MXC_UARTUSR1); + sr2 = readl(umxc->port.membase + MXC_UARTUSR2); + /* Clear the modem status interrupt bits */ + writel(MXC_UARTUSR1_RTSD | MXC_UARTUSR1_DTRD, + umxc->port.membase + MXC_UARTUSR1); + writel(MXC_UARTUSR2_DCDDELT | MXC_UARTUSR2_RIDELT, + umxc->port.membase + MXC_UARTUSR2); + mxcuart_modem_status(umxc, sr1, sr2); + handled = 1; + + return IRQ_RETVAL(handled); +} + +/*! + * This function is called by the core driver to test whether the transmitter + * fifo and shift register for the UART port are empty. + * + * @param port the port structure for the UART passed in by the core driver + * + * @return The function returns TIOCSER_TEMT if it is empty, else returns 0. + */ +static unsigned int mxcuart_tx_empty(struct uart_port *port) +{ + volatile unsigned int sr2; + unsigned long flags; + + spin_lock_irqsave(&port->lock, flags); + sr2 = readl(port->membase + MXC_UARTUSR2); + spin_unlock_irqrestore(&port->lock, flags); + + return sr2 & MXC_UARTUSR2_TXDC ? TIOCSER_TEMT : 0; +} + +/*! + * This function is called by the core driver to get the current status of the + * modem input signals. The state of the output signals is not collected. + * + * @param port the port structure for the UART passed in by the core driver + * + * @return The function returns an integer that contains the ORed value of the + * status of all the modem input signals or error. + */ +static unsigned int mxcuart_get_mctrl(struct uart_port *port) +{ + uart_mxc_port *umxc = (uart_mxc_port *) port; + unsigned int result = 0; + volatile unsigned int sr1, sr2; + + sr1 = readl(umxc->port.membase + MXC_UARTUSR1); + sr2 = readl(umxc->port.membase + MXC_UARTUSR2); + + if (sr1 & MXC_UARTUSR1_RTSS) { + result |= TIOCM_CTS; + } + if (umxc->mode == MODE_DTE) { + if (!(sr2 & MXC_UARTUSR2_DCDIN)) { + result |= TIOCM_CAR; + } + if (!(sr2 & MXC_UARTUSR2_RIIN)) { + result |= TIOCM_RI; + } + } + return result; +} + +/*! + * This function is called by the core driver to set the state of the modem + * control lines. + * + * @param port the port structure for the UART passed in by the core driver + * @param mctrl the state that the modem control lines should be changed to + */ +static void mxcuart_set_mctrl(struct uart_port *port, unsigned int mctrl) +{ + uart_mxc_port *umxc = (uart_mxc_port *) port; + volatile unsigned int cr2 = 0, cr3 = 0, uts = 0; + + cr2 = readl(port->membase + MXC_UARTUCR2); + cr3 = readl(port->membase + MXC_UARTUCR3); + uts = readl(port->membase + MXC_UARTUTS); + + if (mctrl & TIOCM_RTS) { + /* + * Return to hardware-driven hardware flow control if the + * option is enabled + */ + if (umxc->hardware_flow == 1) { + cr2 |= MXC_UARTUCR2_CTSC; + } else { + cr2 |= MXC_UARTUCR2_CTS; + cr2 &= ~MXC_UARTUCR2_CTSC; + } + } else { + cr2 &= ~(MXC_UARTUCR2_CTS | MXC_UARTUCR2_CTSC); + } + writel(cr2, port->membase + MXC_UARTUCR2); + + if (mctrl & TIOCM_DTR) { + cr3 |= MXC_UARTUCR3_DSR; + } else { + cr3 &= ~MXC_UARTUCR3_DSR; + } + writel(cr3, port->membase + MXC_UARTUCR3); + + if (mctrl & TIOCM_LOOP) { + if (umxc->ir_mode == IRDA) { + echo_cancel = 0; + } else { + uts |= MXC_UARTUTS_LOOP; + } + } else { + if (umxc->ir_mode == IRDA) { + echo_cancel = 1; + } else { + uts &= ~MXC_UARTUTS_LOOP; + } + } + writel(uts, port->membase + MXC_UARTUTS); +} + +/*! + * This function is called by the core driver to control the transmission of + * the break signal. If break_state is non-zero, the break signal is + * transmitted, the signal is terminated when another call is made with + * break_state set to 0. + * + * @param port the port structure for the UART passed in by the core + * driver + * @param break_state the requested state of the break signal + */ +static void mxcuart_break_ctl(struct uart_port *port, int break_state) +{ + volatile unsigned int cr1; + unsigned long flags; + + spin_lock_irqsave(&port->lock, flags); + cr1 = readl(port->membase + MXC_UARTUCR1); + if (break_state == -1) { + cr1 |= MXC_UARTUCR1_SNDBRK; + } else { + cr1 &= ~MXC_UARTUCR1_SNDBRK; + } + writel(cr1, port->membase + MXC_UARTUCR1); + spin_unlock_irqrestore(&port->lock, flags); +} + +/*! + * The read DMA callback, this method is called when the DMA buffer has received its + * data. This functions copies the data to the tty buffer and updates the tty buffer + * pointers. It also queues the DMA buffer back to the DMA system. + * + * @param arg driver private data + * @param error any DMA error + * @param cnt amount of data that was transferred + */ +static void mxcuart_dmaread_callback(void *arg, int error, unsigned int cnt) +{ + uart_mxc_port *umxc = arg; + struct tty_struct *tty = umxc->port.state->port.tty; + int buff_id, flip_cnt, num_bufs; + mxc_dma_requestbuf_t readchnl_request; + mxc_uart_rxdmamap *rx_buf_elem = NULL; + unsigned int sr1, sr2; + char flag; + + num_bufs = umxc->dma_rxbuf_size / RXDMA_BUFF_SIZE; + /* Clear the aging timer bit */ + writel(MXC_UARTUSR1_AGTIM, umxc->port.membase + MXC_UARTUSR1); + + buff_id = umxc->dma_rxbuf_id; + flag = TTY_NORMAL; + + umxc->dma_rxbuf_id += 1; + if (umxc->dma_rxbuf_id >= num_bufs) { + umxc->dma_rxbuf_id = 0; + } + + rx_buf_elem = (mxc_uart_rxdmamap *) (umxc->rx_dmamap + buff_id); + + if (error == MXC_DMA_TRANSFER_ERROR) { + + sr1 = __raw_readl(umxc->port.membase + MXC_UARTUSR1); + sr2 = __raw_readl(umxc->port.membase + MXC_UARTUSR2); + + if (sr2 & MXC_UARTUSR2_BRCD) { + umxc->port.icount.brk++; + if (uart_handle_break(&umxc->port)) { + goto drop_data; + } + } else if (sr1 & MXC_UARTUSR1_PARITYERR) { + umxc->port.icount.parity++; + } else if (sr1 & MXC_UARTUSR1_FRAMERR) { + umxc->port.icount.frame++; + } else if (sr2 & MXC_UARTUSR2_ORE) { + umxc->port.icount.overrun++; + + } + + if (umxc->port.read_status_mask & MXC_UARTURXD_BRK) { + if (sr2 & MXC_UARTUSR2_BRCD) + flag = TTY_BREAK; + } else if (umxc->port.read_status_mask & MXC_UARTURXD_PRERR) { + if (sr1 & MXC_UARTUSR1_PARITYERR) + flag = TTY_PARITY; + } else if (umxc->port.read_status_mask & MXC_UARTURXD_FRMERR) { + if (sr1 & MXC_UARTUSR1_FRAMERR) + flag = TTY_FRAME; + } else if (umxc->port.read_status_mask & MXC_UARTURXD_OVRRUN) { + if (sr2 & MXC_UARTUSR2_ORE) + flag = TTY_OVERRUN; + } +/* By default clearing all error bits in status reg */ + __raw_writel((MXC_UARTUSR2_BRCD | MXC_UARTUSR2_ORE), + umxc->port.membase + MXC_UARTUSR2); + __raw_writel((MXC_UARTUSR1_PARITYERR | MXC_UARTUSR1_FRAMERR), + umxc->port.membase + MXC_UARTUSR1); + } + + flip_cnt = tty_buffer_request_room(tty, cnt); + + /* Check for space availability in the TTY Flip buffer */ + if (flip_cnt <= 0) { + goto drop_data; + } + umxc->port.icount.rx += flip_cnt; + + tty_insert_flip_string(tty, rx_buf_elem->rx_buf, flip_cnt); + + if (flag != TTY_NORMAL) { + tty_insert_flip_char(tty, 0, flag); + } + + tty_flip_buffer_push(tty); + umxc->port.state->port.tty->real_raw = 1; + + drop_data: + readchnl_request.src_addr = umxc->port.mapbase; + readchnl_request.dst_addr = rx_buf_elem->rx_handle; + readchnl_request.num_of_bytes = RXDMA_BUFF_SIZE; + mxc_dma_config(dma_list[umxc->port.line].rd_channel, &readchnl_request, + 1, MXC_DMA_MODE_READ); + mxc_dma_enable(dma_list[umxc->port.line].rd_channel); +} + +/*! + * Allocates DMA read and write channels, creates DMA read and write buffers and + * sets the channel specific parameters. + * + * @param d_info the structure that holds all the DMA information for a + * particular MXC UART + * @param umxc the MXC UART port structure, this includes the \b uart_port + * structure and other members that are specific to MXC UARTs + * + * @return The function returns 0 on success and a non-zero value on failure. + */ +static int mxcuart_initdma(dma_info *d_info, uart_mxc_port *umxc) +{ + int ret = 0, rxbufs, i, j; + mxc_dma_requestbuf_t *readchnl_reqelem; + mxc_uart_rxdmamap *rx_buf_elem; + + /* Request for the read and write channels */ + d_info->rd_channel = mxc_dma_request(umxc->dma_rx_id, "MXC UART Read"); + if (d_info->rd_channel < 0) { + printk(KERN_ERR "MXC UART: Cannot allocate DMA read channel\n"); + return -1; + } else { + d_info->wr_channel = + mxc_dma_request(umxc->dma_tx_id, "MXC UART Write"); + if (d_info->wr_channel < 0) { + mxc_dma_free(d_info->rd_channel); + printk(KERN_ERR + "MXC UART: Cannot allocate DMA write channel\n"); + return -1; + } + } + + /* Allocate the DMA Transmit Buffer */ + umxc->tx_buf = kmalloc(TXDMA_BUFF_SIZE, GFP_KERNEL); + if (umxc->tx_buf == NULL) { + ret = -1; + goto err_dma_tx_buff; + } + rxbufs = umxc->dma_rxbuf_size / RXDMA_BUFF_SIZE; + /* Allocate the DMA Virtual Receive Buffer */ + umxc->rx_dmamap = kmalloc(rxbufs * sizeof(mxc_uart_rxdmamap), GFP_KERNEL); + if (umxc->rx_dmamap == NULL) { + ret = -1; + goto err_dma_rx_buff; + } + + /* Allocate the DMA Receive Request structures */ + readchnl_reqelem = kmalloc(rxbufs * sizeof(mxc_dma_requestbuf_t), + GFP_KERNEL); + if (readchnl_reqelem == NULL) { + ret = -1; + goto err_request; + } + + for (i = 0; i < rxbufs; i++) { + rx_buf_elem = (mxc_uart_rxdmamap *) (umxc->rx_dmamap + i); + rx_buf_elem->rx_buf = + dma_alloc_coherent(NULL, RXDMA_BUFF_SIZE, + &rx_buf_elem->rx_handle, GFP_DMA); + if (rx_buf_elem->rx_buf == NULL) { + for (j = 0; j < i; j++) { + rx_buf_elem = + (mxc_uart_rxdmamap *) (umxc->rx_dmamap + j); + dma_free_coherent(NULL, RXDMA_BUFF_SIZE, + rx_buf_elem->rx_buf, + rx_buf_elem->rx_handle); + } + ret = -1; + goto cleanup; + } + } + + umxc->dma_rxbuf_id = 0; + /* Setup the DMA read request structures */ + for (i = 0; i < rxbufs; i++) { + rx_buf_elem = (mxc_uart_rxdmamap *) (umxc->rx_dmamap + i); + (readchnl_reqelem + i)->src_addr = umxc->port.mapbase; + (readchnl_reqelem + i)->dst_addr = rx_buf_elem->rx_handle; + (readchnl_reqelem + i)->num_of_bytes = RXDMA_BUFF_SIZE; + } + mxc_dma_config(d_info->rd_channel, readchnl_reqelem, rxbufs, + MXC_DMA_MODE_READ); + mxc_dma_callback_set(d_info->rd_channel, mxcuart_dmaread_callback, + umxc); + mxc_dma_callback_set(d_info->wr_channel, mxcuart_dma_writecallback, + umxc); + + /* Start the read channel */ + mxc_dma_enable(d_info->rd_channel); + kfree(readchnl_reqelem); + tasklet_init(&d_info->dma_tx_tasklet, dma_tx_do_tasklet, + (unsigned long)umxc); + d_info->dma_txchnl_inuse = 0; + return ret; + cleanup: + kfree(readchnl_reqelem); + err_request: + kfree(umxc->rx_dmamap); + err_dma_rx_buff: + kfree(umxc->tx_buf); + err_dma_tx_buff: + mxc_dma_free(d_info->rd_channel); + mxc_dma_free(d_info->wr_channel); + + return ret; +} + +/*! + * Stops DMA and frees the DMA resources + * + * @param d_info the structure that holds all the DMA information for a + * particular MXC UART + * @param umxc the MXC UART port structure, this includes the \b uart_port + * structure and other members that are specific to MXC UARTs + */ +static void mxcuart_freedma(dma_info *d_info, uart_mxc_port *umxc) +{ + int i, rxbufs; + mxc_uart_rxdmamap *rx_buf_elem; + + rxbufs = umxc->dma_rxbuf_size / RXDMA_BUFF_SIZE; + + for (i = 0; i < rxbufs; i++) { + rx_buf_elem = (mxc_uart_rxdmamap *) (umxc->rx_dmamap + i); + dma_free_coherent(NULL, RXDMA_BUFF_SIZE, + rx_buf_elem->rx_buf, rx_buf_elem->rx_handle); + } + kfree(umxc->rx_dmamap); + kfree(umxc->tx_buf); + mxc_dma_free(d_info->rd_channel); + mxc_dma_free(d_info->wr_channel); +} + +/*! + * This function is called to free the interrupts. + * + * @param umxc the MXC UART port structure, this includes the \b uart_port + * structure and other members that are specific to MXC UARTs + */ +static void mxcuart_free_interrupts(uart_mxc_port *umxc) +{ + free_irq(umxc->port.irq, umxc); + if (umxc->ints_muxed == 0) { + free_irq(umxc->irqs[0], umxc); + free_irq(umxc->irqs[1], umxc); + } +} + +/*! + * Calculate and set the UART port clock value + * + * @param umxc the MXC UART port structure, this includes the \b uart_port + * structure and other members that are specific to MXC UARTs + * @param per_clk peripheral clock coming into the MXC UART module + * @param req_baud current baudrate requested + * @param div returns the reference frequency divider value + */ +static void mxcuart_set_ref_freq(uart_mxc_port *umxc, unsigned long per_clk, + unsigned int req_baud, int *div) +{ + unsigned int d = 1; + + /* + * Choose the smallest possible prescaler to maximize + * the chance of using integer scaling. Ensure that + * the calculation won't overflow. Limit the denom + * to 15 bits since a 16-bit denom doesn't work. + */ + if (req_baud < (1 << (31 - (4 + 15)))) + d = per_clk / (req_baud << (4 + 15)) + 1; + + umxc->port.uartclk = per_clk / d; + + /* + * Set the ONEMS register that is used by IR special case bit and + * the Escape character detect logic + */ + writel(umxc->port.uartclk / 1000, umxc->port.membase + MXC_UARTONEMS); + *div = d; +} + +/*! + * This function is called by the core driver to initialize the low-level + * driver. The function grabs the interrupt resources and registers its + * interrupt service routines. It then initializes the IOMUX registers to + * configure the pins for UART signals and finally initializes the various + * UART registers and enables the port for reception. + * + * @param port the port structure for the UART passed in by the core driver + * + * @return The function returns 0 on success and a non-zero value on failure. + */ +static int mxcuart_startup(struct uart_port *port) +{ + uart_mxc_port *umxc = (uart_mxc_port *) port; + int retval; + volatile unsigned int cr, cr1 = 0, cr2 = 0, ufcr = 0; + + /* + * Some UARTs need separate registrations for the interrupts as + * they do not take the muxed interrupt output to the ARM core + */ + if (umxc->ints_muxed == 1) { + retval = request_irq(umxc->port.irq, mxcuart_int, 0, + "mxcintuart", umxc); + if (retval != 0) { + return retval; + } + } else { + retval = request_irq(umxc->port.irq, mxcuart_tx_int, + 0, "mxcintuart", umxc); + if (retval != 0) { + return retval; + } else { + retval = request_irq(umxc->irqs[0], mxcuart_rx_int, + 0, "mxcintuart", umxc); + if (retval != 0) { + free_irq(umxc->port.irq, umxc); + return retval; + } else { + retval = + request_irq(umxc->irqs[1], mxcuart_mint_int, + 0, "mxcintuart", umxc); + if (retval != 0) { + free_irq(umxc->port.irq, umxc); + free_irq(umxc->irqs[0], umxc); + return retval; + } + } + } + } + + /* Initialize the DMA if we need SDMA data transfer */ + if (umxc->dma_enabled == 1) { + retval = mxcuart_initdma(dma_list + umxc->port.line, umxc); + if (retval != 0) { + printk + (KERN_ERR + "MXC UART: Failed to initialize DMA for UART %d\n", + umxc->port.line); + mxcuart_free_interrupts(umxc); + return retval; + } + /* Configure the GPR register to receive SDMA events */ + config_uartdma_event(umxc->port.line); + } + + /* + * Clear Status Registers 1 and 2 + */ + writel(0xFFFF, umxc->port.membase + MXC_UARTUSR1); + writel(0xFFFF, umxc->port.membase + MXC_UARTUSR2); + + /* Configure the IOMUX for the UART */ + gpio_uart_active(umxc->port.line, umxc->ir_mode); + + /* + * Set the transceiver invert bits if required + */ + if (umxc->ir_mode == IRDA) { + echo_cancel = 1; + writel(umxc->ir_rx_inv | MXC_UARTUCR4_IRSC, umxc->port.membase + + MXC_UARTUCR4); + writel(umxc->rxd_mux | umxc->ir_tx_inv, + umxc->port.membase + MXC_UARTUCR3); + } else { + writel(umxc->rxd_mux, umxc->port.membase + MXC_UARTUCR3); + } + + /* + * Initialize UCR1,2 and UFCR registers + */ + if (umxc->dma_enabled == 1) { + cr2 = (MXC_UARTUCR2_TXEN | MXC_UARTUCR2_RXEN); + } else { + cr2 = + (MXC_UARTUCR2_ATEN | MXC_UARTUCR2_TXEN | MXC_UARTUCR2_RXEN); + } + + writel(cr2, umxc->port.membase + MXC_UARTUCR2); + /* Wait till we are out of software reset */ + do { + cr = readl(umxc->port.membase + MXC_UARTUCR2); + } while (!(cr & MXC_UARTUCR2_SRST)); + + if (umxc->mode == MODE_DTE) { + ufcr |= ((umxc->tx_threshold << MXC_UARTUFCR_TXTL_OFFSET) | + MXC_UARTUFCR_DCEDTE | MXC_UARTUFCR_RFDIV | umxc-> + rx_threshold); + } else { + ufcr |= ((umxc->tx_threshold << MXC_UARTUFCR_TXTL_OFFSET) | + MXC_UARTUFCR_RFDIV | umxc->rx_threshold); + } + writel(ufcr, umxc->port.membase + MXC_UARTUFCR); + + /* + * Finally enable the UART and the Receive interrupts + */ + if (umxc->ir_mode == IRDA) { + cr1 |= MXC_UARTUCR1_IREN; + } + if (umxc->dma_enabled == 1) { + cr1 |= (MXC_UARTUCR1_RXDMAEN | MXC_UARTUCR1_ATDMAEN | + MXC_UARTUCR1_UARTEN); + } else { + cr1 |= (MXC_UARTUCR1_RRDYEN | MXC_UARTUCR1_UARTEN); + } + writel(cr1, umxc->port.membase + MXC_UARTUCR1); + + return 0; +} + +/*! + * This function is called by the core driver for the low-level driver to free + * its resources. The function frees all its interrupts and disables the UART. + * + * @param port the port structure for the UART passed in by the core driver + */ +static void mxcuart_shutdown(struct uart_port *port) +{ + uart_mxc_port *umxc = (uart_mxc_port *) port; + + /* Disable the IOMUX for the UART */ + gpio_uart_inactive(umxc->port.line, umxc->ir_mode); + mxcuart_free_interrupts(umxc); + /* Disable all interrupts, port and break condition */ + writel(0, umxc->port.membase + MXC_UARTUCR1); + writel(0, umxc->port.membase + MXC_UARTUCR3); + if (umxc->dma_enabled == 1) { + mxcuart_freedma(dma_list + umxc->port.line, umxc); + } +} + +/*! + * This function is called by the core driver to change the UART parameters, + * including baudrate, word length, parity, stop bits. The function also updates + * the port structures mask registers to indicate the types of events the user is + * interested in receiving. + * + * @param port the port structure for the UART passed in by the core driver + * @param termios the desired termios settings + * @param old old termios + */ +static void mxcuart_set_termios(struct uart_port *port, + struct ktermios *termios, struct ktermios *old) +{ + uart_mxc_port *umxc = (uart_mxc_port *) port; + volatile unsigned int cr4 = 0, cr2 = 0, ufcr; + u_int num, denom, baud; + u_int cr2_mask; /* Used to add the changes to CR2 */ + unsigned long flags, per_clk; + int div; + + cr2_mask = ~(MXC_UARTUCR2_IRTS | MXC_UARTUCR2_CTSC | MXC_UARTUCR2_PREN | + MXC_UARTUCR2_PROE | MXC_UARTUCR2_STPB | MXC_UARTUCR2_WS); + + per_clk = clk_get_rate(umxc->clk); + + /* + * Ask the core to get the baudrate, if requested baudrate is not + * between max and min, then either use the baudrate in old termios + * setting. If it's still invalid, we try 9600 baud. + */ + baud = uart_get_baud_rate(&umxc->port, termios, old, 0, per_clk / 16); + /* Set the Reference frequency divider */ + mxcuart_set_ref_freq(umxc, per_clk, baud, &div); + + /* Byte size, default is 8-bit mode */ + switch (termios->c_cflag & CSIZE) { + case CS7: + cr2 = 0; + break; + default: + cr2 = MXC_UARTUCR2_WS; + break; + } + /* Check to see if we need 2 Stop bits */ + if (termios->c_cflag & CSTOPB) { + cr2 |= MXC_UARTUCR2_STPB; + } + + /* Check to see if we need Parity checking */ + if (termios->c_cflag & PARENB) { + cr2 |= MXC_UARTUCR2_PREN; + if (termios->c_cflag & PARODD) { + cr2 |= MXC_UARTUCR2_PROE; + } + } + spin_lock_irqsave(&umxc->port.lock, flags); + + ufcr = readl(umxc->port.membase + MXC_UARTUFCR); + ufcr = (ufcr & (~MXC_UARTUFCR_RFDIV_MASK)) | + ((6 - div) << MXC_UARTUFCR_RFDIV_OFFSET); + writel(ufcr, umxc->port.membase + MXC_UARTUFCR); + + /* + * Update the per-port timeout + */ + uart_update_timeout(&umxc->port, termios->c_cflag, baud); + + umxc->port.read_status_mask = MXC_UARTURXD_OVRRUN; + /* + * Enable appropriate events to be passed to the TTY layer + */ + if (termios->c_iflag & INPCK) { + umxc->port.read_status_mask |= MXC_UARTURXD_FRMERR | + MXC_UARTURXD_PRERR; + } + if (termios->c_iflag & (BRKINT | PARMRK)) { + umxc->port.read_status_mask |= MXC_UARTURXD_BRK; + } + + /* + * Characters to ignore + */ + umxc->port.ignore_status_mask = 0; + if (termios->c_iflag & IGNPAR) { + umxc->port.ignore_status_mask |= MXC_UARTURXD_FRMERR | + MXC_UARTURXD_PRERR; + } + if (termios->c_iflag & IGNBRK) { + umxc->port.ignore_status_mask |= MXC_UARTURXD_BRK; + /* + * If we are ignoring parity and break indicators, + * ignore overruns too (for real raw support) + */ + if (termios->c_iflag & IGNPAR) { + umxc->port.ignore_status_mask |= MXC_UARTURXD_OVRRUN; + } + } + + /* + * Ignore all characters if CREAD is not set, still receive characters + * from the port, but throw them away. + */ + if ((termios->c_cflag & CREAD) == 0) { + umxc->port.ignore_status_mask |= UART_CREAD_BIT; + } + + cr4 = readl(umxc->port.membase + MXC_UARTUCR4); + if (UART_ENABLE_MS(port, termios->c_cflag)) { + mxcuart_enable_ms(port); + if (umxc->hardware_flow == 1) { + cr4 = (cr4 & (~MXC_UARTUCR4_CTSTL_MASK)) | + (umxc->cts_threshold << MXC_UARTUCR4_CTSTL_OFFSET); + cr2 |= MXC_UARTUCR2_CTSC; + umxc->port.state->port.tty->hw_stopped = 0; + } else { + cr2 |= MXC_UARTUCR2_IRTS; + } + } else { + cr2 |= MXC_UARTUCR2_IRTS; + } + + /* Add Parity, character length and stop bits information */ + cr2 |= (readl(umxc->port.membase + MXC_UARTUCR2) & cr2_mask); + writel(cr2, umxc->port.membase + MXC_UARTUCR2); + /* + if (umxc->ir_mode == IRDA) { + ret = mxcuart_setir_special(baud); + if (ret == 0) { + cr4 &= ~MXC_UARTUCR4_IRSC; + } else { + cr4 |= MXC_UARTUCR4_IRSC; + } + } */ + writel(cr4, umxc->port.membase + MXC_UARTUCR4); + + /* + * Set baud rate + */ + + /* Use integer scaling, if possible. Limit the denom to 15 bits. */ + num = 0; + denom = (umxc->port.uartclk + 8 * baud) / (16 * baud) - 1; + + /* Use fractional scaling if needed to limit the max error to 0.5% */ + if (denom < 100) { + u64 n64 = (u64) 16 * 0x8000 * baud + (umxc->port.uartclk / 2); + do_div(n64, umxc->port.uartclk); + num = (u_int) n64 - 1; + denom = 0x7fff; + } + writel(num, umxc->port.membase + MXC_UARTUBIR); + writel(denom, umxc->port.membase + MXC_UARTUBMR); + + spin_unlock_irqrestore(&umxc->port.lock, flags); +} + +/*! + * This function is called by the core driver to know the UART type. + * + * @param port the port structure for the UART passed in by the core driver + * + * @return The function returns a pointer to a string describing the UART port. + */ +static const char *mxcuart_type(struct uart_port *port) +{ + return port->type == PORT_IMX ? "Freescale i.MX" : NULL; +} + +/*! + * This function is called by the core driver to release the memory resources + * currently in use by the UART port. + * + * @param port the port structure for the UART passed in by the core driver + */ +static void mxcuart_release_port(struct uart_port *port) +{ + release_mem_region(port->mapbase, SZ_4K); +} + +/*! + * This function is called by the core driver to request memory resources for + * the UART port. + * + * @param port the port structure for the UART passed in by the core driver + * + * @return The function returns \b -EBUSY on failure, else it returns 0. + */ +static int mxcuart_request_port(struct uart_port *port) +{ + struct platform_device *pdev = to_platform_device(port->dev); + struct resource *mmres; + void *ret; + + mmres = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!mmres) + return -ENODEV; + + ret = request_mem_region(mmres->start, mmres->end - mmres->start + 1, + "serial_mxc"); + + return ret ? 0 : -EBUSY; +} + +/*! + * This function is called by the core driver to perform any autoconfiguration + * steps required for the UART port. This function sets the port->type field. + * + * @param port the port structure for the UART passed in by the core driver + * @param flags bit mask of the required configuration + */ +static void mxcuart_config_port(struct uart_port *port, int flags) +{ + if ((flags & UART_CONFIG_TYPE) && (mxcuart_request_port(port) == 0)) { + port->type = PORT_IMX; + } +} + +/*! + * This function is called by the core driver to verify that the new serial + * port information contained within \a ser is suitable for this UART port type. + * The function checks to see if the UART port type specified by the user + * application while setting the UART port information matches what is stored + * in the define \b PORT_MXC found in the header file include/linux/serial_core.h + * + * @param port the port structure for the UART passed in by the core driver + * @param ser the new serial port information + * + * @return The function returns 0 on success or \b -EINVAL if the port type + * specified is not equal to \b PORT_MXC. + */ +static int mxcuart_verify_port(struct uart_port *port, + struct serial_struct *ser) +{ + int ret = 0; + if (ser->type != PORT_UNKNOWN && ser->type != PORT_IMX) { + ret = -EINVAL; + } + return ret; +} + +/*! + * This function is used to send a high priority XON/XOFF character + * + * @param port the port structure for the UART passed in by the core driver + * @param ch the character to send + */ +static void mxcuart_send_xchar(struct uart_port *port, char ch) +{ + unsigned long flags; + + port->x_char = ch; + if (port->state->port.tty->hw_stopped) { + return; + } + + if (ch) { + spin_lock_irqsave(&port->lock, flags); + port->ops->start_tx(port); + spin_unlock_irqrestore(&port->lock, flags); + } +} + +/*! + * This function is used enable/disable the MXC UART clocks + * + * @param port the port structure for the UART passed in by the core driver + * @param state New PM state + * @param oldstate Current PM state + */ +static void +mxcuart_pm(struct uart_port *port, unsigned int state, unsigned int oldstate) +{ + uart_mxc_port *umxc = (uart_mxc_port *) port; + + if (state) + clk_disable(umxc->clk); + else + clk_enable(umxc->clk); +} + +/*! + * This structure contains the pointers to the control functions that are + * invoked by the core serial driver to access the UART hardware. The + * structure is passed to serial_core.c file during registration. + */ +static struct uart_ops mxc_ops = { + .tx_empty = mxcuart_tx_empty, + .set_mctrl = mxcuart_set_mctrl, + .get_mctrl = mxcuart_get_mctrl, + .stop_tx = mxcuart_stop_tx, + .start_tx = mxcuart_start_tx, + .stop_rx = mxcuart_stop_rx, + .enable_ms = mxcuart_enable_ms, + .break_ctl = mxcuart_break_ctl, + .startup = mxcuart_startup, + .shutdown = mxcuart_shutdown, + .set_termios = mxcuart_set_termios, + .type = mxcuart_type, + .pm = mxcuart_pm, + .release_port = mxcuart_release_port, + .request_port = mxcuart_request_port, + .config_port = mxcuart_config_port, + .verify_port = mxcuart_verify_port, + .send_xchar = mxcuart_send_xchar, +}; + +#ifdef CONFIG_SERIAL_MXC_CONSOLE + +/* + * Write out a character once the UART is ready + */ +static inline void mxcuart_console_write_char(struct uart_port *port, char ch) +{ + volatile unsigned int status; + + do { + status = readl(port->membase + MXC_UARTUSR1); + } while ((status & MXC_UARTUSR1_TRDY) == 0); + writel(ch, port->membase + MXC_UARTUTXD); +} + +/*! + * This function is called to write the console messages through the UART port. + * + * @param co the console structure + * @param s the log message to be written to the UART + * @param count length of the message + */ +static void mxcuart_console_write(struct console *co, const char *s, + u_int count) +{ + struct uart_port *port = &mxc_ports[co->index]->port; + volatile unsigned int status, oldcr1, oldcr2, oldcr3, cr2, cr3; + int i; + + /* + * First save the control registers and then disable the interrupts + */ + oldcr1 = readl(port->membase + MXC_UARTUCR1); + oldcr2 = readl(port->membase + MXC_UARTUCR2); + oldcr3 = readl(port->membase + MXC_UARTUCR3); + cr2 = + oldcr2 & ~(MXC_UARTUCR2_ATEN | MXC_UARTUCR2_RTSEN | + MXC_UARTUCR2_ESCI); + cr3 = + oldcr3 & ~(MXC_UARTUCR3_DCD | MXC_UARTUCR3_RI | + MXC_UARTUCR3_DTRDEN); + writel(MXC_UARTUCR1_UARTEN, port->membase + MXC_UARTUCR1); + writel(cr2, port->membase + MXC_UARTUCR2); + writel(cr3, port->membase + MXC_UARTUCR3); + /* + * Do each character + */ + for (i = 0; i < count; i++) { + mxcuart_console_write_char(port, s[i]); + if (s[i] == '\n') { + mxcuart_console_write_char(port, '\r'); + } + } + /* + * Finally, wait for the transmitter to become empty + */ + do { + status = readl(port->membase + MXC_UARTUSR2); + } while (!(status & MXC_UARTUSR2_TXDC)); + + /* + * Restore the control registers + */ + writel(oldcr1, port->membase + MXC_UARTUCR1); + writel(oldcr2, port->membase + MXC_UARTUCR2); + writel(oldcr3, port->membase + MXC_UARTUCR3); +} + +/*! + * Initializes the UART port to be used to print console message with the + * options specified. If no options are specified, then the function + * initializes the UART with the default options of baudrate=115200, 8 bit + * word size, no parity, no flow control. + * + * @param co The console structure + * @param options Any console options passed in from the command line + * + * @return The function returns 0 on success or error. + */ +static int __init mxcuart_console_setup(struct console *co, char *options) +{ + uart_mxc_port *umxc; + int baud = 115200; + int bits = 8; + int parity = 'n'; + int flow = 'n'; + volatile unsigned int cr = 0; + + /* + * Check whether an invalid uart number had been specified, and if + * so, search for the first available port that does have console + * support + */ + if (co->index >= MXC_UART_NR) { + co->index = 0; + } + umxc = mxc_ports[co->index]; + + if (umxc == NULL) { + return -ENODEV; + } + + clk_enable(umxc->clk); + + /* initialize port.lock else oops */ + spin_lock_init(&umxc->port.lock); + + /* + * Initialize the UART registers + */ + writel(MXC_UARTUCR1_UARTEN, umxc->port.membase + MXC_UARTUCR1); + /* Enable the transmitter and do a software reset */ + writel(MXC_UARTUCR2_TXEN, umxc->port.membase + MXC_UARTUCR2); + /* Wait till we are out of software reset */ + do { + cr = readl(umxc->port.membase + MXC_UARTUCR2); + } while (!(cr & MXC_UARTUCR2_SRST)); + + writel(0x0, umxc->port.membase + MXC_UARTUCR3); + writel(0x0, umxc->port.membase + MXC_UARTUCR4); + /* Set TXTL to 2, RXTL to 1 and RFDIV to 2 */ + cr = 0x0800 | MXC_UARTUFCR_RFDIV | 0x1; + if (umxc->mode == MODE_DTE) { + cr |= MXC_UARTUFCR_DCEDTE; + } + writel(cr, umxc->port.membase + MXC_UARTUFCR); + writel(0xFFFF, umxc->port.membase + MXC_UARTUSR1); + writel(0xFFFF, umxc->port.membase + MXC_UARTUSR2); + + if (options != NULL) { + uart_parse_options(options, &baud, &parity, &bits, &flow); + } + gpio_uart_active(umxc->port.line, umxc->ir_mode); + return uart_set_options(&umxc->port, co, baud, parity, bits, flow); +} + +static struct uart_driver mxc_reg; + +/*! + * This structure contains the pointers to the UART console functions. It is + * passed as an argument when registering the console. + */ +static struct console mxc_console = { + .name = "ttymxc", + .write = mxcuart_console_write, + .device = uart_console_device, + .setup = mxcuart_console_setup, + .flags = CON_PRINTBUFFER, + .index = -1, + .data = &mxc_reg, +}; + +/*! + * This function registers the console callback functions with the kernel. + */ +static int __init mxcuart_console_init(void) +{ + register_console(&mxc_console); + return 0; +} + +console_initcall(mxcuart_console_init); + +static int __init find_port(struct uart_port *p) +{ + int line; + struct uart_port *port; + for (line = 0; line < MXC_UART_NR; line++) { + if (!mxc_ports[line]) + continue; + port = &mxc_ports[line]->port; + if (uart_match_port(p, port)) + return line; + } + return -ENODEV; +} + +int __init mxc_uart_start_console(struct uart_port *port, char *options) +{ + int line; + line = find_port(port); + if (line < 0) + return -ENODEV; + + add_preferred_console("ttymxc", line, options); + printk("Switching Console to ttymxc%d at %s 0x%lx (options '%s')\n", + line, port->iotype == UPIO_MEM ? "MMIO" : "I/O port", + port->iotype == + UPIO_MEM ? (unsigned long)port->mapbase : (unsigned long)port-> + iobase, options); + + if (!(mxc_console.flags & CON_ENABLED)) { + mxc_console.flags &= ~CON_PRINTBUFFER; + register_console(&mxc_console); + } + return 0; +} + +#define MXC_CONSOLE (&mxc_console) +#else +#define MXC_CONSOLE NULL +#endif /* CONFIG_SERIAL_MXC_CONSOLE */ + +/*! + * This structure contains the information such as the name of the UART driver + * that appears in the /dev folder, major and minor numbers etc. This structure + * is passed to the serial_core.c file. + */ +static struct uart_driver mxc_reg = { + .owner = THIS_MODULE, + .driver_name = "ttymxc", + .dev_name = "ttymxc", + .major = SERIAL_MXC_MAJOR, + .minor = SERIAL_MXC_MINOR, + .nr = MXC_UART_NR, + .cons = MXC_CONSOLE, +}; + +/*! + * This function is called to put the UART in a low power state. Refer to the + * document driver-model/driver.txt in the kernel source tree for more + * information. + * + * @param pdev the device structure used to give information on which UART + * to suspend + * @param state the power state the device is entering + * + * @return The function returns 0 on success and -1 on failure + */ +static int mxcuart_suspend(struct platform_device *pdev, pm_message_t state) +{ + uart_mxc_port *umxc = platform_get_drvdata(pdev); + + if (umxc == NULL) + return 0; /* skip disabled ports */ + + if (umxc && umxc->port.flags & ASYNC_INITIALIZED) + uart_suspend_port(&mxc_reg, &umxc->port); + + if (umxc && umxc->port.flags & ASYNC_SUSPENDED) + umxc->port.state->port.tty->hw_stopped = 1; + + return 0; +} + +/*! + * This function is called to bring the UART back from a low power state. Refer + * to the document driver-model/driver.txt in the kernel source tree for more + * information. + * + * @param pdev the device structure used to give information on which UART + * to resume + * + * @return The function returns 0 on success and -1 on failure + */ +static int mxcuart_resume(struct platform_device *pdev) +{ + uart_mxc_port *umxc = platform_get_drvdata(pdev); + + if (umxc == NULL) + return 0; /* skip disabled ports */ + + if (umxc && umxc->port.flags & ASYNC_SUSPENDED) { + umxc->port.state->port.tty->hw_stopped = 0; + uart_resume_port(&mxc_reg, &umxc->port); + } + + return 0; +} + +/*! + * This function is called during the driver binding process. Based on the UART + * that is being probed this function adds the appropriate UART port structure + * in the core driver. + * + * @param pdev the device structure used to store device specific + * information that is used by the suspend, resume and remove + * functions + * + * @return The function returns 0 if successful; -1 otherwise. + */ +static int mxcuart_probe(struct platform_device *pdev) +{ + int id = pdev->id; + struct resource *res; + void __iomem *base; + + mxc_ports[id] = pdev->dev.platform_data; + mxc_ports[id]->port.ops = &mxc_ops; + + /* Do not use UARTs that are disabled during integration */ + if (mxc_ports[id]->enabled == 1) { + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!res) + return -ENODEV; + + base = ioremap(res->start, res->end - res->start + 1); + if (!base) + return -ENOMEM; + + mxc_ports[id]->port.membase = base; + mxc_ports[id]->port.mapbase = res->start; + mxc_ports[id]->port.dev = &pdev->dev; + mxc_ports[id]->port.irq = platform_get_irq(pdev, 0); + mxc_ports[id]->irqs[0] = platform_get_irq(pdev, 1); + mxc_ports[id]->irqs[1] = platform_get_irq(pdev, 2); + spin_lock_init(&mxc_ports[id]->port.lock); + /* Enable the low latency flag for DMA UART ports */ + if (mxc_ports[id]->dma_enabled == 1) { + mxc_ports[id]->port.flags |= ASYNC_LOW_LATENCY; + } + + mxc_ports[id]->clk = clk_get(&pdev->dev, NULL); + if (mxc_ports[id]->clk == NULL) + return -1; + + uart_add_one_port(&mxc_reg, &mxc_ports[id]->port); + platform_set_drvdata(pdev, mxc_ports[id]); + } + return 0; +} + +/*! + * Dissociates the driver from the UART device. Removes the appropriate UART + * port structure from the core driver. + * + * @param pdev the device structure used to give information on which UART + * to remove + * + * @return The function always returns 0. + */ +static int mxcuart_remove(struct platform_device *pdev) +{ + uart_mxc_port *umxc = platform_get_drvdata(pdev); + + platform_set_drvdata(pdev, NULL); + + if (umxc) { + uart_remove_one_port(&mxc_reg, &umxc->port); + iounmap(umxc->port.membase); + } + return 0; +} + +/*! + * This structure contains pointers to the power management callback functions. + */ +static struct platform_driver mxcuart_driver = { + .driver = { + .name = "mxcintuart", + }, + .probe = mxcuart_probe, + .remove = mxcuart_remove, + .suspend = mxcuart_suspend, + .resume = mxcuart_resume, +}; + +/*! + * This function is used to initialize the UART driver module. The function + * registers the power management callback functions with the kernel and also + * registers the UART callback functions with the core serial driver. + * + * @return The function returns 0 on success and a non-zero value on failure. + */ +static int __init mxcuart_init(void) +{ + int ret = 0; + + printk(KERN_INFO "Serial: MXC Internal UART driver\n"); + ret = uart_register_driver(&mxc_reg); + if (ret == 0) { + /* Register the device driver structure. */ + ret = platform_driver_register(&mxcuart_driver); + if (ret != 0) { + uart_unregister_driver(&mxc_reg); + } + } + return ret; +} + +/*! + * This function is used to cleanup all resources before the driver exits. + */ +static void __exit mxcuart_exit(void) +{ + platform_driver_unregister(&mxcuart_driver); + uart_unregister_driver(&mxc_reg); +} + +module_init(mxcuart_init); +module_exit(mxcuart_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MXC serial port driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/serial/mxc_uart_early.c b/drivers/serial/mxc_uart_early.c new file mode 100644 index 000000000000..f4b6493a9a64 --- /dev/null +++ b/drivers/serial/mxc_uart_early.c @@ -0,0 +1,184 @@ +/* + * Copyright (C) 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file drivers/serial/mxc_uart_early.c + * + * @brief Driver for the Freescale Semiconductor MXC serial ports based on + * drivers/char/8250_early.c, Copyright 2004 Hewlett-Packard Development Company, + * L.P. by Bjorn Helgaasby. + * + * Early serial console for MXC UARTS. + * + * This is for use before the serial driver has initialized, in + * particular, before the UARTs have been discovered and named. + * Instead of specifying the console device as, e.g., "ttymxc0", + * we locate the device directly by its MMIO or I/O port address. + * + * The user can specify the device directly, e.g., + * console=mxcuart,0x43f90000,115200n8 + * or platform code can call early_uart_console_init() to set + * the early UART device. + * + * After the normal serial driver starts, we try to locate the + * matching ttymxc device and start a console there. + */ + +/* + * Include Files + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +struct mxc_early_uart_device { + struct uart_port port; + char options[16]; /* e.g., 115200n8 */ + unsigned int baud; + struct clk *clk; +}; +static struct mxc_early_uart_device mxc_early_device __initdata; + +/* + * Write out a character once the UART is ready + */ +static void __init mxcuart_console_write_char(struct uart_port *port, int ch) +{ + unsigned int status; + + do { + status = readl(port->membase + MXC_UARTUSR2); + } while ((status & MXC_UARTUSR2_TXFE) == 0); + writel(ch, port->membase + MXC_UARTUTXD); +} + +/*! + * This function is called to write the console messages through the UART port. + * + * @param co the console structure + * @param s the log message to be written to the UART + * @param count length of the message + */ +void __init early_mxcuart_console_write(struct console *co, const char *s, + u_int count) +{ + struct uart_port *port = &mxc_early_device.port; + volatile unsigned int status, oldcr1, oldcr2, oldcr3, cr2, cr3; + + /* + * First save the control registers and then disable the interrupts + */ + oldcr1 = readl(port->membase + MXC_UARTUCR1); + oldcr2 = readl(port->membase + MXC_UARTUCR2); + oldcr3 = readl(port->membase + MXC_UARTUCR3); + cr2 = + oldcr2 & ~(MXC_UARTUCR2_ATEN | MXC_UARTUCR2_RTSEN | + MXC_UARTUCR2_ESCI); + cr3 = + oldcr3 & ~(MXC_UARTUCR3_DCD | MXC_UARTUCR3_RI | + MXC_UARTUCR3_DTRDEN); + writel(MXC_UARTUCR1_UARTEN, port->membase + MXC_UARTUCR1); + writel(cr2, port->membase + MXC_UARTUCR2); + writel(cr3, port->membase + MXC_UARTUCR3); + + /* Transmit string */ + uart_console_write(port, s, count, mxcuart_console_write_char); + + /* + * Finally, wait for the transmitter to become empty + */ + do { + status = readl(port->membase + MXC_UARTUSR2); + } while (!(status & MXC_UARTUSR2_TXDC)); + + /* + * Restore the control registers + */ + writel(oldcr1, port->membase + MXC_UARTUCR1); + writel(oldcr2, port->membase + MXC_UARTUCR2); + writel(oldcr3, port->membase + MXC_UARTUCR3); +} + +static unsigned int __init probe_baud(struct uart_port *port) +{ + /* FIXME Return Default Baud Rate */ + return 115200; +} + +static int __init mxc_early_uart_setup(struct console *console, char *options) +{ + struct mxc_early_uart_device *device = &mxc_early_device; + struct uart_port *port = &device->port; + int length; + + if (device->port.membase || device->port.iobase) + return -ENODEV; + + /* Enable Early MXC UART Clock */ + clk_enable(device->clk); + + port->uartclk = 5600000; + port->iotype = UPIO_MEM; + port->membase = ioremap(port->mapbase, SZ_4K); + + if (options) { + device->baud = simple_strtoul(options, NULL, 0); + length = min(strlen(options), sizeof(device->options)); + strncpy(device->options, options, length); + } else { + device->baud = probe_baud(port); + snprintf(device->options, sizeof(device->options), "%u", + device->baud); + } + printk(KERN_INFO + "MXC_Early serial console at MMIO 0x%x (options '%s')\n", + port->mapbase, device->options); + return 0; +} + +static struct console mxc_early_uart_console __initdata = { + .name = "ttymxc", + .write = early_mxcuart_console_write, + .setup = mxc_early_uart_setup, + .flags = CON_PRINTBUFFER | CON_BOOT, + .index = -1, +}; + +int __init mxc_early_serial_console_init(unsigned long base, struct clk *clk) +{ + mxc_early_device.clk = clk; + mxc_early_device.port.mapbase = base; + + register_console(&mxc_early_uart_console); + return 0; +} + +int __init mxc_early_uart_console_disable(void) +{ + struct mxc_early_uart_device *device = &mxc_early_device; + struct uart_port *port = &device->port; + + if (mxc_early_uart_console.index >= 0) { + iounmap(port->membase); + clk_disable(device->clk); + clk_put(device->clk); + } + return 0; +} +late_initcall(mxc_early_uart_console_disable); diff --git a/drivers/serial/mxc_uart_reg.h b/drivers/serial/mxc_uart_reg.h new file mode 100644 index 000000000000..dcdcbdb476c1 --- /dev/null +++ b/drivers/serial/mxc_uart_reg.h @@ -0,0 +1,128 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#ifndef __MXC_UART_REG_H__ +#define __MXC_UART_REG_H__ + +/* Address offsets of the UART registers */ +#define MXC_UARTURXD 0x000 /* Receive reg */ +#define MXC_UARTUTXD 0x040 /* Transmitter reg */ +#define MXC_UARTUCR1 0x080 /* Control reg 1 */ +#define MXC_UARTUCR2 0x084 /* Control reg 2 */ +#define MXC_UARTUCR3 0x088 /* Control reg 3 */ +#define MXC_UARTUCR4 0x08C /* Control reg 4 */ +#define MXC_UARTUFCR 0x090 /* FIFO control reg */ +#define MXC_UARTUSR1 0x094 /* Status reg 1 */ +#define MXC_UARTUSR2 0x098 /* Status reg 2 */ +#define MXC_UARTUESC 0x09C /* Escape character reg */ +#define MXC_UARTUTIM 0x0A0 /* Escape timer reg */ +#define MXC_UARTUBIR 0x0A4 /* BRM incremental reg */ +#define MXC_UARTUBMR 0x0A8 /* BRM modulator reg */ +#define MXC_UARTUBRC 0x0AC /* Baud rate count reg */ +#define MXC_UARTONEMS 0x0B0 /* One millisecond reg */ +#define MXC_UARTUTS 0x0B4 /* Test reg */ + +/* Bit definations of UCR1 */ +#define MXC_UARTUCR1_ADEN 0x8000 +#define MXC_UARTUCR1_ADBR 0x4000 +#define MXC_UARTUCR1_TRDYEN 0x2000 +#define MXC_UARTUCR1_IDEN 0x1000 +#define MXC_UARTUCR1_RRDYEN 0x0200 +#define MXC_UARTUCR1_RXDMAEN 0x0100 +#define MXC_UARTUCR1_IREN 0x0080 +#define MXC_UARTUCR1_TXMPTYEN 0x0040 +#define MXC_UARTUCR1_RTSDEN 0x0020 +#define MXC_UARTUCR1_SNDBRK 0x0010 +#define MXC_UARTUCR1_TXDMAEN 0x0008 +#define MXC_UARTUCR1_ATDMAEN 0x0004 +#define MXC_UARTUCR1_DOZE 0x0002 +#define MXC_UARTUCR1_UARTEN 0x0001 + +/* Bit definations of UCR2 */ +#define MXC_UARTUCR2_ESCI 0x8000 +#define MXC_UARTUCR2_IRTS 0x4000 +#define MXC_UARTUCR2_CTSC 0x2000 +#define MXC_UARTUCR2_CTS 0x1000 +#define MXC_UARTUCR2_PREN 0x0100 +#define MXC_UARTUCR2_PROE 0x0080 +#define MXC_UARTUCR2_STPB 0x0040 +#define MXC_UARTUCR2_WS 0x0020 +#define MXC_UARTUCR2_RTSEN 0x0010 +#define MXC_UARTUCR2_ATEN 0x0008 +#define MXC_UARTUCR2_TXEN 0x0004 +#define MXC_UARTUCR2_RXEN 0x0002 +#define MXC_UARTUCR2_SRST 0x0001 + +/* Bit definations of UCR3 */ +#define MXC_UARTUCR3_DTREN 0x2000 +#define MXC_UARTUCR3_PARERREN 0x1000 +#define MXC_UARTUCR3_FRAERREN 0x0800 +#define MXC_UARTUCR3_DSR 0x0400 +#define MXC_UARTUCR3_DCD 0x0200 +#define MXC_UARTUCR3_RI 0x0100 +#define MXC_UARTUCR3_RXDSEN 0x0040 +#define MXC_UARTUCR3_AWAKEN 0x0010 +#define MXC_UARTUCR3_DTRDEN 0x0008 +#define MXC_UARTUCR3_RXDMUXSEL 0x0004 +#define MXC_UARTUCR3_INVT 0x0002 + +/* Bit definations of UCR4 */ +#define MXC_UARTUCR4_CTSTL_OFFSET 10 +#define MXC_UARTUCR4_CTSTL_MASK (0x3F << 10) +#define MXC_UARTUCR4_INVR 0x0200 +#define MXC_UARTUCR4_ENIRI 0x0100 +#define MXC_UARTUCR4_REF16 0x0040 +#define MXC_UARTUCR4_IRSC 0x0020 +#define MXC_UARTUCR4_TCEN 0x0008 +#define MXC_UARTUCR4_OREN 0x0002 +#define MXC_UARTUCR4_DREN 0x0001 + +/* Bit definations of UFCR */ +#define MXC_UARTUFCR_RFDIV 0x0200 /* Ref freq div is set to 2 */ +#define MXC_UARTUFCR_RFDIV_OFFSET 7 +#define MXC_UARTUFCR_RFDIV_MASK (0x7 << 7) +#define MXC_UARTUFCR_TXTL_OFFSET 10 +#define MXC_UARTUFCR_DCEDTE 0x0040 + +/* Bit definations of URXD */ +#define MXC_UARTURXD_ERR 0x4000 +#define MXC_UARTURXD_OVRRUN 0x2000 +#define MXC_UARTURXD_FRMERR 0x1000 +#define MXC_UARTURXD_BRK 0x0800 +#define MXC_UARTURXD_PRERR 0x0400 + +/* Bit definations of USR1 */ +#define MXC_UARTUSR1_PARITYERR 0x8000 +#define MXC_UARTUSR1_RTSS 0x4000 +#define MXC_UARTUSR1_TRDY 0x2000 +#define MXC_UARTUSR1_RTSD 0x1000 +#define MXC_UARTUSR1_FRAMERR 0x0400 +#define MXC_UARTUSR1_RRDY 0x0200 +#define MXC_UARTUSR1_AGTIM 0x0100 +#define MXC_UARTUSR1_DTRD 0x0080 +#define MXC_UARTUSR1_AWAKE 0x0010 + +/* Bit definations of USR2 */ +#define MXC_UARTUSR2_TXFE 0x4000 +#define MXC_UARTUSR2_IDLE 0x1000 +#define MXC_UARTUSR2_RIDELT 0x0400 +#define MXC_UARTUSR2_RIIN 0x0200 +#define MXC_UARTUSR2_DCDDELT 0x0040 +#define MXC_UARTUSR2_DCDIN 0x0020 +#define MXC_UARTUSR2_TXDC 0x0008 +#define MXC_UARTUSR2_ORE 0x0002 +#define MXC_UARTUSR2_RDR 0x0001 + +/* Bit definations of UTS */ +#define MXC_UARTUTS_LOOP 0x1000 + +#endif /* __MXC_UART_REG_H__ */ diff --git a/drivers/serial/mxs-auart.c b/drivers/serial/mxs-auart.c new file mode 100644 index 000000000000..63d7d9128efc --- /dev/null +++ b/drivers/serial/mxs-auart.c @@ -0,0 +1,1108 @@ +/* + * Freescale STMP37XX/STMP378X Application UART driver + * + * Author: dmitry pervushin + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. + * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +#include "regs-uartapp.h" + +#define MXS_AUART_MAJOR 242 +#define MXS_AUART_RX_THRESHOLD 16 + +static struct uart_driver auart_driver; + +struct mxs_auart_port { + struct uart_port port; + + unsigned int flags; +#define MXS_AUART_PORT_OPEN 0x80000000 +#define MXS_AUART_PORT_DMA_MODE 0x80000000 + unsigned int ctrl; + + unsigned int irq[3]; + + struct clk *clk; + struct device *dev; + unsigned int dma_rx_chan; + unsigned int dma_tx_chan; + unsigned int dma_rx_buffer_size; + struct list_head rx_done; + struct list_head free; + struct mxs_dma_desc *tx; + struct tasklet_struct rx_task; +}; + +static void mxs_auart_stop_tx(struct uart_port *u); +static void mxs_auart_submit_tx(struct mxs_auart_port *s, int size); +static void mxs_auart_submit_rx(struct mxs_auart_port *s); + +static inline struct mxs_auart_port *to_auart_port(struct uart_port *u) +{ + return container_of(u, struct mxs_auart_port, port); +} + +static inline void mxs_auart_tx_chars(struct mxs_auart_port *s) +{ + struct circ_buf *xmit = &s->port.info->xmit; + + if (s->flags & MXS_AUART_PORT_DMA_MODE) { + int i = 0, size; + char *buffer = s->tx->buffer; + + if (mxs_dma_desc_pending(s->tx)) + return; + while (!uart_circ_empty(xmit) && !uart_tx_stopped(&s->port)) { + if (i >= PAGE_SIZE) + break; + if (s->port.x_char) { + buffer[i++] = s->port.x_char; + s->port.x_char = 0; + continue; + } + size = min_t(u32, PAGE_SIZE - i, + CIRC_CNT_TO_END(xmit->head, + xmit->tail, + UART_XMIT_SIZE)); + memcpy(buffer + i, xmit->buf + xmit->tail, size); + xmit->tail = (xmit->tail + size) & (UART_XMIT_SIZE - 1); + if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS) + uart_write_wakeup(&s->port); + i += size; + } + if (i) + mxs_auart_submit_tx(s, i); + else { + if (uart_tx_stopped(&s->port)) + mxs_auart_stop_tx(&s->port); + } + return; + } + + while (!(__raw_readl(s->port.membase + HW_UARTAPP_STAT) & + BM_UARTAPP_STAT_TXFF)) { + if (s->port.x_char) { + __raw_writel(s->port.x_char, + s->port.membase + HW_UARTAPP_DATA); + s->port.x_char = 0; + continue; + } + if (!uart_circ_empty(xmit) && !uart_tx_stopped(&s->port)) { + __raw_writel(xmit->buf[xmit->tail], + s->port.membase + HW_UARTAPP_DATA); + xmit->tail = (xmit->tail + 1) & (UART_XMIT_SIZE - 1); + if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS) + uart_write_wakeup(&s->port); + } else + break; + } + if (uart_circ_empty(&(s->port.info->xmit))) + __raw_writel(BM_UARTAPP_INTR_TXIEN, + s->port.membase + HW_UARTAPP_INTR_CLR); + else + __raw_writel(BM_UARTAPP_INTR_TXIEN, + s->port.membase + HW_UARTAPP_INTR_SET); + + if (uart_tx_stopped(&s->port)) + mxs_auart_stop_tx(&s->port); +} + +static inline unsigned int +mxs_auart_rx_char(struct mxs_auart_port *s, unsigned int stat, u8 c) +{ + int flag; + + flag = TTY_NORMAL; + if (stat & BM_UARTAPP_STAT_BERR) { + stat &= ~BM_UARTAPP_STAT_BERR; + s->port.icount.brk++; + if (uart_handle_break(&s->port)) + return stat; + flag = TTY_BREAK; + } else if (stat & BM_UARTAPP_STAT_PERR) { + stat &= ~BM_UARTAPP_STAT_PERR; + s->port.icount.parity++; + flag = TTY_PARITY; + } else if (stat & BM_UARTAPP_STAT_FERR) { + stat &= ~BM_UARTAPP_STAT_FERR; + s->port.icount.frame++; + flag = TTY_FRAME; + } + + if (stat & BM_UARTAPP_STAT_OERR) + s->port.icount.overrun++; + + if (uart_handle_sysrq_char(&s->port, c)) + return stat; + + uart_insert_char(&s->port, stat, BM_UARTAPP_STAT_OERR, c, flag); + return stat; +} + +static void mxs_auart_rx_chars(struct mxs_auart_port *s) +{ + u8 c; + struct tty_struct *tty = s->port.info->port.tty; + u32 stat = 0; + + if (s->flags & MXS_AUART_PORT_DMA_MODE) { + int i, count; + struct list_head *p, *q; + LIST_HEAD(list); + struct mxs_dma_desc *pdesc; + mxs_dma_cooked(s->dma_rx_chan, &list); + stat = __raw_readl(s->port.membase + HW_UARTAPP_STAT); + list_for_each_safe(p, q, &list) { + u8 *buffer; + list_del(p); + pdesc = list_entry(p, struct mxs_dma_desc, node); + count = stat & BM_UARTAPP_STAT_RXCOUNT; + buffer = pdesc->buffer; + for (i = 0; i < count; i++) + stat = mxs_auart_rx_char(s, stat, buffer[i]); + list_add(p, &s->free); + stat = __raw_readl(s->port.membase + HW_UARTAPP_STAT); + } + mxs_auart_submit_rx(s); + goto out; + } + for (;;) { + stat = __raw_readl(s->port.membase + HW_UARTAPP_STAT); + if (stat & BM_UARTAPP_STAT_RXFE) + break; + c = __raw_readl(s->port.membase + HW_UARTAPP_DATA); + stat = mxs_auart_rx_char(s, stat, c); + __raw_writel(stat, s->port.membase + HW_UARTAPP_STAT); + } +out: + __raw_writel(stat, s->port.membase + HW_UARTAPP_STAT); + tty_flip_buffer_push(tty); +} + +/* Allocate and initialize rx and tx DMA chains */ +static int mxs_auart_dma_init(struct mxs_auart_port *s) +{ + int ret, i; + struct list_head *p, *n; + struct mxs_dma_desc *pdesc; + + ret = mxs_dma_request(s->dma_rx_chan, s->dev, dev_name(s->dev)); + if (ret) + goto fail_get_dma_rx; + ret = mxs_dma_request(s->dma_tx_chan, s->dev, dev_name(s->dev)); + if (ret) + goto fail_get_dma_tx; + ret = -ENOMEM; + INIT_LIST_HEAD(&s->rx_done); + INIT_LIST_HEAD(&s->free); + s->tx = NULL; + + + for (i = 0; i < 5; i++) { + pdesc = mxs_dma_alloc_desc(); + if (pdesc == NULL || IS_ERR(pdesc)) + goto fail_alloc_desc; + + if (s->tx == NULL) { + pdesc->buffer = dma_alloc_coherent(s->dev, PAGE_SIZE, + &pdesc->cmd.address, + GFP_DMA); + if (pdesc->buffer == NULL) + goto fail_alloc_desc; + s->tx = pdesc; + } else { + pdesc->buffer = dma_alloc_coherent(s->dev, + s->dma_rx_buffer_size, + &pdesc->cmd.address, + GFP_DMA); + if (pdesc->buffer == NULL) + goto fail_alloc_desc; + list_add_tail(&pdesc->node, &s->free); + } + } + /* + Tell DMA to select UART. + Both DMA channels are shared between app UART and IrDA. + Target id of 0 means UART, 1 means IrDA + */ + mxs_dma_set_target(s->dma_rx_chan, 0); + mxs_dma_set_target(s->dma_tx_chan, 0); + + mxs_dma_enable_irq(s->dma_rx_chan, 1); + mxs_dma_enable_irq(s->dma_tx_chan, 1); + + return 0; +fail_alloc_desc: + if (s->tx) { + if (s->tx->buffer) + dma_free_coherent(s->dev, + PAGE_SIZE, + s->tx->buffer, + s->tx->cmd.address); + s->tx->buffer = NULL; + mxs_dma_free_desc(s->tx); + s->tx = NULL; + } + list_for_each_safe(p, n, &s->free) { + list_del(p); + pdesc = list_entry(p, struct mxs_dma_desc, node); + if (pdesc->buffer) + dma_free_coherent(s->dev, + s->dma_rx_buffer_size, + pdesc->buffer, + pdesc->cmd.address); + pdesc->buffer = NULL; + mxs_dma_free_desc(pdesc); + } + mxs_dma_release(s->dma_tx_chan, s->dev); +fail_get_dma_tx: + mxs_dma_release(s->dma_rx_chan, s->dev); +fail_get_dma_rx: + WARN_ON(ret); + return ret; +} + +static void mxs_auart_dma_exit(struct mxs_auart_port *s) +{ + struct list_head *p, *n; + LIST_HEAD(list); + struct mxs_dma_desc *pdesc; + + mxs_dma_enable_irq(s->dma_rx_chan, 0); + mxs_dma_enable_irq(s->dma_tx_chan, 0); + + mxs_dma_disable(s->dma_tx_chan); + mxs_dma_disable(s->dma_rx_chan); + + mxs_dma_get_cooked(s->dma_tx_chan, &list); + mxs_dma_get_cooked(s->dma_rx_chan, &s->free); + + mxs_dma_release(s->dma_tx_chan, s->dev); + mxs_dma_release(s->dma_rx_chan, s->dev); + + if (s->tx) { + if (s->tx->buffer) + dma_free_coherent(s->dev, + PAGE_SIZE, + s->tx->buffer, + s->tx->cmd.address); + s->tx->buffer = NULL; + mxs_dma_free_desc(s->tx); + s->tx = NULL; + } + list_for_each_safe(p, n, &s->free) { + list_del(p); + pdesc = list_entry(p, struct mxs_dma_desc, node); + if (pdesc->buffer) + dma_free_coherent(s->dev, + s->dma_rx_buffer_size, + pdesc->buffer, + pdesc->cmd.address); + pdesc->buffer = NULL; + mxs_dma_free_desc(pdesc); + } +} + +static void mxs_auart_submit_rx(struct mxs_auart_port *s) +{ + int ret; + unsigned int pio_value; + struct list_head *p, *n; + struct mxs_dma_desc *pdesc; + + pio_value = BM_UARTAPP_CTRL0_RXTO_ENABLE | + BF_UARTAPP_CTRL0_RXTIMEOUT(0x80) | + BF_UARTAPP_CTRL0_XFER_COUNT(s->dma_rx_buffer_size); + + list_for_each_safe(p, n, &s->free) { + list_del(p); + pdesc = list_entry(p, struct mxs_dma_desc, node); + pdesc->cmd.cmd.bits.bytes = s->dma_rx_buffer_size; + pdesc->cmd.cmd.bits.terminate_flush = 1; + pdesc->cmd.cmd.bits.pio_words = 1; + pdesc->cmd.cmd.bits.wait4end = 1; + pdesc->cmd.cmd.bits.dec_sem = 1; + pdesc->cmd.cmd.bits.irq = 1; + pdesc->cmd.cmd.bits.chain = 1; + pdesc->cmd.cmd.bits.command = DMA_WRITE; + pdesc->cmd.pio_words[0] = pio_value; + ret = mxs_dma_desc_append(s->dma_rx_chan, pdesc); + if (ret) + pr_info("%s append dma desc, %d\n", __func__, ret); + } + ret = mxs_dma_enable(s->dma_rx_chan); + if (ret) + pr_info("%s enable dma desc, %d\n", __func__, ret); +} + +static irqreturn_t mxs_auart_irq_dma_rx(int irq, void *context) +{ + struct mxs_auart_port *s = context; + + mxs_dma_ack_irq(s->dma_rx_chan); + mxs_auart_rx_chars(s); + return IRQ_HANDLED; +} + +static void mxs_auart_submit_tx(struct mxs_auart_port *s, int size) +{ + int ret; + struct mxs_dma_desc *d = s->tx; + + d->cmd.pio_words[0] = BF_UARTAPP_CTRL1_XFER_COUNT(size); + d->cmd.cmd.bits.bytes = size; + d->cmd.cmd.bits.pio_words = 1; + d->cmd.cmd.bits.wait4end = 1; + d->cmd.cmd.bits.dec_sem = 1; + d->cmd.cmd.bits.irq = 1; + d->cmd.cmd.bits.command = DMA_READ; + ret = mxs_dma_desc_append(s->dma_tx_chan, s->tx); + if (ret) + pr_info("append dma desc, %d\n", ret); + + ret = mxs_dma_enable(s->dma_tx_chan); + if (ret) + pr_info("enable dma desc, %d\n", ret); +} + +static irqreturn_t mxs_auart_irq_dma_tx(int irq, void *context) +{ + struct mxs_auart_port *s = context; + + LIST_HEAD(list); + mxs_dma_ack_irq(s->dma_tx_chan); + mxs_dma_cooked(s->dma_tx_chan, &list); + mxs_auart_tx_chars(s); + return IRQ_HANDLED; +} + +static int mxs_auart_request_port(struct uart_port *u) +{ + struct mxs_auart_port *s = to_auart_port(u); + + if (!request_mem_region((u32)u->mapbase, SZ_4K, dev_name(s->dev))) + return -EBUSY; + return 0; + +} + +static int mxs_auart_verify_port(struct uart_port *u, + struct serial_struct *ser) +{ + if (u->type != PORT_UNKNOWN && u->type != PORT_IMX) + return -EINVAL; + return 0; +} + +static void mxs_auart_config_port(struct uart_port *u, int flags) +{ +} + +static const char *mxs_auart_type(struct uart_port *u) +{ + struct mxs_auart_port *s = to_auart_port(u); + + return dev_name(s->dev); +} + +static void mxs_auart_release_port(struct uart_port *u) +{ + release_mem_region(u->mapbase, SZ_4K); +} + +static void mxs_auart_set_mctrl(struct uart_port *u, unsigned mctrl) +{ + struct mxs_auart_port *s = to_auart_port(u); + + u32 ctrl = __raw_readl(u->membase + HW_UARTAPP_CTRL2); + + ctrl &= ~BM_UARTAPP_CTRL2_RTS; + if (mctrl & TIOCM_RTS) + ctrl |= BM_UARTAPP_CTRL2_RTS; + s->ctrl = mctrl; + __raw_writel(ctrl, u->membase + HW_UARTAPP_CTRL2); +} + +static u32 mxs_auart_get_mctrl(struct uart_port *u) +{ + struct mxs_auart_port *s = to_auart_port(u); + u32 stat = __raw_readl(u->membase + HW_UARTAPP_STAT); + int ctrl2 = __raw_readl(u->membase + HW_UARTAPP_CTRL2); + u32 mctrl = s->ctrl; + + mctrl &= ~TIOCM_CTS; + if (stat & BM_UARTAPP_STAT_CTS) + mctrl |= TIOCM_CTS; + + if (ctrl2 & BM_UARTAPP_CTRL2_RTS) + mctrl |= TIOCM_RTS; + + return mctrl; +} + +static void mxs_auart_settermios(struct uart_port *u, + struct ktermios *termios, + struct ktermios *old) +{ + u32 bm, ctrl, ctrl2, div; + unsigned int cflag, baud; + + if (termios == NULL) { + printk(KERN_ERR "Empty ktermios setting:!\n"); + return; + } + + cflag = termios->c_cflag; + + ctrl = BM_UARTAPP_LINECTRL_FEN; + ctrl2 = __raw_readl(u->membase + HW_UARTAPP_CTRL2); + + /* byte size */ + switch (cflag & CSIZE) { + case CS5: + bm = 0; + break; + case CS6: + bm = 1; + break; + case CS7: + bm = 2; + break; + case CS8: + bm = 3; + break; + default: + return; + } + + ctrl |= BF_UARTAPP_LINECTRL_WLEN(bm); + + /* parity */ + if (cflag & PARENB) { + ctrl |= BM_UARTAPP_LINECTRL_PEN; + if ((cflag & PARODD) == 0) + ctrl |= BM_UARTAPP_LINECTRL_EPS; + } + + /* figure out the stop bits requested */ + if (cflag & CSTOPB) + ctrl |= BM_UARTAPP_LINECTRL_STP2; + + /* figure out the hardware flow control settings */ + if (cflag & CRTSCTS) + ctrl2 |= BM_UARTAPP_CTRL2_CTSEN /* | BM_UARTAPP_CTRL2_RTSEN */ ; + else + ctrl2 &= ~BM_UARTAPP_CTRL2_CTSEN; + + /* set baud rate */ + baud = uart_get_baud_rate(u, termios, old, 0, u->uartclk); + div = u->uartclk * 32 / baud; + ctrl |= BF_UARTAPP_LINECTRL_BAUD_DIVFRAC(div & 0x3F); + ctrl |= BF_UARTAPP_LINECTRL_BAUD_DIVINT(div >> 6); + + if ((cflag & CREAD) != 0) + ctrl2 |= BM_UARTAPP_CTRL2_RXE; + + __raw_writel(ctrl, u->membase + HW_UARTAPP_LINECTRL); + __raw_writel(ctrl2, u->membase + HW_UARTAPP_CTRL2); +} + +static irqreturn_t mxs_auart_irq_handle(int irq, void *context) +{ + u32 istatus, istat; + struct mxs_auart_port *s = context; + u32 stat = __raw_readl(s->port.membase + HW_UARTAPP_STAT); + + istatus = istat = __raw_readl(s->port.membase + HW_UARTAPP_INTR); + + if (istat & BM_UARTAPP_INTR_CTSMIS) { + uart_handle_cts_change(&s->port, stat & BM_UARTAPP_STAT_CTS); + __raw_writel(BM_UARTAPP_INTR_CTSMIS, + s->port.membase + HW_UARTAPP_INTR_CLR); + istat &= ~BM_UARTAPP_INTR_CTSMIS; + } + if (istat & (BM_UARTAPP_INTR_RTIS | BM_UARTAPP_INTR_RXIS)) { + mxs_auart_rx_chars(s); + istat &= ~(BM_UARTAPP_INTR_RTIS | BM_UARTAPP_INTR_RXIS); + } + + if (istat & BM_UARTAPP_INTR_TXIS) { + mxs_auart_tx_chars(s); + istat &= ~BM_UARTAPP_INTR_TXIS; + } + /* modem status interrupt bits are undefined + after reset,and the hardware do not support + DSRMIS,DCDMIS and RIMIS bit,so we should ingore + them when they are pending. */ + if (istat & (BM_UARTAPP_INTR_ABDIS + | BM_UARTAPP_INTR_OEIS + | BM_UARTAPP_INTR_BEIS + | BM_UARTAPP_INTR_PEIS + | BM_UARTAPP_INTR_FEIS + | BM_UARTAPP_INTR_RTIS + | BM_UARTAPP_INTR_TXIS + | BM_UARTAPP_INTR_RXIS + | BM_UARTAPP_INTR_CTSMIS)) { + dev_info(s->dev, "Unhandled status %x\n", istat); + } + __raw_writel(istatus & (BM_UARTAPP_INTR_ABDIS + | BM_UARTAPP_INTR_OEIS + | BM_UARTAPP_INTR_BEIS + | BM_UARTAPP_INTR_PEIS + | BM_UARTAPP_INTR_FEIS + | BM_UARTAPP_INTR_RTIS + | BM_UARTAPP_INTR_TXIS + | BM_UARTAPP_INTR_RXIS + | BM_UARTAPP_INTR_DSRMIS + | BM_UARTAPP_INTR_DCDMIS + | BM_UARTAPP_INTR_CTSMIS + | BM_UARTAPP_INTR_RIMIS), + s->port.membase + HW_UARTAPP_INTR_CLR); + + return IRQ_HANDLED; +} + +static int mxs_auart_free_irqs(struct mxs_auart_port *s) +{ + int irqn = 0; + + for (irqn = 0; irqn < ARRAY_SIZE(s->irq); irqn++) + free_irq(s->irq[irqn], s); + return 0; +} + +static int mxs_auart_request_irqs(struct mxs_auart_port *s) +{ + int err = 0; + + /* + * order counts. resources should be listed in the same order + */ + irq_handler_t handlers[] = { + mxs_auart_irq_handle, + mxs_auart_irq_dma_rx, + mxs_auart_irq_dma_tx, + }; + char *handlers_names[] = { + "auart internal", + "auart dma rx", + "auart dma tx", + }; + int irqn; + + for (irqn = 0; irqn < ARRAY_SIZE(handlers); irqn++) { + err = request_irq(s->irq[irqn], handlers[irqn], + 0, handlers_names[irqn], s); + if (err) + goto out; + } + return 0; +out: + mxs_auart_free_irqs(s); + return err; +} + +static inline void mxs_auart_reset(struct uart_port *u) +{ + int i; + unsigned int reg; + + __raw_writel(BM_UARTAPP_CTRL0_SFTRST, + u->membase + HW_UARTAPP_CTRL0_CLR); + + for (i = 0; i < 10000; i++) { + reg = __raw_readl(u->membase + HW_UARTAPP_CTRL0); + if (!(reg & BM_UARTAPP_CTRL0_SFTRST)) + break; + udelay(3); + } + + __raw_writel(BM_UARTAPP_CTRL0_CLKGATE, + u->membase + HW_UARTAPP_CTRL0_CLR); +} + +static int mxs_auart_startup(struct uart_port *u) +{ + struct mxs_auart_port *s = to_auart_port(u); + + mxs_auart_reset(u); + + __raw_writel(BM_UARTAPP_CTRL2_UARTEN, + s->port.membase + HW_UARTAPP_CTRL2_SET); + + /* Enable the Application UART DMA bits. */ + if (s->flags & MXS_AUART_PORT_DMA_MODE) { + int ret; + ret = mxs_auart_dma_init(s); + if (ret) { + __raw_writel(BM_UARTAPP_CTRL2_UARTEN, + s->port.membase + HW_UARTAPP_CTRL2_CLR); + return ret; + } + __raw_writel(BM_UARTAPP_CTRL2_TXDMAE | BM_UARTAPP_CTRL2_RXDMAE + | BM_UARTAPP_CTRL2_DMAONERR, + s->port.membase + HW_UARTAPP_CTRL2_SET); + /* clear any pending interrupts */ + __raw_writel(0, s->port.membase + HW_UARTAPP_INTR); + + /* reset all dma channels */ + mxs_dma_reset(s->dma_tx_chan); + mxs_dma_reset(s->dma_rx_chan); + } else + __raw_writel(BM_UARTAPP_INTR_RXIEN | BM_UARTAPP_INTR_RTIEN, + s->port.membase + HW_UARTAPP_INTR); + + __raw_writel(BM_UARTAPP_INTR_CTSMIEN, + s->port.membase + HW_UARTAPP_INTR_SET); + + /* + * Enable fifo so all four bytes of a DMA word are written to + * output (otherwise, only the LSB is written, ie. 1 in 4 bytes) + */ + __raw_writel(BM_UARTAPP_LINECTRL_FEN, + s->port.membase + HW_UARTAPP_LINECTRL_SET); + + if (s->flags & MXS_AUART_PORT_DMA_MODE) + mxs_auart_submit_rx(s); + return mxs_auart_request_irqs(s); +} + +static void mxs_auart_shutdown(struct uart_port *u) +{ + struct mxs_auart_port *s = to_auart_port(u); + + __raw_writel(BM_UARTAPP_CTRL0_SFTRST, + s->port.membase + HW_UARTAPP_CTRL0_SET); + + if (s->flags & MXS_AUART_PORT_DMA_MODE) + mxs_auart_dma_exit(s); + else + __raw_writel(BM_UARTAPP_INTR_RXIEN | BM_UARTAPP_INTR_RTIEN | + BM_UARTAPP_INTR_CTSMIEN, + s->port.membase + HW_UARTAPP_INTR_CLR); + mxs_auart_free_irqs(s); +} + +static unsigned int mxs_auart_tx_empty(struct uart_port *u) +{ + struct mxs_auart_port *s = to_auart_port(u); + + if (s->flags & MXS_AUART_PORT_DMA_MODE) + return mxs_dma_desc_pending(s->tx) ? 0 : TIOCSER_TEMT; + + if (__raw_readl(u->membase + HW_UARTAPP_STAT) & + BM_UARTAPP_STAT_TXFE) + return TIOCSER_TEMT; + else + return 0; +} + +static void mxs_auart_start_tx(struct uart_port *u) +{ + struct mxs_auart_port *s = to_auart_port(u); + + /* enable transmitter */ + __raw_writel(BM_UARTAPP_CTRL2_TXE, u->membase + HW_UARTAPP_CTRL2_SET); + + mxs_auart_tx_chars(s); +} + +static void mxs_auart_stop_tx(struct uart_port *u) +{ + __raw_writel(BM_UARTAPP_CTRL2_TXE, u->membase + HW_UARTAPP_CTRL2_CLR); +} + +static void mxs_auart_stop_rx(struct uart_port *u) +{ + __raw_writel(BM_UARTAPP_CTRL2_RXE, u->membase + HW_UARTAPP_CTRL2_CLR); +} + +static void mxs_auart_break_ctl(struct uart_port *u, int ctl) +{ + if (ctl) + __raw_writel(BM_UARTAPP_LINECTRL_BRK, + u->membase + HW_UARTAPP_LINECTRL_SET); + else + __raw_writel(BM_UARTAPP_LINECTRL_BRK, + u->membase + HW_UARTAPP_LINECTRL_CLR); +} + +static void mxs_auart_enable_ms(struct uart_port *port) +{ + /* just empty */ +} + +static struct uart_ops mxs_auart_ops = { + .tx_empty = mxs_auart_tx_empty, + .start_tx = mxs_auart_start_tx, + .stop_tx = mxs_auart_stop_tx, + .stop_rx = mxs_auart_stop_rx, + .enable_ms = mxs_auart_enable_ms, + .break_ctl = mxs_auart_break_ctl, + .set_mctrl = mxs_auart_set_mctrl, + .get_mctrl = mxs_auart_get_mctrl, + .startup = mxs_auart_startup, + .shutdown = mxs_auart_shutdown, + .set_termios = mxs_auart_settermios, + .type = mxs_auart_type, + .release_port = mxs_auart_release_port, + .request_port = mxs_auart_request_port, + .config_port = mxs_auart_config_port, + .verify_port = mxs_auart_verify_port, +}; +#ifdef CONFIG_SERIAL_MXS_AUART_CONSOLE +static struct mxs_auart_port auart_port[CONFIG_MXS_AUART_PORTS] = {}; + +static void +auart_console_write(struct console *co, const char *s, unsigned int count) +{ + struct uart_port *port; + unsigned int status, old_cr; + int i; + + if (co->index > CONFIG_MXS_AUART_PORTS || co->index < 0) + return; + + port = &auart_port[co->index].port; + + /* First save the CR then disable the interrupts */ + old_cr = __raw_readl(port->membase + HW_UARTAPP_CTRL2); + __raw_writel(BM_UARTAPP_CTRL2_UARTEN | BM_UARTAPP_CTRL2_TXE, + port->membase + HW_UARTAPP_CTRL2_SET); + + /* Now, do each character */ + for (i = 0; i < count; i++) { + do { + status = __raw_readl(port->membase + HW_UARTAPP_STAT); + } while (status & BM_UARTAPP_STAT_TXFF); + + __raw_writel(s[i], port->membase + HW_UARTAPP_DATA); + if (s[i] == '\n') { + do { + status = __raw_readl(port->membase + + HW_UARTAPP_STAT); + } while (status & BM_UARTAPP_STAT_TXFF); + __raw_writel('\r', port->membase + HW_UARTAPP_DATA); + } + } + + /* + * Finally, wait for transmitter to become empty + * and restore the TCR + */ + do { + status = __raw_readl(port->membase + HW_UARTAPP_STAT); + } while (status & BM_UARTAPP_STAT_BUSY); + __raw_writel(old_cr, port->membase + HW_UARTAPP_CTRL2); +} + +static void __init +auart_console_get_options(struct uart_port *port, int *baud, + int *parity, int *bits) +{ + if (__raw_readl(port->membase + HW_UARTAPP_CTRL2) + & BM_UARTAPP_CTRL2_UARTEN) { + unsigned int lcr_h, quot; + lcr_h = __raw_readl(port->membase + HW_UARTAPP_LINECTRL); + + *parity = 'n'; + if (lcr_h & BM_UARTAPP_LINECTRL_PEN) { + if (lcr_h & BM_UARTAPP_LINECTRL_EPS) + *parity = 'e'; + else + *parity = 'o'; + } + + if ((lcr_h & BM_UARTAPP_LINECTRL_WLEN) + == BF_UARTAPP_LINECTRL_WLEN(2)) + *bits = 7; + else + *bits = 8; + + quot = (((__raw_readl(port->membase + HW_UARTAPP_LINECTRL) + & BM_UARTAPP_LINECTRL_BAUD_DIVINT)) + >> (BP_UARTAPP_LINECTRL_BAUD_DIVINT - 6)) + | (((__raw_readl(port->membase + HW_UARTAPP_LINECTRL) + & BM_UARTAPP_LINECTRL_BAUD_DIVFRAC)) + >> BP_UARTAPP_LINECTRL_BAUD_DIVFRAC); + if (quot == 0) + quot = 1; + *baud = (port->uartclk << 2) / quot; + } +} + +static int __init auart_console_setup(struct console *co, char *options) +{ + struct mxs_auart_port *port; + int baud = 115200; + int bits = 8; + int parity = 'n'; + int flow = 'n'; + /* + * Check whether an invalid uart number has been specified, and + * if so, search for the first available port that does have + * console support. + */ + if (co->index > CONFIG_MXS_AUART_PORTS || co->index < 0) + return -EINVAL; + + port = &auart_port[co->index].port; + + if (port->port.membase == 0) { + if (cpu_is_mx23()) { + if (co->index == 1) { + port->port.membase = IO_ADDRESS(0x8006C000); + port->port.mapbase = 0x8006C000; + } else { + port->port.membase = IO_ADDRESS(0x8006E000); + port->port.mapbase = 0x8006E000; + } + } + + port->port.fifosize = 16; + port->port.ops = &mxs_auart_ops; + port->port.flags = ASYNC_BOOT_AUTOCONF; + port->port.line = 0; + } + mxs_auart_reset(port); + + __raw_writel(BM_UARTAPP_CTRL2_UARTEN, + port->port.membase + HW_UARTAPP_CTRL2_SET); + + if (port->clk == NULL || IS_ERR(port->clk)) { + port->clk = clk_get(NULL, "uart"); + if (port->clk == NULL || IS_ERR(port->clk)) + return -ENODEV; + port->port.uartclk = clk_get_rate(port->clk); + } + + if (options) + uart_parse_options(options, &baud, &parity, &bits, &flow); + else + auart_console_get_options(port, &baud, &parity, &bits); + return uart_set_options(port, co, baud, parity, bits, flow); +} + +static struct console auart_console = { + .name = "ttySP", + .write = auart_console_write, + .device = uart_console_device, + .setup = auart_console_setup, + .flags = CON_PRINTBUFFER, + .index = -1, + .data = &auart_driver, +}; + +#ifdef CONFIG_MXS_EARLY_CONSOLE +static int __init auart_console_init(void) +{ + register_console(&auart_console); + return 0; +} + +console_initcall(auart_console_init); +#endif + +#endif +static struct uart_driver auart_driver = { + .owner = THIS_MODULE, + .driver_name = "auart", + .dev_name = "ttySP", + .major = MXS_AUART_MAJOR, + .minor = 0, + .nr = CONFIG_MXS_AUART_PORTS, +#ifdef CONFIG_SERIAL_MXS_AUART_CONSOLE + .cons = &auart_console, +#endif +}; + +static int __devinit mxs_auart_probe(struct platform_device *pdev) +{ + struct mxs_auart_plat_data *plat; + struct mxs_auart_port *s; + u32 version; + int i, ret = 0; + struct resource *r; + + s = kzalloc(sizeof(struct mxs_auart_port), GFP_KERNEL); + if (!s) { + ret = -ENOMEM; + goto out; + } + + plat = pdev->dev.platform_data; + if (plat == NULL) { + ret = -ENOMEM; + goto out_free; + } + + if (plat && plat->clk) + s->clk = clk_get(NULL, plat->clk); + else + s->clk = clk_get(NULL, "uart"); + if (IS_ERR(s->clk)) { + ret = PTR_ERR(s->clk); + goto out_free; + } + + clk_enable(s->clk); + + r = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!r) { + ret = -ENXIO; + goto out_free_clk; + } + s->port.mapbase = r->start; + s->port.membase = (void __iomem *)IO_ADDRESS(r->start); + s->port.ops = &mxs_auart_ops; + s->port.iotype = UPIO_MEM; + s->port.line = pdev->id < 0 ? 0 : pdev->id; + s->port.fifosize = plat->fifo_size; + s->port.timeout = plat->timeout ? plat->timeout : (HZ / 10); + s->port.uartclk = clk_get_rate(s->clk); + s->port.type = PORT_IMX; + s->port.dev = s->dev = get_device(&pdev->dev); + + s->flags = plat->dma_mode ? MXS_AUART_PORT_DMA_MODE : 0; + s->ctrl = 0; + s->dma_rx_buffer_size = plat->dma_rx_buffer_size; + + for (i = 0; i < ARRAY_SIZE(s->irq); i++) { + s->irq[i] = platform_get_irq(pdev, i); + if (s->irq[i] < 0) { + ret = s->irq[i]; + goto out_free_clk; + } + } + s->port.irq = s->irq[0]; + + r = platform_get_resource(pdev, IORESOURCE_DMA, 0); + if (!r) { + ret = -ENXIO; + goto out_free_clk; + } + s->dma_rx_chan = r->start; + + r = platform_get_resource(pdev, IORESOURCE_DMA, 1); + if (!r) { + ret = -ENXIO; + goto out_free_clk; + } + s->dma_tx_chan = r->start; + + platform_set_drvdata(pdev, s); + + device_init_wakeup(&pdev->dev, 1); + +#ifdef CONFIG_SERIAL_MXS_AUART_CONSOLE + memcpy(&auart_port[pdev->id], s, sizeof(struct mxs_auart_port)); +#endif + + ret = uart_add_one_port(&auart_driver, &s->port); + if (ret) + goto out_free_clk; + + version = __raw_readl(s->port.membase + HW_UARTAPP_VERSION); + printk(KERN_INFO "Found APPUART %d.%d.%d\n", + (version >> 24) & 0xFF, + (version >> 16) & 0xFF, version & 0xFFFF); + return 0; + +out_free_clk: + if (!IS_ERR(s->clk)) + clk_put(s->clk); +out_free: + kfree(s); +out: + return ret; +} + +static int __devexit mxs_auart_remove(struct platform_device *pdev) +{ + struct mxs_auart_port *s; + + s = platform_get_drvdata(pdev); + if (s) { + put_device(s->dev); + clk_disable(s->clk); + clk_put(s->clk); + uart_remove_one_port(&auart_driver, &s->port); + kfree(s); + } + return 0; +} + +static struct platform_driver mxs_auart_driver = { + .probe = mxs_auart_probe, + .remove = __devexit_p(mxs_auart_remove), + .driver = { + .name = "mxs-auart", + .owner = THIS_MODULE, + }, +}; + +static int __init mxs_auart_init(void) +{ + int r; + + r = uart_register_driver(&auart_driver); + if (r) + goto out; + r = platform_driver_register(&mxs_auart_driver); + if (r) + goto out_err; + return 0; +out_err: + uart_unregister_driver(&auart_driver); +out: + return r; +} + +static void __exit mxs_auart_exit(void) +{ + platform_driver_unregister(&mxs_auart_driver); + uart_unregister_driver(&auart_driver); +} + +module_init(mxs_auart_init) +module_exit(mxs_auart_exit) +MODULE_LICENSE("GPL"); +MODULE_DESCRIPTION("Freescale MXS application uart driver"); diff --git a/drivers/serial/mxs-duart.c b/drivers/serial/mxs-duart.c new file mode 100644 index 000000000000..171b8628faee --- /dev/null +++ b/drivers/serial/mxs-duart.c @@ -0,0 +1,803 @@ +/* + * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. + * Copyright (C) 2009-2010 Freescale Semiconductor, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#if defined(CONFIG_SERIAL_MXS_DUART_CONSOLE) && defined(CONFIG_MAGIC_SYSRQ) +#define SUPPORT_SYSRQ +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include "regs-duart.h" + +/* treated as variable unless submitted to open-source */ +#define PORT_DUART 100 +#define SERIAL_DUART_MAJOR 204 +#define SERIAL_DUART_MINOR 16 +#define SERIAL_RX_LIMIT 256 +#define ISR_PASS_LIMIT 256 + +#define DUART_DEVID "DebugUART" + +static int force_cd = 1; +static struct uart_driver duart_drv; + +/* + * We wrap our port structure around the generic uart_port. + */ +struct duart_port { + struct uart_port port; + struct clk *clk; + unsigned int im; /* interrupt mask */ + unsigned int old_status; + int suspended; +}; + +static void duart_stop_tx(struct uart_port *port) +{ + struct duart_port *dp = container_of(port, struct duart_port, port); + + dp->im &= ~BM_UARTDBGIMSC_TXIM; + __raw_writel(dp->im, dp->port.membase + HW_UARTDBGIMSC); +} + +static void duart_start_tx(struct uart_port *port) +{ + struct duart_port *dp = container_of(port, struct duart_port, port); + + dp->im |= BM_UARTDBGIMSC_TXIM; + __raw_writel(dp->im, dp->port.membase + HW_UARTDBGIMSC); +} + +static void duart_stop_rx(struct uart_port *port) +{ + struct duart_port *dp = container_of(port, struct duart_port, port); + + dp->im &= ~(BM_UARTDBGIMSC_OEIM | BM_UARTDBGIMSC_BEIM | + BM_UARTDBGIMSC_PEIM | BM_UARTDBGIMSC_FEIM | + BM_UARTDBGIMSC_RTIM | BM_UARTDBGIMSC_RXIM); + __raw_writel(dp->im, dp->port.membase + HW_UARTDBGIMSC); +} + +static void duart_enable_ms(struct uart_port *port) +{ + struct duart_port *dp = container_of(port, struct duart_port, port); + + dp->im |= BM_UARTDBGIMSC_RIMIM | BM_UARTDBGIMSC_CTSMIM | + BM_UARTDBGIMSC_DCDMIM | BM_UARTDBGIMSC_DSRMIM; + __raw_writel(dp->im, dp->port.membase + HW_UARTDBGIMSC); +} + +static void duart_rx_chars(struct duart_port *dp) +{ + struct tty_struct *tty = dp->port.info->port.tty; + unsigned int status, ch, flag, rsr, max_count = SERIAL_RX_LIMIT; + + status = __raw_readl(dp->port.membase + HW_UARTDBGFR); + while ((status & BM_UARTDBGFR_RXFE) == 0 && max_count--) { + ch = __raw_readl(dp->port.membase + HW_UARTDBGDR); + flag = TTY_NORMAL; + dp->port.icount.rx++; + + /* + * Note that the error handling code is + * out of the main execution path + */ + rsr = __raw_readl(dp->port.membase + HW_UARTDBGRSR_ECR); + if (unlikely(rsr & (BM_UARTDBGRSR_ECR_OE | + BM_UARTDBGRSR_ECR_BE | + BM_UARTDBGRSR_ECR_PE | + BM_UARTDBGRSR_ECR_FE))) { + if (rsr & BM_UARTDBGRSR_ECR_BE) { + rsr &= ~(BM_UARTDBGRSR_ECR_FE | + BM_UARTDBGRSR_ECR_PE); + dp->port.icount.brk++; + if (uart_handle_break(&dp->port)) + goto ignore_char; + } else if (rsr & BM_UARTDBGRSR_ECR_PE) + dp->port.icount.parity++; + else if (rsr & BM_UARTDBGRSR_ECR_FE) + dp->port.icount.frame++; + if (rsr & BM_UARTDBGRSR_ECR_OE) + dp->port.icount.overrun++; + + rsr &= dp->port.read_status_mask; + + if (rsr & BM_UARTDBGRSR_ECR_BE) + flag = TTY_BREAK; + else if (rsr & BM_UARTDBGRSR_ECR_PE) + flag = TTY_PARITY; + else if (rsr & BM_UARTDBGRSR_ECR_FE) + flag = TTY_FRAME; + } + + if (uart_handle_sysrq_char(&dp->port, ch)) + goto ignore_char; + + uart_insert_char(&dp->port, rsr, BM_UARTDBGRSR_ECR_OE, ch, + flag); + +ignore_char: + status = __raw_readl(dp->port.membase + HW_UARTDBGFR); + } + tty_flip_buffer_push(tty); + return; +} + +static void duart_tx_chars(struct duart_port *dp) +{ + int count; + struct circ_buf *xmit = &dp->port.info->xmit; + + if (dp->port.x_char) { + __raw_writel(dp->port.x_char, dp->port.membase + HW_UARTDBGDR); + dp->port.icount.tx++; + dp->port.x_char = 0; + return; + } + if (uart_circ_empty(xmit) || uart_tx_stopped(&dp->port)) { + duart_stop_tx(&dp->port); + return; + } + + count = dp->port.fifosize >> 1; + do { + __raw_writel(xmit->buf[xmit->tail], + dp->port.membase + HW_UARTDBGDR); + xmit->tail = (xmit->tail + 1) & (UART_XMIT_SIZE - 1); + dp->port.icount.tx++; + if (uart_circ_empty(xmit)) + break; + } while (--count > 0); + + if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS) + uart_write_wakeup(&dp->port); + + if (uart_circ_empty(xmit)) + duart_stop_tx(&dp->port); +} + +static void duart_modem_status(struct duart_port *dp) +{ + unsigned int status, delta; + status = __raw_readl(dp->port.membase + HW_UARTDBGFR) & + (BM_UARTDBGFR_DCD | BM_UARTDBGFR_DSR | BM_UARTDBGFR_CTS); + + delta = status ^ dp->old_status; + dp->old_status = status; + + if (!delta) + return; + + if (delta & BM_UARTDBGFR_DCD) + uart_handle_dcd_change(&dp->port, status & BM_UARTDBGFR_DCD); + + if (delta & BM_UARTDBGFR_DSR) + dp->port.icount.dsr++; + + if (delta & BM_UARTDBGFR_CTS) + uart_handle_cts_change(&dp->port, status & BM_UARTDBGFR_CTS); + + wake_up_interruptible(&dp->port.info->delta_msr_wait); +} + +static irqreturn_t duart_int(int irq, void *dev_id) +{ + int handled = 0; + struct duart_port *dp = dev_id; + unsigned int status, pass_counter = ISR_PASS_LIMIT; + + spin_lock(&dp->port.lock); + + status = __raw_readl(dp->port.membase + HW_UARTDBGMIS); + while (status) { + handled = 1; + + __raw_writel(status & ~(BM_UARTDBGMIS_TXMIS | + BM_UARTDBGMIS_RTMIS | + BM_UARTDBGMIS_RXMIS), + dp->port.membase + HW_UARTDBGICR); + + if (status & (BM_UARTDBGMIS_RTMIS | BM_UARTDBGMIS_RXMIS)) + duart_rx_chars(dp); + if (status & (BM_UARTDBGMIS_DSRMMIS | + BM_UARTDBGMIS_DCDMMIS | + BM_UARTDBGMIS_CTSMMIS | BM_UARTDBGMIS_RIMMIS)) + duart_modem_status(dp); + if (status & BM_UARTDBGMIS_TXMIS) + duart_tx_chars(dp); + + if (pass_counter-- == 0) + break; + + status = __raw_readl(dp->port.membase + HW_UARTDBGMIS); + }; + + spin_unlock(&dp->port.lock); + + return IRQ_RETVAL(handled); +} + +static unsigned int duart_tx_empty(struct uart_port *port) +{ + struct duart_port *dp = (struct duart_port *)port; + unsigned int status = __raw_readl(dp->port.membase + HW_UARTDBGFR); + return status & (BM_UARTDBGFR_BUSY | BM_UARTDBGFR_TXFF) ? + 0 : TIOCSER_TEMT; +} + +static unsigned int duart_get_mctrl(struct uart_port *port) +{ + unsigned int result = 0; + struct duart_port *dp = (struct duart_port *)port; + unsigned int status = __raw_readl(dp->port.membase + HW_UARTDBGFR); + +#define TEST_AND_SET_BIT(uartbit, tiocmbit) do { \ + if (status & uartbit) \ + result |= tiocmbit; \ + } while (0) + + TEST_AND_SET_BIT(BM_UARTDBGFR_DCD, TIOCM_CAR); + TEST_AND_SET_BIT(BM_UARTDBGFR_DSR, TIOCM_DSR); + TEST_AND_SET_BIT(BM_UARTDBGFR_CTS, TIOCM_CTS); + TEST_AND_SET_BIT(BM_UARTDBGFR_RI, TIOCM_RNG); +#undef TEST_AND_SET_BIT + if (force_cd) + result |= TIOCM_CAR; + return result; +} + +static void duart_set_mctrl(struct uart_port *port, unsigned int mctrl) +{ + unsigned int cr; + struct duart_port *dp = (struct duart_port *)port; + + cr = __raw_readl(dp->port.membase + HW_UARTDBGCR); + +#define TEST_AND_SET_BIT(tiocmbit, uartbit) do { \ + if (mctrl & tiocmbit) \ + cr |= uartbit; \ + else \ + cr &= ~uartbit; \ + } while (0) + + TEST_AND_SET_BIT(TIOCM_RTS, BM_UARTDBGCR_RTS); + TEST_AND_SET_BIT(TIOCM_DTR, BM_UARTDBGCR_DTR); + TEST_AND_SET_BIT(TIOCM_OUT1, BM_UARTDBGCR_OUT1); + TEST_AND_SET_BIT(TIOCM_OUT2, BM_UARTDBGCR_OUT2); + TEST_AND_SET_BIT(TIOCM_LOOP, BM_UARTDBGCR_LBE); +#undef TEST_AND_SET_BIT + + __raw_writel(cr, dp->port.membase + HW_UARTDBGCR); +} + +static void duart_break_ctl(struct uart_port *port, int break_state) +{ + unsigned long flags; + unsigned int lcr_h; + struct duart_port *dp = (struct duart_port *)port; + + spin_lock_irqsave(&dp->port.lock, flags); + lcr_h = __raw_readl(dp->port.membase + HW_UARTDBGLCR_H); + if (break_state == -1) + lcr_h |= BM_UARTDBGLCR_H_BRK; + else + lcr_h &= ~BM_UARTDBGLCR_H_BRK; + __raw_writel(lcr_h, dp->port.membase + HW_UARTDBGLCR_H); + spin_unlock_irqrestore(&dp->port.lock, flags); +} + +static int duart_startup(struct uart_port *port) +{ + u32 cr, lcr; + int retval; + struct duart_port *dp = (struct duart_port *)port; + + /* + * Allocate the IRQ + */ + retval = request_irq(dp->port.irq, duart_int, 0, DUART_DEVID, dp); + if (retval) + return retval; + + /* wake up the UART */ + __raw_writel(0, dp->port.membase + HW_UARTDBGDR); + + __raw_writel(BF_UARTDBGIFLS_TXIFLSEL(BV_UARTDBGIFLS_TXIFLSEL__ONE_HALF) + | + BF_UARTDBGIFLS_RXIFLSEL(BV_UARTDBGIFLS_RXIFLSEL__ONE_HALF), + dp->port.membase + HW_UARTDBGIFLS); + + /* + * Provoke TX FIFO interrupt into asserting. + */ + cr = BM_UARTDBGCR_UARTEN | BM_UARTDBGCR_RXE | BM_UARTDBGCR_TXE; + __raw_writel(cr, dp->port.membase + HW_UARTDBGCR); + + lcr = __raw_readl(dp->port.membase + HW_UARTDBGLCR_H); + lcr |= BM_UARTDBGLCR_H_FEN; + __raw_writel(lcr, dp->port.membase + HW_UARTDBGLCR_H); + + /* + * initialise the old status of the modem signals + */ + dp->old_status = __raw_readl(dp->port.membase + HW_UARTDBGFR) & + (BM_UARTDBGFR_DCD | BM_UARTDBGFR_DSR | BM_UARTDBGFR_CTS); + /* + * Finally, enable interrupts + */ + dp->im = BM_UARTDBGIMSC_RXIM | BM_UARTDBGIMSC_RTIM; + __raw_writel(dp->im, dp->port.membase + HW_UARTDBGIMSC); + + return 0; +} + +static void duart_shutdown(struct uart_port *port) +{ + unsigned long flags; + unsigned int val; + struct duart_port *dp = (struct duart_port *)port; + + /* + * disable all interrupts + */ + spin_lock_irqsave(&dp->port.lock, flags); + dp->im = 0; + __raw_writel(dp->im, dp->port.membase + HW_UARTDBGIMSC); + __raw_writel(0xffff, dp->port.membase + HW_UARTDBGICR); + spin_unlock_irqrestore(&dp->port.lock, flags); + + free_irq(dp->port.irq, dp); + + /* + * disable the port + */ + __raw_writel(BM_UARTDBGCR_UARTEN | BM_UARTDBGCR_TXE, + dp->port.membase + HW_UARTDBGCR); + /* + * disable break condition and fifos + */ + val = __raw_readl(dp->port.membase + HW_UARTDBGLCR_H); + val &= ~(BM_UARTDBGLCR_H_BRK | BM_UARTDBGLCR_H_FEN); + __raw_writel(val, dp->port.membase + HW_UARTDBGLCR_H); +} + +static void +duart_set_termios(struct uart_port *port, struct ktermios *termios, + struct ktermios *old) +{ + unsigned int lcr_h, old_cr; + unsigned long flags; + unsigned int baud, quot; + + /* + * Ask the core to calculate the divisor for us. + */ + baud = uart_get_baud_rate(port, termios, old, 0, port->uartclk / 16); + quot = (port->uartclk << 2) / baud; + + switch (termios->c_cflag & CSIZE) { + case CS5: + lcr_h = BF_UARTDBGLCR_H_WLEN(0); + break; + case CS6: + lcr_h = BF_UARTDBGLCR_H_WLEN(1); + break; + case CS7: + lcr_h = BF_UARTDBGLCR_H_WLEN(2); + break; + default: /* CS8 */ + lcr_h = BF_UARTDBGLCR_H_WLEN(3); + break; + } + if (termios->c_cflag & CSTOPB) + lcr_h |= BM_UARTDBGLCR_H_STP2; + if (termios->c_cflag & PARENB) { + lcr_h |= BM_UARTDBGLCR_H_PEN; + if (!(termios->c_cflag & PARODD)) + lcr_h |= BM_UARTDBGLCR_H_EPS; + } + lcr_h |= BM_UARTDBGLCR_H_FEN; + + spin_lock_irqsave(&port->lock, flags); + + /* + * Update the per-port timeout. + */ + uart_update_timeout(port, termios->c_cflag, baud); + + port->read_status_mask = BM_UARTDBGRSR_ECR_OE; + if (termios->c_iflag & INPCK) + port->read_status_mask |= BM_UARTDBGRSR_ECR_FE | + BM_UARTDBGRSR_ECR_PE; + if (termios->c_iflag & (BRKINT | PARMRK)) + port->read_status_mask |= BM_UARTDBGRSR_ECR_BE; + + /* + * Characters to ignore + */ + port->ignore_status_mask = 0; + if (termios->c_iflag & IGNPAR) + port->ignore_status_mask |= BM_UARTDBGRSR_ECR_FE | + BM_UARTDBGRSR_ECR_PE; + if (termios->c_iflag & IGNBRK) { + port->ignore_status_mask |= BM_UARTDBGRSR_ECR_BE; + /* + * If we're ignoring parity and break indicators, + * ignore overruns too (for real raw support). + */ + if (termios->c_iflag & IGNPAR) + port->ignore_status_mask |= BM_UARTDBGRSR_ECR_OE; + } + + if (UART_ENABLE_MS(port, termios->c_cflag)) + duart_enable_ms(port); + + /* first, disable everything */ + old_cr = __raw_readl(port->membase + HW_UARTDBGCR); + __raw_writel(0, port->membase + HW_UARTDBGCR); + + /* Set baud rate */ + __raw_writel(quot & 0x3f, port->membase + HW_UARTDBGFBRD); + __raw_writel(quot >> 6, port->membase + HW_UARTDBGIBRD); + /* + * ----------v----------v----------v----------v----- + * NOTE: MUST BE WRITTEN AFTER UARTLCR_M & UARTLCR_L + * ----------^----------^----------^----------^----- + */ + __raw_writel(lcr_h, port->membase + HW_UARTDBGLCR_H); + __raw_writel(old_cr, port->membase + HW_UARTDBGCR); + + spin_unlock_irqrestore(&port->lock, flags); +} + +static const char *duart_type(struct uart_port *port) +{ + return port->type == PORT_DUART ? DUART_DEVID : NULL; +} + +/* + * Release the memory region(s) being used by 'port' + */ +static void duart_release_port(struct uart_port *port) +{ + release_mem_region(port->mapbase, PAGE_SIZE); +} + +/* + * Request the memory region(s) being used by 'port' + */ +static int duart_request_port(struct uart_port *port) +{ + return request_mem_region(port->mapbase, PAGE_SIZE, DUART_DEVID) + != NULL ? 0 : -EBUSY; +} + +/* + * Configure/autoconfigure the port. + */ +static void duart_config_port(struct uart_port *port, int flags) +{ + if (flags & UART_CONFIG_TYPE) { + port->type = PORT_DUART; + duart_request_port(port); + } +} + +/* + * verify the new serial_struct (for TIOCSSERIAL). + */ +static int duart_verify_port(struct uart_port *port, struct serial_struct *ser) +{ + int ret = 0; + if (ser->type != PORT_UNKNOWN && ser->type != PORT_DUART) + ret = -EINVAL; + if (ser->irq < 0 || ser->irq >= NR_IRQS) + ret = -EINVAL; + if (ser->baud_base < 9600) + ret = -EINVAL; + return ret; +} + +static struct uart_ops duart_pops = { + .tx_empty = duart_tx_empty, + .set_mctrl = duart_set_mctrl, + .get_mctrl = duart_get_mctrl, + .stop_tx = duart_stop_tx, + .start_tx = duart_start_tx, + .stop_rx = duart_stop_rx, + .enable_ms = duart_enable_ms, + .break_ctl = duart_break_ctl, + .startup = duart_startup, + .shutdown = duart_shutdown, + .set_termios = duart_set_termios, + .type = duart_type, + .release_port = duart_release_port, + .request_port = duart_request_port, + .config_port = duart_config_port, + .verify_port = duart_verify_port, +}; + +static struct duart_port duart_port = { + .port = { + .iotype = SERIAL_IO_MEM, +#ifdef CONFIG_MXS_EARLY_CONSOLE + .membase = MXS_DEBUG_CONSOLE_VIRT, + .mapbase = MXS_DEBUG_CONSOLE_PHYS, +#endif + .fifosize = 16, + .ops = &duart_pops, + .flags = ASYNC_BOOT_AUTOCONF, + .line = 0, + }, +}; + +#ifdef CONFIG_SERIAL_MXS_DUART_CONSOLE + +static void +duart_console_write(struct console *co, const char *s, unsigned int count) +{ + struct uart_port *port = &duart_port.port; + unsigned int status, old_cr; + int i; + /* + * First save the CR then disable the interrupts + */ + old_cr = __raw_readl(port->membase + HW_UARTDBGCR); + __raw_writel(BM_UARTDBGCR_UARTEN | BM_UARTDBGCR_TXE, + port->membase + HW_UARTDBGCR); + /* + * Now, do each character + */ + for (i = 0; i < count; i++) { + do { + status = __raw_readl(port->membase + HW_UARTDBGFR); + } while (status & BM_UARTDBGFR_TXFF); + + __raw_writel(s[i], port->membase + HW_UARTDBGDR); + if (s[i] == '\n') { + do { + status = __raw_readl(port->membase + + HW_UARTDBGFR); + } while (status & BM_UARTDBGFR_TXFF); + __raw_writel('\r', port->membase + HW_UARTDBGDR); + } + } + + /* + * Finally, wait for transmitter to become empty + * and restore the TCR + */ + do { + status = __raw_readl(port->membase + HW_UARTDBGFR); + } while (status & BM_UARTDBGFR_BUSY); + __raw_writel(old_cr, port->membase + HW_UARTDBGCR); +} + +static void __init +duart_console_get_options(struct uart_port *port, int *baud, + int *parity, int *bits) +{ + if (__raw_readl(port->membase + HW_UARTDBGCR) & BM_UARTDBGCR_UARTEN) { + unsigned int lcr_h, quot; + lcr_h = __raw_readl(port->membase + HW_UARTDBGLCR_H); + + *parity = 'n'; + if (lcr_h & BM_UARTDBGLCR_H_PEN) { + if (lcr_h & BM_UARTDBGLCR_H_EPS) + *parity = 'e'; + else + *parity = 'o'; + } + + if ((lcr_h & BM_UARTDBGLCR_H_WLEN) == BF_UARTDBGLCR_H_WLEN(2)) + *bits = 7; + else + *bits = 8; + + quot = (__raw_readl(port->membase + HW_UARTDBGFBRD) & 0x3F) | + __raw_readl(port->membase + HW_UARTDBGIBRD) << 6; + if (quot == 0) + quot = 1; + *baud = (port->uartclk << 2) / quot; + } +} + +static int __init duart_console_setup(struct console *co, char *options) +{ + struct uart_port *port; + int baud = 115200; + int bits = 8; + int parity = 'n'; + int flow = 'n'; + /* + * Check whether an invalid uart number has been specified, and + * if so, search for the first available port that does have + * console support. + */ + if (co->index) + return -EINVAL; + + port = &duart_port.port; + + if (duart_port.clk == NULL || IS_ERR(duart_port.clk)) { + duart_port.clk = clk_get(NULL, "uart"); + if (duart_port.clk == NULL || IS_ERR(duart_port.clk)) + return -ENODEV; + duart_port.port.uartclk = clk_get_rate(duart_port.clk); + } + + if (options) + uart_parse_options(options, &baud, &parity, &bits, &flow); + else + duart_console_get_options(port, &baud, &parity, &bits); + return uart_set_options(port, co, baud, parity, bits, flow); +} + +static struct console duart_console = { + .name = "ttyAM", + .write = duart_console_write, + .device = uart_console_device, + .setup = duart_console_setup, + .flags = CON_PRINTBUFFER, + .index = -1, + .data = &duart_drv, +}; + +#ifdef CONFIG_MXS_EARLY_CONSOLE +static int __init duart_console_init(void) +{ + register_console(&duart_console); + return 0; +} + +console_initcall(duart_console_init); +#endif + +#endif + +static struct uart_driver duart_drv = { + .owner = THIS_MODULE, + .driver_name = "ttyAM", + .dev_name = "ttyAM", + .major = SERIAL_DUART_MAJOR, + .minor = SERIAL_DUART_MINOR, + .nr = 1, +#ifdef CONFIG_SERIAL_MXS_DUART_CONSOLE + .cons = &duart_console, +#endif +}; + +static int __devinit duart_probe(struct platform_device *pdev) +{ + struct resource *res; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!res) + return -ENOMEM; + /* + * Will use mapbase and membase here if !CONFIG_MXS_EARLY_CONSOLE, + * or use the overridden values later if CONFIG_MXS_EARLY_CONSOLE + */ + duart_port.port.mapbase = res->start; + duart_port.port.membase = + (unsigned char __iomem *)IO_ADDRESS(res->start); + + duart_port.port.irq = platform_get_irq(pdev, 0); + if (duart_port.port.irq < 0) + return -EINVAL; + device_init_wakeup(&pdev->dev, 1); + + duart_port.clk = clk_get(NULL, "uart"); + if (duart_port.clk == NULL || IS_ERR(duart_port.clk)) + return -ENODEV; + duart_port.suspended = 0; + duart_port.port.dev = &pdev->dev; + duart_port.port.uartclk = clk_get_rate(duart_port.clk); + uart_add_one_port(&duart_drv, &duart_port.port); + return 0; +} + +static int __devexit duart_remove(struct platform_device *pdev) +{ + clk_put(duart_port.clk); + uart_remove_one_port(&duart_drv, &duart_port.port); + return 0; +} + +#ifdef CONFIG_PM +static int duart_suspend(struct platform_device *pdev, + pm_message_t state) +{ + int ret = 0; + if (!duart_port.suspended) { + ret = uart_suspend_port(&duart_drv, &duart_port.port); + if (!ret) + duart_port.suspended = 1; + } + return ret; +} + +static int duart_resume(struct platform_device *pdev, + pm_message_t state) +{ + int ret = 0; + if (duart_port.suspended) { + ret = uart_resume_port(&duart_drv, &duart_port.port); + if (!ret) + duart_port.suspended = 0; + } + return ret; +} +#else +#define duart_suspend NULL +#define duart_resume NULL +#endif + +static struct platform_driver duart_driver = { + .probe = duart_probe, + .remove = __devexit_p(duart_remove), + .suspend = duart_suspend, + .resume = duart_resume, + .driver = { + .name = "mxs-duart", + .owner = THIS_MODULE, + }, +}; + +static int __init duart_init(void) +{ + int ret; + ret = uart_register_driver(&duart_drv); + if (ret) + return ret; + + ret = platform_driver_register(&duart_driver); + if (ret) + uart_unregister_driver(&duart_drv); + + return ret; +} + +static void __exit duart_exit(void) +{ + platform_driver_unregister(&duart_driver); + uart_unregister_driver(&duart_drv); +} + +module_init(duart_init); +module_exit(duart_exit); +module_param(force_cd, int, 0644); +MODULE_AUTHOR("ARM Ltd/Deep Blue Solutions Ltd/Freescale Inc"); +MODULE_DESCRIPTION("i.MXS debug uart"); +MODULE_LICENSE("GPL"); diff --git a/drivers/serial/regs-duart.h b/drivers/serial/regs-duart.h new file mode 100644 index 000000000000..0b5932c79a55 --- /dev/null +++ b/drivers/serial/regs-duart.h @@ -0,0 +1,301 @@ +/* + * Freescale UARTDBG Register Definitions + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * This file is created by xml file. Don't Edit it. + * + * Xml Revision: 1.21 + * Template revision: 26195 + */ + +#ifndef __ARCH_ARM___UARTDBG_H +#define __ARCH_ARM___UARTDBG_H + + +#define HW_UARTDBGDR (0x00000000) + +#define BP_UARTDBGDR_UNAVAILABLE 16 +#define BM_UARTDBGDR_UNAVAILABLE 0xFFFF0000 +#define BF_UARTDBGDR_UNAVAILABLE(v) \ + (((v) << 16) & BM_UARTDBGDR_UNAVAILABLE) +#define BP_UARTDBGDR_RESERVED 12 +#define BM_UARTDBGDR_RESERVED 0x0000F000 +#define BF_UARTDBGDR_RESERVED(v) \ + (((v) << 12) & BM_UARTDBGDR_RESERVED) +#define BM_UARTDBGDR_OE 0x00000800 +#define BM_UARTDBGDR_BE 0x00000400 +#define BM_UARTDBGDR_PE 0x00000200 +#define BM_UARTDBGDR_FE 0x00000100 +#define BP_UARTDBGDR_DATA 0 +#define BM_UARTDBGDR_DATA 0x000000FF +#define BF_UARTDBGDR_DATA(v) \ + (((v) << 0) & BM_UARTDBGDR_DATA) + +#define HW_UARTDBGRSR_ECR (0x00000004) + +#define BP_UARTDBGRSR_ECR_UNAVAILABLE 8 +#define BM_UARTDBGRSR_ECR_UNAVAILABLE 0xFFFFFF00 +#define BF_UARTDBGRSR_ECR_UNAVAILABLE(v) \ + (((v) << 8) & BM_UARTDBGRSR_ECR_UNAVAILABLE) +#define BP_UARTDBGRSR_ECR_EC 4 +#define BM_UARTDBGRSR_ECR_EC 0x000000F0 +#define BF_UARTDBGRSR_ECR_EC(v) \ + (((v) << 4) & BM_UARTDBGRSR_ECR_EC) +#define BM_UARTDBGRSR_ECR_OE 0x00000008 +#define BM_UARTDBGRSR_ECR_BE 0x00000004 +#define BM_UARTDBGRSR_ECR_PE 0x00000002 +#define BM_UARTDBGRSR_ECR_FE 0x00000001 + +#define HW_UARTDBGFR (0x00000018) + +#define BP_UARTDBGFR_UNAVAILABLE 16 +#define BM_UARTDBGFR_UNAVAILABLE 0xFFFF0000 +#define BF_UARTDBGFR_UNAVAILABLE(v) \ + (((v) << 16) & BM_UARTDBGFR_UNAVAILABLE) +#define BP_UARTDBGFR_RESERVED 9 +#define BM_UARTDBGFR_RESERVED 0x0000FE00 +#define BF_UARTDBGFR_RESERVED(v) \ + (((v) << 9) & BM_UARTDBGFR_RESERVED) +#define BM_UARTDBGFR_RI 0x00000100 +#define BM_UARTDBGFR_TXFE 0x00000080 +#define BM_UARTDBGFR_RXFF 0x00000040 +#define BM_UARTDBGFR_TXFF 0x00000020 +#define BM_UARTDBGFR_RXFE 0x00000010 +#define BM_UARTDBGFR_BUSY 0x00000008 +#define BM_UARTDBGFR_DCD 0x00000004 +#define BM_UARTDBGFR_DSR 0x00000002 +#define BM_UARTDBGFR_CTS 0x00000001 + +#define HW_UARTDBGILPR (0x00000020) + +#define BP_UARTDBGILPR_UNAVAILABLE 8 +#define BM_UARTDBGILPR_UNAVAILABLE 0xFFFFFF00 +#define BF_UARTDBGILPR_UNAVAILABLE(v) \ + (((v) << 8) & BM_UARTDBGILPR_UNAVAILABLE) +#define BP_UARTDBGILPR_ILPDVSR 0 +#define BM_UARTDBGILPR_ILPDVSR 0x000000FF +#define BF_UARTDBGILPR_ILPDVSR(v) \ + (((v) << 0) & BM_UARTDBGILPR_ILPDVSR) + +#define HW_UARTDBGIBRD (0x00000024) + +#define BP_UARTDBGIBRD_UNAVAILABLE 16 +#define BM_UARTDBGIBRD_UNAVAILABLE 0xFFFF0000 +#define BF_UARTDBGIBRD_UNAVAILABLE(v) \ + (((v) << 16) & BM_UARTDBGIBRD_UNAVAILABLE) +#define BP_UARTDBGIBRD_BAUD_DIVINT 0 +#define BM_UARTDBGIBRD_BAUD_DIVINT 0x0000FFFF +#define BF_UARTDBGIBRD_BAUD_DIVINT(v) \ + (((v) << 0) & BM_UARTDBGIBRD_BAUD_DIVINT) + +#define HW_UARTDBGFBRD (0x00000028) + +#define BP_UARTDBGFBRD_UNAVAILABLE 8 +#define BM_UARTDBGFBRD_UNAVAILABLE 0xFFFFFF00 +#define BF_UARTDBGFBRD_UNAVAILABLE(v) \ + (((v) << 8) & BM_UARTDBGFBRD_UNAVAILABLE) +#define BP_UARTDBGFBRD_RESERVED 6 +#define BM_UARTDBGFBRD_RESERVED 0x000000C0 +#define BF_UARTDBGFBRD_RESERVED(v) \ + (((v) << 6) & BM_UARTDBGFBRD_RESERVED) +#define BP_UARTDBGFBRD_BAUD_DIVFRAC 0 +#define BM_UARTDBGFBRD_BAUD_DIVFRAC 0x0000003F +#define BF_UARTDBGFBRD_BAUD_DIVFRAC(v) \ + (((v) << 0) & BM_UARTDBGFBRD_BAUD_DIVFRAC) + +#define HW_UARTDBGLCR_H (0x0000002c) + +#define BP_UARTDBGLCR_H_UNAVAILABLE 16 +#define BM_UARTDBGLCR_H_UNAVAILABLE 0xFFFF0000 +#define BF_UARTDBGLCR_H_UNAVAILABLE(v) \ + (((v) << 16) & BM_UARTDBGLCR_H_UNAVAILABLE) +#define BP_UARTDBGLCR_H_RESERVED 8 +#define BM_UARTDBGLCR_H_RESERVED 0x0000FF00 +#define BF_UARTDBGLCR_H_RESERVED(v) \ + (((v) << 8) & BM_UARTDBGLCR_H_RESERVED) +#define BM_UARTDBGLCR_H_SPS 0x00000080 +#define BP_UARTDBGLCR_H_WLEN 5 +#define BM_UARTDBGLCR_H_WLEN 0x00000060 +#define BF_UARTDBGLCR_H_WLEN(v) \ + (((v) << 5) & BM_UARTDBGLCR_H_WLEN) +#define BM_UARTDBGLCR_H_FEN 0x00000010 +#define BM_UARTDBGLCR_H_STP2 0x00000008 +#define BM_UARTDBGLCR_H_EPS 0x00000004 +#define BM_UARTDBGLCR_H_PEN 0x00000002 +#define BM_UARTDBGLCR_H_BRK 0x00000001 + +#define HW_UARTDBGCR (0x00000030) + +#define BP_UARTDBGCR_UNAVAILABLE 16 +#define BM_UARTDBGCR_UNAVAILABLE 0xFFFF0000 +#define BF_UARTDBGCR_UNAVAILABLE(v) \ + (((v) << 16) & BM_UARTDBGCR_UNAVAILABLE) +#define BM_UARTDBGCR_CTSEN 0x00008000 +#define BM_UARTDBGCR_RTSEN 0x00004000 +#define BM_UARTDBGCR_OUT2 0x00002000 +#define BM_UARTDBGCR_OUT1 0x00001000 +#define BM_UARTDBGCR_RTS 0x00000800 +#define BM_UARTDBGCR_DTR 0x00000400 +#define BM_UARTDBGCR_RXE 0x00000200 +#define BM_UARTDBGCR_TXE 0x00000100 +#define BM_UARTDBGCR_LBE 0x00000080 +#define BP_UARTDBGCR_RESERVED 3 +#define BM_UARTDBGCR_RESERVED 0x00000078 +#define BF_UARTDBGCR_RESERVED(v) \ + (((v) << 3) & BM_UARTDBGCR_RESERVED) +#define BM_UARTDBGCR_SIRLP 0x00000004 +#define BM_UARTDBGCR_SIREN 0x00000002 +#define BM_UARTDBGCR_UARTEN 0x00000001 + +#define HW_UARTDBGIFLS (0x00000034) + +#define BP_UARTDBGIFLS_UNAVAILABLE 16 +#define BM_UARTDBGIFLS_UNAVAILABLE 0xFFFF0000 +#define BF_UARTDBGIFLS_UNAVAILABLE(v) \ + (((v) << 16) & BM_UARTDBGIFLS_UNAVAILABLE) +#define BP_UARTDBGIFLS_RESERVED 6 +#define BM_UARTDBGIFLS_RESERVED 0x0000FFC0 +#define BF_UARTDBGIFLS_RESERVED(v) \ + (((v) << 6) & BM_UARTDBGIFLS_RESERVED) +#define BP_UARTDBGIFLS_RXIFLSEL 3 +#define BM_UARTDBGIFLS_RXIFLSEL 0x00000038 +#define BF_UARTDBGIFLS_RXIFLSEL(v) \ + (((v) << 3) & BM_UARTDBGIFLS_RXIFLSEL) +#define BV_UARTDBGIFLS_RXIFLSEL__ONE_EIGHT 0x0 +#define BV_UARTDBGIFLS_RXIFLSEL__ONE_QUARTER 0x1 +#define BV_UARTDBGIFLS_RXIFLSEL__ONE_HALF 0x2 +#define BV_UARTDBGIFLS_RXIFLSEL__THREE_QUARTERS 0x3 +#define BV_UARTDBGIFLS_RXIFLSEL__SEVEN_EIGHTHS 0x4 +#define BV_UARTDBGIFLS_RXIFLSEL__INVALID5 0x5 +#define BV_UARTDBGIFLS_RXIFLSEL__INVALID6 0x6 +#define BV_UARTDBGIFLS_RXIFLSEL__INVALID7 0x7 +#define BP_UARTDBGIFLS_TXIFLSEL 0 +#define BM_UARTDBGIFLS_TXIFLSEL 0x00000007 +#define BF_UARTDBGIFLS_TXIFLSEL(v) \ + (((v) << 0) & BM_UARTDBGIFLS_TXIFLSEL) +#define BV_UARTDBGIFLS_TXIFLSEL__ONE_EIGHT 0x0 +#define BV_UARTDBGIFLS_TXIFLSEL__ONE_QUARTER 0x1 +#define BV_UARTDBGIFLS_TXIFLSEL__ONE_HALF 0x2 +#define BV_UARTDBGIFLS_TXIFLSEL__THREE_QUARTERS 0x3 +#define BV_UARTDBGIFLS_TXIFLSEL__SEVEN_EIGHTHS 0x4 +#define BV_UARTDBGIFLS_TXIFLSEL__INVALID5 0x5 +#define BV_UARTDBGIFLS_TXIFLSEL__INVALID6 0x6 +#define BV_UARTDBGIFLS_TXIFLSEL__INVALID7 0x7 + +#define HW_UARTDBGIMSC (0x00000038) + +#define BP_UARTDBGIMSC_UNAVAILABLE 16 +#define BM_UARTDBGIMSC_UNAVAILABLE 0xFFFF0000 +#define BF_UARTDBGIMSC_UNAVAILABLE(v) \ + (((v) << 16) & BM_UARTDBGIMSC_UNAVAILABLE) +#define BP_UARTDBGIMSC_RESERVED 11 +#define BM_UARTDBGIMSC_RESERVED 0x0000F800 +#define BF_UARTDBGIMSC_RESERVED(v) \ + (((v) << 11) & BM_UARTDBGIMSC_RESERVED) +#define BM_UARTDBGIMSC_OEIM 0x00000400 +#define BM_UARTDBGIMSC_BEIM 0x00000200 +#define BM_UARTDBGIMSC_PEIM 0x00000100 +#define BM_UARTDBGIMSC_FEIM 0x00000080 +#define BM_UARTDBGIMSC_RTIM 0x00000040 +#define BM_UARTDBGIMSC_TXIM 0x00000020 +#define BM_UARTDBGIMSC_RXIM 0x00000010 +#define BM_UARTDBGIMSC_DSRMIM 0x00000008 +#define BM_UARTDBGIMSC_DCDMIM 0x00000004 +#define BM_UARTDBGIMSC_CTSMIM 0x00000002 +#define BM_UARTDBGIMSC_RIMIM 0x00000001 + +#define HW_UARTDBGRIS (0x0000003c) + +#define BP_UARTDBGRIS_UNAVAILABLE 16 +#define BM_UARTDBGRIS_UNAVAILABLE 0xFFFF0000 +#define BF_UARTDBGRIS_UNAVAILABLE(v) \ + (((v) << 16) & BM_UARTDBGRIS_UNAVAILABLE) +#define BP_UARTDBGRIS_RESERVED 11 +#define BM_UARTDBGRIS_RESERVED 0x0000F800 +#define BF_UARTDBGRIS_RESERVED(v) \ + (((v) << 11) & BM_UARTDBGRIS_RESERVED) +#define BM_UARTDBGRIS_OERIS 0x00000400 +#define BM_UARTDBGRIS_BERIS 0x00000200 +#define BM_UARTDBGRIS_PERIS 0x00000100 +#define BM_UARTDBGRIS_FERIS 0x00000080 +#define BM_UARTDBGRIS_RTRIS 0x00000040 +#define BM_UARTDBGRIS_TXRIS 0x00000020 +#define BM_UARTDBGRIS_RXRIS 0x00000010 +#define BM_UARTDBGRIS_DSRRMIS 0x00000008 +#define BM_UARTDBGRIS_DCDRMIS 0x00000004 +#define BM_UARTDBGRIS_CTSRMIS 0x00000002 +#define BM_UARTDBGRIS_RIRMIS 0x00000001 + +#define HW_UARTDBGMIS (0x00000040) + +#define BP_UARTDBGMIS_UNAVAILABLE 16 +#define BM_UARTDBGMIS_UNAVAILABLE 0xFFFF0000 +#define BF_UARTDBGMIS_UNAVAILABLE(v) \ + (((v) << 16) & BM_UARTDBGMIS_UNAVAILABLE) +#define BP_UARTDBGMIS_RESERVED 11 +#define BM_UARTDBGMIS_RESERVED 0x0000F800 +#define BF_UARTDBGMIS_RESERVED(v) \ + (((v) << 11) & BM_UARTDBGMIS_RESERVED) +#define BM_UARTDBGMIS_OEMIS 0x00000400 +#define BM_UARTDBGMIS_BEMIS 0x00000200 +#define BM_UARTDBGMIS_PEMIS 0x00000100 +#define BM_UARTDBGMIS_FEMIS 0x00000080 +#define BM_UARTDBGMIS_RTMIS 0x00000040 +#define BM_UARTDBGMIS_TXMIS 0x00000020 +#define BM_UARTDBGMIS_RXMIS 0x00000010 +#define BM_UARTDBGMIS_DSRMMIS 0x00000008 +#define BM_UARTDBGMIS_DCDMMIS 0x00000004 +#define BM_UARTDBGMIS_CTSMMIS 0x00000002 +#define BM_UARTDBGMIS_RIMMIS 0x00000001 + +#define HW_UARTDBGICR (0x00000044) + +#define BP_UARTDBGICR_UNAVAILABLE 16 +#define BM_UARTDBGICR_UNAVAILABLE 0xFFFF0000 +#define BF_UARTDBGICR_UNAVAILABLE(v) \ + (((v) << 16) & BM_UARTDBGICR_UNAVAILABLE) +#define BP_UARTDBGICR_RESERVED 11 +#define BM_UARTDBGICR_RESERVED 0x0000F800 +#define BF_UARTDBGICR_RESERVED(v) \ + (((v) << 11) & BM_UARTDBGICR_RESERVED) +#define BM_UARTDBGICR_OEIC 0x00000400 +#define BM_UARTDBGICR_BEIC 0x00000200 +#define BM_UARTDBGICR_PEIC 0x00000100 +#define BM_UARTDBGICR_FEIC 0x00000080 +#define BM_UARTDBGICR_RTIC 0x00000040 +#define BM_UARTDBGICR_TXIC 0x00000020 +#define BM_UARTDBGICR_RXIC 0x00000010 +#define BM_UARTDBGICR_DSRMIC 0x00000008 +#define BM_UARTDBGICR_DCDMIC 0x00000004 +#define BM_UARTDBGICR_CTSMIC 0x00000002 +#define BM_UARTDBGICR_RIMIC 0x00000001 + +#define HW_UARTDBGDMACR (0x00000048) + +#define BP_UARTDBGDMACR_UNAVAILABLE 16 +#define BM_UARTDBGDMACR_UNAVAILABLE 0xFFFF0000 +#define BF_UARTDBGDMACR_UNAVAILABLE(v) \ + (((v) << 16) & BM_UARTDBGDMACR_UNAVAILABLE) +#define BP_UARTDBGDMACR_RESERVED 3 +#define BM_UARTDBGDMACR_RESERVED 0x0000FFF8 +#define BF_UARTDBGDMACR_RESERVED(v) \ + (((v) << 3) & BM_UARTDBGDMACR_RESERVED) +#define BM_UARTDBGDMACR_DMAONERR 0x00000004 +#define BM_UARTDBGDMACR_TXDMAE 0x00000002 +#define BM_UARTDBGDMACR_RXDMAE 0x00000001 +#endif /* __ARCH_ARM___UARTDBG_H */ diff --git a/drivers/serial/regs-uartapp.h b/drivers/serial/regs-uartapp.h new file mode 100644 index 000000000000..aad9a7866556 --- /dev/null +++ b/drivers/serial/regs-uartapp.h @@ -0,0 +1,307 @@ +/* + * Freescale UARTAPP Register Definitions + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * This file is created by xml file. Don't Edit it. + * + * Xml Revision: 1.42 + * Template revision: 26195 + */ + +#ifndef __ARCH_ARM___UARTAPP_H +#define __ARCH_ARM___UARTAPP_H + + +#define HW_UARTAPP_CTRL0 (0x00000000) +#define HW_UARTAPP_CTRL0_SET (0x00000004) +#define HW_UARTAPP_CTRL0_CLR (0x00000008) +#define HW_UARTAPP_CTRL0_TOG (0x0000000c) + +#define BM_UARTAPP_CTRL0_SFTRST 0x80000000 +#define BM_UARTAPP_CTRL0_CLKGATE 0x40000000 +#define BM_UARTAPP_CTRL0_RUN 0x20000000 +#define BM_UARTAPP_CTRL0_RX_SOURCE 0x10000000 +#define BM_UARTAPP_CTRL0_RXTO_ENABLE 0x08000000 +#define BP_UARTAPP_CTRL0_RXTIMEOUT 16 +#define BM_UARTAPP_CTRL0_RXTIMEOUT 0x07FF0000 +#define BF_UARTAPP_CTRL0_RXTIMEOUT(v) \ + (((v) << 16) & BM_UARTAPP_CTRL0_RXTIMEOUT) +#define BP_UARTAPP_CTRL0_XFER_COUNT 0 +#define BM_UARTAPP_CTRL0_XFER_COUNT 0x0000FFFF +#define BF_UARTAPP_CTRL0_XFER_COUNT(v) \ + (((v) << 0) & BM_UARTAPP_CTRL0_XFER_COUNT) + +#define HW_UARTAPP_CTRL1 (0x00000010) +#define HW_UARTAPP_CTRL1_SET (0x00000014) +#define HW_UARTAPP_CTRL1_CLR (0x00000018) +#define HW_UARTAPP_CTRL1_TOG (0x0000001c) + +#define BP_UARTAPP_CTRL1_RSVD2 29 +#define BM_UARTAPP_CTRL1_RSVD2 0xE0000000 +#define BF_UARTAPP_CTRL1_RSVD2(v) \ + (((v) << 29) & BM_UARTAPP_CTRL1_RSVD2) +#define BM_UARTAPP_CTRL1_RUN 0x10000000 +#define BP_UARTAPP_CTRL1_RSVD1 16 +#define BM_UARTAPP_CTRL1_RSVD1 0x0FFF0000 +#define BF_UARTAPP_CTRL1_RSVD1(v) \ + (((v) << 16) & BM_UARTAPP_CTRL1_RSVD1) +#define BP_UARTAPP_CTRL1_XFER_COUNT 0 +#define BM_UARTAPP_CTRL1_XFER_COUNT 0x0000FFFF +#define BF_UARTAPP_CTRL1_XFER_COUNT(v) \ + (((v) << 0) & BM_UARTAPP_CTRL1_XFER_COUNT) + +#define HW_UARTAPP_CTRL2 (0x00000020) +#define HW_UARTAPP_CTRL2_SET (0x00000024) +#define HW_UARTAPP_CTRL2_CLR (0x00000028) +#define HW_UARTAPP_CTRL2_TOG (0x0000002c) + +#define BM_UARTAPP_CTRL2_INVERT_RTS 0x80000000 +#define BM_UARTAPP_CTRL2_INVERT_CTS 0x40000000 +#define BM_UARTAPP_CTRL2_INVERT_TX 0x20000000 +#define BM_UARTAPP_CTRL2_INVERT_RX 0x10000000 +#define BM_UARTAPP_CTRL2_RTS_SEMAPHORE 0x08000000 +#define BM_UARTAPP_CTRL2_DMAONERR 0x04000000 +#define BM_UARTAPP_CTRL2_TXDMAE 0x02000000 +#define BM_UARTAPP_CTRL2_RXDMAE 0x01000000 +#define BM_UARTAPP_CTRL2_RSVD2 0x00800000 +#define BP_UARTAPP_CTRL2_RXIFLSEL 20 +#define BM_UARTAPP_CTRL2_RXIFLSEL 0x00700000 +#define BF_UARTAPP_CTRL2_RXIFLSEL(v) \ + (((v) << 20) & BM_UARTAPP_CTRL2_RXIFLSEL) +#define BV_UARTAPP_CTRL2_RXIFLSEL__NOT_EMPTY 0x0 +#define BV_UARTAPP_CTRL2_RXIFLSEL__ONE_QUARTER 0x1 +#define BV_UARTAPP_CTRL2_RXIFLSEL__ONE_HALF 0x2 +#define BV_UARTAPP_CTRL2_RXIFLSEL__THREE_QUARTERS 0x3 +#define BV_UARTAPP_CTRL2_RXIFLSEL__SEVEN_EIGHTHS 0x4 +#define BV_UARTAPP_CTRL2_RXIFLSEL__INVALID5 0x5 +#define BV_UARTAPP_CTRL2_RXIFLSEL__INVALID6 0x6 +#define BV_UARTAPP_CTRL2_RXIFLSEL__INVALID7 0x7 +#define BM_UARTAPP_CTRL2_RSVD3 0x00080000 +#define BP_UARTAPP_CTRL2_TXIFLSEL 16 +#define BM_UARTAPP_CTRL2_TXIFLSEL 0x00070000 +#define BF_UARTAPP_CTRL2_TXIFLSEL(v) \ + (((v) << 16) & BM_UARTAPP_CTRL2_TXIFLSEL) +#define BV_UARTAPP_CTRL2_TXIFLSEL__EMPTY 0x0 +#define BV_UARTAPP_CTRL2_TXIFLSEL__ONE_QUARTER 0x1 +#define BV_UARTAPP_CTRL2_TXIFLSEL__ONE_HALF 0x2 +#define BV_UARTAPP_CTRL2_TXIFLSEL__THREE_QUARTERS 0x3 +#define BV_UARTAPP_CTRL2_TXIFLSEL__SEVEN_EIGHTHS 0x4 +#define BV_UARTAPP_CTRL2_TXIFLSEL__INVALID5 0x5 +#define BV_UARTAPP_CTRL2_TXIFLSEL__INVALID6 0x6 +#define BV_UARTAPP_CTRL2_TXIFLSEL__INVALID7 0x7 +#define BM_UARTAPP_CTRL2_CTSEN 0x00008000 +#define BM_UARTAPP_CTRL2_RTSEN 0x00004000 +#define BM_UARTAPP_CTRL2_OUT2 0x00002000 +#define BM_UARTAPP_CTRL2_OUT1 0x00001000 +#define BM_UARTAPP_CTRL2_RTS 0x00000800 +#define BM_UARTAPP_CTRL2_DTR 0x00000400 +#define BM_UARTAPP_CTRL2_RXE 0x00000200 +#define BM_UARTAPP_CTRL2_TXE 0x00000100 +#define BM_UARTAPP_CTRL2_LBE 0x00000080 +#define BM_UARTAPP_CTRL2_USE_LCR2 0x00000040 +#define BP_UARTAPP_CTRL2_RSVD4 3 +#define BM_UARTAPP_CTRL2_RSVD4 0x00000038 +#define BF_UARTAPP_CTRL2_RSVD4(v) \ + (((v) << 3) & BM_UARTAPP_CTRL2_RSVD4) +#define BM_UARTAPP_CTRL2_SIRLP 0x00000004 +#define BM_UARTAPP_CTRL2_SIREN 0x00000002 +#define BM_UARTAPP_CTRL2_UARTEN 0x00000001 + +#define HW_UARTAPP_LINECTRL (0x00000030) +#define HW_UARTAPP_LINECTRL_SET (0x00000034) +#define HW_UARTAPP_LINECTRL_CLR (0x00000038) +#define HW_UARTAPP_LINECTRL_TOG (0x0000003c) + +#define BP_UARTAPP_LINECTRL_BAUD_DIVINT 16 +#define BM_UARTAPP_LINECTRL_BAUD_DIVINT 0xFFFF0000 +#define BF_UARTAPP_LINECTRL_BAUD_DIVINT(v) \ + (((v) << 16) & BM_UARTAPP_LINECTRL_BAUD_DIVINT) +#define BP_UARTAPP_LINECTRL_RSVD 14 +#define BM_UARTAPP_LINECTRL_RSVD 0x0000C000 +#define BF_UARTAPP_LINECTRL_RSVD(v) \ + (((v) << 14) & BM_UARTAPP_LINECTRL_RSVD) +#define BP_UARTAPP_LINECTRL_BAUD_DIVFRAC 8 +#define BM_UARTAPP_LINECTRL_BAUD_DIVFRAC 0x00003F00 +#define BF_UARTAPP_LINECTRL_BAUD_DIVFRAC(v) \ + (((v) << 8) & BM_UARTAPP_LINECTRL_BAUD_DIVFRAC) +#define BM_UARTAPP_LINECTRL_SPS 0x00000080 +#define BP_UARTAPP_LINECTRL_WLEN 5 +#define BM_UARTAPP_LINECTRL_WLEN 0x00000060 +#define BF_UARTAPP_LINECTRL_WLEN(v) \ + (((v) << 5) & BM_UARTAPP_LINECTRL_WLEN) +#define BM_UARTAPP_LINECTRL_FEN 0x00000010 +#define BM_UARTAPP_LINECTRL_STP2 0x00000008 +#define BM_UARTAPP_LINECTRL_EPS 0x00000004 +#define BM_UARTAPP_LINECTRL_PEN 0x00000002 +#define BM_UARTAPP_LINECTRL_BRK 0x00000001 + +#define HW_UARTAPP_LINECTRL2 (0x00000040) +#define HW_UARTAPP_LINECTRL2_SET (0x00000044) +#define HW_UARTAPP_LINECTRL2_CLR (0x00000048) +#define HW_UARTAPP_LINECTRL2_TOG (0x0000004c) + +#define BP_UARTAPP_LINECTRL2_BAUD_DIVINT 16 +#define BM_UARTAPP_LINECTRL2_BAUD_DIVINT 0xFFFF0000 +#define BF_UARTAPP_LINECTRL2_BAUD_DIVINT(v) \ + (((v) << 16) & BM_UARTAPP_LINECTRL2_BAUD_DIVINT) +#define BP_UARTAPP_LINECTRL2_RSVD 14 +#define BM_UARTAPP_LINECTRL2_RSVD 0x0000C000 +#define BF_UARTAPP_LINECTRL2_RSVD(v) \ + (((v) << 14) & BM_UARTAPP_LINECTRL2_RSVD) +#define BP_UARTAPP_LINECTRL2_BAUD_DIVFRAC 8 +#define BM_UARTAPP_LINECTRL2_BAUD_DIVFRAC 0x00003F00 +#define BF_UARTAPP_LINECTRL2_BAUD_DIVFRAC(v) \ + (((v) << 8) & BM_UARTAPP_LINECTRL2_BAUD_DIVFRAC) +#define BM_UARTAPP_LINECTRL2_SPS 0x00000080 +#define BP_UARTAPP_LINECTRL2_WLEN 5 +#define BM_UARTAPP_LINECTRL2_WLEN 0x00000060 +#define BF_UARTAPP_LINECTRL2_WLEN(v) \ + (((v) << 5) & BM_UARTAPP_LINECTRL2_WLEN) +#define BM_UARTAPP_LINECTRL2_FEN 0x00000010 +#define BM_UARTAPP_LINECTRL2_STP2 0x00000008 +#define BM_UARTAPP_LINECTRL2_EPS 0x00000004 +#define BM_UARTAPP_LINECTRL2_PEN 0x00000002 +#define BM_UARTAPP_LINECTRL2_RSVD1 0x00000001 + +#define HW_UARTAPP_INTR (0x00000050) +#define HW_UARTAPP_INTR_SET (0x00000054) +#define HW_UARTAPP_INTR_CLR (0x00000058) +#define HW_UARTAPP_INTR_TOG (0x0000005c) + +#define BP_UARTAPP_INTR_RSVD1 28 +#define BM_UARTAPP_INTR_RSVD1 0xF0000000 +#define BF_UARTAPP_INTR_RSVD1(v) \ + (((v) << 28) & BM_UARTAPP_INTR_RSVD1) +#define BM_UARTAPP_INTR_ABDIEN 0x08000000 +#define BM_UARTAPP_INTR_OEIEN 0x04000000 +#define BM_UARTAPP_INTR_BEIEN 0x02000000 +#define BM_UARTAPP_INTR_PEIEN 0x01000000 +#define BM_UARTAPP_INTR_FEIEN 0x00800000 +#define BM_UARTAPP_INTR_RTIEN 0x00400000 +#define BM_UARTAPP_INTR_TXIEN 0x00200000 +#define BM_UARTAPP_INTR_RXIEN 0x00100000 +#define BM_UARTAPP_INTR_DSRMIEN 0x00080000 +#define BM_UARTAPP_INTR_DCDMIEN 0x00040000 +#define BM_UARTAPP_INTR_CTSMIEN 0x00020000 +#define BM_UARTAPP_INTR_RIMIEN 0x00010000 +#define BP_UARTAPP_INTR_RSVD2 12 +#define BM_UARTAPP_INTR_RSVD2 0x0000F000 +#define BF_UARTAPP_INTR_RSVD2(v) \ + (((v) << 12) & BM_UARTAPP_INTR_RSVD2) +#define BM_UARTAPP_INTR_ABDIS 0x00000800 +#define BM_UARTAPP_INTR_OEIS 0x00000400 +#define BM_UARTAPP_INTR_BEIS 0x00000200 +#define BM_UARTAPP_INTR_PEIS 0x00000100 +#define BM_UARTAPP_INTR_FEIS 0x00000080 +#define BM_UARTAPP_INTR_RTIS 0x00000040 +#define BM_UARTAPP_INTR_TXIS 0x00000020 +#define BM_UARTAPP_INTR_RXIS 0x00000010 +#define BM_UARTAPP_INTR_DSRMIS 0x00000008 +#define BM_UARTAPP_INTR_DCDMIS 0x00000004 +#define BM_UARTAPP_INTR_CTSMIS 0x00000002 +#define BM_UARTAPP_INTR_RIMIS 0x00000001 + +#define HW_UARTAPP_DATA (0x00000060) + +#define BP_UARTAPP_DATA_DATA 0 +#define BM_UARTAPP_DATA_DATA 0xFFFFFFFF +#define BF_UARTAPP_DATA_DATA(v) (v) + +#define HW_UARTAPP_STAT (0x00000070) + +#define BM_UARTAPP_STAT_PRESENT 0x80000000 +#define BV_UARTAPP_STAT_PRESENT__UNAVAILABLE 0x0 +#define BV_UARTAPP_STAT_PRESENT__AVAILABLE 0x1 +#define BM_UARTAPP_STAT_HISPEED 0x40000000 +#define BV_UARTAPP_STAT_HISPEED__UNAVAILABLE 0x0 +#define BV_UARTAPP_STAT_HISPEED__AVAILABLE 0x1 +#define BM_UARTAPP_STAT_BUSY 0x20000000 +#define BM_UARTAPP_STAT_CTS 0x10000000 +#define BM_UARTAPP_STAT_TXFE 0x08000000 +#define BM_UARTAPP_STAT_RXFF 0x04000000 +#define BM_UARTAPP_STAT_TXFF 0x02000000 +#define BM_UARTAPP_STAT_RXFE 0x01000000 +#define BP_UARTAPP_STAT_RXBYTE_INVALID 20 +#define BM_UARTAPP_STAT_RXBYTE_INVALID 0x00F00000 +#define BF_UARTAPP_STAT_RXBYTE_INVALID(v) \ + (((v) << 20) & BM_UARTAPP_STAT_RXBYTE_INVALID) +#define BM_UARTAPP_STAT_OERR 0x00080000 +#define BM_UARTAPP_STAT_BERR 0x00040000 +#define BM_UARTAPP_STAT_PERR 0x00020000 +#define BM_UARTAPP_STAT_FERR 0x00010000 +#define BP_UARTAPP_STAT_RXCOUNT 0 +#define BM_UARTAPP_STAT_RXCOUNT 0x0000FFFF +#define BF_UARTAPP_STAT_RXCOUNT(v) \ + (((v) << 0) & BM_UARTAPP_STAT_RXCOUNT) + +#define HW_UARTAPP_DEBUG (0x00000080) + +#define BP_UARTAPP_DEBUG_RXIBAUD_DIV 16 +#define BM_UARTAPP_DEBUG_RXIBAUD_DIV 0xFFFF0000 +#define BF_UARTAPP_DEBUG_RXIBAUD_DIV(v) \ + (((v) << 16) & BM_UARTAPP_DEBUG_RXIBAUD_DIV) +#define BP_UARTAPP_DEBUG_RXFBAUD_DIV 10 +#define BM_UARTAPP_DEBUG_RXFBAUD_DIV 0x0000FC00 +#define BF_UARTAPP_DEBUG_RXFBAUD_DIV(v) \ + (((v) << 10) & BM_UARTAPP_DEBUG_RXFBAUD_DIV) +#define BP_UARTAPP_DEBUG_RSVD1 6 +#define BM_UARTAPP_DEBUG_RSVD1 0x000003C0 +#define BF_UARTAPP_DEBUG_RSVD1(v) \ + (((v) << 6) & BM_UARTAPP_DEBUG_RSVD1) +#define BM_UARTAPP_DEBUG_TXDMARUN 0x00000020 +#define BM_UARTAPP_DEBUG_RXDMARUN 0x00000010 +#define BM_UARTAPP_DEBUG_TXCMDEND 0x00000008 +#define BM_UARTAPP_DEBUG_RXCMDEND 0x00000004 +#define BM_UARTAPP_DEBUG_TXDMARQ 0x00000002 +#define BM_UARTAPP_DEBUG_RXDMARQ 0x00000001 + +#define HW_UARTAPP_VERSION (0x00000090) + +#define BP_UARTAPP_VERSION_MAJOR 24 +#define BM_UARTAPP_VERSION_MAJOR 0xFF000000 +#define BF_UARTAPP_VERSION_MAJOR(v) \ + (((v) << 24) & BM_UARTAPP_VERSION_MAJOR) +#define BP_UARTAPP_VERSION_MINOR 16 +#define BM_UARTAPP_VERSION_MINOR 0x00FF0000 +#define BF_UARTAPP_VERSION_MINOR(v) \ + (((v) << 16) & BM_UARTAPP_VERSION_MINOR) +#define BP_UARTAPP_VERSION_STEP 0 +#define BM_UARTAPP_VERSION_STEP 0x0000FFFF +#define BF_UARTAPP_VERSION_STEP(v) \ + (((v) << 0) & BM_UARTAPP_VERSION_STEP) + +#define HW_UARTAPP_AUTOBAUD (0x000000a0) + +#define BP_UARTAPP_AUTOBAUD_REFCHAR1 24 +#define BM_UARTAPP_AUTOBAUD_REFCHAR1 0xFF000000 +#define BF_UARTAPP_AUTOBAUD_REFCHAR1(v) \ + (((v) << 24) & BM_UARTAPP_AUTOBAUD_REFCHAR1) +#define BP_UARTAPP_AUTOBAUD_REFCHAR0 16 +#define BM_UARTAPP_AUTOBAUD_REFCHAR0 0x00FF0000 +#define BF_UARTAPP_AUTOBAUD_REFCHAR0(v) \ + (((v) << 16) & BM_UARTAPP_AUTOBAUD_REFCHAR0) +#define BP_UARTAPP_AUTOBAUD_RSVD1 5 +#define BM_UARTAPP_AUTOBAUD_RSVD1 0x0000FFE0 +#define BF_UARTAPP_AUTOBAUD_RSVD1(v) \ + (((v) << 5) & BM_UARTAPP_AUTOBAUD_RSVD1) +#define BM_UARTAPP_AUTOBAUD_UPDATE_TX 0x00000010 +#define BM_UARTAPP_AUTOBAUD_TWO_REF_CHARS 0x00000008 +#define BM_UARTAPP_AUTOBAUD_START_WITH_RUNBIT 0x00000004 +#define BM_UARTAPP_AUTOBAUD_START_BAUD_DETECT 0x00000002 +#define BM_UARTAPP_AUTOBAUD_BAUD_DETECT_ENABLE 0x00000001 +#endif /* __ARCH_ARM___UARTAPP_H */ diff --git a/drivers/spi/Kconfig b/drivers/spi/Kconfig index 91c2f4f3af10..7248cb14cb5f 100644 --- a/drivers/spi/Kconfig +++ b/drivers/spi/Kconfig @@ -337,6 +337,18 @@ config SPI_NUC900 help SPI driver for Nuvoton NUC900 series ARM SoCs +config SPI_MXC + tristate "Freescale MXC CSPI controller" + depends on ARCH_MXC && SPI_MASTER + help + SPI driver for Freescale MXC CSPI interface + +config SPI_MXS + tristate "Freescale MXS SPI/SSP controller" + depends on ARCH_MXS && SPI_MASTER + help + SPI driver for Freescale MXS SoC SSP interface + # # Add new SPI master controllers in alphabetical order above this line # diff --git a/drivers/spi/Makefile b/drivers/spi/Makefile index e9cbd18217a0..ac1fb109a48c 100644 --- a/drivers/spi/Makefile +++ b/drivers/spi/Makefile @@ -47,6 +47,8 @@ obj-$(CONFIG_SPI_SH_SCI) += spi_sh_sci.o obj-$(CONFIG_SPI_SH_MSIOF) += spi_sh_msiof.o obj-$(CONFIG_SPI_STMP3XXX) += spi_stmp.o obj-$(CONFIG_SPI_NUC900) += spi_nuc900.o +obj-$(CONFIG_SPI_MXS) += spi_mxs.o +obj-$(CONFIG_SPI_MXC) += mxc_spi.o # special build for s3c24xx spi driver with fiq support spi_s3c24xx_hw-y := spi_s3c24xx.o diff --git a/drivers/spi/mxc_spi.c b/drivers/spi/mxc_spi.c new file mode 100644 index 000000000000..93a66715e0c3 --- /dev/null +++ b/drivers/spi/mxc_spi.c @@ -0,0 +1,1313 @@ +/* + * Copyright (C) 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-licensisr_locke.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @defgroup SPI Configurable Serial Peripheral Interface (CSPI) Driver + */ + +/*! + * @file mxc_spi.c + * @brief This file contains the implementation of the SPI master controller services + * + * + * @ingroup SPI + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MXC_CSPIRXDATA 0x00 +#define MXC_CSPITXDATA 0x04 +#define MXC_CSPICTRL 0x08 +#define MXC_CSPICONFIG 0x08 +#define MXC_CSPIINT 0x0C + +#define MXC_CSPICTRL_DISABLE 0x0 +#define MXC_CSPICTRL_SLAVE 0x0 +#define MXC_CSPICTRL_CSMASK 0x3 +#define MXC_CSPICTRL_SMC (1 << 3) + +#define MXC_CSPIINT_TEEN_SHIFT 0 +#define MXC_CSPIINT_THEN_SHIFT 1 +#define MXC_CSPIINT_TFEN_SHIFT 2 +#define MXC_CSPIINT_RREN_SHIFT 3 +#define MXC_CSPIINT_RHEN_SHIFT 4 +#define MXC_CSPIINT_RFEN_SHIFT 5 +#define MXC_CSPIINT_ROEN_SHIFT 6 + +#define MXC_HIGHPOL 0x0 +#define MXC_NOPHA 0x0 +#define MXC_LOWSSPOL 0x0 + +#define MXC_CSPISTAT_TE 0 +#define MXC_CSPISTAT_TH 1 +#define MXC_CSPISTAT_TF 2 +#define MXC_CSPISTAT_RR 3 +#define MXC_CSPISTAT_RH 4 +#define MXC_CSPISTAT_RF 5 +#define MXC_CSPISTAT_RO 6 + +#define MXC_CSPIPERIOD_32KHZ (1 << 15) + +/*! + * @struct mxc_spi_unique_def + * @brief This structure contains information that differs with + * SPI master controller hardware version + */ +struct mxc_spi_unique_def { + /* Width of valid bits in MXC_CSPIINT */ + unsigned int intr_bit_shift; + /* Chip Select shift */ + unsigned int cs_shift; + /* Bit count shift */ + unsigned int bc_shift; + /* Bit count mask */ + unsigned int bc_mask; + /* Data Control shift */ + unsigned int drctrl_shift; + /* Transfer Complete shift */ + unsigned int xfer_complete; + /* Bit counnter overflow shift */ + unsigned int bc_overflow; + /* FIFO Size */ + unsigned int fifo_size; + /* Control reg address */ + unsigned int ctrl_reg_addr; + /* Status reg address */ + unsigned int stat_reg_addr; + /* Period reg address */ + unsigned int period_reg_addr; + /* Test reg address */ + unsigned int test_reg_addr; + /* Reset reg address */ + unsigned int reset_reg_addr; + /* SPI mode mask */ + unsigned int mode_mask; + /* SPI enable */ + unsigned int spi_enable; + /* XCH bit */ + unsigned int xch; + /* Spi mode shift */ + unsigned int mode_shift; + /* Spi master mode enable */ + unsigned int master_enable; + /* TX interrupt enable diff */ + unsigned int tx_inten_dif; + /* RX interrupt enable bit diff */ + unsigned int rx_inten_dif; + /* Interrupt status diff */ + unsigned int int_status_dif; + /* Low pol shift */ + unsigned int low_pol_shift; + /* Phase shift */ + unsigned int pha_shift; + /* SS control shift */ + unsigned int ss_ctrl_shift; + /* SS pol shift */ + unsigned int ss_pol_shift; + /* Maximum data rate */ + unsigned int max_data_rate; + /* Data mask */ + unsigned int data_mask; + /* Data shift */ + unsigned int data_shift; + /* Loopback control */ + unsigned int lbc; + /* RX count off */ + unsigned int rx_cnt_off; + /* RX count mask */ + unsigned int rx_cnt_mask; + /* Reset start */ + unsigned int reset_start; + /* SCLK control inactive state shift */ + unsigned int sclk_ctl_shift; +}; + +struct mxc_spi; + +/*! + * Structure to group together all the data buffers and functions + * used in data transfers. + */ +struct mxc_spi_xfer { + /* Transmit buffer */ + const void *tx_buf; + /* Receive buffer */ + void *rx_buf; + /* Data transfered count */ + unsigned int count; + /* Data received count, descending sequence, zero means no more data to + be received */ + unsigned int rx_count; + /* Function to read the FIFO data to rx_buf */ + void (*rx_get) (struct mxc_spi *, u32 val); + /* Function to get the data to be written to FIFO */ + u32(*tx_get) (struct mxc_spi *); +}; + +/*! + * This structure is a way for the low level driver to define their own + * \b spi_master structure. This structure includes the core \b spi_master + * structure that is provided by Linux SPI Framework/driver as an + * element and has other elements that are specifically required by this + * low-level driver. + */ +struct mxc_spi { + /* SPI Master and a simple I/O queue runner */ + struct spi_bitbang mxc_bitbang; + /* Completion flags used in data transfers */ + struct completion xfer_done; + /* Data transfer structure */ + struct mxc_spi_xfer transfer; + /* Resource structure, which will maintain base addresses and IRQs */ + struct resource *res; + /* Base address of CSPI, used in readl and writel */ + void *base; + /* CSPI IRQ number */ + int irq; + /* CSPI Clock id */ + struct clk *clk; + /* CSPI input clock SCLK */ + unsigned long spi_ipg_clk; + /* CSPI registers' bit pattern */ + struct mxc_spi_unique_def *spi_ver_def; + /* Control reg address */ + void *ctrl_addr; + /* Status reg address */ + void *stat_addr; + /* Period reg address */ + void *period_addr; + /* Test reg address */ + void *test_addr; + /* Reset reg address */ + void *reset_addr; + /* Chipselect active function */ + void (*chipselect_active) (int cspi_mode, int status, int chipselect); + /* Chipselect inactive function */ + void (*chipselect_inactive) (int cspi_mode, int status, int chipselect); +}; + +#ifdef CONFIG_SPI_MXC_TEST_LOOPBACK +struct spi_chip_info { + int lb_enable; +}; + +static struct spi_chip_info lb_chip_info = { + .lb_enable = 1, +}; + +static struct spi_board_info loopback_info[] = { +#ifdef CONFIG_SPI_MXC_SELECT1 + { + .modalias = "spidev", + .controller_data = &lb_chip_info, + .irq = 0, + .max_speed_hz = 4000000, + .bus_num = 1, + .chip_select = 4, + }, +#endif +#ifdef CONFIG_SPI_MXC_SELECT2 + { + .modalias = "spidev", + .controller_data = &lb_chip_info, + .irq = 0, + .max_speed_hz = 4000000, + .bus_num = 2, + .chip_select = 4, + }, +#endif +#ifdef CONFIG_SPI_MXC_SELECT3 + { + .modalias = "spidev", + .controller_data = &lb_chip_info, + .irq = 0, + .max_speed_hz = 4000000, + .bus_num = 3, + .chip_select = 4, + }, +#endif +}; +#endif + +static struct mxc_spi_unique_def spi_ver_2_3 = { + .intr_bit_shift = 8, + .cs_shift = 18, + .bc_shift = 20, + .bc_mask = 0xFFF, + .drctrl_shift = 16, + .xfer_complete = (1 << 7), + .bc_overflow = 0, + .fifo_size = 64, + .ctrl_reg_addr = 4, + .stat_reg_addr = 0x18, + .period_reg_addr = 0x1C, + .test_reg_addr = 0x20, + .reset_reg_addr = 0x8, + .mode_mask = 0xF, + .spi_enable = 0x1, + .xch = (1 << 2), + .mode_shift = 4, + .master_enable = 0, + .tx_inten_dif = 0, + .rx_inten_dif = 0, + .int_status_dif = 0, + .low_pol_shift = 4, + .pha_shift = 0, + .ss_ctrl_shift = 8, + .ss_pol_shift = 12, + .max_data_rate = 0xF, + .data_mask = 0xFF, + .data_shift = 8, + .lbc = (1 << 31), + .rx_cnt_off = 8, + .rx_cnt_mask = (0x7F << 8), + .reset_start = 0, + .sclk_ctl_shift = 20, +}; + +static struct mxc_spi_unique_def spi_ver_0_7 = { + .intr_bit_shift = 8, + .cs_shift = 12, + .bc_shift = 20, + .bc_mask = 0xFFF, + .drctrl_shift = 8, + .xfer_complete = (1 << 7), + .bc_overflow = 0, + .fifo_size = 8, + .ctrl_reg_addr = 0, + .stat_reg_addr = 0x14, + .period_reg_addr = 0x18, + .test_reg_addr = 0x1C, + .reset_reg_addr = 0x0, + .mode_mask = 0x1, + .spi_enable = 0x1, + .xch = (1 << 2), + .mode_shift = 1, + .master_enable = 1 << 1, + .tx_inten_dif = 0, + .rx_inten_dif = 0, + .int_status_dif = 0, + .low_pol_shift = 4, + .pha_shift = 5, + .ss_ctrl_shift = 6, + .ss_pol_shift = 7, + .max_data_rate = 0x7, + .data_mask = 0x7, + .data_shift = 16, + .lbc = (1 << 14), + .rx_cnt_off = 4, + .rx_cnt_mask = (0xF << 4), + .reset_start = 1, +}; + +static struct mxc_spi_unique_def spi_ver_0_5 = { + .intr_bit_shift = 9, + .cs_shift = 12, + .bc_shift = 20, + .bc_mask = 0xFFF, + .drctrl_shift = 8, + .xfer_complete = (1 << 8), + .bc_overflow = (1 << 7), + .fifo_size = 8, + .ctrl_reg_addr = 0, + .stat_reg_addr = 0x14, + .period_reg_addr = 0x18, + .test_reg_addr = 0x1C, + .reset_reg_addr = 0x0, + .mode_mask = 0x1, + .spi_enable = 0x1, + .xch = (1 << 2), + .mode_shift = 1, + .master_enable = 1 << 1, + .tx_inten_dif = 0, + .rx_inten_dif = 0, + .int_status_dif = 0, + .low_pol_shift = 4, + .pha_shift = 5, + .ss_ctrl_shift = 6, + .ss_pol_shift = 7, + .max_data_rate = 0x7, + .data_mask = 0x7, + .data_shift = 16, + .lbc = (1 << 14), + .rx_cnt_off = 4, + .rx_cnt_mask = (0xF << 4), + .reset_start = 1, +}; + +static struct mxc_spi_unique_def spi_ver_0_4 = { + .intr_bit_shift = 9, + .cs_shift = 24, + .bc_shift = 8, + .bc_mask = 0x1F, + .drctrl_shift = 20, + .xfer_complete = (1 << 8), + .bc_overflow = (1 << 7), + .fifo_size = 8, + .ctrl_reg_addr = 0, + .stat_reg_addr = 0x14, + .period_reg_addr = 0x18, + .test_reg_addr = 0x1C, + .reset_reg_addr = 0x0, + .mode_mask = 0x1, + .spi_enable = 0x1, + .xch = (1 << 2), + .mode_shift = 1, + .master_enable = 1 << 1, + .tx_inten_dif = 0, + .rx_inten_dif = 0, + .int_status_dif = 0, + .low_pol_shift = 4, + .pha_shift = 5, + .ss_ctrl_shift = 6, + .ss_pol_shift = 7, + .max_data_rate = 0x7, + .data_mask = 0x7, + .data_shift = 16, + .lbc = (1 << 14), + .rx_cnt_off = 4, + .rx_cnt_mask = (0xF << 4), + .reset_start = 1, +}; + +static struct mxc_spi_unique_def spi_ver_0_0 = { + .intr_bit_shift = 18, + .cs_shift = 19, + .bc_shift = 0, + .bc_mask = 0x1F, + .drctrl_shift = 12, + .xfer_complete = (1 << 3), + .bc_overflow = (1 << 8), + .fifo_size = 8, + .ctrl_reg_addr = 0, + .stat_reg_addr = 0x0C, + .period_reg_addr = 0x14, + .test_reg_addr = 0x10, + .reset_reg_addr = 0x1C, + .mode_mask = 0x1, + .spi_enable = (1 << 10), + .xch = (1 << 9), + .mode_shift = 11, + .master_enable = 1 << 11, + .tx_inten_dif = 9, + .rx_inten_dif = 10, + .int_status_dif = 1, + .low_pol_shift = 5, + .pha_shift = 6, + .ss_ctrl_shift = 7, + .ss_pol_shift = 8, + .max_data_rate = 0x10, + .data_mask = 0x1F, + .data_shift = 14, + .lbc = (1 << 14), + .rx_cnt_off = 4, + .rx_cnt_mask = (0xF << 4), + .reset_start = 1, +}; + +extern void gpio_spi_active(int cspi_mod); +extern void gpio_spi_inactive(int cspi_mod); + +#define MXC_SPI_BUF_RX(type) \ +void mxc_spi_buf_rx_##type(struct mxc_spi *master_drv_data, u32 val)\ +{\ + type *rx = master_drv_data->transfer.rx_buf;\ + *rx++ = (type)val;\ + master_drv_data->transfer.rx_buf = rx;\ +} + +#define MXC_SPI_BUF_TX(type) \ +u32 mxc_spi_buf_tx_##type(struct mxc_spi *master_drv_data)\ +{\ + u32 val;\ + const type *tx = master_drv_data->transfer.tx_buf;\ + val = *tx++;\ + master_drv_data->transfer.tx_buf = tx;\ + return val;\ +} + +MXC_SPI_BUF_RX(u8) + MXC_SPI_BUF_TX(u8) + MXC_SPI_BUF_RX(u16) + MXC_SPI_BUF_TX(u16) + MXC_SPI_BUF_RX(u32) + MXC_SPI_BUF_TX(u32) + +/*! + * This function enables CSPI interrupt(s) + * + * @param master_data the pointer to mxc_spi structure + * @param irqs the irq(s) to set (can be a combination) + * + * @return This function returns 0 if successful, -1 otherwise. + */ +static int spi_enable_interrupt(struct mxc_spi *master_data, unsigned int irqs) +{ + if (irqs & ~((1 << master_data->spi_ver_def->intr_bit_shift) - 1)) { + return -1; + } + + __raw_writel((irqs | __raw_readl(MXC_CSPIINT + master_data->ctrl_addr)), + MXC_CSPIINT + master_data->ctrl_addr); + return 0; +} + +/*! + * This function disables CSPI interrupt(s) + * + * @param master_data the pointer to mxc_spi structure + * @param irqs the irq(s) to reset (can be a combination) + * + * @return This function returns 0 if successful, -1 otherwise. + */ +static int spi_disable_interrupt(struct mxc_spi *master_data, unsigned int irqs) +{ + if (irqs & ~((1 << master_data->spi_ver_def->intr_bit_shift) - 1)) { + return -1; + } + + __raw_writel((~irqs & + __raw_readl(MXC_CSPIINT + master_data->ctrl_addr)), + MXC_CSPIINT + master_data->ctrl_addr); + return 0; +} + +/*! + * This function sets the baud rate for the SPI module. + * + * @param master_data the pointer to mxc_spi structure + * @param baud the baud rate + * + * @return This function returns the baud rate divisor. + */ +static unsigned int spi_find_baudrate(struct mxc_spi *master_data, + unsigned int baud) +{ + unsigned int divisor; + unsigned int shift = 0; + + /* Calculate required divisor (rounded) */ + divisor = (master_data->spi_ipg_clk + baud / 2) / baud; + while (divisor >>= 1) + shift++; + + if (master_data->spi_ver_def == &spi_ver_0_0) { + shift = (shift - 1) * 2; + } else if (master_data->spi_ver_def == &spi_ver_2_3) { + shift = shift; + } else { + shift -= 2; + } + + if (shift > master_data->spi_ver_def->max_data_rate) + shift = master_data->spi_ver_def->max_data_rate; + + return shift << master_data->spi_ver_def->data_shift; +} + +/*! + * This function loads the transmit fifo. + * + * @param base the CSPI base address + * @param count number of words to put in the TxFIFO + * @param master_drv_data spi master structure + */ +static void spi_put_tx_data(void *base, unsigned int count, + struct mxc_spi *master_drv_data) +{ + unsigned int ctrl_reg; + unsigned int data; + int i = 0; + + /* Perform Tx transaction */ + for (i = 0; i < count; i++) { + data = master_drv_data->transfer.tx_get(master_drv_data); + __raw_writel(data, base + MXC_CSPITXDATA); + } + + ctrl_reg = __raw_readl(base + MXC_CSPICTRL); + + ctrl_reg |= master_drv_data->spi_ver_def->xch; + + __raw_writel(ctrl_reg, base + MXC_CSPICTRL); + + return; +} + +/*! + * This function configures the hardware CSPI for the current SPI device. + * It sets the word size, transfer mode, data rate for this device. + * + * @param spi the current SPI device + * @param is_active indicates whether to active/deactivate the current device + */ +void mxc_spi_chipselect(struct spi_device *spi, int is_active) +{ + struct mxc_spi *master_drv_data; + struct mxc_spi_xfer *ptransfer; + struct mxc_spi_unique_def *spi_ver_def; + unsigned int ctrl_reg = 0; + unsigned int config_reg = 0; + unsigned int xfer_len; + unsigned int cs_value; + + if (is_active == BITBANG_CS_INACTIVE) { + /*Need to deselect the slave */ + return; + } + + /* Get the master controller driver data from spi device's master */ + + master_drv_data = spi_master_get_devdata(spi->master); + clk_enable(master_drv_data->clk); + spi_ver_def = master_drv_data->spi_ver_def; + + xfer_len = spi->bits_per_word; + + if (spi_ver_def == &spi_ver_2_3) { + /* Control Register Settings for transfer to this slave */ + ctrl_reg = master_drv_data->spi_ver_def->spi_enable; + ctrl_reg |= + ((spi->chip_select & MXC_CSPICTRL_CSMASK) << spi_ver_def-> + cs_shift); + ctrl_reg |= + (((1 << (spi->chip_select & MXC_CSPICTRL_CSMASK)) & + spi_ver_def->mode_mask) << spi_ver_def->mode_shift); + ctrl_reg |= + spi_find_baudrate(master_drv_data, spi->max_speed_hz); + ctrl_reg |= + (((xfer_len - + 1) & spi_ver_def->bc_mask) << spi_ver_def->bc_shift); + + if (spi->mode & SPI_CPHA) + config_reg |= + (((1 << (spi->chip_select & MXC_CSPICTRL_CSMASK)) & + spi_ver_def->mode_mask) << + spi_ver_def->pha_shift); + + if ((spi->mode & SPI_CPOL)) { + config_reg |= + (((1 << (spi->chip_select & MXC_CSPICTRL_CSMASK)) & + spi_ver_def->mode_mask) << + spi_ver_def->low_pol_shift); + config_reg |= + (((1 << (spi->chip_select & MXC_CSPICTRL_CSMASK)) & + spi_ver_def->mode_mask) << + spi_ver_def->sclk_ctl_shift); + } + cs_value = (__raw_readl(MXC_CSPICONFIG + + master_drv_data->ctrl_addr) >> + spi_ver_def->ss_pol_shift) & spi_ver_def->mode_mask; + if (spi->mode & SPI_CS_HIGH) { + config_reg |= + ((((1 << (spi->chip_select & MXC_CSPICTRL_CSMASK)) & + spi_ver_def->mode_mask) | cs_value) << + spi_ver_def->ss_pol_shift); + } else + config_reg |= + ((~((1 << (spi->chip_select & + MXC_CSPICTRL_CSMASK)) & + spi_ver_def->mode_mask) & cs_value) << + spi_ver_def->ss_pol_shift); + config_reg |= + (((1 << (spi->chip_select & MXC_CSPICTRL_CSMASK)) & + spi_ver_def->mode_mask) << spi_ver_def->ss_ctrl_shift); + __raw_writel(0, master_drv_data->base + MXC_CSPICTRL); + __raw_writel(ctrl_reg, master_drv_data->base + MXC_CSPICTRL); + __raw_writel(config_reg, + MXC_CSPICONFIG + master_drv_data->ctrl_addr); + } else { + /* Control Register Settings for transfer to this slave */ + ctrl_reg = master_drv_data->spi_ver_def->spi_enable; + ctrl_reg |= + (((spi->chip_select & MXC_CSPICTRL_CSMASK) << spi_ver_def-> + cs_shift) | spi_ver_def->mode_mask << + spi_ver_def->mode_shift); + ctrl_reg |= + spi_find_baudrate(master_drv_data, spi->max_speed_hz); + ctrl_reg |= + (((xfer_len - + 1) & spi_ver_def->bc_mask) << spi_ver_def->bc_shift); + if (spi->mode & SPI_CPHA) + ctrl_reg |= + spi_ver_def->mode_mask << spi_ver_def->pha_shift; + if (spi->mode & SPI_CPOL) + ctrl_reg |= + spi_ver_def->mode_mask << spi_ver_def-> + low_pol_shift; + if (spi->mode & SPI_CS_HIGH) + ctrl_reg |= + spi_ver_def->mode_mask << spi_ver_def->ss_pol_shift; + if (spi_ver_def == &spi_ver_0_7) + ctrl_reg |= + spi_ver_def->mode_mask << spi_ver_def-> + ss_ctrl_shift; + + __raw_writel(ctrl_reg, master_drv_data->base + MXC_CSPICTRL); + } + + /* Initialize the functions for transfer */ + ptransfer = &master_drv_data->transfer; + if (xfer_len <= 8) { + ptransfer->rx_get = mxc_spi_buf_rx_u8; + ptransfer->tx_get = mxc_spi_buf_tx_u8; + } else if (xfer_len <= 16) { + ptransfer->rx_get = mxc_spi_buf_rx_u16; + ptransfer->tx_get = mxc_spi_buf_tx_u16; + } else { + ptransfer->rx_get = mxc_spi_buf_rx_u32; + ptransfer->tx_get = mxc_spi_buf_tx_u32; + } +#ifdef CONFIG_SPI_MXC_TEST_LOOPBACK + { + struct spi_chip_info *lb_chip = + (struct spi_chip_info *)spi->controller_data; + if (!lb_chip) + __raw_writel(0, master_drv_data->test_addr); + else if (lb_chip->lb_enable) + __raw_writel(spi_ver_def->lbc, + master_drv_data->test_addr); + } +#endif + clk_disable(master_drv_data->clk); + return; +} + +/*! + * This function is called when an interrupt occurs on the SPI modules. + * It is the interrupt handler for the SPI modules. + * + * @param irq the irq number + * @param dev_id the pointer on the device + * + * @return The function returns IRQ_HANDLED when handled. + */ +static irqreturn_t mxc_spi_isr(int irq, void *dev_id) +{ + struct mxc_spi *master_drv_data = dev_id; + irqreturn_t ret = IRQ_NONE; + unsigned int status; + int fifo_size; + unsigned int pass_counter; + + fifo_size = master_drv_data->spi_ver_def->fifo_size; + pass_counter = fifo_size; + + /* Read the interrupt status register to determine the source */ + status = __raw_readl(master_drv_data->stat_addr); + do { + u32 rx_tmp = + __raw_readl(master_drv_data->base + MXC_CSPIRXDATA); + + if (master_drv_data->transfer.rx_buf) + master_drv_data->transfer.rx_get(master_drv_data, + rx_tmp); + (master_drv_data->transfer.count)--; + (master_drv_data->transfer.rx_count)--; + ret = IRQ_HANDLED; + if (pass_counter-- == 0) { + break; + } + status = __raw_readl(master_drv_data->stat_addr); + } while (status & + (1 << + (MXC_CSPISTAT_RR + + master_drv_data->spi_ver_def->int_status_dif))); + + if (master_drv_data->transfer.rx_count) + return ret; + + if (master_drv_data->transfer.count) { + if (master_drv_data->transfer.tx_buf) { + u32 count = (master_drv_data->transfer.count > + fifo_size) ? fifo_size : + master_drv_data->transfer.count; + master_drv_data->transfer.rx_count = count; + spi_put_tx_data(master_drv_data->base, count, + master_drv_data); + } + } else { + complete(&master_drv_data->xfer_done); + } + + return ret; +} + +/*! + * This function initialize the current SPI device. + * + * @param spi the current SPI device. + * + */ +int mxc_spi_setup(struct spi_device *spi) +{ + if (spi->max_speed_hz < 0) { + return -EINVAL; + } + + if (!spi->bits_per_word) + spi->bits_per_word = 8; + + pr_debug("%s: mode %d, %u bpw, %d hz\n", __FUNCTION__, + spi->mode, spi->bits_per_word, spi->max_speed_hz); + + return 0; +} + +static int mxc_spi_setup_transfer(struct spi_device *spi, struct spi_transfer *t) +{ + return 0; +} + +/*! + * This function is called when the data has to transfer from/to the + * current SPI device in poll mode + * + * @param spi the current spi device + * @param t the transfer request - read/write buffer pairs + * + * @return Returns 0 on success. + */ +int mxc_spi_poll_transfer(struct spi_device *spi, struct spi_transfer *t) +{ + struct mxc_spi *master_drv_data = NULL; + int count, i; + volatile unsigned int status; + u32 rx_tmp; + u32 fifo_size; + int chipselect_status; + + mxc_spi_chipselect(spi, BITBANG_CS_ACTIVE); + + /* Get the master controller driver data from spi device's master */ + master_drv_data = spi_master_get_devdata(spi->master); + + chipselect_status = __raw_readl(MXC_CSPICONFIG + + master_drv_data->ctrl_addr); + chipselect_status >>= master_drv_data->spi_ver_def->ss_pol_shift & + master_drv_data->spi_ver_def->mode_mask; + if (master_drv_data->chipselect_active) + master_drv_data->chipselect_active(spi->master->bus_num, + chipselect_status, + (spi->chip_select & + MXC_CSPICTRL_CSMASK) + 1); + + clk_enable(master_drv_data->clk); + + /* Modify the Tx, Rx, Count */ + master_drv_data->transfer.tx_buf = t->tx_buf; + master_drv_data->transfer.rx_buf = t->rx_buf; + master_drv_data->transfer.count = t->len; + fifo_size = master_drv_data->spi_ver_def->fifo_size; + + count = (t->len > fifo_size) ? fifo_size : t->len; + spi_put_tx_data(master_drv_data->base, count, master_drv_data); + + while ((((status = __raw_readl(master_drv_data->test_addr)) & + master_drv_data->spi_ver_def->rx_cnt_mask) >> master_drv_data-> + spi_ver_def->rx_cnt_off) != count) + ; + + for (i = 0; i < count; i++) { + rx_tmp = __raw_readl(master_drv_data->base + MXC_CSPIRXDATA); + master_drv_data->transfer.rx_get(master_drv_data, rx_tmp); + } + + clk_disable(master_drv_data->clk); + if (master_drv_data->chipselect_inactive) + master_drv_data->chipselect_inactive(spi->master->bus_num, + chipselect_status, + (spi->chip_select & + MXC_CSPICTRL_CSMASK) + 1); + return 0; +} + +/*! + * This function is called when the data has to transfer from/to the + * current SPI device. It enables the Rx interrupt, initiates the transfer. + * When Rx interrupt occurs, the completion flag is set. It then disables + * the Rx interrupt. + * + * @param spi the current spi device + * @param t the transfer request - read/write buffer pairs + * + * @return Returns 0 on success -1 on failure. + */ +int mxc_spi_transfer(struct spi_device *spi, struct spi_transfer *t) +{ + struct mxc_spi *master_drv_data = NULL; + int count; + int chipselect_status; + u32 fifo_size; + + /* Get the master controller driver data from spi device's master */ + + master_drv_data = spi_master_get_devdata(spi->master); + + chipselect_status = __raw_readl(MXC_CSPICONFIG + + master_drv_data->ctrl_addr); + chipselect_status >>= master_drv_data->spi_ver_def->ss_pol_shift & + master_drv_data->spi_ver_def->mode_mask; + if (master_drv_data->chipselect_active) + master_drv_data->chipselect_active(spi->master->bus_num, + chipselect_status, + (spi->chip_select & + MXC_CSPICTRL_CSMASK) + 1); + + clk_enable(master_drv_data->clk); + /* Modify the Tx, Rx, Count */ + master_drv_data->transfer.tx_buf = t->tx_buf; + master_drv_data->transfer.rx_buf = t->rx_buf; + master_drv_data->transfer.count = t->len; + fifo_size = master_drv_data->spi_ver_def->fifo_size; + INIT_COMPLETION(master_drv_data->xfer_done); + + /* Enable the Rx Interrupts */ + + spi_enable_interrupt(master_drv_data, + 1 << (MXC_CSPIINT_RREN_SHIFT + + master_drv_data->spi_ver_def->rx_inten_dif)); + count = (t->len > fifo_size) ? fifo_size : t->len; + + /* Perform Tx transaction */ + master_drv_data->transfer.rx_count = count; + spi_put_tx_data(master_drv_data->base, count, master_drv_data); + + /* Wait for transfer completion */ + wait_for_completion(&master_drv_data->xfer_done); + + /* Disable the Rx Interrupts */ + + spi_disable_interrupt(master_drv_data, + 1 << (MXC_CSPIINT_RREN_SHIFT + + master_drv_data->spi_ver_def-> + rx_inten_dif)); + + clk_disable(master_drv_data->clk); + if (master_drv_data->chipselect_inactive) + master_drv_data->chipselect_inactive(spi->master->bus_num, + chipselect_status, + (spi->chip_select & + MXC_CSPICTRL_CSMASK) + 1); + return t->len - master_drv_data->transfer.count; +} + +/*! + * This function releases the current SPI device's resources. + * + * @param spi the current SPI device. + * + */ +void mxc_spi_cleanup(struct spi_device *spi) +{ +} + +/*! + * This function is called during the driver binding process. Based on the CSPI + * hardware module that is being probed this function adds the appropriate SPI module + * structure in the SPI core driver. + * + * @param pdev the device structure used to store device specific + * information that is used by the suspend, resume and remove + * functions. + * + * @return The function returns 0 on successful registration and initialization + * of CSPI module. Otherwise returns specific error code. + */ +static int mxc_spi_probe(struct platform_device *pdev) +{ + struct mxc_spi_master *mxc_platform_info; + struct spi_master *master; + struct mxc_spi *master_drv_data = NULL; + unsigned int spi_ver; + int ret = -ENODEV; + + /* Get the platform specific data for this master device */ + + mxc_platform_info = (struct mxc_spi_master *)pdev->dev.platform_data; + if (!mxc_platform_info) { + dev_err(&pdev->dev, "can't get the platform data for CSPI\n"); + return -EINVAL; + } + + /* Allocate SPI master controller */ + + master = spi_alloc_master(&pdev->dev, sizeof(struct mxc_spi)); + if (!master) { + dev_err(&pdev->dev, "can't alloc for spi_master\n"); + return -ENOMEM; + } + + /* Set this device's driver data to master */ + + platform_set_drvdata(pdev, master); + + /* Set this master's data from platform_info */ + + master->bus_num = pdev->id + 1; + master->num_chipselect = mxc_platform_info->maxchipselect; + master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_CS_HIGH; +#ifdef CONFIG_SPI_MXC_TEST_LOOPBACK + master->num_chipselect += 1; +#endif + /* Set the master controller driver data for this master */ + + master_drv_data = spi_master_get_devdata(master); + master_drv_data->mxc_bitbang.master = spi_master_get(master); + if (mxc_platform_info->chipselect_active) + master_drv_data->chipselect_active = + mxc_platform_info->chipselect_active; + if (mxc_platform_info->chipselect_inactive) + master_drv_data->chipselect_inactive = + mxc_platform_info->chipselect_inactive; + + /* Identify SPI version */ + + spi_ver = mxc_platform_info->spi_version; + if (spi_ver == 7) { + master_drv_data->spi_ver_def = &spi_ver_0_7; + } else if (spi_ver == 5) { + master_drv_data->spi_ver_def = &spi_ver_0_5; + } else if (spi_ver == 4) { + master_drv_data->spi_ver_def = &spi_ver_0_4; + } else if (spi_ver == 0) { + master_drv_data->spi_ver_def = &spi_ver_0_0; + } else if (spi_ver == 23) { + master_drv_data->spi_ver_def = &spi_ver_2_3; + } + + dev_dbg(&pdev->dev, "SPI_REV 0.%d\n", spi_ver); + + /* Set the master bitbang data */ + + master_drv_data->mxc_bitbang.chipselect = mxc_spi_chipselect; + master_drv_data->mxc_bitbang.txrx_bufs = mxc_spi_transfer; + master_drv_data->mxc_bitbang.master->setup = mxc_spi_setup; + master_drv_data->mxc_bitbang.master->cleanup = mxc_spi_cleanup; + master_drv_data->mxc_bitbang.setup_transfer = mxc_spi_setup_transfer; + + /* Initialize the completion object */ + + init_completion(&master_drv_data->xfer_done); + + /* Set the master controller register addresses and irqs */ + + master_drv_data->res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!master_drv_data->res) { + dev_err(&pdev->dev, "can't get platform resource for CSPI%d\n", + master->bus_num); + ret = -ENOMEM; + goto err; + } + + if (!request_mem_region(master_drv_data->res->start, + master_drv_data->res->end - + master_drv_data->res->start + 1, pdev->name)) { + dev_err(&pdev->dev, "request_mem_region failed for CSPI%d\n", + master->bus_num); + ret = -ENOMEM; + goto err; + } + + master_drv_data->base = ioremap(master_drv_data->res->start, + master_drv_data->res->end - master_drv_data->res->start + 1); + if (!master_drv_data->base) { + dev_err(&pdev->dev, "invalid base address for CSPI%d\n", + master->bus_num); + ret = -EINVAL; + goto err1; + } + + master_drv_data->irq = platform_get_irq(pdev, 0); + if (master_drv_data->irq < 0) { + dev_err(&pdev->dev, "can't get IRQ for CSPI%d\n", + master->bus_num); + ret = -EINVAL; + goto err1; + } + + /* Register for SPI Interrupt */ + + ret = request_irq(master_drv_data->irq, mxc_spi_isr, + 0, "CSPI_IRQ", master_drv_data); + if (ret != 0) { + dev_err(&pdev->dev, "request_irq failed for CSPI%d\n", + master->bus_num); + goto err1; + } + + /* Setup any GPIO active */ + + gpio_spi_active(master->bus_num - 1); + + /* Enable the CSPI Clock, CSPI Module, set as a master */ + + master_drv_data->ctrl_addr = + master_drv_data->base + master_drv_data->spi_ver_def->ctrl_reg_addr; + master_drv_data->stat_addr = + master_drv_data->base + master_drv_data->spi_ver_def->stat_reg_addr; + master_drv_data->period_addr = + master_drv_data->base + + master_drv_data->spi_ver_def->period_reg_addr; + master_drv_data->test_addr = + master_drv_data->base + master_drv_data->spi_ver_def->test_reg_addr; + master_drv_data->reset_addr = + master_drv_data->base + + master_drv_data->spi_ver_def->reset_reg_addr; + + master_drv_data->clk = clk_get(&pdev->dev, "cspi_clk"); + clk_enable(master_drv_data->clk); + master_drv_data->spi_ipg_clk = clk_get_rate(master_drv_data->clk); + + __raw_writel(master_drv_data->spi_ver_def->reset_start, + master_drv_data->reset_addr); + udelay(1); + __raw_writel((master_drv_data->spi_ver_def->spi_enable + + master_drv_data->spi_ver_def->master_enable), + master_drv_data->base + MXC_CSPICTRL); + __raw_writel(MXC_CSPIPERIOD_32KHZ, master_drv_data->period_addr); + __raw_writel(0, MXC_CSPIINT + master_drv_data->ctrl_addr); + + /* Start the SPI Master Controller driver */ + + ret = spi_bitbang_start(&master_drv_data->mxc_bitbang); + + if (ret != 0) + goto err2; + + printk(KERN_INFO "CSPI: %s-%d probed\n", pdev->name, pdev->id); + +#ifdef CONFIG_SPI_MXC_TEST_LOOPBACK + { + int i; + struct spi_board_info *bi = &loopback_info[0]; + for (i = 0; i < ARRAY_SIZE(loopback_info); i++, bi++) { + if (bi->bus_num != master->bus_num) + continue; + + dev_info(&pdev->dev, + "registering loopback device '%s'\n", + bi->modalias); + + spi_new_device(master, bi); + } + } +#endif + clk_disable(master_drv_data->clk); + return ret; + + err2: + gpio_spi_inactive(master->bus_num - 1); + clk_disable(master_drv_data->clk); + clk_put(master_drv_data->clk); + free_irq(master_drv_data->irq, master_drv_data); + err1: + iounmap(master_drv_data->base); + release_mem_region(pdev->resource[0].start, + pdev->resource[0].end - pdev->resource[0].start + 1); + err: + spi_master_put(master); + kfree(master); + platform_set_drvdata(pdev, NULL); + return ret; +} + +/*! + * Dissociates the driver from the SPI master controller. Disables the CSPI module. + * It handles the release of SPI resources like IRQ, memory,..etc. + * + * @param pdev the device structure used to give information on which SPI + * to remove + * + * @return The function always returns 0. + */ +static int mxc_spi_remove(struct platform_device *pdev) +{ + struct spi_master *master = platform_get_drvdata(pdev); + + if (master) { + struct mxc_spi *master_drv_data = + spi_master_get_devdata(master); + + gpio_spi_inactive(master->bus_num - 1); + + /* Disable the CSPI module */ + clk_enable(master_drv_data->clk); + __raw_writel(MXC_CSPICTRL_DISABLE, + master_drv_data->base + MXC_CSPICTRL); + clk_disable(master_drv_data->clk); + /* Unregister for SPI Interrupt */ + + free_irq(master_drv_data->irq, master_drv_data); + + iounmap(master_drv_data->base); + release_mem_region(master_drv_data->res->start, + master_drv_data->res->end - + master_drv_data->res->start + 1); + + /* Stop the SPI Master Controller driver */ + + spi_bitbang_stop(&master_drv_data->mxc_bitbang); + + spi_master_put(master); + } + + printk(KERN_INFO "CSPI: %s-%d removed\n", pdev->name, pdev->id); + platform_set_drvdata(pdev, NULL); + + return 0; +} + +#ifdef CONFIG_PM +static int spi_bitbang_suspend(struct spi_bitbang *bitbang) +{ + unsigned long flags; + unsigned limit = 500; + + spin_lock_irqsave(&bitbang->lock, flags); + while (!list_empty(&bitbang->queue) && limit--) { + spin_unlock_irqrestore(&bitbang->lock, flags); + + dev_dbg(&bitbang->master->dev, "wait for queue\n"); + msleep(10); + + spin_lock_irqsave(&bitbang->lock, flags); + } + if (!list_empty(&bitbang->queue)) { + dev_err(&bitbang->master->dev, "queue didn't empty\n"); + return -EBUSY; + } + spin_unlock_irqrestore(&bitbang->lock, flags); + + return 0; +} + +static void spi_bitbang_resume(struct spi_bitbang *bitbang) +{ + spin_lock_init(&bitbang->lock); + INIT_LIST_HEAD(&bitbang->queue); + + bitbang->busy = 0; +} + +/*! + * This function puts the SPI master controller in low-power mode/state. + * + * @param pdev the device structure used to give information on which SDHC + * to suspend + * @param state the power state the device is entering + * + * @return The function always returns 0. + */ +static int mxc_spi_suspend(struct platform_device *pdev, pm_message_t state) +{ + struct spi_master *master = platform_get_drvdata(pdev); + struct mxc_spi *master_drv_data = spi_master_get_devdata(master); + int ret = 0; + + spi_bitbang_suspend(&master_drv_data->mxc_bitbang); + clk_enable(master_drv_data->clk); + __raw_writel(MXC_CSPICTRL_DISABLE, + master_drv_data->base + MXC_CSPICTRL); + clk_disable(master_drv_data->clk); + gpio_spi_inactive(master->bus_num - 1); + + return ret; +} + +/*! + * This function brings the SPI master controller back from low-power state. + * + * @param pdev the device structure used to give information on which SDHC + * to resume + * + * @return The function always returns 0. + */ +static int mxc_spi_resume(struct platform_device *pdev) +{ + struct spi_master *master = platform_get_drvdata(pdev); + struct mxc_spi *master_drv_data = spi_master_get_devdata(master); + + gpio_spi_active(master->bus_num - 1); + + spi_bitbang_resume(&master_drv_data->mxc_bitbang); + clk_enable(master_drv_data->clk); + __raw_writel(master_drv_data->spi_ver_def->spi_enable, + master_drv_data->base + MXC_CSPICTRL); + clk_disable(master_drv_data->clk); + return 0; +} +#else +#define mxc_spi_suspend NULL +#define mxc_spi_resume NULL +#endif /* CONFIG_PM */ + +/*! + * This structure contains pointers to the power management callback functions. + */ +static struct platform_driver mxc_spi_driver = { + .driver = { + .name = "mxc_spi", + .owner = THIS_MODULE, + }, + .probe = mxc_spi_probe, + .remove = mxc_spi_remove, + .suspend = mxc_spi_suspend, + .resume = mxc_spi_resume, +}; + +/*! + * This function implements the init function of the SPI device. + * It is called when the module is loaded. It enables the required + * clocks to CSPI module(if any) and activates necessary GPIO pins. + * + * @return This function returns 0. + */ +static int __init mxc_spi_init(void) +{ + pr_debug("Registering the SPI Controller Driver\n"); + return platform_driver_register(&mxc_spi_driver); +} + +/*! + * This function implements the exit function of the SPI device. + * It is called when the module is unloaded. It deactivates the + * the GPIO pin associated with CSPI hardware modules. + * + */ +static void __exit mxc_spi_exit(void) +{ + pr_debug("Unregistering the SPI Controller Driver\n"); + platform_driver_unregister(&mxc_spi_driver); +} + +subsys_initcall(mxc_spi_init); +module_exit(mxc_spi_exit); + +MODULE_DESCRIPTION("SPI Master Controller driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/spi/spi_mxs.c b/drivers/spi/spi_mxs.c new file mode 100644 index 000000000000..744be68d9433 --- /dev/null +++ b/drivers/spi/spi_mxs.c @@ -0,0 +1,711 @@ +/* + * Freescale MXS SPI master driver + * + * Author: dmitry pervushin + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. + * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "spi_mxs.h" + +/* 0 means DMA modei(recommended, default), !0 - PIO mode */ +static int pio /* = 0 */ ; +static int debug; + +/** + * mxs_spi_init_hw + * + * Initialize the SSP port + */ +static int mxs_spi_init_hw(struct mxs_spi *ss) +{ + int err; + + ss->clk = clk_get(NULL, "ssp.0"); + if (IS_ERR(ss->clk)) { + err = PTR_ERR(ss->clk); + goto out; + } + clk_enable(ss->clk); + + mxs_reset_block((void *)ss->regs, 0); + mxs_dma_reset(ss->dma); + + return 0; + +out: + return err; +} + +static void mxs_spi_release_hw(struct mxs_spi *ss) +{ + if (ss->clk && !IS_ERR(ss->clk)) { + clk_disable(ss->clk); + clk_put(ss->clk); + } +} + +static int mxs_spi_setup_transfer(struct spi_device *spi, + struct spi_transfer *t) +{ + u8 bits_per_word; + u32 hz; + struct mxs_spi *ss /* = spi_master_get_devdata(spi->master) */ ; + u16 rate; + + ss = spi_master_get_devdata(spi->master); + + bits_per_word = spi->bits_per_word; + if (t && t->bits_per_word) + bits_per_word = t->bits_per_word; + + /* + Calculate speed: + - by default, use maximum speed from ssp clk + - if device overrides it, use it + - if transfer specifies other speed, use transfer's one + */ + hz = 1000 * ss->speed_khz / ss->divider; + if (spi->max_speed_hz) + hz = min(hz, spi->max_speed_hz); + if (t && t->speed_hz) + hz = min(hz, t->speed_hz); + + if (hz == 0) { + dev_err(&spi->dev, "Cannot continue with zero clock\n"); + return -EINVAL; + } + + if (bits_per_word != 8) { + dev_err(&spi->dev, "%s, unsupported bits_per_word=%d\n", + __func__, bits_per_word); + return -EINVAL; + } + + dev_dbg(&spi->dev, "Requested clk rate = %uHz, max = %ukHz/%d = %uHz\n", + hz, ss->speed_khz, ss->divider, + ss->speed_khz * 1000 / ss->divider); + + if (ss->speed_khz * 1000 / ss->divider < hz) { + dev_err(&spi->dev, "%s, unsupported clock rate %uHz\n", + __func__, hz); + return -EINVAL; + } + + rate = 1000 * ss->speed_khz / ss->divider / hz; + + __raw_writel(BF_SSP_TIMING_CLOCK_DIVIDE(ss->divider) | + BF_SSP_TIMING_CLOCK_RATE(rate - 1), + ss->regs + HW_SSP_TIMING); + + __raw_writel(BF_SSP_CTRL1_SSP_MODE(BV_SSP_CTRL1_SSP_MODE__SPI) | + BF_SSP_CTRL1_WORD_LENGTH + (BV_SSP_CTRL1_WORD_LENGTH__EIGHT_BITS) | + ((spi->mode & SPI_CPOL) ? BM_SSP_CTRL1_POLARITY : 0) | + ((spi->mode & SPI_CPHA) ? BM_SSP_CTRL1_PHASE : 0) | + (pio ? 0 : BM_SSP_CTRL1_DMA_ENABLE), + ss->regs + HW_SSP_CTRL1); + + __raw_writel(0x00, ss->regs + HW_SSP_CMD0_SET); + + return 0; +} + +static void mxs_spi_cleanup(struct spi_device *spi) +{ + struct mxs_spi_platform_data *pdata = spi->dev.platform_data; + + if (pdata && pdata->hw_pin_release) + pdata->hw_pin_release(); +} + +/* the spi->mode bits understood by this driver: */ +#define MODEBITS (SPI_CPOL | SPI_CPHA) +static int mxs_spi_setup(struct spi_device *spi) +{ + struct mxs_spi_platform_data *pdata; + struct mxs_spi *ss; + int err = 0; + + ss = spi_master_get_devdata(spi->master); + + if (!spi->bits_per_word) + spi->bits_per_word = 8; + + if (spi->mode & ~MODEBITS) { + dev_err(&spi->dev, "%s: unsupported mode bits %x\n", + __func__, spi->mode & ~MODEBITS); + err = -EINVAL; + goto out; + } + + dev_dbg(&spi->dev, "%s, mode %d, %u bits/w\n", + __func__, spi->mode & MODEBITS, spi->bits_per_word); + + pdata = spi->dev.platform_data; + + if (pdata && pdata->hw_pin_init) { + err = pdata->hw_pin_init(); + if (err) + goto out; + } + + err = mxs_spi_setup_transfer(spi, NULL); + if (err) + goto out2; + return 0; + +out2: + if (pdata && pdata->hw_pin_release) + pdata->hw_pin_release(); +out: + dev_err(&spi->dev, "Failed to setup transfer, error = %d\n", err); + return err; +} + +static inline u32 mxs_spi_cs(unsigned cs) +{ + return ((cs & 1) ? BM_SSP_CTRL0_WAIT_FOR_CMD : 0) | + ((cs & 2) ? BM_SSP_CTRL0_WAIT_FOR_IRQ : 0); +} + +static int mxs_spi_txrx_dma(struct mxs_spi *ss, int cs, + unsigned char *buf, dma_addr_t dma_buf, int len, + int *first, int *last, int write) +{ + u32 c0 = 0; + dma_addr_t spi_buf_dma = dma_buf; + int count, status = 0; + enum dma_data_direction dir = write ? DMA_TO_DEVICE : DMA_FROM_DEVICE; + + c0 |= (*first ? BM_SSP_CTRL0_LOCK_CS : 0); + c0 |= (*last ? BM_SSP_CTRL0_IGNORE_CRC : 0); + c0 |= (write ? 0 : BM_SSP_CTRL0_READ); + c0 |= BM_SSP_CTRL0_DATA_XFER; + + c0 |= mxs_spi_cs(cs); + + c0 |= BF_SSP_CTRL0_XFER_COUNT(len); + + if (!dma_buf) + spi_buf_dma = dma_map_single(ss->master_dev, buf, len, dir); + + ss->pdesc->cmd.cmd.bits.bytes = len; + ss->pdesc->cmd.cmd.bits.pio_words = 1; + ss->pdesc->cmd.cmd.bits.wait4end = 1; + ss->pdesc->cmd.cmd.bits.dec_sem = 1; + ss->pdesc->cmd.cmd.bits.irq = 1; + ss->pdesc->cmd.cmd.bits.command = write ? DMA_READ : DMA_WRITE; + ss->pdesc->cmd.address = spi_buf_dma; + ss->pdesc->cmd.pio_words[0] = c0; + mxs_dma_desc_append(ss->dma, ss->pdesc); + + mxs_dma_reset(ss->dma); + mxs_dma_ack_irq(ss->dma); + mxs_dma_enable_irq(ss->dma, 1); + init_completion(&ss->done); + mxs_dma_enable(ss->dma); + wait_for_completion(&ss->done); + count = 10000; + while ((__raw_readl(ss->regs + HW_SSP_CTRL0) & BM_SSP_CTRL0_RUN) + && count--) + continue; + if (count <= 0) { + printk(KERN_ERR "%c: timeout on line %s:%d\n", + write ? 'W' : 'C', __func__, __LINE__); + status = -ETIMEDOUT; + } + + if (!dma_buf) + dma_unmap_single(ss->master_dev, spi_buf_dma, len, dir); + + return status; +} + +static inline void mxs_spi_enable(struct mxs_spi *ss) +{ + __raw_writel(BM_SSP_CTRL0_LOCK_CS, ss->regs + HW_SSP_CTRL0_SET); + __raw_writel(BM_SSP_CTRL0_IGNORE_CRC, ss->regs + HW_SSP_CTRL0_CLR); +} + +static inline void mxs_spi_disable(struct mxs_spi *ss) +{ + __raw_writel(BM_SSP_CTRL0_LOCK_CS, ss->regs + HW_SSP_CTRL0_CLR); + __raw_writel(BM_SSP_CTRL0_IGNORE_CRC, ss->regs + HW_SSP_CTRL0_SET); +} + +static int mxs_spi_txrx_pio(struct mxs_spi *ss, int cs, + unsigned char *buf, int len, + int *first, int *last, int write) +{ + int count; + + if (*first) { + mxs_spi_enable(ss); + *first = 0; + } + + __raw_writel(mxs_spi_cs(cs), ss->regs + HW_SSP_CTRL0_SET); + + while (len--) { + if (*last && len == 0) { + mxs_spi_disable(ss); + *last = 0; + } + __raw_writel(BM_SSP_CTRL0_XFER_COUNT, + ss->regs + HW_SSP_CTRL0_CLR); + __raw_writel(1, ss->regs + HW_SSP_CTRL0_SET); /* byte-by-byte */ + + if (write) + __raw_writel(BM_SSP_CTRL0_READ, + ss->regs + HW_SSP_CTRL0_CLR); + else + __raw_writel(BM_SSP_CTRL0_READ, + ss->regs + HW_SSP_CTRL0_SET); + + /* Run! */ + __raw_writel(BM_SSP_CTRL0_RUN, ss->regs + HW_SSP_CTRL0_SET); + count = 10000; + while (((__raw_readl(ss->regs + HW_SSP_CTRL0) & + BM_SSP_CTRL0_RUN) == 0) && count--) + continue; + if (count <= 0) { + printk(KERN_ERR "%c: timeout on line %s:%d\n", + write ? 'W' : 'C', __func__, __LINE__); + break; + } + + if (write) + __raw_writel(*buf, ss->regs + HW_SSP_DATA); + + /* Set TRANSFER */ + __raw_writel(BM_SSP_CTRL0_DATA_XFER, + ss->regs + HW_SSP_CTRL0_SET); + + if (!write) { + count = 10000; + while (count-- && + (__raw_readl(ss->regs + HW_SSP_STATUS) & + BM_SSP_STATUS_FIFO_EMPTY)) + continue; + if (count <= 0) { + printk(KERN_ERR "%c: timeout on line %s:%d\n", + write ? 'W' : 'C', __func__, __LINE__); + break; + } + *buf = (__raw_readl(ss->regs + HW_SSP_DATA) & 0xFF); + } + + count = 10000; + while ((__raw_readl(ss->regs + HW_SSP_CTRL0) & BM_SSP_CTRL0_RUN) + && count--) + continue; + if (count <= 0) { + printk(KERN_ERR "%c: timeout on line %s:%d\n", + write ? 'W' : 'C', __func__, __LINE__); + break; + } + + /* advance to the next byte */ + buf++; + } + return len < 0 ? 0 : -ETIMEDOUT; +} + +static int mxs_spi_handle_message(struct mxs_spi *ss, struct spi_message *m) +{ + int first, last; + struct spi_transfer *t, *tmp_t; + int status = 0; + int cs; + + first = last = 0; + + cs = m->spi->chip_select; + + list_for_each_entry_safe(t, tmp_t, &m->transfers, transfer_list) { + + mxs_spi_setup_transfer(m->spi, t); + + if (&t->transfer_list == m->transfers.next) + first = !0; + if (&t->transfer_list == m->transfers.prev) + last = !0; + if (t->rx_buf && t->tx_buf) { + pr_debug("%s: cannot send and receive simultaneously\n", + __func__); + return -EINVAL; + } + + /* + REVISIT: + here driver completely ignores setting of t->cs_change + */ + if (t->tx_buf) { + status = pio ? + mxs_spi_txrx_pio(ss, cs, (void *)t->tx_buf, + t->len, &first, &last, 1) : + mxs_spi_txrx_dma(ss, cs, (void *)t->tx_buf, + t->tx_dma, t->len, &first, &last, + 1); + if (debug) { + if (t->len < 0x10) + print_hex_dump_bytes("Tx ", + DUMP_PREFIX_OFFSET, + t->tx_buf, t->len); + else + pr_debug("Tx: %d bytes\n", t->len); + } + } + if (t->rx_buf) { + status = pio ? + mxs_spi_txrx_pio(ss, cs, t->rx_buf, + t->len, &first, &last, 0) : + mxs_spi_txrx_dma(ss, cs, t->rx_buf, + t->rx_dma, t->len, &first, &last, + 0); + if (debug) { + if (t->len < 0x10) + print_hex_dump_bytes("Rx ", + DUMP_PREFIX_OFFSET, + t->rx_buf, t->len); + else + pr_debug("Rx: %d bytes\n", t->len); + } + } + + if (status) + break; + + first = last = 0; + + } + return status; +} + +/** + * mxs_spi_handle + * + * The workhorse of the driver - it handles messages from the list + * + **/ +static void mxs_spi_handle(struct work_struct *w) +{ + struct mxs_spi *ss = container_of(w, struct mxs_spi, work); + unsigned long flags; + struct spi_message *m; + + BUG_ON(w == NULL); + + spin_lock_irqsave(&ss->lock, flags); + while (!list_empty(&ss->queue)) { + m = list_entry(ss->queue.next, struct spi_message, queue); + list_del_init(&m->queue); + spin_unlock_irqrestore(&ss->lock, flags); + + m->status = mxs_spi_handle_message(ss, m); + if (m->complete) + m->complete(m->context); + + spin_lock_irqsave(&ss->lock, flags); + } + spin_unlock_irqrestore(&ss->lock, flags); + + return; +} + +/** + * mxs_spi_transfer + * + * Called indirectly from spi_async, queues all the messages to + * spi_handle_message + * + * @spi: spi device + * @m: message to be queued +**/ +static int mxs_spi_transfer(struct spi_device *spi, struct spi_message *m) +{ + struct mxs_spi *ss = spi_master_get_devdata(spi->master); + unsigned long flags; + + m->status = -EINPROGRESS; + spin_lock_irqsave(&ss->lock, flags); + list_add_tail(&m->queue, &ss->queue); + queue_work(ss->workqueue, &ss->work); + spin_unlock_irqrestore(&ss->lock, flags); + return 0; +} + +static irqreturn_t mxs_spi_irq_dma(int irq, void *dev_id) +{ + struct mxs_spi *ss = dev_id; + + mxs_dma_ack_irq(ss->dma); + mxs_dma_cooked(ss->dma, NULL); + complete(&ss->done); + return IRQ_HANDLED; +} + +static irqreturn_t mxs_spi_irq_err(int irq, void *dev_id) +{ + struct mxs_spi *ss = dev_id; + u32 c1, st; + + c1 = __raw_readl(ss->regs + HW_SSP_CTRL1); + st = __raw_readl(ss->regs + HW_SSP_STATUS); + printk(KERN_ERR "IRQ - ERROR!, status = 0x%08X, c1 = 0x%08X\n", st, c1); + __raw_writel(c1 & 0xCCCC0000, ss->regs + HW_SSP_CTRL1_CLR); + + return IRQ_HANDLED; +} + +static int __init mxs_spi_probe(struct platform_device *dev) +{ + int err = 0; + struct spi_master *master; + struct mxs_spi *ss; + struct resource *r; + u32 mem; + + /* Get resources(memory, IRQ) associated with the device */ + master = spi_alloc_master(&dev->dev, sizeof(struct mxs_spi)); + + if (master == NULL) { + err = -ENOMEM; + goto out0; + } + + platform_set_drvdata(dev, master); + + r = platform_get_resource(dev, IORESOURCE_MEM, 0); + if (r == NULL) { + err = -ENODEV; + goto out_put_master; + } + + ss = spi_master_get_devdata(master); + ss->master_dev = &dev->dev; + + INIT_WORK(&ss->work, mxs_spi_handle); + INIT_LIST_HEAD(&ss->queue); + spin_lock_init(&ss->lock); + ss->workqueue = create_singlethread_workqueue(dev_name(&dev->dev)); + master->transfer = mxs_spi_transfer; + master->setup = mxs_spi_setup; + master->cleanup = mxs_spi_cleanup; + + if (!request_mem_region(r->start, + resource_size(r), dev_name(&dev->dev))) { + err = -ENXIO; + goto out_put_master; + } + mem = r->start; + + ss->regs = IO_ADDRESS(r->start); + + ss->irq_dma = platform_get_irq(dev, 0); + if (ss->irq_dma < 0) { + err = -ENXIO; + goto out_put_master; + } + ss->irq_err = platform_get_irq(dev, 1); + if (ss->irq_err < 0) { + err = -ENXIO; + goto out_put_master; + } + + r = platform_get_resource(dev, IORESOURCE_DMA, 0); + if (r == NULL) { + err = -ENODEV; + goto out_put_master; + } + + ss->dma = r->start; + err = mxs_dma_request(ss->dma, &dev->dev, (char *)dev_name(&dev->dev)); + if (err) + goto out_put_master; + + ss->pdesc = mxs_dma_alloc_desc(); + if (ss->pdesc == NULL || IS_ERR(ss->pdesc)) { + err = -ENOMEM; + goto out_free_dma; + } + + master->bus_num = dev->id + 1; + master->num_chipselect = 1; + + /* SPI controller initializations */ + err = mxs_spi_init_hw(ss); + if (err) { + dev_dbg(&dev->dev, "cannot initialize hardware\n"); + goto out_free_dma_desc; + } + + clk_set_rate(ss->clk, 120 * 1000 * 1000); + ss->speed_khz = clk_get_rate(ss->clk) / 1000; + ss->divider = 2; + dev_info(&dev->dev, "Max possible speed %d = %ld/%d kHz\n", + ss->speed_khz, clk_get_rate(ss->clk), ss->divider); + + /* Register for SPI Interrupt */ + err = request_irq(ss->irq_dma, mxs_spi_irq_dma, 0, + dev_name(&dev->dev), ss); + if (err) { + dev_dbg(&dev->dev, "request_irq failed, %d\n", err); + goto out_release_hw; + } + err = request_irq(ss->irq_err, mxs_spi_irq_err, IRQF_SHARED, + dev_name(&dev->dev), ss); + if (err) { + dev_dbg(&dev->dev, "request_irq(error) failed, %d\n", err); + goto out_free_irq; + } + + err = spi_register_master(master); + if (err) { + dev_dbg(&dev->dev, "cannot register spi master, %d\n", err); + goto out_free_irq_2; + } + dev_info(&dev->dev, "at 0x%08X mapped to 0x%08X, irq=%d, bus %d, %s\n", + mem, (u32) ss->regs, ss->irq_dma, + master->bus_num, pio ? "PIO" : "DMA"); + return 0; + +out_free_irq_2: + free_irq(ss->irq_err, ss); +out_free_irq: + free_irq(ss->irq_dma, ss); +out_free_dma_desc: + mxs_dma_free_desc(ss->pdesc); +out_free_dma: + mxs_dma_release(ss->dma, &dev->dev); +out_release_hw: + mxs_spi_release_hw(ss); +out_put_master: + spi_master_put(master); +out0: + return err; +} + +static int __devexit mxs_spi_remove(struct platform_device *dev) +{ + struct mxs_spi *ss; + struct spi_master *master; + + master = platform_get_drvdata(dev); + if (master == NULL) + goto out0; + ss = spi_master_get_devdata(master); + if (ss == NULL) + goto out1; + free_irq(ss->irq_err, ss); + free_irq(ss->irq_dma, ss); + if (ss->workqueue) + destroy_workqueue(ss->workqueue); + mxs_dma_free_desc(ss->pdesc); + mxs_dma_release(ss->dma, &dev->dev); + mxs_spi_release_hw(ss); + platform_set_drvdata(dev, 0); +out1: + spi_master_put(master); +out0: + return 0; +} + +#ifdef CONFIG_PM +static int mxs_spi_suspend(struct platform_device *pdev, pm_message_t pmsg) +{ + struct mxs_spi *ss; + struct spi_master *master; + + master = platform_get_drvdata(pdev); + ss = spi_master_get_devdata(master); + + ss->saved_timings = __raw_readl(ss->regs + HW_SSP_TIMING); + clk_disable(ss->clk); + + return 0; +} + +static int mxs_spi_resume(struct platform_device *pdev) +{ + struct mxs_spi *ss; + struct spi_master *master; + + master = platform_get_drvdata(pdev); + ss = spi_master_get_devdata(master); + + clk_enable(ss->clk); + __raw_writel(BM_SSP_CTRL0_SFTRST | BM_SSP_CTRL0_CLKGATE, + ss->regs + HW_SSP_CTRL0_CLR); + __raw_writel(ss->saved_timings, ss->regs + HW_SSP_TIMING); + + return 0; +} + +#else +#define mxs_spi_suspend NULL +#define mxs_spi_resume NULL +#endif + +static struct platform_driver mxs_spi_driver = { + .probe = mxs_spi_probe, + .remove = __devexit_p(mxs_spi_remove), + .driver = { + .name = "mxs-spi", + .owner = THIS_MODULE, + }, + .suspend = mxs_spi_suspend, + .resume = mxs_spi_resume, +}; + +static int __init mxs_spi_init(void) +{ + return platform_driver_register(&mxs_spi_driver); +} + +static void __exit mxs_spi_exit(void) +{ + platform_driver_unregister(&mxs_spi_driver); +} + +module_init(mxs_spi_init); +module_exit(mxs_spi_exit); +module_param(pio, int, S_IRUGO); +module_param(debug, int, S_IRUGO); +MODULE_AUTHOR("dmitry pervushin "); +MODULE_DESCRIPTION("MXS SPI/SSP"); +MODULE_LICENSE("GPL"); diff --git a/drivers/spi/spi_mxs.h b/drivers/spi/spi_mxs.h new file mode 100644 index 000000000000..ba605bf3b56e --- /dev/null +++ b/drivers/spi/spi_mxs.h @@ -0,0 +1,52 @@ +/* + * Freescale MXS SPI master driver + * + * Author: dmitry pervushin + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. + * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#ifndef __SPI_STMP_H +#define __SPI_STMP_H + +#include + +struct mxs_spi { + void __iomem *regs; /* vaddr of the control registers */ + + u32 irq_dma; + u32 irq_err; + u32 dma; + struct mxs_dma_desc *pdesc; + + u32 speed_khz; + u32 saved_timings; + u32 divider; + + struct clk *clk; + struct device *master_dev; + + struct work_struct work; + struct workqueue_struct *workqueue; + spinlock_t lock; + struct list_head queue; + + struct completion done; +}; + +#endif /* __SPI_STMP_H */ diff --git a/drivers/usb/gadget/Kconfig b/drivers/usb/gadget/Kconfig index 0401a40bc300..cc5f056bb33e 100644 --- a/drivers/usb/gadget/Kconfig +++ b/drivers/usb/gadget/Kconfig @@ -209,17 +209,6 @@ config USB_OMAP default USB_GADGET select USB_GADGET_SELECTED -config USB_OTG - boolean "OTG Support" - depends on USB_GADGET_OMAP && ARCH_OMAP_OTG && USB_OHCI_HCD - help - The most notable feature of USB OTG is support for a - "Dual-Role" device, which can act as either a device - or a host. The initial role choice can be changed - later, when two dual-role devices talk to each other. - - Select this only if your OMAP board has a Mini-AB connector. - config USB_GADGET_PXA25X boolean "PXA 25x or IXP 4xx" depends on (ARCH_PXA && PXA25x) || ARCH_IXP4XX @@ -484,6 +473,40 @@ config USB_GOKU default USB_GADGET select USB_GADGET_SELECTED +config USB_GADGET_ARC + boolean "Freescale USB Device Controller" + depends on ARCH_MXC || ARCH_STMP3XXX || ARCH_MXS + select USB_GADGET_DUALSPEED + select USB_OTG_UTILS + select USB_GADGET_DUALSPEED if USB_GADGET_FSL_1504 || USB_GADGET_FSL_UTMI + help + Some Freescale processors have a USBOTG controller, + which supports device mode. + + Say "y" to link the driver statically, or "m" to build a + dynamically linked module called "arc_udc" and force all + gadget drivers to also be dynamically linked. + +config USB_STATIC_IRAM_PPH + bool "Apply static IRAM patch" + depends on USB_GADGET_ARC && (ARCH_MX37 || ARCH_MX3 || ARCH_MX25 || ARCH_MX51) + help + Apply static IRAM patch to peripheral driver. + +config USB_ARC + tristate + depends on USB_GADGET_ARC + default USB_GADGET + select USB_GADGET_SELECTED + +config WORKAROUND_ARCUSB_REG_RW + bool "work around mx28 arch register write" + depends on ARCH_MX28 && USB_ARC + default ARCH_MX28 + help + MX28 require read ARC register before write. Use SWP intructure to + implement this requirement. + config USB_GADGET_LANGWELL boolean "Intel Langwell USB Device Controller" depends on PCI @@ -552,6 +575,18 @@ config USB_GADGET_DUALSPEED Means that gadget drivers should include extra descriptors and code to handle dual-speed controllers. +config USB_OTG + boolean "OTG Support" + depends on (USB_GADGET_OMAP && ARCH_OMAP_OTG && USB_OHCI_HCD) || \ + (USB_GADGET_ARC && (ARCH_MXC || ARCH_STMP3XXX || ARCH_MXS) && USB_EHCI_HCD) + help + The most notable feature of USB OTG is support for a + "Dual-Role" device, which can act as either a device + or a host. The initial role choice can be changed + later, when two dual-role devices talk to each other. + + Select this only if your OMAP board has a Mini-AB connector. + # # USB Gadget Drivers # diff --git a/drivers/usb/gadget/Makefile b/drivers/usb/gadget/Makefile index 9bcde110feb1..7f2d86c431aa 100644 --- a/drivers/usb/gadget/Makefile +++ b/drivers/usb/gadget/Makefile @@ -28,6 +28,7 @@ obj-$(CONFIG_USB_FSL_QE) += fsl_qe_udc.o obj-$(CONFIG_USB_CI13XXX) += ci13xxx_udc.o obj-$(CONFIG_USB_S3C_HSOTG) += s3c-hsotg.o obj-$(CONFIG_USB_LANGWELL) += langwell_udc.o +obj-$(CONFIG_USB_ARC) += arcotg_udc.o # # USB gadget drivers diff --git a/drivers/usb/gadget/arcotg_udc.c b/drivers/usb/gadget/arcotg_udc.c new file mode 100644 index 000000000000..f41690273385 --- /dev/null +++ b/drivers/usb/gadget/arcotg_udc.c @@ -0,0 +1,3105 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#undef DEBUG +#undef VERBOSE + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "arcotg_udc.h" +#include +#include + +#define DRIVER_DESC "ARC USBOTG Device Controller driver" +#define DRIVER_AUTHOR "Freescale Semiconductor" +#define DRIVER_VERSION "1 August 2005" + +#ifdef CONFIG_PPC_MPC512x +#define BIG_ENDIAN_DESC +#endif + +#ifdef BIG_ENDIAN_DESC +#define cpu_to_hc32(x) (x) +#define hc32_to_cpu(x) (x) +#else +#define cpu_to_hc32(x) cpu_to_le32((x)) +#define hc32_to_cpu(x) le32_to_cpu((x)) +#endif + +#define DMA_ADDR_INVALID (~(dma_addr_t)0) + +static const char driver_name[] = "fsl-usb2-udc"; +static const char driver_desc[] = DRIVER_DESC; + +volatile static struct usb_dr_device *dr_regs; +volatile static struct usb_sys_interface *usb_sys_regs; + +/* it is initialized in probe() */ +static struct fsl_udc *udc_controller; + +#ifdef POSTPONE_FREE_LAST_DTD +static struct ep_td_struct *last_free_td; +#endif +static const struct usb_endpoint_descriptor +fsl_ep0_desc = { + .bLength = USB_DT_ENDPOINT_SIZE, + .bDescriptorType = USB_DT_ENDPOINT, + .bEndpointAddress = 0, + .bmAttributes = USB_ENDPOINT_XFER_CONTROL, + .wMaxPacketSize = USB_MAX_CTRL_PAYLOAD, +}; +static const size_t g_iram_size = IRAM_TD_PPH_SIZE; +static unsigned long g_iram_base; +static __iomem void *g_iram_addr; + +typedef int (*dev_sus)(struct device *dev, pm_message_t state); +typedef int (*dev_res) (struct device *dev); +static int udc_suspend(struct fsl_udc *udc); +static int fsl_udc_suspend(struct platform_device *pdev, pm_message_t state); +static int fsl_udc_resume(struct platform_device *pdev); +static void fsl_ep_fifo_flush(struct usb_ep *_ep); + +#ifdef CONFIG_USB_OTG +/* Get platform resource from OTG driver */ +extern struct resource *otg_get_resources(void); +#endif + +extern void fsl_platform_set_test_mode(struct fsl_usb2_platform_data *pdata, enum usb_test_mode mode); + +static inline void +dr_wake_up_enable(struct fsl_udc *udc, bool enable) +{ + struct fsl_usb2_platform_data *pdata; + pdata = udc->pdata; + + if (enable && (!device_may_wakeup(udc_controller->gadget.dev.parent))) + return; + + if (pdata->wake_up_enable) + pdata->wake_up_enable(pdata, enable); +} + +#ifdef CONFIG_WORKAROUND_ARCUSB_REG_RW +static void safe_writel(u32 val32, void *addr) +{ + __asm__ ("swp %0, %0, [%1]" : : "r"(val32), "r"(addr)); +} +#endif + +#ifdef CONFIG_PPC32 +#define fsl_readl(addr) in_le32((addr)) +#define fsl_writel(addr, val32) out_le32((val32), (addr)) +#elif defined (CONFIG_WORKAROUND_ARCUSB_REG_RW) +#define fsl_readl(addr) readl((addr)) +#define fsl_writel(val32, addr) safe_writel(val32, addr) +#else +#define fsl_readl(addr) readl((addr)) +#define fsl_writel(addr, val32) writel((addr), (val32)) +#endif + +/******************************************************************** + * Internal Used Function +********************************************************************/ + +#ifdef DUMP_QUEUES +static void dump_ep_queue(struct fsl_ep *ep) +{ + int ep_index; + struct fsl_req *req; + struct ep_td_struct *dtd; + + if (list_empty(&ep->queue)) { + pr_debug("udc: empty\n"); + return; + } + + ep_index = ep_index(ep) * 2 + ep_is_in(ep); + pr_debug("udc: ep=0x%p index=%d\n", ep, ep_index); + + list_for_each_entry(req, &ep->queue, queue) { + pr_debug("udc: req=0x%p dTD count=%d\n", req, req->dtd_count); + pr_debug("udc: dTD head=0x%p tail=0x%p\n", req->head, + req->tail); + + dtd = req->head; + + while (dtd) { + if (le32_to_cpu(dtd->next_td_ptr) & DTD_NEXT_TERMINATE) + break; /* end of dTD list */ + + dtd = dtd->next_td_virt; + } + } +} +#else +static inline void dump_ep_queue(struct fsl_ep *ep) +{ +} +#endif + +#if (defined CONFIG_ARCH_MX35 || defined CONFIG_ARCH_MX25) +/* + * The Phy at MX35 and MX25 have bugs, it must disable, and re-eable phy + * if the phy clock is disabled before + */ +static void reset_phy(void) +{ + u32 phyctrl; + phyctrl = fsl_readl(&dr_regs->phyctrl1); + phyctrl &= ~PHY_CTRL0_USBEN; + fsl_writel(phyctrl, &dr_regs->phyctrl1); + + phyctrl = fsl_readl(&dr_regs->phyctrl1); + phyctrl |= PHY_CTRL0_USBEN; + fsl_writel(phyctrl, &dr_regs->phyctrl1); +} +#else +static void reset_phy(void){; } +#endif +/*----------------------------------------------------------------- + * done() - retire a request; caller blocked irqs + * @status : request status to be set, only works when + * request is still in progress. + *--------------------------------------------------------------*/ +static void done(struct fsl_ep *ep, struct fsl_req *req, int status) +{ + struct fsl_udc *udc = NULL; + unsigned char stopped = ep->stopped; + struct ep_td_struct *curr_td, *next_td; + int j; + + udc = (struct fsl_udc *)ep->udc; + /* Removed the req from fsl_ep->queue */ + list_del_init(&req->queue); + + /* req.status should be set as -EINPROGRESS in ep_queue() */ + if (req->req.status == -EINPROGRESS) + req->req.status = status; + else + status = req->req.status; + + /* Free dtd for the request */ + next_td = req->head; + for (j = 0; j < req->dtd_count; j++) { + curr_td = next_td; + if (j != req->dtd_count - 1) { + next_td = curr_td->next_td_virt; +#ifdef POSTPONE_FREE_LAST_DTD + dma_pool_free(udc->td_pool, curr_td, curr_td->td_dma); + } else { + if (last_free_td != NULL) + dma_pool_free(udc->td_pool, last_free_td, + last_free_td->td_dma); + last_free_td = curr_td; + } +#else + } + + dma_pool_free(udc->td_pool, curr_td, curr_td->td_dma); +#endif + } + + if (USE_MSC_WR(req->req.length)) { + req->req.dma -= 1; + memmove(req->req.buf, req->req.buf + 1, MSC_BULK_CB_WRAP_LEN); + } + + if (req->mapped) { + dma_unmap_single(ep->udc->gadget.dev.parent, + req->req.dma, req->req.length, + ep_is_in(ep) + ? DMA_TO_DEVICE + : DMA_FROM_DEVICE); + req->req.dma = DMA_ADDR_INVALID; + req->mapped = 0; + } else + dma_sync_single_for_cpu(ep->udc->gadget.dev.parent, + req->req.dma, req->req.length, + ep_is_in(ep) + ? DMA_TO_DEVICE + : DMA_FROM_DEVICE); + + if (status && (status != -ESHUTDOWN)) + VDBG("complete %s req %p stat %d len %u/%u", + ep->ep.name, &req->req, status, + req->req.actual, req->req.length); + + ep->stopped = 1; + + spin_unlock(&ep->udc->lock); + /* complete() is from gadget layer, + * eg fsg->bulk_in_complete() */ + if (req->req.complete) + req->req.complete(&ep->ep, &req->req); + + spin_lock(&ep->udc->lock); + ep->stopped = stopped; +} + +/*----------------------------------------------------------------- + * nuke(): delete all requests related to this ep + * called with spinlock held + *--------------------------------------------------------------*/ +static void nuke(struct fsl_ep *ep, int status) +{ + ep->stopped = 1; + + /* Flush fifo */ + fsl_ep_fifo_flush(&ep->ep); + + /* Whether this eq has request linked */ + while (!list_empty(&ep->queue)) { + struct fsl_req *req = NULL; + + req = list_entry(ep->queue.next, struct fsl_req, queue); + done(ep, req, status); + } + dump_ep_queue(ep); +} + +/*------------------------------------------------------------------ + Internal Hardware related function + ------------------------------------------------------------------*/ + +static void dr_phy_low_power_mode(struct fsl_udc *udc, bool enable) +{ + u32 temp; + + if (!device_may_wakeup(udc_controller->gadget.dev.parent)) + return; + + if (enable) { + temp = fsl_readl(&dr_regs->portsc1); + temp |= PORTSCX_PHY_LOW_POWER_SPD; + fsl_writel(temp, &dr_regs->portsc1); + + if (udc_controller->pdata->usb_clock_for_pm) + udc_controller->pdata->usb_clock_for_pm(false); + } else { + if (udc_controller->pdata->usb_clock_for_pm) + udc_controller->pdata->usb_clock_for_pm(true); + + /* Due to mx35/mx25's phy's bug */ + reset_phy(); + temp = fsl_readl(&dr_regs->portsc1); + temp &= ~PORTSCX_PHY_LOW_POWER_SPD; + fsl_writel(temp, &dr_regs->portsc1); + } +} + +static int dr_controller_setup(struct fsl_udc *udc) +{ + unsigned int tmp = 0, portctrl = 0; + unsigned int __attribute((unused)) ctrl = 0; + unsigned long timeout; + struct fsl_usb2_platform_data *pdata; + +#define FSL_UDC_RESET_TIMEOUT 1000 + + /* before here, make sure dr_regs has been initialized */ + if (!udc) + return -EINVAL; + pdata = udc->pdata; + + /* Stop and reset the usb controller */ + tmp = fsl_readl(&dr_regs->usbcmd); + tmp &= ~USB_CMD_RUN_STOP; + fsl_writel(tmp, &dr_regs->usbcmd); + + tmp = fsl_readl(&dr_regs->usbcmd); + tmp |= USB_CMD_CTRL_RESET; + fsl_writel(tmp, &dr_regs->usbcmd); + + /* Wait for reset to complete */ + timeout = jiffies + FSL_UDC_RESET_TIMEOUT; + while (fsl_readl(&dr_regs->usbcmd) & USB_CMD_CTRL_RESET) { + if (time_after(jiffies, timeout)) { + ERR("udc reset timeout! \n"); + return -ETIMEDOUT; + } + cpu_relax(); + } + + /* Set the controller as device mode */ + tmp = fsl_readl(&dr_regs->usbmode); + tmp &= ~USB_MODE_CTRL_MODE_MASK; /* clear mode bits */ + tmp |= USB_MODE_CTRL_MODE_DEVICE; + /* Disable Setup Lockout */ + tmp |= USB_MODE_SETUP_LOCK_OFF; + if (pdata->es) + tmp |= USB_MODE_ES; + fsl_writel(tmp, &dr_regs->usbmode); + + fsl_platform_set_device_mode(pdata); + + /* Clear the setup status */ + fsl_writel(0, &dr_regs->usbsts); + + tmp = udc->ep_qh_dma; + tmp &= USB_EP_LIST_ADDRESS_MASK; + fsl_writel(tmp, &dr_regs->endpointlistaddr); + + VDBG("vir[qh_base] is %p phy[qh_base] is 0x%8x reg is 0x%8x", + (int)udc->ep_qh, (int)tmp, + fsl_readl(&dr_regs->endpointlistaddr)); + + /* Config PHY interface */ + portctrl = fsl_readl(&dr_regs->portsc1); + portctrl &= ~(PORTSCX_PHY_TYPE_SEL | PORTSCX_PORT_WIDTH); + switch (udc->phy_mode) { + case FSL_USB2_PHY_ULPI: + portctrl |= PORTSCX_PTS_ULPI; + break; + case FSL_USB2_PHY_UTMI_WIDE: + portctrl |= PORTSCX_PTW_16BIT; + /* fall through */ + case FSL_USB2_PHY_UTMI: + portctrl |= PORTSCX_PTS_UTMI; + break; + case FSL_USB2_PHY_SERIAL: + portctrl |= PORTSCX_PTS_FSLS; + break; + default: + return -EINVAL; + } + fsl_writel(portctrl, &dr_regs->portsc1); + + if (pdata->change_ahb_burst) { + /* if usb should not work in default INCRx mode */ + tmp = fsl_readl(&dr_regs->sbuscfg); + tmp = (tmp & ~0x07) | pdata->ahb_burst_mode; + fsl_writel(tmp, &dr_regs->sbuscfg); + } + + if (pdata->have_sysif_regs) { + /* Config control enable i/o output, cpu endian register */ + ctrl = __raw_readl(&usb_sys_regs->control); + ctrl |= USB_CTRL_IOENB; + __raw_writel(ctrl, &usb_sys_regs->control); + } + +#if defined(CONFIG_PPC32) && !defined(CONFIG_NOT_COHERENT_CACHE) + /* Turn on cache snooping hardware, since some PowerPC platforms + * wholly rely on hardware to deal with cache coherent. */ + + if (pdata->have_sysif_regs) { + /* Setup Snooping for all the 4GB space */ + tmp = SNOOP_SIZE_2GB; /* starts from 0x0, size 2G */ + __raw_writel(tmp, &usb_sys_regs->snoop1); + tmp |= 0x80000000; /* starts from 0x8000000, size 2G */ + __raw_writel(tmp, &usb_sys_regs->snoop2); + } +#endif + + return 0; +} + +/* Enable DR irq and set controller to run state */ +static void dr_controller_run(struct fsl_udc *udc) +{ + u32 temp; + + fsl_platform_pullup_enable(udc->pdata); + + /* Enable DR irq reg */ + temp = USB_INTR_INT_EN | USB_INTR_ERR_INT_EN + | USB_INTR_PTC_DETECT_EN | USB_INTR_RESET_EN + | USB_INTR_DEVICE_SUSPEND | USB_INTR_SYS_ERR_EN; + + fsl_writel(temp, &dr_regs->usbintr); + + if (device_may_wakeup(udc_controller->gadget.dev.parent)) { + /* enable BSV irq */ + temp = fsl_readl(&dr_regs->otgsc); + temp |= OTGSC_B_SESSION_VALID_IRQ_EN; + fsl_writel(temp, &dr_regs->otgsc); + } + + /* If vbus not on and used low power mode */ + if (!(fsl_readl(&dr_regs->otgsc) & OTGSC_B_SESSION_VALID) + && device_may_wakeup(udc_controller->gadget.dev.parent)) { + /* enable wake up */ + dr_wake_up_enable(udc, true); + /* Set stopped before low power mode */ + udc->stopped = 1; + /* close PHY clock */ + dr_phy_low_power_mode(udc, true); + printk(KERN_INFO "udc enter low power mode \n"); + } else { +#ifdef CONFIG_ARCH_MX37 + /* + add some delay for USB timing issue. USB may be + recognize as FS device + during USB gadget remote wake up function + */ + mdelay(100); +#endif + /* Clear stopped bit */ + udc->stopped = 0; + /* Set controller to Run */ + temp = fsl_readl(&dr_regs->usbcmd); + temp |= USB_CMD_RUN_STOP; + fsl_writel(temp, &dr_regs->usbcmd); + printk(KERN_INFO "udc run \n"); + } + + return; +} + +static void dr_controller_stop(struct fsl_udc *udc) +{ + unsigned int tmp; + + pr_debug("%s\n", __func__); + + /* if we're in OTG mode, and the Host is currently using the port, + * stop now and don't rip the controller out from under the + * ehci driver + */ + if (udc->gadget.is_otg) { + if (!(fsl_readl(&dr_regs->otgsc) & OTGSC_STS_USB_ID)) { + pr_debug("udc: Leaving early\n"); + return; + } + } + + /* disable all INTR */ + fsl_writel(0, &dr_regs->usbintr); + + /* disable wake up */ + dr_wake_up_enable(udc, false); + /* disable BSV irq */ + tmp = fsl_readl(&dr_regs->otgsc); + tmp &= ~OTGSC_B_SESSION_VALID_IRQ_EN; + fsl_writel(tmp, &dr_regs->otgsc); + + /* Set stopped bit for isr */ + udc->stopped = 1; + + /* disable IO output */ +/* usb_sys_regs->control = 0; */ + + fsl_platform_pullup_disable(udc->pdata); + + /* set controller to Stop */ + tmp = fsl_readl(&dr_regs->usbcmd); + tmp &= ~USB_CMD_RUN_STOP; + fsl_writel(tmp, &dr_regs->usbcmd); + + return; +} + +void dr_ep_setup(unsigned char ep_num, unsigned char dir, unsigned char ep_type) +{ + unsigned int tmp_epctrl = 0; + + tmp_epctrl = fsl_readl(&dr_regs->endptctrl[ep_num]); + if (dir) { + if (ep_num) + tmp_epctrl |= EPCTRL_TX_DATA_TOGGLE_RST; + tmp_epctrl |= EPCTRL_TX_ENABLE; + tmp_epctrl |= ((unsigned int)(ep_type) + << EPCTRL_TX_EP_TYPE_SHIFT); + } else { + if (ep_num) + tmp_epctrl |= EPCTRL_RX_DATA_TOGGLE_RST; + tmp_epctrl |= EPCTRL_RX_ENABLE; + tmp_epctrl |= ((unsigned int)(ep_type) + << EPCTRL_RX_EP_TYPE_SHIFT); + } + + fsl_writel(tmp_epctrl, &dr_regs->endptctrl[ep_num]); +} + +static void +dr_ep_change_stall(unsigned char ep_num, unsigned char dir, int value) +{ + u32 tmp_epctrl = 0; + + tmp_epctrl = fsl_readl(&dr_regs->endptctrl[ep_num]); + + if (value) { + /* set the stall bit */ + if (dir) + tmp_epctrl |= EPCTRL_TX_EP_STALL; + else + tmp_epctrl |= EPCTRL_RX_EP_STALL; + } else { + /* clear the stall bit and reset data toggle */ + if (dir) { + tmp_epctrl &= ~EPCTRL_TX_EP_STALL; + tmp_epctrl |= EPCTRL_TX_DATA_TOGGLE_RST; + } else { + tmp_epctrl &= ~EPCTRL_RX_EP_STALL; + tmp_epctrl |= EPCTRL_RX_DATA_TOGGLE_RST; + } + } + fsl_writel(tmp_epctrl, &dr_regs->endptctrl[ep_num]); +} + +/* Get stall status of a specific ep + Return: 0: not stalled; 1:stalled */ +static int dr_ep_get_stall(unsigned char ep_num, unsigned char dir) +{ + u32 epctrl; + + epctrl = fsl_readl(&dr_regs->endptctrl[ep_num]); + if (dir) + return (epctrl & EPCTRL_TX_EP_STALL) ? 1 : 0; + else + return (epctrl & EPCTRL_RX_EP_STALL) ? 1 : 0; +} + +/******************************************************************** + Internal Structure Build up functions +********************************************************************/ + +/*------------------------------------------------------------------ +* struct_ep_qh_setup(): set the Endpoint Capabilites field of QH + * @zlt: Zero Length Termination Select (1: disable; 0: enable) + * @mult: Mult field + ------------------------------------------------------------------*/ +static void struct_ep_qh_setup(struct fsl_udc *udc, unsigned char ep_num, + unsigned char dir, unsigned char ep_type, + unsigned int max_pkt_len, + unsigned int zlt, unsigned char mult) +{ + struct ep_queue_head *p_QH = &udc->ep_qh[2 * ep_num + dir]; + unsigned int tmp = 0; + + /* set the Endpoint Capabilites in QH */ + switch (ep_type) { + case USB_ENDPOINT_XFER_CONTROL: + /* Interrupt On Setup (IOS). for control ep */ + tmp = (max_pkt_len << EP_QUEUE_HEAD_MAX_PKT_LEN_POS) + | EP_QUEUE_HEAD_IOS; + break; + case USB_ENDPOINT_XFER_ISOC: + tmp = (max_pkt_len << EP_QUEUE_HEAD_MAX_PKT_LEN_POS) + | (mult << EP_QUEUE_HEAD_MULT_POS); + break; + case USB_ENDPOINT_XFER_BULK: + case USB_ENDPOINT_XFER_INT: + tmp = max_pkt_len << EP_QUEUE_HEAD_MAX_PKT_LEN_POS; + break; + default: + VDBG("error ep type is %d", ep_type); + return; + } + if (zlt) + tmp |= EP_QUEUE_HEAD_ZLT_SEL; + p_QH->max_pkt_length = cpu_to_hc32(tmp); + + return; +} + +/* Setup qh structure and ep register for ep0. */ +static void ep0_setup(struct fsl_udc *udc) +{ + /* the intialization of an ep includes: fields in QH, Regs, + * fsl_ep struct */ + struct_ep_qh_setup(udc, 0, USB_RECV, USB_ENDPOINT_XFER_CONTROL, + USB_MAX_CTRL_PAYLOAD, 0, 0); + struct_ep_qh_setup(udc, 0, USB_SEND, USB_ENDPOINT_XFER_CONTROL, + USB_MAX_CTRL_PAYLOAD, 0, 0); + dr_ep_setup(0, USB_RECV, USB_ENDPOINT_XFER_CONTROL); + dr_ep_setup(0, USB_SEND, USB_ENDPOINT_XFER_CONTROL); + + return; + +} + +/*********************************************************************** + Endpoint Management Functions +***********************************************************************/ + +/*------------------------------------------------------------------------- + * when configurations are set, or when interface settings change + * for example the do_set_interface() in gadget layer, + * the driver will enable or disable the relevant endpoints + * ep0 doesn't use this routine. It is always enabled. +-------------------------------------------------------------------------*/ +static int fsl_ep_enable(struct usb_ep *_ep, + const struct usb_endpoint_descriptor *desc) +{ + struct fsl_udc *udc = NULL; + struct fsl_ep *ep = NULL; + unsigned short max = 0; + unsigned char mult = 0, zlt; + int retval = -EINVAL; + unsigned long flags = 0; + + ep = container_of(_ep, struct fsl_ep, ep); + + pr_debug("udc: %s ep.name=%s\n", __func__, ep->ep.name); + /* catch various bogus parameters */ + if (!_ep || !desc || ep->desc + || (desc->bDescriptorType != USB_DT_ENDPOINT)) + return -EINVAL; + + udc = ep->udc; + + if (!udc->driver || (udc->gadget.speed == USB_SPEED_UNKNOWN)) + return -ESHUTDOWN; + + max = le16_to_cpu(desc->wMaxPacketSize); + + /* Disable automatic zlp generation. Driver is reponsible to indicate + * explicitly through req->req.zero. This is needed to enable multi-td + * request. */ + zlt = 1; + + /* Assume the max packet size from gadget is always correct */ + switch (desc->bmAttributes & 0x03) { + case USB_ENDPOINT_XFER_CONTROL: + case USB_ENDPOINT_XFER_BULK: + case USB_ENDPOINT_XFER_INT: + /* mult = 0. Execute N Transactions as demonstrated by + * the USB variable length packet protocol where N is + * computed using the Maximum Packet Length (dQH) and + * the Total Bytes field (dTD) */ + mult = 0; + break; + case USB_ENDPOINT_XFER_ISOC: + /* Calculate transactions needed for high bandwidth iso */ + mult = (unsigned char)(1 + ((max >> 11) & 0x03)); + max = max & 0x7ff; /* bit 0~10 */ + /* 3 transactions at most */ + if (mult > 3) + goto en_done; + break; + default: + goto en_done; + } + + spin_lock_irqsave(&udc->lock, flags); + ep->ep.maxpacket = max; + ep->desc = desc; + ep->stopped = 0; + + /* Controller related setup */ + /* Init EPx Queue Head (Ep Capabilites field in QH + * according to max, zlt, mult) */ + struct_ep_qh_setup(udc, (unsigned char) ep_index(ep), + (unsigned char) ((desc->bEndpointAddress & USB_DIR_IN) + ? USB_SEND : USB_RECV), + (unsigned char) (desc->bmAttributes + & USB_ENDPOINT_XFERTYPE_MASK), + max, zlt, mult); + + /* Init endpoint ctrl register */ + dr_ep_setup((unsigned char) ep_index(ep), + (unsigned char) ((desc->bEndpointAddress & USB_DIR_IN) + ? USB_SEND : USB_RECV), + (unsigned char) (desc->bmAttributes + & USB_ENDPOINT_XFERTYPE_MASK)); + + spin_unlock_irqrestore(&udc->lock, flags); + retval = 0; + + VDBG("enabled %s (ep%d%s) maxpacket %d", ep->ep.name, + ep->desc->bEndpointAddress & 0x0f, + (desc->bEndpointAddress & USB_DIR_IN) + ? "in" : "out", max); +en_done: + return retval; +} + +/*--------------------------------------------------------------------- + * @ep : the ep being unconfigured. May not be ep0 + * Any pending and uncomplete req will complete with status (-ESHUTDOWN) +*---------------------------------------------------------------------*/ +static int fsl_ep_disable(struct usb_ep *_ep) +{ + struct fsl_udc *udc = NULL; + struct fsl_ep *ep = NULL; + unsigned long flags = 0; + u32 epctrl; + int ep_num; + + ep = container_of(_ep, struct fsl_ep, ep); + if (!_ep || !ep->desc) { + VDBG("%s not enabled", _ep ? ep->ep.name : NULL); + return -EINVAL; + } + + /* disable ep on controller */ + ep_num = ep_index(ep); + epctrl = fsl_readl(&dr_regs->endptctrl[ep_num]); + if (ep_is_in(ep)) + epctrl &= ~EPCTRL_TX_ENABLE; + else + epctrl &= ~EPCTRL_RX_ENABLE; + fsl_writel(epctrl, &dr_regs->endptctrl[ep_num]); + + udc = (struct fsl_udc *)ep->udc; + spin_lock_irqsave(&udc->lock, flags); + + /* nuke all pending requests (does flush) */ + nuke(ep, -ESHUTDOWN); + + ep->desc = 0; + ep->stopped = 1; + spin_unlock_irqrestore(&udc->lock, flags); + + VDBG("disabled %s OK", _ep->name); + return 0; +} + +/*--------------------------------------------------------------------- + * allocate a request object used by this endpoint + * the main operation is to insert the req->queue to the eq->queue + * Returns the request, or null if one could not be allocated +*---------------------------------------------------------------------*/ +static struct usb_request * +fsl_alloc_request(struct usb_ep *_ep, gfp_t gfp_flags) +{ + struct fsl_req *req = NULL; + + req = kzalloc(sizeof *req, gfp_flags); + if (!req) + return NULL; + + req->req.dma = DMA_ADDR_INVALID; + pr_debug("udc: req=0x%p set req.dma=0x%x\n", req, req->req.dma); + INIT_LIST_HEAD(&req->queue); + + return &req->req; +} + +static void fsl_free_request(struct usb_ep *_ep, struct usb_request *_req) +{ + struct fsl_req *req = NULL; + + req = container_of(_req, struct fsl_req, req); + + if (_req) + kfree(req); +} + +static void update_qh(struct fsl_req *req) +{ + struct fsl_ep *ep = req->ep; + int i = ep_index(ep) * 2 + ep_is_in(ep); + u32 temp; + struct ep_queue_head *dQH = &ep->udc->ep_qh[i]; + + /* Write dQH next pointer and terminate bit to 0 */ + temp = req->head->td_dma & EP_QUEUE_HEAD_NEXT_POINTER_MASK; + if (NEED_IRAM(req->ep)) { + /* set next dtd stop bit,ensure only one dtd in this list */ + req->cur->next_td_ptr |= cpu_to_hc32(DTD_NEXT_TERMINATE); + temp = req->cur->td_dma & EP_QUEUE_HEAD_NEXT_POINTER_MASK; + } + dQH->next_dtd_ptr = cpu_to_hc32(temp); + /* Clear active and halt bit */ + temp = cpu_to_hc32(~(EP_QUEUE_HEAD_STATUS_ACTIVE + | EP_QUEUE_HEAD_STATUS_HALT)); + dQH->size_ioc_int_sts &= temp; + + /* Prime endpoint by writing 1 to ENDPTPRIME */ + temp = ep_is_in(ep) + ? (1 << (ep_index(ep) + 16)) + : (1 << (ep_index(ep))); + fsl_writel(temp, &dr_regs->endpointprime); +} + +/*-------------------------------------------------------------------------*/ +static int fsl_queue_td(struct fsl_ep *ep, struct fsl_req *req) +{ + u32 temp, bitmask, tmp_stat; + + /* VDBG("QH addr Register 0x%8x", dr_regs->endpointlistaddr); + VDBG("ep_qh[%d] addr is 0x%8x", i, (u32)&(ep->udc->ep_qh[i])); */ + + bitmask = ep_is_in(ep) + ? (1 << (ep_index(ep) + 16)) + : (1 << (ep_index(ep))); + + /* check if the pipe is empty */ + if (!(list_empty(&ep->queue))) { + /* Add td to the end */ + struct fsl_req *lastreq; + lastreq = list_entry(ep->queue.prev, struct fsl_req, queue); + if (NEED_IRAM(ep)) { + /* only one dtd in dqh */ + lastreq->tail->next_td_ptr = + cpu_to_hc32(req->head->td_dma | DTD_NEXT_TERMINATE); + goto out; + } else { + lastreq->tail->next_td_ptr = + cpu_to_hc32(req->head->td_dma & DTD_ADDR_MASK); + } + /* Read prime bit, if 1 goto done */ + if (fsl_readl(&dr_regs->endpointprime) & bitmask) + goto out; + do { + /* Set ATDTW bit in USBCMD */ + temp = fsl_readl(&dr_regs->usbcmd); + fsl_writel(temp | USB_CMD_ATDTW, &dr_regs->usbcmd); + + /* Read correct status bit */ + tmp_stat = fsl_readl(&dr_regs->endptstatus) & bitmask; + + } while (!(fsl_readl(&dr_regs->usbcmd) & USB_CMD_ATDTW)); + + /* Write ATDTW bit to 0 */ + temp = fsl_readl(&dr_regs->usbcmd); + fsl_writel(temp & ~USB_CMD_ATDTW, &dr_regs->usbcmd); + + if (tmp_stat) + goto out; + } + update_qh(req); +out: + return 0; +} + +/* Fill in the dTD structure + * @req: request that the transfer belongs to + * @length: return actually data length of the dTD + * @dma: return dma address of the dTD + * @is_last: return flag if it is the last dTD of the request + * return: pointer to the built dTD */ +static struct ep_td_struct *fsl_build_dtd(struct fsl_req *req, unsigned *length, + dma_addr_t *dma, int *is_last) +{ + u32 swap_temp; + struct ep_td_struct *dtd; + + /* how big will this transfer be? */ + *length = min(req->req.length - req->req.actual, + (unsigned)EP_MAX_LENGTH_TRANSFER); + if (NEED_IRAM(req->ep)) + *length = min(*length, g_iram_size); + dtd = dma_pool_alloc(udc_controller->td_pool, GFP_KERNEL, dma); + if (dtd == NULL) + return dtd; + + dtd->td_dma = *dma; + /* Clear reserved field */ + swap_temp = hc32_to_cpu(dtd->size_ioc_sts); + swap_temp &= ~DTD_RESERVED_FIELDS; + dtd->size_ioc_sts = cpu_to_hc32(swap_temp); + + /* Init all of buffer page pointers */ + swap_temp = (u32) (req->req.dma + req->req.actual); + if (NEED_IRAM(req->ep)) + swap_temp = (u32) (req->req.dma); + dtd->buff_ptr0 = cpu_to_hc32(swap_temp); + dtd->buff_ptr1 = cpu_to_hc32(swap_temp + 0x1000); + dtd->buff_ptr2 = cpu_to_hc32(swap_temp + 0x2000); + dtd->buff_ptr3 = cpu_to_hc32(swap_temp + 0x3000); + dtd->buff_ptr4 = cpu_to_hc32(swap_temp + 0x4000); + + req->req.actual += *length; + + /* zlp is needed if req->req.zero is set */ + if (req->req.zero) { + if (*length == 0 || (*length % req->ep->ep.maxpacket) != 0) + *is_last = 1; + else + *is_last = 0; + } else if (req->req.length == req->req.actual) + *is_last = 1; + else + *is_last = 0; + + if ((*is_last) == 0) + VDBG("multi-dtd request!\n"); + /* Fill in the transfer size; set active bit */ + swap_temp = ((*length << DTD_LENGTH_BIT_POS) | DTD_STATUS_ACTIVE); + + /* Enable interrupt for the last dtd of a request */ + if (*is_last && !req->req.no_interrupt) + swap_temp |= DTD_IOC; + if (NEED_IRAM(req->ep)) + swap_temp |= DTD_IOC; + + dtd->size_ioc_sts = cpu_to_hc32(swap_temp); + + mb(); + + VDBG("length = %d address= 0x%x", *length, (int)*dma); + + return dtd; +} + +/* Generate dtd chain for a request */ +static int fsl_req_to_dtd(struct fsl_req *req) +{ + unsigned count; + int is_last; + int is_first = 1; + struct ep_td_struct *last_dtd = NULL, *dtd; + dma_addr_t dma; + + if (NEED_IRAM(req->ep)) { + req->oridma = req->req.dma; + /* here, replace user buffer to iram buffer */ + if (ep_is_in(req->ep)) { + req->req.dma = req->ep->udc->iram_buffer[1]; + if ((list_empty(&req->ep->queue))) { + /* copy data only when no bulk in transfer is + running */ + memcpy((char *)req->ep->udc->iram_buffer_v[1], + req->req.buf, min(req->req.length, + g_iram_size)); + } + } else { + req->req.dma = req->ep->udc->iram_buffer[0]; + } + } + + if (USE_MSC_WR(req->req.length)) + req->req.dma += 1; + + do { + dtd = fsl_build_dtd(req, &count, &dma, &is_last); + if (dtd == NULL) + return -ENOMEM; + + if (is_first) { + is_first = 0; + req->head = dtd; + } else { + last_dtd->next_td_ptr = cpu_to_hc32(dma); + last_dtd->next_td_virt = dtd; + } + last_dtd = dtd; + + req->dtd_count++; + } while (!is_last); + + dtd->next_td_ptr = cpu_to_hc32(DTD_NEXT_TERMINATE); + req->cur = req->head; + req->tail = dtd; + + return 0; +} + +/* queues (submits) an I/O request to an endpoint */ +static int +fsl_ep_queue(struct usb_ep *_ep, struct usb_request *_req, gfp_t gfp_flags) +{ + struct fsl_ep *ep = container_of(_ep, struct fsl_ep, ep); + struct fsl_req *req = container_of(_req, struct fsl_req, req); + struct fsl_udc *udc; + unsigned long flags; + int is_iso = 0; + + /* catch various bogus parameters */ + if (!_req || !req->req.buf || (ep_index(ep) + && !list_empty(&req->queue))) { + VDBG("%s, bad params\n", __func__); + return -EINVAL; + } + if (!_ep || (!ep->desc && ep_index(ep))) { + VDBG("%s, bad ep\n", __func__); + return -EINVAL; + } + if (ep->desc->bmAttributes == USB_ENDPOINT_XFER_ISOC) { + if (req->req.length > ep->ep.maxpacket) + return -EMSGSIZE; + is_iso = 1; + } + + udc = ep->udc; + if (!udc->driver || udc->gadget.speed == USB_SPEED_UNKNOWN) + return -ESHUTDOWN; + + req->ep = ep; + + /* map virtual address to hardware */ + if (req->req.dma == DMA_ADDR_INVALID) { + req->req.dma = dma_map_single(ep->udc->gadget.dev.parent, + req->req.buf, + req->req.length, ep_is_in(ep) + ? DMA_TO_DEVICE + : DMA_FROM_DEVICE); + req->mapped = 1; + } else { + dma_sync_single_for_device(ep->udc->gadget.dev.parent, + req->req.dma, req->req.length, + ep_is_in(ep) + ? DMA_TO_DEVICE + : DMA_FROM_DEVICE); + req->mapped = 0; + } + + req->req.status = -EINPROGRESS; + req->req.actual = 0; + req->dtd_count = 0; + if (NEED_IRAM(ep)) { + req->last_one = 0; + req->buffer_offset = 0; + } + + spin_lock_irqsave(&udc->lock, flags); + + /* build dtds and push them to device queue */ + if (!fsl_req_to_dtd(req)) { + fsl_queue_td(ep, req); + } else { + spin_unlock_irqrestore(&udc->lock, flags); + return -ENOMEM; + } + + /* irq handler advances the queue */ + if (req != NULL) + list_add_tail(&req->queue, &ep->queue); + spin_unlock_irqrestore(&udc->lock, flags); + + return 0; +} + +/* dequeues (cancels, unlinks) an I/O request from an endpoint */ +static int fsl_ep_dequeue(struct usb_ep *_ep, struct usb_request *_req) +{ + struct fsl_ep *ep = container_of(_ep, struct fsl_ep, ep); + struct fsl_req *req; + unsigned long flags; + int ep_num, stopped, ret = 0; + u32 epctrl; + + if (!_ep || !_req) + return -EINVAL; + + spin_lock_irqsave(&ep->udc->lock, flags); + stopped = ep->stopped; + + /* Stop the ep before we deal with the queue */ + ep->stopped = 1; + ep_num = ep_index(ep); + epctrl = fsl_readl(&dr_regs->endptctrl[ep_num]); + if (ep_is_in(ep)) + epctrl &= ~EPCTRL_TX_ENABLE; + else + epctrl &= ~EPCTRL_RX_ENABLE; + fsl_writel(epctrl, &dr_regs->endptctrl[ep_num]); + + /* make sure it's actually queued on this endpoint */ + list_for_each_entry(req, &ep->queue, queue) { + if (&req->req == _req) + break; + } + if (&req->req != _req) { + ret = -EINVAL; + goto out; + } + + /* The request is in progress, or completed but not dequeued */ + if (ep->queue.next == &req->queue) { + _req->status = -ECONNRESET; + fsl_ep_fifo_flush(_ep); /* flush current transfer */ + + /* The request isn't the last request in this ep queue */ + if (req->queue.next != &ep->queue) { + struct ep_queue_head *qh; + struct fsl_req *next_req; + + qh = ep->qh; + next_req = list_entry(req->queue.next, struct fsl_req, + queue); + + /* Point the QH to the first TD of next request */ + fsl_writel((u32) next_req->head, &qh->curr_dtd_ptr); + } + + /* The request hasn't been processed, patch up the TD chain */ + } else { + struct fsl_req *prev_req; + + prev_req = list_entry(req->queue.prev, struct fsl_req, queue); + fsl_writel(fsl_readl(&req->tail->next_td_ptr), + &prev_req->tail->next_td_ptr); + + } + + done(ep, req, -ECONNRESET); + + /* Enable EP */ +out: epctrl = fsl_readl(&dr_regs->endptctrl[ep_num]); + if (ep_is_in(ep)) + epctrl |= EPCTRL_TX_ENABLE; + else + epctrl |= EPCTRL_RX_ENABLE; + fsl_writel(epctrl, &dr_regs->endptctrl[ep_num]); + ep->stopped = stopped; + + spin_unlock_irqrestore(&ep->udc->lock, flags); + return ret; +} + +/*-------------------------------------------------------------------------*/ + +/*----------------------------------------------------------------- + * modify the endpoint halt feature + * @ep: the non-isochronous endpoint being stalled + * @value: 1--set halt 0--clear halt + * Returns zero, or a negative error code. +*----------------------------------------------------------------*/ +static int fsl_ep_set_halt(struct usb_ep *_ep, int value) +{ + struct fsl_ep *ep = NULL; + unsigned long flags = 0; + int status = -EOPNOTSUPP; /* operation not supported */ + unsigned char ep_dir = 0, ep_num = 0; + struct fsl_udc *udc = NULL; + + ep = container_of(_ep, struct fsl_ep, ep); + udc = ep->udc; + if (!_ep || !ep->desc) { + status = -EINVAL; + goto out; + } + + if (ep->desc->bmAttributes == USB_ENDPOINT_XFER_ISOC) { + status = -EOPNOTSUPP; + goto out; + } + + /* Attempt to halt IN ep will fail if any transfer requests + * are still queue */ + if (value && ep_is_in(ep) && !list_empty(&ep->queue)) { + status = -EAGAIN; + goto out; + } + + status = 0; + ep_dir = ep_is_in(ep) ? USB_SEND : USB_RECV; + ep_num = (unsigned char)(ep_index(ep)); + spin_lock_irqsave(&ep->udc->lock, flags); + dr_ep_change_stall(ep_num, ep_dir, value); + spin_unlock_irqrestore(&ep->udc->lock, flags); + + if (ep_index(ep) == 0) { + udc->ep0_dir = 0; + } +out: + VDBG(" %s %s halt stat %d", ep->ep.name, + value ? "set" : "clear", status); + + return status; +} + +static int arcotg_fifo_status(struct usb_ep *_ep) +{ + struct fsl_ep *ep; + struct fsl_udc *udc; + int size = 0; + u32 bitmask; + struct ep_queue_head *d_qh; + + ep = container_of(_ep, struct fsl_ep, ep); + if (!_ep || (!ep->desc && ep_index(ep) != 0)) + return -ENODEV; + + udc = (struct fsl_udc *)ep->udc; + + if (!udc->driver || udc->gadget.speed == USB_SPEED_UNKNOWN) + return -ESHUTDOWN; + + d_qh = &ep->udc->ep_qh[ep_index(ep) * 2 + ep_is_in(ep)]; + + bitmask = (ep_is_in(ep)) ? (1 << (ep_index(ep) + 16)) : + (1 << (ep_index(ep))); + + if (fsl_readl(&dr_regs->endptstatus) & bitmask) + size = (d_qh->size_ioc_int_sts & DTD_PACKET_SIZE) + >> DTD_LENGTH_BIT_POS; + + pr_debug("%s %u\n", __func__, size); + return size; +} + +static void fsl_ep_fifo_flush(struct usb_ep *_ep) +{ + struct fsl_ep *ep; + int ep_num, ep_dir; + u32 bits; + unsigned long timeout; +#define FSL_UDC_FLUSH_TIMEOUT 1000 + + if (!_ep) { + return; + } else { + ep = container_of(_ep, struct fsl_ep, ep); + if (!ep->desc) + return; + } + ep_num = ep_index(ep); + ep_dir = ep_is_in(ep) ? USB_SEND : USB_RECV; + + if (ep_num == 0) + bits = (1 << 16) | 1; + else if (ep_dir == USB_SEND) + bits = 1 << (16 + ep_num); + else + bits = 1 << ep_num; + + timeout = jiffies + FSL_UDC_FLUSH_TIMEOUT; + do { + fsl_writel(bits, &dr_regs->endptflush); + + /* Wait until flush complete */ + while (fsl_readl(&dr_regs->endptflush)) { + if (time_after(jiffies, timeout)) { + ERR("ep flush timeout\n"); + return; + } + cpu_relax(); + } + /* See if we need to flush again */ + } while (fsl_readl(&dr_regs->endptstatus) & bits); +} + +static struct usb_ep_ops fsl_ep_ops = { + .enable = fsl_ep_enable, + .disable = fsl_ep_disable, + + .alloc_request = fsl_alloc_request, + .free_request = fsl_free_request, + + .queue = fsl_ep_queue, + .dequeue = fsl_ep_dequeue, + + .set_halt = fsl_ep_set_halt, + .fifo_status = arcotg_fifo_status, + .fifo_flush = fsl_ep_fifo_flush, /* flush fifo */ +}; + +/*------------------------------------------------------------------------- + Gadget Driver Layer Operations +-------------------------------------------------------------------------*/ + +/*---------------------------------------------------------------------- + * Get the current frame number (from DR frame_index Reg ) + *----------------------------------------------------------------------*/ +static int fsl_get_frame(struct usb_gadget *gadget) +{ + return (int)(fsl_readl(&dr_regs->frindex) & USB_FRINDEX_MASKS); +} + +/*----------------------------------------------------------------------- + * Tries to wake up the host connected to this gadget + -----------------------------------------------------------------------*/ +static int fsl_wakeup(struct usb_gadget *gadget) +{ + struct fsl_udc *udc = container_of(gadget, struct fsl_udc, gadget); + u32 portsc; + + /* Remote wakeup feature not enabled by host */ + if (!udc->remote_wakeup) + return -ENOTSUPP; + + portsc = fsl_readl(&dr_regs->portsc1); + /* not suspended? */ + if (!(portsc & PORTSCX_PORT_SUSPEND)) + return 0; + /* trigger force resume */ + portsc |= PORTSCX_PORT_FORCE_RESUME; + fsl_writel(portsc, &dr_regs->portsc1); + return 0; +} + +static int can_pullup(struct fsl_udc *udc) +{ + return udc->driver && udc->softconnect && udc->vbus_active; +} + +/* Notify controller that VBUS is powered, Called by whatever + detects VBUS sessions */ +static int fsl_vbus_session(struct usb_gadget *gadget, int is_active) +{ + struct fsl_udc *udc; + unsigned long flags; + + udc = container_of(gadget, struct fsl_udc, gadget); + spin_lock_irqsave(&udc->lock, flags); + VDBG("VBUS %s\n", is_active ? "on" : "off"); + udc->vbus_active = (is_active != 0); + if (can_pullup(udc)) + fsl_writel((fsl_readl(&dr_regs->usbcmd) | USB_CMD_RUN_STOP), + &dr_regs->usbcmd); + else + fsl_writel((fsl_readl(&dr_regs->usbcmd) & ~USB_CMD_RUN_STOP), + &dr_regs->usbcmd); + spin_unlock_irqrestore(&udc->lock, flags); + return 0; +} + +/* constrain controller's VBUS power usage + * This call is used by gadget drivers during SET_CONFIGURATION calls, + * reporting how much power the device may consume. For example, this + * could affect how quickly batteries are recharged. + * + * Returns zero on success, else negative errno. + */ +static int fsl_vbus_draw(struct usb_gadget *gadget, unsigned mA) +{ + struct fsl_udc *udc; + struct fsl_usb2_platform_data *pdata; + + udc = container_of(gadget, struct fsl_udc, gadget); + if (udc->transceiver) + return otg_set_power(udc->transceiver, mA); + pdata = udc->pdata; + if (pdata->xcvr_ops && pdata->xcvr_ops->set_vbus_draw) { + pdata->xcvr_ops->set_vbus_draw(pdata->xcvr_ops, pdata, mA); + return 0; + } + return -ENOTSUPP; +} + +/* Change Data+ pullup status + * this func is used by usb_gadget_connect/disconnet + */ +static int fsl_pullup(struct usb_gadget *gadget, int is_on) +{ + struct fsl_udc *udc; + + udc = container_of(gadget, struct fsl_udc, gadget); + udc->softconnect = (is_on != 0); + if (can_pullup(udc)) + fsl_writel((fsl_readl(&dr_regs->usbcmd) | USB_CMD_RUN_STOP), + &dr_regs->usbcmd); + else + fsl_writel((fsl_readl(&dr_regs->usbcmd) & ~USB_CMD_RUN_STOP), + &dr_regs->usbcmd); + + return 0; +} + +/* defined in gadget.h */ +static struct usb_gadget_ops fsl_gadget_ops = { + .get_frame = fsl_get_frame, + .wakeup = fsl_wakeup, +/* .set_selfpowered = fsl_set_selfpowered, */ /* Always selfpowered */ + .vbus_session = fsl_vbus_session, + .vbus_draw = fsl_vbus_draw, + .pullup = fsl_pullup, +}; + +/* Set protocol stall on ep0, protocol stall will automatically be cleared + on new transaction */ +static void ep0stall(struct fsl_udc *udc) +{ + u32 tmp; + + /* must set tx and rx to stall at the same time */ + tmp = fsl_readl(&dr_regs->endptctrl[0]); + tmp |= EPCTRL_TX_EP_STALL | EPCTRL_RX_EP_STALL; + fsl_writel(tmp, &dr_regs->endptctrl[0]); + udc->ep0_dir = 0; +} + +/* Prime a status phase for ep0 */ +static int ep0_prime_status(struct fsl_udc *udc, int direction) +{ + struct fsl_req *req = udc->status_req; + struct fsl_ep *ep; + int status = 0; + + if (direction == EP_DIR_IN) + udc->ep0_dir = USB_DIR_IN; + else + udc->ep0_dir = USB_DIR_OUT; + + ep = &udc->eps[0]; + + req->ep = ep; + req->req.length = 0; + req->req.status = -EINPROGRESS; + + status = fsl_ep_queue(&ep->ep, &req->req, GFP_ATOMIC); + return status; +} + +static inline int udc_reset_ep_queue(struct fsl_udc *udc, u8 pipe) +{ + struct fsl_ep *ep = get_ep_by_pipe(udc, pipe); + + if (!ep->name) + return 0; + + nuke(ep, -ESHUTDOWN); + + return 0; +} + +/* + * ch9 Set address + */ +static void ch9setaddress(struct fsl_udc *udc, u16 value, u16 index, u16 length) +{ + /* Save the new address to device struct */ + udc->device_address = (u8) value; + /* Update usb state */ + udc->usb_state = USB_STATE_ADDRESS; + /* Status phase */ + if (ep0_prime_status(udc, EP_DIR_IN)) + ep0stall(udc); +} + +/* + * ch9 Get status + */ +static void ch9getstatus(struct fsl_udc *udc, u8 request_type, u16 value, + u16 index, u16 length) +{ + u16 tmp = 0; /* Status, cpu endian */ + + struct fsl_req *req; + struct fsl_ep *ep; + int status = 0; + + ep = &udc->eps[0]; + + if ((request_type & USB_RECIP_MASK) == USB_RECIP_DEVICE) { + /* Get device status */ + tmp = 1 << USB_DEVICE_SELF_POWERED; + tmp |= udc->remote_wakeup << USB_DEVICE_REMOTE_WAKEUP; + } else if ((request_type & USB_RECIP_MASK) == USB_RECIP_INTERFACE) { + /* Get interface status */ + /* We don't have interface information in udc driver */ + tmp = 0; + } else if ((request_type & USB_RECIP_MASK) == USB_RECIP_ENDPOINT) { + /* Get endpoint status */ + struct fsl_ep *target_ep; + + target_ep = get_ep_by_pipe(udc, get_pipe_by_windex(index)); + + /* stall if endpoint doesn't exist */ + if (!target_ep->desc) + goto stall; + tmp = dr_ep_get_stall(ep_index(target_ep), ep_is_in(target_ep)) + << USB_ENDPOINT_HALT; + } + + udc->ep0_dir = USB_DIR_IN; + /* Borrow the per device data_req */ + /* status_req had been used to prime status */ + req = udc->data_req; + /* Fill in the reqest structure */ + *((u16 *) req->req.buf) = cpu_to_le16(tmp); + req->ep = ep; + req->req.length = 2; + + status = fsl_ep_queue(&ep->ep, &req->req, GFP_ATOMIC); + if (status) { + udc_reset_ep_queue(udc, 0); + ERR("Can't respond to getstatus request \n"); + goto stall; + } + return; +stall: + ep0stall(udc); + +} + +static void setup_received_irq(struct fsl_udc *udc, + struct usb_ctrlrequest *setup) +{ + u16 wValue = le16_to_cpu(setup->wValue); + u16 wIndex = le16_to_cpu(setup->wIndex); + u16 wLength = le16_to_cpu(setup->wLength); + struct usb_gadget *gadget = &(udc->gadget); + unsigned mA = 500; + udc_reset_ep_queue(udc, 0); + + if (wLength) { + int dir; + dir = EP_DIR_IN; + if (setup->bRequestType & USB_DIR_IN) { + dir = EP_DIR_OUT; + } + if (ep0_prime_status(udc, dir)) + ep0stall(udc); + } + /* We process some stardard setup requests here */ + switch (setup->bRequest) { + case USB_REQ_GET_STATUS: + /* Data+Status phase from udc */ + if ((setup->bRequestType & (USB_DIR_IN | USB_TYPE_MASK)) + != (USB_DIR_IN | USB_TYPE_STANDARD)) + break; + ch9getstatus(udc, setup->bRequestType, wValue, wIndex, wLength); + return; + + case USB_REQ_SET_ADDRESS: + /* Status phase from udc */ + if (setup->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD + | USB_RECIP_DEVICE)) + break; + ch9setaddress(udc, wValue, wIndex, wLength); + return; + case USB_REQ_SET_CONFIGURATION: + fsl_vbus_draw(gadget, mA); + break; + case USB_REQ_CLEAR_FEATURE: + case USB_REQ_SET_FEATURE: + /* Status phase from udc */ + { + int rc = -EOPNOTSUPP; + u16 ptc = 0; + + if ((setup->bRequestType & (USB_RECIP_MASK | USB_TYPE_MASK)) + == (USB_RECIP_ENDPOINT | USB_TYPE_STANDARD)) { + int pipe = get_pipe_by_windex(wIndex); + struct fsl_ep *ep; + + if (wValue != 0 || wLength != 0 || pipe > udc->max_ep) + break; + ep = get_ep_by_pipe(udc, pipe); + + spin_unlock(&udc->lock); + rc = fsl_ep_set_halt(&ep->ep, + (setup->bRequest == USB_REQ_SET_FEATURE) + ? 1 : 0); + spin_lock(&udc->lock); + + } else if ((setup->bRequestType & (USB_RECIP_MASK + | USB_TYPE_MASK)) == (USB_RECIP_DEVICE + | USB_TYPE_STANDARD)) { + /* Note: The driver has not include OTG support yet. + * This will be set when OTG support is added */ + if (setup->wValue == USB_DEVICE_TEST_MODE) + ptc = setup->wIndex >> 8; + else if (gadget_is_otg(&udc->gadget)) { + if (setup->bRequest == + USB_DEVICE_B_HNP_ENABLE) + udc->gadget.b_hnp_enable = 1; + else if (setup->bRequest == + USB_DEVICE_A_HNP_SUPPORT) + udc->gadget.a_hnp_support = 1; + else if (setup->bRequest == + USB_DEVICE_A_ALT_HNP_SUPPORT) + udc->gadget.a_alt_hnp_support = 1; + } + rc = 0; + } else + break; + + if (rc == 0) { + if (ep0_prime_status(udc, EP_DIR_IN)) + ep0stall(udc); + } + if (ptc) { + u32 tmp; + + mdelay(10); + fsl_platform_set_test_mode(udc->pdata, ptc); + tmp = fsl_readl(&dr_regs->portsc1) | (ptc << 16); + fsl_writel(tmp, &dr_regs->portsc1); + printk(KERN_INFO "udc: switch to test mode 0x%x.\n", ptc); + } + + return; + } + + default: + break; + } + + /* Requests handled by gadget */ + if (wLength) { + /* Data phase from gadget, status phase from udc */ + udc->ep0_dir = (setup->bRequestType & USB_DIR_IN) + ? USB_DIR_IN : USB_DIR_OUT; + spin_unlock(&udc->lock); + if (udc->driver->setup(&udc->gadget, + &udc->local_setup_buff) < 0) { + /* cancel status phase */ + udc_reset_ep_queue(udc, 0); + ep0stall(udc); + } + } else { + /* No data phase, IN status from gadget */ + udc->ep0_dir = USB_DIR_IN; + spin_unlock(&udc->lock); + if (udc->driver->setup(&udc->gadget, + &udc->local_setup_buff) < 0) + ep0stall(udc); + } + spin_lock(&udc->lock); +} + +/* Process request for Data or Status phase of ep0 + * prime status phase if needed */ +static void ep0_req_complete(struct fsl_udc *udc, struct fsl_ep *ep0, + struct fsl_req *req) +{ + if (udc->usb_state == USB_STATE_ADDRESS) { + /* Set the new address */ + u32 new_address = (u32) udc->device_address; + fsl_writel(new_address << USB_DEVICE_ADDRESS_BIT_POS, + &dr_regs->deviceaddr); + } + + done(ep0, req, 0); +} + +/* Tripwire mechanism to ensure a setup packet payload is extracted without + * being corrupted by another incoming setup packet */ +static void tripwire_handler(struct fsl_udc *udc, u8 ep_num, u8 *buffer_ptr) +{ + u32 temp; + struct ep_queue_head *qh; + struct fsl_usb2_platform_data *pdata = udc->pdata; + + qh = &udc->ep_qh[ep_num * 2 + EP_DIR_OUT]; + + /* Clear bit in ENDPTSETUPSTAT */ + temp = fsl_readl(&dr_regs->endptsetupstat); + fsl_writel(temp | (1 << ep_num), &dr_regs->endptsetupstat); + + /* while a hazard exists when setup package arrives */ + do { + /* Set Setup Tripwire */ + temp = fsl_readl(&dr_regs->usbcmd); + fsl_writel(temp | USB_CMD_SUTW, &dr_regs->usbcmd); + + /* Copy the setup packet to local buffer */ + if (pdata->le_setup_buf) { + u32 *p = (u32 *)buffer_ptr; + u32 *s = (u32 *)qh->setup_buffer; + + /* Convert little endian setup buffer to CPU endian */ + *p++ = le32_to_cpu(*s++); + *p = le32_to_cpu(*s); + } else { + memcpy(buffer_ptr, (u8 *) qh->setup_buffer, 8); + } + } while (!(fsl_readl(&dr_regs->usbcmd) & USB_CMD_SUTW)); + + /* Clear Setup Tripwire */ + temp = fsl_readl(&dr_regs->usbcmd); + fsl_writel(temp & ~USB_CMD_SUTW, &dr_regs->usbcmd); +} + +static void iram_process_ep_complete(struct fsl_req *curr_req, + int cur_transfer) +{ + char *buf; + u32 len; + int in = ep_is_in(curr_req->ep); + + if (in) + buf = (char *)udc_controller->iram_buffer_v[1]; + else + buf = (char *)udc_controller->iram_buffer_v[0]; + + if (curr_req->cur->next_td_ptr == cpu_to_hc32(DTD_NEXT_TERMINATE) + || (cur_transfer < g_iram_size) + || (curr_req->req.length == curr_req->req.actual)) + curr_req->last_one = 1; + + if (curr_req->last_one) { + /* the last transfer */ + if (!in) { + memcpy(curr_req->req.buf + curr_req->buffer_offset, buf, + cur_transfer); + } + if (curr_req->tail->next_td_ptr != + cpu_to_hc32(DTD_NEXT_TERMINATE)) { + /* have next request,queue it */ + struct fsl_req *next_req; + next_req = + list_entry(curr_req->queue.next, + struct fsl_req, queue); + if (in) + memcpy(buf, next_req->req.buf, + min(g_iram_size, next_req->req.length)); + update_qh(next_req); + } + curr_req->req.dma = curr_req->oridma; + } else { + /* queue next dtd */ + /* because had next dtd, so should finish */ + /* tranferring g_iram_size data */ + curr_req->buffer_offset += g_iram_size; + /* pervious set stop bit,now clear it */ + curr_req->cur->next_td_ptr &= ~cpu_to_hc32(DTD_NEXT_TERMINATE); + curr_req->cur = curr_req->cur->next_td_virt; + if (in) { + len = + min(curr_req->req.length - curr_req->buffer_offset, + g_iram_size); + memcpy(buf, curr_req->req.buf + curr_req->buffer_offset, + len); + } else { + memcpy(curr_req->req.buf + curr_req->buffer_offset - + g_iram_size, buf, g_iram_size); + } + update_qh(curr_req); + } +} + +/* process-ep_req(): free the completed Tds for this req */ +static int process_ep_req(struct fsl_udc *udc, int pipe, + struct fsl_req *curr_req) +{ + struct ep_td_struct *curr_td; + int td_complete, actual, remaining_length, j, tmp; + int status = 0; + int errors = 0; + struct ep_queue_head *curr_qh = &udc->ep_qh[pipe]; + int direction = pipe % 2; + int total = 0, real_len; + + curr_td = curr_req->head; + td_complete = 0; + actual = curr_req->req.length; + real_len = curr_req->req.length; + + for (j = 0; j < curr_req->dtd_count; j++) { + remaining_length = (hc32_to_cpu(curr_td->size_ioc_sts) + & DTD_PACKET_SIZE) + >> DTD_LENGTH_BIT_POS; + if (NEED_IRAM(curr_req->ep)) { + if (real_len >= g_iram_size) { + actual = g_iram_size; + real_len -= g_iram_size; + } else { /* the last packet */ + actual = real_len; + curr_req->last_one = 1; + } + } + actual -= remaining_length; + total += actual; + + errors = hc32_to_cpu(curr_td->size_ioc_sts) & DTD_ERROR_MASK; + if (errors) { + if (errors & DTD_STATUS_HALTED) { + ERR("dTD error %08x QH=%d\n", errors, pipe); + /* Clear the errors and Halt condition */ + tmp = hc32_to_cpu(curr_qh->size_ioc_int_sts); + tmp &= ~errors; + curr_qh->size_ioc_int_sts = cpu_to_hc32(tmp); + status = -EPIPE; + /* FIXME: continue with next queued TD? */ + + break; + } + if (errors & DTD_STATUS_DATA_BUFF_ERR) { + VDBG("Transfer overflow"); + status = -EPROTO; + break; + } else if (errors & DTD_STATUS_TRANSACTION_ERR) { + VDBG("ISO error"); + status = -EILSEQ; + break; + } else + ERR("Unknown error has occured (0x%x)!\r\n", + errors); + + } else if (hc32_to_cpu(curr_td->size_ioc_sts) + & DTD_STATUS_ACTIVE) { + VDBG("Request not complete"); + status = REQ_UNCOMPLETE; + return status; + } else if (remaining_length) { + if (direction) { + VDBG("Transmit dTD remaining length not zero"); + status = -EPROTO; + break; + } else { + td_complete++; + break; + } + } else { + td_complete++; + VDBG("dTD transmitted successful "); + } + if (NEED_IRAM(curr_req->ep)) + if (curr_td-> + next_td_ptr & cpu_to_hc32(DTD_NEXT_TERMINATE)) + break; + if (j != curr_req->dtd_count - 1) + curr_td = (struct ep_td_struct *)curr_td->next_td_virt; + } + + if (status) + return status; + curr_req->req.actual = total; + if (NEED_IRAM(curr_req->ep)) + iram_process_ep_complete(curr_req, actual); + return 0; +} + +/* Process a DTD completion interrupt */ +static void dtd_complete_irq(struct fsl_udc *udc) +{ + u32 bit_pos; + int i, ep_num, direction, bit_mask, status; + struct fsl_ep *curr_ep; + struct fsl_req *curr_req, *temp_req; + + /* Clear the bits in the register */ + bit_pos = fsl_readl(&dr_regs->endptcomplete); + fsl_writel(bit_pos, &dr_regs->endptcomplete); + + if (!bit_pos) + return; + + for (i = 0; i < udc->max_ep * 2; i++) { + ep_num = i >> 1; + direction = i % 2; + + bit_mask = 1 << (ep_num + 16 * direction); + + if (!(bit_pos & bit_mask)) + continue; + + curr_ep = get_ep_by_pipe(udc, i); + + /* If the ep is configured */ + if (curr_ep->name == NULL) { + INFO("Invalid EP?"); + continue; + } + + /* process the req queue until an uncomplete request */ + list_for_each_entry_safe(curr_req, temp_req, &curr_ep->queue, + queue) { + status = process_ep_req(udc, i, curr_req); + + VDBG("status of process_ep_req= %d, ep = %d", + status, ep_num); + if (status == REQ_UNCOMPLETE) + break; + /* write back status to req */ + curr_req->req.status = status; + + if (ep_num == 0) { + ep0_req_complete(udc, curr_ep, curr_req); + break; + } else { + if (NEED_IRAM(curr_ep)) { + if (curr_req->last_one) + done(curr_ep, curr_req, status); + /* only check the 1th req */ + break; + } else + done(curr_ep, curr_req, status); + } + } + dump_ep_queue(curr_ep); + } +} + +/* Process a port change interrupt */ +static void port_change_irq(struct fsl_udc *udc) +{ + u32 speed; + + if (udc->bus_reset) + udc->bus_reset = 0; + + /* Bus resetting is finished */ + if (!(fsl_readl(&dr_regs->portsc1) & PORTSCX_PORT_RESET)) { + /* Get the speed */ + speed = (fsl_readl(&dr_regs->portsc1) + & PORTSCX_PORT_SPEED_MASK); + switch (speed) { + case PORTSCX_PORT_SPEED_HIGH: + udc->gadget.speed = USB_SPEED_HIGH; + break; + case PORTSCX_PORT_SPEED_FULL: + udc->gadget.speed = USB_SPEED_FULL; + break; + case PORTSCX_PORT_SPEED_LOW: + udc->gadget.speed = USB_SPEED_LOW; + break; + default: + udc->gadget.speed = USB_SPEED_UNKNOWN; + break; + } + } + + /* Update USB state */ + if (!udc->resume_state) + udc->usb_state = USB_STATE_DEFAULT; +} + +/* Process suspend interrupt */ +static void suspend_irq(struct fsl_udc *udc) +{ + pr_debug("%s\n", __func__); + + udc->resume_state = udc->usb_state; + udc->usb_state = USB_STATE_SUSPENDED; + + /* report suspend to the driver, serial.c does not support this */ + if (udc->driver->suspend) + udc->driver->suspend(&udc->gadget); +} + +/* Process Wake up interrupt */ +static void wake_up_irq(struct fsl_udc *udc) +{ + pr_debug("%s\n", __func__); + + /* disable wake up irq */ + dr_wake_up_enable(udc_controller, false); + + udc->stopped = 0; +} + +static void bus_resume(struct fsl_udc *udc) +{ + udc->usb_state = udc->resume_state; + udc->resume_state = 0; + + /* report resume to the driver, serial.c does not support this */ + if (udc->driver->resume) + udc->driver->resume(&udc->gadget); +} + +/* Clear up all ep queues */ +static int reset_queues(struct fsl_udc *udc) +{ + u8 pipe; + + for (pipe = 0; pipe < udc->max_pipes; pipe++) + udc_reset_ep_queue(udc, pipe); + + /* report disconnect; the driver is already quiesced */ + udc->driver->disconnect(&udc->gadget); + + return 0; +} + +/* Process reset interrupt */ +static void reset_irq(struct fsl_udc *udc) +{ + u32 temp; + + /* Clear the device address */ + temp = fsl_readl(&dr_regs->deviceaddr); + fsl_writel(temp & ~USB_DEVICE_ADDRESS_MASK, &dr_regs->deviceaddr); + + udc->device_address = 0; + + /* Clear usb state */ + udc->resume_state = 0; + udc->ep0_dir = 0; + udc->remote_wakeup = 0; /* default to 0 on reset */ + udc->gadget.b_hnp_enable = 0; + udc->gadget.a_hnp_support = 0; + udc->gadget.a_alt_hnp_support = 0; + + /* Clear all the setup token semaphores */ + temp = fsl_readl(&dr_regs->endptsetupstat); + fsl_writel(temp, &dr_regs->endptsetupstat); + + /* Clear all the endpoint complete status bits */ + temp = fsl_readl(&dr_regs->endptcomplete); + fsl_writel(temp, &dr_regs->endptcomplete); + + /* Write 1s to the flush register */ + fsl_writel(0xffffffff, &dr_regs->endptflush); + + /* Bus is reseting */ + udc->bus_reset = 1; + /* Reset all the queues, include XD, dTD, EP queue + * head and TR Queue */ + reset_queues(udc); + udc->usb_state = USB_STATE_DEFAULT; +} + +/* if wakup udc, return true; else return false*/ +bool try_wake_up_udc(struct fsl_udc *udc) +{ + u32 irq_src; + + /* when udc is stopped, only handle wake up irq */ + if (udc->stopped) { + if (!device_may_wakeup(&(udc->pdata->pdev->dev))) + return false; + + dr_phy_low_power_mode(udc_controller, false); + + /* check to see if wake up irq */ + irq_src = fsl_readl(&dr_regs->usbctrl); + if (irq_src & USB_CTRL_OTG_WUIR) { + wake_up_irq(udc); + } else { + dr_phy_low_power_mode(udc_controller, true); + } + } + + if (!device_may_wakeup(udc_controller->gadget.dev.parent)) + return true; + + /* check if Vbus change irq */ + irq_src = fsl_readl(&dr_regs->otgsc); + if (irq_src & OTGSC_B_SESSION_VALID_IRQ_STS) { + u32 tmp; + fsl_writel(irq_src, &dr_regs->otgsc); + tmp = fsl_readl(&dr_regs->usbcmd); + /* check BSV bit to see if fall or rise */ + if (irq_src & OTGSC_B_SESSION_VALID) { + udc->stopped = 0; + fsl_writel(tmp | USB_CMD_RUN_STOP, &dr_regs->usbcmd); + printk(KERN_INFO "udc out low power mode\n"); + } else { + printk(KERN_INFO "udc enter low power mode \n"); + fsl_writel(tmp & ~USB_CMD_RUN_STOP, &dr_regs->usbcmd); + /* enable wake up */ + dr_wake_up_enable(udc, true); + udc->stopped = 1; + /* close USB PHY clock */ + dr_phy_low_power_mode(udc, true); + return false; + } + } + + return true; +} + +/* + * USB device controller interrupt handler + */ +static irqreturn_t fsl_udc_irq(int irq, void *_udc) +{ + struct fsl_udc *udc = _udc; + u32 irq_src; + irqreturn_t status = IRQ_NONE; + unsigned long flags; + + if (try_wake_up_udc(udc) == false) + return IRQ_NONE; + + spin_lock_irqsave(&udc->lock, flags); + irq_src = fsl_readl(&dr_regs->usbsts) & fsl_readl(&dr_regs->usbintr); + /* Clear notification bits */ + fsl_writel(irq_src, &dr_regs->usbsts); + + /* VDBG("irq_src [0x%8x]", irq_src); */ + + /* Need to resume? */ + if (udc->usb_state == USB_STATE_SUSPENDED) + if ((fsl_readl(&dr_regs->portsc1) & PORTSCX_PORT_SUSPEND) == 0) + bus_resume(udc); + + /* USB Interrupt */ + if (irq_src & USB_STS_INT) { + VDBG("Packet int"); + /* Setup package, we only support ep0 as control ep */ + if (fsl_readl(&dr_regs->endptsetupstat) & EP_SETUP_STATUS_EP0) { + tripwire_handler(udc, 0, + (u8 *) (&udc->local_setup_buff)); + setup_received_irq(udc, &udc->local_setup_buff); + status = IRQ_HANDLED; + } + + /* completion of dtd */ + if (fsl_readl(&dr_regs->endptcomplete)) { + dtd_complete_irq(udc); + status = IRQ_HANDLED; + } + } + + /* SOF (for ISO transfer) */ + if (irq_src & USB_STS_SOF) { + status = IRQ_HANDLED; + } + + /* Port Change */ + if (irq_src & USB_STS_PORT_CHANGE) { + port_change_irq(udc); + status = IRQ_HANDLED; + } + + /* Reset Received */ + if (irq_src & USB_STS_RESET) { + VDBG("reset int"); + reset_irq(udc); + status = IRQ_HANDLED; + } + + /* Sleep Enable (Suspend) */ + if (irq_src & USB_STS_SUSPEND) { + suspend_irq(udc); + status = IRQ_HANDLED; + } + + if (irq_src & (USB_STS_ERR | USB_STS_SYS_ERR)) { + VDBG("Error IRQ %x ", irq_src); + } + + spin_unlock_irqrestore(&udc->lock, flags); + return status; +} + +/*----------------------------------------------------------------* + * Hook to gadget drivers + * Called by initialization code of gadget drivers +*----------------------------------------------------------------*/ +int usb_gadget_register_driver(struct usb_gadget_driver *driver) +{ + int retval = -ENODEV; + unsigned long flags = 0; + u32 portsc; + + if (!udc_controller) + return -ENODEV; + + if (!driver || (driver->speed != USB_SPEED_FULL + && driver->speed != USB_SPEED_HIGH) + || !driver->bind || !driver->disconnect + || !driver->setup) + return -EINVAL; + + if (udc_controller->driver) + return -EBUSY; + + /* lock is needed but whether should use this lock or another */ + spin_lock_irqsave(&udc_controller->lock, flags); + + driver->driver.bus = 0; + /* hook up the driver */ + udc_controller->driver = driver; + udc_controller->gadget.dev.driver = &driver->driver; + spin_unlock_irqrestore(&udc_controller->lock, flags); + + if (!device_may_wakeup(udc_controller->gadget.dev.parent)) { + if (udc_controller->pdata->usb_clock_for_pm) + udc_controller->pdata->usb_clock_for_pm(true); + + portsc = fsl_readl(&dr_regs->portsc1); + portsc &= ~PORTSCX_PHY_LOW_POWER_SPD; + fsl_writel(portsc, &dr_regs->portsc1); + } + /* bind udc driver to gadget driver */ + retval = driver->bind(&udc_controller->gadget); + if (retval) { + VDBG("bind to %s --> %d", driver->driver.name, retval); + udc_controller->gadget.dev.driver = 0; + udc_controller->driver = 0; + goto out; + } + + if (udc_controller->transceiver) { + /* Suspend the controller until OTG enable it */ + udc_controller->stopped = 1; + printk(KERN_INFO "Suspend udc for OTG auto detect\n"); + dr_wake_up_enable(udc_controller, true); + dr_phy_low_power_mode(udc_controller, true); + + /* export udc suspend/resume call to OTG */ + udc_controller->gadget.dev.driver->suspend = (dev_sus)fsl_udc_suspend; + udc_controller->gadget.dev.driver->resume = (dev_res)fsl_udc_resume; + + /* connect to bus through transceiver */ + if (udc_controller->transceiver) { + retval = otg_set_peripheral(udc_controller->transceiver, + &udc_controller->gadget); + if (retval < 0) { + ERR("can't bind to transceiver\n"); + driver->unbind(&udc_controller->gadget); + udc_controller->gadget.dev.driver = 0; + udc_controller->driver = 0; + return retval; + } + } + } else { + /* Enable DR IRQ reg and Set usbcmd reg Run bit */ + dr_controller_run(udc_controller); + udc_controller->usb_state = USB_STATE_ATTACHED; + udc_controller->ep0_dir = 0; + } + printk(KERN_INFO "%s: bind to driver %s \n", + udc_controller->gadget.name, driver->driver.name); + +out: + if (retval) + printk(KERN_DEBUG "retval %d \n", retval); + return retval; +} +EXPORT_SYMBOL(usb_gadget_register_driver); + +/* Disconnect from gadget driver */ +int usb_gadget_unregister_driver(struct usb_gadget_driver *driver) +{ + struct fsl_ep *loop_ep; + unsigned long flags; + u32 portsc; + + if (!udc_controller) + return -ENODEV; + + if (!driver || driver != udc_controller->driver || !driver->unbind) + return -EINVAL; + + if (udc_controller->transceiver) + (void)otg_set_peripheral(udc_controller->transceiver, 0); + + /* open phy clock for following operation */ + dr_phy_low_power_mode(udc_controller, false); + + /* stop DR, disable intr */ + dr_controller_stop(udc_controller); + + /* in fact, no needed */ + udc_controller->usb_state = USB_STATE_ATTACHED; + udc_controller->ep0_dir = 0; + + /* stand operation */ + spin_lock_irqsave(&udc_controller->lock, flags); + udc_controller->gadget.speed = USB_SPEED_UNKNOWN; + nuke(&udc_controller->eps[0], -ESHUTDOWN); + list_for_each_entry(loop_ep, &udc_controller->gadget.ep_list, + ep.ep_list) + nuke(loop_ep, -ESHUTDOWN); + spin_unlock_irqrestore(&udc_controller->lock, flags); + + /* disconnect gadget before unbinding */ + driver->disconnect(&udc_controller->gadget); + + /* unbind gadget and unhook driver. */ + driver->unbind(&udc_controller->gadget); + udc_controller->gadget.dev.driver = 0; + udc_controller->driver = 0; + + dr_wake_up_enable(udc_controller, false); + + portsc = fsl_readl(&dr_regs->portsc1); + portsc |= PORTSCX_PHY_LOW_POWER_SPD; + fsl_writel(portsc, &dr_regs->portsc1); + + if (udc_controller->pdata->usb_clock_for_pm) + udc_controller->pdata->usb_clock_for_pm(false); + + printk(KERN_INFO "unregistered gadget driver '%s'\r\n", + driver->driver.name); + return 0; +} +EXPORT_SYMBOL(usb_gadget_unregister_driver); + +/*------------------------------------------------------------------------- + PROC File System Support +-------------------------------------------------------------------------*/ +#ifdef CONFIG_USB_GADGET_DEBUG_FILES + +#include + +static const char proc_filename[] = "driver/fsl_usb2_udc"; + +static int fsl_proc_read(char *page, char **start, off_t off, int count, + int *eof, void *_dev) +{ + char *buf = page; + char *next = buf; + unsigned size = count; + unsigned long flags; + int t, i; + u32 tmp_reg; + struct fsl_ep *ep = NULL; + struct fsl_req *req; + struct fsl_usb2_platform_data *pdata; + + struct fsl_udc *udc = udc_controller; + pdata = udc->pdata; + if (off != 0) + return 0; + + spin_lock_irqsave(&udc->lock, flags); + + /* ------basic driver infomation ---- */ + t = scnprintf(next, size, + DRIVER_DESC "\n" + "%s version: %s\n" + "Gadget driver: %s\n\n", + driver_name, DRIVER_VERSION, + udc->driver ? udc->driver->driver.name : "(none)"); + size -= t; + next += t; + + /* ------ DR Registers ----- */ + tmp_reg = fsl_readl(&dr_regs->usbcmd); + t = scnprintf(next, size, + "USBCMD reg:\n" + "SetupTW: %d\n" + "Run/Stop: %s\n\n", + (tmp_reg & USB_CMD_SUTW) ? 1 : 0, + (tmp_reg & USB_CMD_RUN_STOP) ? "Run" : "Stop"); + size -= t; + next += t; + + tmp_reg = fsl_readl(&dr_regs->usbsts); + t = scnprintf(next, size, + "USB Status Reg:\n" + "Dr Suspend: %d" "Reset Received: %d" "System Error: %s" + "USB Error Interrupt: %s\n\n", + (tmp_reg & USB_STS_SUSPEND) ? 1 : 0, + (tmp_reg & USB_STS_RESET) ? 1 : 0, + (tmp_reg & USB_STS_SYS_ERR) ? "Err" : "Normal", + (tmp_reg & USB_STS_ERR) ? "Err detected" : "No err"); + size -= t; + next += t; + + tmp_reg = fsl_readl(&dr_regs->usbintr); + t = scnprintf(next, size, + "USB Intrrupt Enable Reg:\n" + "Sleep Enable: %d" "SOF Received Enable: %d" + "Reset Enable: %d\n" + "System Error Enable: %d" + "Port Change Dectected Enable: %d\n" + "USB Error Intr Enable: %d" "USB Intr Enable: %d\n\n", + (tmp_reg & USB_INTR_DEVICE_SUSPEND) ? 1 : 0, + (tmp_reg & USB_INTR_SOF_EN) ? 1 : 0, + (tmp_reg & USB_INTR_RESET_EN) ? 1 : 0, + (tmp_reg & USB_INTR_SYS_ERR_EN) ? 1 : 0, + (tmp_reg & USB_INTR_PTC_DETECT_EN) ? 1 : 0, + (tmp_reg & USB_INTR_ERR_INT_EN) ? 1 : 0, + (tmp_reg & USB_INTR_INT_EN) ? 1 : 0); + size -= t; + next += t; + + tmp_reg = fsl_readl(&dr_regs->frindex); + t = scnprintf(next, size, + "USB Frame Index Reg:" "Frame Number is 0x%x\n\n", + (tmp_reg & USB_FRINDEX_MASKS)); + size -= t; + next += t; + + tmp_reg = fsl_readl(&dr_regs->deviceaddr); + t = scnprintf(next, size, + "USB Device Address Reg:" "Device Addr is 0x%x\n\n", + (tmp_reg & USB_DEVICE_ADDRESS_MASK)); + size -= t; + next += t; + + tmp_reg = fsl_readl(&dr_regs->endpointlistaddr); + t = scnprintf(next, size, + "USB Endpoint List Address Reg:" + "Device Addr is 0x%x\n\n", + (tmp_reg & USB_EP_LIST_ADDRESS_MASK)); + size -= t; + next += t; + + tmp_reg = fsl_readl(&dr_regs->portsc1); + t = scnprintf(next, size, + "USB Port Status&Control Reg:\n" + "Port Transceiver Type : %s" "Port Speed: %s \n" + "PHY Low Power Suspend: %s" "Port Reset: %s" + "Port Suspend Mode: %s \n" "Over-current Change: %s" + "Port Enable/Disable Change: %s\n" + "Port Enabled/Disabled: %s" + "Current Connect Status: %s\n\n", ({ + char *s; + switch (tmp_reg & PORTSCX_PTS_FSLS) { + case PORTSCX_PTS_UTMI: + s = "UTMI"; break; + case PORTSCX_PTS_ULPI: + s = "ULPI "; break; + case PORTSCX_PTS_FSLS: + s = "FS/LS Serial"; break; + default: + s = "None"; break; + } + s; }), ({ + char *s; + switch (tmp_reg & PORTSCX_PORT_SPEED_UNDEF) { + case PORTSCX_PORT_SPEED_FULL: + s = "Full Speed"; break; + case PORTSCX_PORT_SPEED_LOW: + s = "Low Speed"; break; + case PORTSCX_PORT_SPEED_HIGH: + s = "High Speed"; break; + default: + s = "Undefined"; break; + } + s; + }), + (tmp_reg & PORTSCX_PHY_LOW_POWER_SPD) ? + "Normal PHY mode" : "Low power mode", + (tmp_reg & PORTSCX_PORT_RESET) ? "In Reset" : + "Not in Reset", + (tmp_reg & PORTSCX_PORT_SUSPEND) ? "In " : "Not in", + (tmp_reg & PORTSCX_OVER_CURRENT_CHG) ? "Dected" : + "No", + (tmp_reg & PORTSCX_PORT_EN_DIS_CHANGE) ? "Disable" : + "Not change", + (tmp_reg & PORTSCX_PORT_ENABLE) ? "Enable" : + "Not correct", + (tmp_reg & PORTSCX_CURRENT_CONNECT_STATUS) ? + "Attached" : "Not-Att"); + size -= t; + next += t; + + tmp_reg = fsl_readl(&dr_regs->usbmode); + t = scnprintf(next, size, + "USB Mode Reg:" "Controller Mode is : %s\n\n", ({ + char *s; + switch (tmp_reg & USB_MODE_CTRL_MODE_HOST) { + case USB_MODE_CTRL_MODE_IDLE: + s = "Idle"; break; + case USB_MODE_CTRL_MODE_DEVICE: + s = "Device Controller"; break; + case USB_MODE_CTRL_MODE_HOST: + s = "Host Controller"; break; + default: + s = "None"; break; + } + s; + })); + size -= t; + next += t; + + tmp_reg = fsl_readl(&dr_regs->endptsetupstat); + t = scnprintf(next, size, + "Endpoint Setup Status Reg:" "SETUP on ep 0x%x\n\n", + (tmp_reg & EP_SETUP_STATUS_MASK)); + size -= t; + next += t; + + for (i = 0; i < udc->max_ep / 2; i++) { + tmp_reg = fsl_readl(&dr_regs->endptctrl[i]); + t = scnprintf(next, size, "EP Ctrl Reg [0x%x]: = [0x%x]\n", + i, tmp_reg); + size -= t; + next += t; + } + tmp_reg = fsl_readl(&dr_regs->endpointprime); + t = scnprintf(next, size, "EP Prime Reg = [0x%x]\n", tmp_reg); + size -= t; + next += t; + + if (pdata->have_sysif_regs) { + tmp_reg = usb_sys_regs->snoop1; + t = scnprintf(next, size, "\nSnoop1 Reg = [0x%x]\n\n", tmp_reg); + size -= t; + next += t; + + tmp_reg = usb_sys_regs->control; + t = scnprintf(next, size, "General Control Reg = [0x%x]\n\n", + tmp_reg); + size -= t; + next += t; + } + + /* ------fsl_udc, fsl_ep, fsl_request structure information ----- */ + ep = &udc->eps[0]; + t = scnprintf(next, size, "For %s Maxpkt is 0x%x index is 0x%x\n", + ep->ep.name, ep_maxpacket(ep), ep_index(ep)); + size -= t; + next += t; + + if (list_empty(&ep->queue)) { + t = scnprintf(next, size, "its req queue is empty\n\n"); + size -= t; + next += t; + } else { + list_for_each_entry(req, &ep->queue, queue) { + t = scnprintf(next, size, + "req %p actual 0x%x length 0x%x buf %p\n", + &req->req, req->req.actual, + req->req.length, req->req.buf); + size -= t; + next += t; + } + } + /* other gadget->eplist ep */ + list_for_each_entry(ep, &udc->gadget.ep_list, ep.ep_list) { + if (ep->desc) { + t = scnprintf(next, size, + "\nFor %s Maxpkt is 0x%x " + "index is 0x%x\n", + ep->ep.name, ep_maxpacket(ep), + ep_index(ep)); + size -= t; + next += t; + + if (list_empty(&ep->queue)) { + t = scnprintf(next, size, + "its req queue is empty\n\n"); + size -= t; + next += t; + } else { + list_for_each_entry(req, &ep->queue, queue) { + t = scnprintf(next, size, + "req %p actual 0x%x length" + "0x%x buf %p\n", + &req->req, req->req.actual, + req->req.length, req->req.buf); + size -= t; + next += t; + } /* end for each_entry of ep req */ + } /* end for else */ + } /* end for if(ep->queue) */ + } /* end (ep->desc) */ + + spin_unlock_irqrestore(&udc->lock, flags); + + *eof = 1; + return count - size; +} + +#define create_proc_file() create_proc_read_entry(proc_filename, \ + 0, NULL, fsl_proc_read, NULL) + +#define remove_proc_file() remove_proc_entry(proc_filename, NULL) + +#else /* !CONFIG_USB_GADGET_DEBUG_FILES */ + +#define create_proc_file() do {} while (0) +#define remove_proc_file() do {} while (0) + +#endif /* CONFIG_USB_GADGET_DEBUG_FILES */ + +/*-------------------------------------------------------------------------*/ + +/* Release udc structures */ +static void fsl_udc_release(struct device *dev) +{ + complete(udc_controller->done); + dma_free_coherent(dev, udc_controller->ep_qh_size, + udc_controller->ep_qh, udc_controller->ep_qh_dma); + kfree(udc_controller); +} + +/****************************************************************** + Internal structure setup functions +*******************************************************************/ +/*------------------------------------------------------------------ + * init resource for globle controller + * Return the udc handle on success or NULL on failure + ------------------------------------------------------------------*/ +static int __init struct_udc_setup(struct fsl_udc *udc, + struct platform_device *pdev) +{ + struct fsl_usb2_platform_data *pdata; + size_t size; + + pdata = pdev->dev.platform_data; + udc->phy_mode = pdata->phy_mode; + + udc->eps = kzalloc(sizeof(struct fsl_ep) * udc->max_ep, GFP_KERNEL); + if (!udc->eps) { + ERR("malloc fsl_ep failed\n"); + return -1; + } + + /* initialized QHs, take care of alignment */ + size = udc->max_ep * sizeof(struct ep_queue_head); + if (size < QH_ALIGNMENT) + size = QH_ALIGNMENT; + else if ((size % QH_ALIGNMENT) != 0) { + size += QH_ALIGNMENT + 1; + size &= ~(QH_ALIGNMENT - 1); + } + udc->ep_qh = dma_alloc_coherent(&pdev->dev, size, + &udc->ep_qh_dma, GFP_KERNEL); + if (!udc->ep_qh) { + ERR("malloc QHs for udc failed\n"); + kfree(udc->eps); + return -1; + } + + udc->ep_qh_size = size; + + /* Initialize ep0 status request structure */ + /* FIXME: fsl_alloc_request() ignores ep argument */ + udc->status_req = container_of(fsl_alloc_request(NULL, GFP_KERNEL), + struct fsl_req, req); + /* allocate a small amount of memory to get valid address */ + udc->status_req->req.buf = kmalloc(8, GFP_KERNEL); + udc->status_req->req.dma = virt_to_phys(udc->status_req->req.buf); + /* Initialize ep0 data request structure */ + udc->data_req = container_of(fsl_alloc_request(NULL, GFP_KERNEL), + struct fsl_req, req); + udc->data_req->req.buf = kmalloc(8, GFP_KERNEL); + udc->data_req->req.dma = virt_to_phys(udc->data_req->req.buf); + + udc->resume_state = USB_STATE_NOTATTACHED; + udc->usb_state = USB_STATE_POWERED; + udc->ep0_dir = 0; + udc->remote_wakeup = 0; /* default to 0 on reset */ + spin_lock_init(&udc->lock); + + return 0; +} + +/*---------------------------------------------------------------- + * Setup the fsl_ep struct for eps + * Link fsl_ep->ep to gadget->ep_list + * ep0out is not used so do nothing here + * ep0in should be taken care + *--------------------------------------------------------------*/ +static int __init struct_ep_setup(struct fsl_udc *udc, unsigned char index, + char *name, int link) +{ + struct fsl_ep *ep = &udc->eps[index]; + + ep->udc = udc; + strcpy(ep->name, name); + ep->ep.name = ep->name; + + ep->ep.ops = &fsl_ep_ops; + ep->stopped = 0; + + /* for ep0: maxP defined in desc + * for other eps, maxP is set by epautoconfig() called by gadget layer + */ + ep->ep.maxpacket = (unsigned short) ~0; + + /* the queue lists any req for this ep */ + INIT_LIST_HEAD(&ep->queue); + + /* gagdet.ep_list used for ep_autoconfig so no ep0 */ + if (link) + list_add_tail(&ep->ep.ep_list, &udc->gadget.ep_list); + ep->gadget = &udc->gadget; + ep->qh = &udc->ep_qh[index]; + + return 0; +} + +/* Driver probe function + * all intialization operations implemented here except enabling usb_intr reg + * board setup should have been done in the platform code + */ +static int __init fsl_udc_probe(struct platform_device *pdev) +{ + struct resource *res; + struct fsl_usb2_platform_data *pdata = pdev->dev.platform_data; + int ret = -ENODEV; + unsigned int i; + u32 dccparams; + + udc_controller = kzalloc(sizeof(struct fsl_udc), GFP_KERNEL); + if (udc_controller == NULL) { + ERR("malloc udc failed\n"); + return -ENOMEM; + } + udc_controller->pdata = pdata; + +#ifdef CONFIG_USB_OTG + /* Memory and interrupt resources will be passed from OTG */ + udc_controller->transceiver = otg_get_transceiver(); + if (!udc_controller->transceiver) { + printk(KERN_ERR "Can't find OTG driver!\n"); + ret = -ENODEV; + goto err1a; + } +#endif + + if ((pdev->dev.parent) && + (to_platform_device(pdev->dev.parent)->resource)) { + pdev->resource = + to_platform_device(pdev->dev.parent)->resource; + pdev->num_resources = + to_platform_device(pdev->dev.parent)->num_resources; + } + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!res) { + ret = -ENXIO; + goto err1a; + } + +#ifndef CONFIG_USB_OTG + if (!request_mem_region(res->start, resource_size(res), + driver_name)) { + ERR("request mem region for %s failed \n", pdev->name); + ret = -EBUSY; + goto err1a; + } +#endif + + dr_regs = ioremap(res->start, resource_size(res)); + if (!dr_regs) { + ret = -ENOMEM; + goto err1; + } + pdata->regs = (void *)dr_regs; + /* + * do platform specific init: check the clock, grab/config pins, etc. + */ + if (pdata->platform_init && pdata->platform_init(pdev)) { + ret = -ENODEV; + goto err2a; + } + + /* Due to mx35/mx25's phy's bug */ + reset_phy(); + + if (pdata->have_sysif_regs) + usb_sys_regs = (struct usb_sys_interface *) + ((u32)dr_regs + USB_DR_SYS_OFFSET); + + /* Read Device Controller Capability Parameters register */ + dccparams = fsl_readl(&dr_regs->dccparams); + if (!(dccparams & DCCPARAMS_DC)) { + ERR("This SOC doesn't support device role\n"); + ret = -ENODEV; + goto err2; + } + /* Get max device endpoints */ + /* DEN is bidirectional ep number, max_ep doubles the number */ + udc_controller->max_ep = (dccparams & DCCPARAMS_DEN_MASK) * 2; + + udc_controller->irq = platform_get_irq(pdev, 0); + if (!udc_controller->irq) { + ret = -ENODEV; + goto err2; + } + + ret = request_irq(udc_controller->irq, fsl_udc_irq, IRQF_SHARED, + driver_name, udc_controller); + if (ret != 0) { + ERR("cannot request irq %d err %d \n", + udc_controller->irq, ret); + goto err2; + } + + /* Initialize the udc structure including QH member and other member */ + if (struct_udc_setup(udc_controller, pdev)) { + ERR("Can't initialize udc data structure\n"); + ret = -ENOMEM; + goto err3; + } + + if (!udc_controller->transceiver) { + /* initialize usb hw reg except for regs for EP, + * leave usbintr reg untouched */ + dr_controller_setup(udc_controller); + } + + /* Setup gadget structure */ + udc_controller->gadget.ops = &fsl_gadget_ops; + udc_controller->gadget.is_dualspeed = 1; + udc_controller->gadget.ep0 = &udc_controller->eps[0].ep; + INIT_LIST_HEAD(&udc_controller->gadget.ep_list); + udc_controller->gadget.speed = USB_SPEED_UNKNOWN; + udc_controller->gadget.name = driver_name; + + /* Setup gadget.dev and register with kernel */ + dev_set_name(&udc_controller->gadget.dev, "gadget"); + udc_controller->gadget.dev.release = fsl_udc_release; + udc_controller->gadget.dev.parent = &pdev->dev; + ret = device_register(&udc_controller->gadget.dev); + if (ret < 0) + goto err3; + + if (udc_controller->transceiver) { + udc_controller->gadget.is_otg = 1; + /* now didn't support lpm in OTG mode*/ + device_set_wakeup_capable(&pdev->dev, 0); + } + + /* setup QH and epctrl for ep0 */ + ep0_setup(udc_controller); + + /* setup udc->eps[] for ep0 */ + struct_ep_setup(udc_controller, 0, "ep0", 0); + /* for ep0: the desc defined here; + * for other eps, gadget layer called ep_enable with defined desc + */ + udc_controller->eps[0].desc = &fsl_ep0_desc; + udc_controller->eps[0].ep.maxpacket = USB_MAX_CTRL_PAYLOAD; + + /* setup the udc->eps[] for non-control endpoints and link + * to gadget.ep_list */ + for (i = 1; i < (int)(udc_controller->max_ep / 2); i++) { + char name[14]; + + sprintf(name, "ep%dout", i); + struct_ep_setup(udc_controller, i * 2, name, 1); + sprintf(name, "ep%din", i); + struct_ep_setup(udc_controller, i * 2 + 1, name, 1); + } + + /* use dma_pool for TD management */ + udc_controller->td_pool = dma_pool_create("udc_td", &pdev->dev, + sizeof(struct ep_td_struct), + DTD_ALIGNMENT, UDC_DMA_BOUNDARY); + if (udc_controller->td_pool == NULL) { + ret = -ENOMEM; + goto err4; + } + if (g_iram_size) { + g_iram_addr = iram_alloc(USB_IRAM_SIZE, &g_iram_base); + for (i = 0; i < IRAM_PPH_NTD; i++) { + udc_controller->iram_buffer[i] = + g_iram_base + i * g_iram_size; + udc_controller->iram_buffer_v[i] = + g_iram_addr + i * g_iram_size; + } + } +#ifdef POSTPONE_FREE_LAST_DTD + last_free_td = NULL; +#endif +#ifndef CONFIG_USB_OTG + /* disable all INTR */ + fsl_writel(0, &dr_regs->usbintr); + + dr_wake_up_enable(udc_controller, false); + udc_controller->stopped = 1; + +#if !(defined CONFIG_ARCH_MX35 || defined CONFIG_ARCH_MX25) +{ + u32 portsc; + portsc = fsl_readl(&dr_regs->portsc1); + portsc |= PORTSCX_PHY_LOW_POWER_SPD; + fsl_writel(portsc, &dr_regs->portsc1); +} +#endif + if (udc_controller->pdata->usb_clock_for_pm) + udc_controller->pdata->usb_clock_for_pm(false); +#endif + create_proc_file(); + return 0; + +err4: + device_unregister(&udc_controller->gadget.dev); +err3: + free_irq(udc_controller->irq, udc_controller); +err2: + if (pdata->platform_uninit) + pdata->platform_uninit(pdata); +err2a: + iounmap((u8 __iomem *)dr_regs); +err1: + if (!udc_controller->transceiver) + release_mem_region(res->start, resource_size(res)); +err1a: + kfree(udc_controller); + udc_controller = NULL; + return ret; +} + +/* Driver removal function + * Free resources and finish pending transactions + */ +static int __exit fsl_udc_remove(struct platform_device *pdev) +{ + struct resource *res; + struct fsl_usb2_platform_data *pdata = pdev->dev.platform_data; + + DECLARE_COMPLETION(done); + + if (!udc_controller) + return -ENODEV; + udc_controller->done = &done; + /* open USB PHY clock */ + dr_phy_low_power_mode(udc_controller, false); + + /* DR has been stopped in usb_gadget_unregister_driver() */ + remove_proc_file(); + + /* Free allocated memory */ + if (g_iram_size) + iram_free(g_iram_base, IRAM_PPH_NTD * g_iram_size); + kfree(udc_controller->status_req->req.buf); + kfree(udc_controller->status_req); + kfree(udc_controller->data_req->req.buf); + kfree(udc_controller->data_req); + kfree(udc_controller->eps); +#ifdef POSTPONE_FREE_LAST_DTD + if (last_free_td != NULL) + dma_pool_free(udc_controller->td_pool, last_free_td, + last_free_td->td_dma); +#endif + dma_pool_destroy(udc_controller->td_pool); + free_irq(udc_controller->irq, udc_controller); + iounmap((u8 __iomem *)dr_regs); + +#ifndef CONFIG_USB_OTG + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + release_mem_region(res->start, resource_size(res)); +#endif + + device_unregister(&udc_controller->gadget.dev); + /* free udc --wait for the release() finished */ + wait_for_completion(&done); + + /* + * do platform specific un-initialization: + * release iomux pins, etc. + */ + if (pdata->platform_uninit) + pdata->platform_uninit(pdata); + + return 0; +} + +static int udc_suspend(struct fsl_udc *udc) +{ + u32 mode, usbcmd; + + /* open clock for register access */ + if (udc_controller->pdata->usb_clock_for_pm) + udc_controller->pdata->usb_clock_for_pm(true); + + mode = fsl_readl(&dr_regs->usbmode) & USB_MODE_CTRL_MODE_MASK; + usbcmd = fsl_readl(&dr_regs->usbcmd); + + pr_debug("%s(): mode 0x%x stopped %d\n", __func__, mode, udc->stopped); + + /* + * If the controller is already stopped, then this must be a + * PM suspend. Remember this fact, so that we will leave the + * controller stopped at PM resume time. + */ + if (udc->stopped) { + pr_debug("gadget already stopped, leaving early\n"); + udc->already_stopped = 1; + goto out; + } + + if (mode != USB_MODE_CTRL_MODE_DEVICE) { + pr_debug("gadget not in device mode, leaving early\n"); + goto out; + } + + udc->stopped = 1; + /* if the suspend is not for switch to host in otg mode */ + if ((!(udc->gadget.is_otg)) || + (fsl_readl(&dr_regs->otgsc) & OTGSC_STS_USB_ID)) { + dr_wake_up_enable(udc, true); + dr_phy_low_power_mode(udc, true); + } + + /* stop the controller */ + usbcmd = fsl_readl(&dr_regs->usbcmd) & ~USB_CMD_RUN_STOP; + fsl_writel(usbcmd, &dr_regs->usbcmd); + + printk(KERN_INFO "USB Gadget suspended\n"); +out: + if (udc_controller->pdata->usb_clock_for_pm) + udc_controller->pdata->usb_clock_for_pm(false); + return 0; +} + +/*----------------------------------------------------------------- + * Modify Power management attributes + * Used by OTG statemachine to disable gadget temporarily + -----------------------------------------------------------------*/ +static int fsl_udc_suspend(struct platform_device *pdev, pm_message_t state) +{ + if (((!(udc_controller->gadget.is_otg)) || + (fsl_readl(&dr_regs->otgsc) & OTGSC_STS_USB_ID)) && + (udc_controller->usb_state > USB_STATE_POWERED) && + (udc_controller->usb_state < USB_STATE_SUSPENDED)) + return -EBUSY; + + return udc_suspend(udc_controller); +} + +/*----------------------------------------------------------------- + * Invoked on USB resume. May be called in_interrupt. + * Here we start the DR controller and enable the irq + *-----------------------------------------------------------------*/ +static int fsl_udc_resume(struct platform_device *pdev) +{ + pr_debug("%s(): stopped %d already_stopped %d\n", __func__, + udc_controller->stopped, udc_controller->already_stopped); + + /* + * If the controller was stopped at suspend time, then + * don't resume it now. + */ + if (udc_controller->already_stopped) { + udc_controller->already_stopped = 0; + pr_debug("gadget was already stopped, leaving early\n"); + return 0; + } + + /* Enable DR irq reg and set controller Run */ + if (udc_controller->stopped) { + dr_wake_up_enable(udc_controller, false); + dr_phy_low_power_mode(udc_controller, false); + mdelay(1); + + dr_controller_setup(udc_controller); + dr_controller_run(udc_controller); + } + udc_controller->usb_state = USB_STATE_ATTACHED; + udc_controller->ep0_dir = 0; + + printk(KERN_INFO "USB Gadget resumed\n"); + return 0; +} + +/*------------------------------------------------------------------------- + Register entry point for the peripheral controller driver +--------------------------------------------------------------------------*/ + +static struct platform_driver udc_driver = { + .remove = __exit_p(fsl_udc_remove), + /* these suspend and resume are not usb suspend and resume */ + .suspend = fsl_udc_suspend, + .resume = fsl_udc_resume, + .probe = fsl_udc_probe, + .driver = { + .name = driver_name, + .owner = THIS_MODULE, + }, +}; + +static int __init udc_init(void) +{ + printk(KERN_INFO "%s (%s)\n", driver_desc, DRIVER_VERSION); + return platform_driver_register(&udc_driver); +} +#ifdef CONFIG_MXS_VBUS_CURRENT_DRAW + fs_initcall(udc_init); +#else + module_init(udc_init); +#endif +static void __exit udc_exit(void) +{ + platform_driver_unregister(&udc_driver); + printk(KERN_INFO "%s unregistered \n", driver_desc); +} + +module_exit(udc_exit); + +MODULE_DESCRIPTION(DRIVER_DESC); +MODULE_AUTHOR(DRIVER_AUTHOR); +MODULE_LICENSE("GPL"); diff --git a/drivers/usb/gadget/arcotg_udc.h b/drivers/usb/gadget/arcotg_udc.h new file mode 100644 index 000000000000..466a4447d3dd --- /dev/null +++ b/drivers/usb/gadget/arcotg_udc.h @@ -0,0 +1,703 @@ +/* + * Copyright (C) 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +/*! + * @file arcotg_udc.h + * @brief Freescale USB device/endpoint management registers + * @ingroup USB + */ + +#ifndef __ARCOTG_UDC_H +#define __ARCOTG_UDC_H + +#define TRUE 1 +#define FALSE 0 + +#define MSC_BULK_CB_WRAP_LEN 31 +#define USE_MSC_WR(len) false + +/* Iram patch */ +#ifdef CONFIG_USB_STATIC_IRAM_PPH +/* size of 1 qTD's buffer,one is for BULK IN and other is BULK OUT */ +#define USB_IRAM_SIZE SZ_8K +#define IRAM_TD_PPH_SIZE (USB_IRAM_SIZE / 2) +#define IRAM_PPH_NTD 2 /* number of TDs in IRAM */ +#else +#define USB_IRAM_SIZE 0 +#define IRAM_TD_PPH_SIZE 0 +#define IRAM_PPH_NTD 0 +#endif + +#define NEED_IRAM(ep) ((g_iram_size) && \ + ((ep)->desc->bmAttributes == USB_ENDPOINT_XFER_BULK)) + +#ifdef CONFIG_ARCH_MX5 +#define POSTPONE_FREE_LAST_DTD +#else +#undef POSTPONE_FREE_LAST_DTD +#endif + +/* ### define USB registers here + */ +#define USB_MAX_ENDPOINTS 8 +#define USB_MAX_PIPES (USB_MAX_ENDPOINTS*2) +#define USB_MAX_CTRL_PAYLOAD 64 +#define USB_DR_SYS_OFFSET 0x400 + +#define USB_DR_OFFSET 0x3100 + +struct usb_dr_device { + /* Capability register */ + u32 id; + u32 res1[35]; + u32 sbuscfg; /* sbuscfg ahb burst */ + u32 res11[27]; + u16 caplength; /* Capability Register Length */ + u16 hciversion; /* Host Controller Interface Version */ + u32 hcsparams; /* Host Controller Structual Parameters */ + u32 hccparams; /* Host Controller Capability Parameters */ + u32 res2[5]; + u32 dciversion; /* Device Controller Interface Version */ + u32 dccparams; /* Device Controller Capability Parameters */ + u32 res3[6]; + /* Operation register */ + u32 usbcmd; /* USB Command Register */ + u32 usbsts; /* USB Status Register */ + u32 usbintr; /* USB Interrupt Enable Register */ + u32 frindex; /* Frame Index Register */ + u32 res4; + u32 deviceaddr; /* Device Address */ + u32 endpointlistaddr; /* Endpoint List Address Register */ + u32 res5; + u32 burstsize; /* Master Interface Data Burst Size Register */ + u32 txttfilltuning; /* Transmit FIFO Tuning Controls Register */ + u32 res6[6]; + u32 configflag; /* Configure Flag Register */ + u32 portsc1; /* Port 1 Status and Control Register */ + u32 res7[7]; + u32 otgsc; /* On-The-Go Status and Control */ + u32 usbmode; /* USB Mode Register */ + u32 endptsetupstat; /* Endpoint Setup Status Register */ + u32 endpointprime; /* Endpoint Initialization Register */ + u32 endptflush; /* Endpoint Flush Register */ + u32 endptstatus; /* Endpoint Status Register */ + u32 endptcomplete; /* Endpoint Complete Register */ + u32 endptctrl[8 * 2]; /* Endpoint Control Registers */ + u32 res8[256]; +#ifdef CONFIG_ARCH_MX5 + u32 res9[128]; /* i.MX51 start from 0x800 */ +#endif + u32 usbctrl; + u32 otgmirror; + u32 phyctrl0; + u32 phyctrl1; + u32 ctrl1; + u32 uh2ctrl; +}; + + /* non-EHCI USB system interface registers (Big Endian) */ +struct usb_sys_interface { + u32 snoop1; + u32 snoop2; + u32 age_cnt_thresh; /* Age Count Threshold Register */ + u32 pri_ctrl; /* Priority Control Register */ + u32 si_ctrl; /* System Interface Control Register */ + u8 res[236]; + u32 control; /* General Purpose Control Register */ +}; + +/* ep0 transfer state */ +#define WAIT_FOR_SETUP 0 +#define DATA_STATE_XMIT 1 +#define DATA_STATE_NEED_ZLP 2 +#define WAIT_FOR_OUT_STATUS 3 +#define DATA_STATE_RECV 4 + +/* Device Controller Capability Parameter register */ +#define DCCPARAMS_DC 0x00000080 +#define DCCPARAMS_DEN_MASK 0x0000001f + +/* Frame Index Register Bit Masks */ +#define USB_FRINDEX_MASKS (0x3fff) +/* USB CMD Register Bit Masks */ +#define USB_CMD_RUN_STOP (0x00000001) +#define USB_CMD_CTRL_RESET (0x00000002) +#define USB_CMD_PERIODIC_SCHEDULE_EN (0x00000010) +#define USB_CMD_ASYNC_SCHEDULE_EN (0x00000020) +#define USB_CMD_INT_AA_DOORBELL (0x00000040) +#define USB_CMD_ASP (0x00000300) +#define USB_CMD_ASYNC_SCH_PARK_EN (0x00000800) +#define USB_CMD_SUTW (0x00002000) +#define USB_CMD_ATDTW (0x00004000) +#define USB_CMD_ITC (0x00FF0000) + +/* bit 15,3,2 are frame list size */ +#define USB_CMD_FRAME_SIZE_1024 (0x00000000) +#define USB_CMD_FRAME_SIZE_512 (0x00000004) +#define USB_CMD_FRAME_SIZE_256 (0x00000008) +#define USB_CMD_FRAME_SIZE_128 (0x0000000C) +#define USB_CMD_FRAME_SIZE_64 (0x00008000) +#define USB_CMD_FRAME_SIZE_32 (0x00008004) +#define USB_CMD_FRAME_SIZE_16 (0x00008008) +#define USB_CMD_FRAME_SIZE_8 (0x0000800C) + +/* bit 9-8 are async schedule park mode count */ +#define USB_CMD_ASP_00 (0x00000000) +#define USB_CMD_ASP_01 (0x00000100) +#define USB_CMD_ASP_10 (0x00000200) +#define USB_CMD_ASP_11 (0x00000300) +#define USB_CMD_ASP_BIT_POS (8) + +/* bit 23-16 are interrupt threshold control */ +#define USB_CMD_ITC_NO_THRESHOLD (0x00000000) +#define USB_CMD_ITC_1_MICRO_FRM (0x00010000) +#define USB_CMD_ITC_2_MICRO_FRM (0x00020000) +#define USB_CMD_ITC_4_MICRO_FRM (0x00040000) +#define USB_CMD_ITC_8_MICRO_FRM (0x00080000) +#define USB_CMD_ITC_16_MICRO_FRM (0x00100000) +#define USB_CMD_ITC_32_MICRO_FRM (0x00200000) +#define USB_CMD_ITC_64_MICRO_FRM (0x00400000) +#define USB_CMD_ITC_BIT_POS (16) + +/* USB STS Register Bit Masks */ +#define USB_STS_INT (0x00000001) +#define USB_STS_ERR (0x00000002) +#define USB_STS_PORT_CHANGE (0x00000004) +#define USB_STS_FRM_LST_ROLL (0x00000008) +#define USB_STS_SYS_ERR (0x00000010) +#define USB_STS_IAA (0x00000020) +#define USB_STS_RESET (0x00000040) +#define USB_STS_SOF (0x00000080) +#define USB_STS_SUSPEND (0x00000100) +#define USB_STS_HC_HALTED (0x00001000) +#define USB_STS_RCL (0x00002000) +#define USB_STS_PERIODIC_SCHEDULE (0x00004000) +#define USB_STS_ASYNC_SCHEDULE (0x00008000) + +/* USB INTR Register Bit Masks */ +#define USB_INTR_INT_EN (0x00000001) +#define USB_INTR_ERR_INT_EN (0x00000002) +#define USB_INTR_PTC_DETECT_EN (0x00000004) +#define USB_INTR_FRM_LST_ROLL_EN (0x00000008) +#define USB_INTR_SYS_ERR_EN (0x00000010) +#define USB_INTR_ASYN_ADV_EN (0x00000020) +#define USB_INTR_RESET_EN (0x00000040) +#define USB_INTR_SOF_EN (0x00000080) +#define USB_INTR_DEVICE_SUSPEND (0x00000100) + +/* Device Address bit masks */ +#define USB_DEVICE_ADDRESS_MASK (0xFE000000) +#define USB_DEVICE_ADDRESS_BIT_POS (25) + +/* endpoint list address bit masks */ +#define USB_EP_LIST_ADDRESS_MASK (0xfffff800) + +/* PORTSCX Register Bit Masks */ +#define PORTSCX_CURRENT_CONNECT_STATUS (0x00000001) +#define PORTSCX_CONNECT_STATUS_CHANGE (0x00000002) +#define PORTSCX_PORT_ENABLE (0x00000004) +#define PORTSCX_PORT_EN_DIS_CHANGE (0x00000008) +#define PORTSCX_OVER_CURRENT_ACT (0x00000010) +#define PORTSCX_OVER_CURRENT_CHG (0x00000020) +#define PORTSCX_PORT_FORCE_RESUME (0x00000040) +#define PORTSCX_PORT_SUSPEND (0x00000080) +#define PORTSCX_PORT_RESET (0x00000100) +#define PORTSCX_LINE_STATUS_BITS (0x00000C00) +#define PORTSCX_PORT_POWER (0x00001000) +#define PORTSCX_PORT_INDICTOR_CTRL (0x0000C000) +#define PORTSCX_PORT_TEST_CTRL (0x000F0000) +#define PORTSCX_WAKE_ON_CONNECT_EN (0x00100000) +#define PORTSCX_WAKE_ON_CONNECT_DIS (0x00200000) +#define PORTSCX_WAKE_ON_OVER_CURRENT (0x00400000) +#define PORTSCX_PHY_LOW_POWER_SPD (0x00800000) +#define PORTSCX_PORT_FORCE_FULL_SPEED (0x01000000) +#define PORTSCX_PORT_SPEED_MASK (0x0C000000) +#define PORTSCX_PORT_WIDTH (0x10000000) +#define PORTSCX_PHY_TYPE_SEL (0xC0000000) + +/* bit 11-10 are line status */ +#define PORTSCX_LINE_STATUS_SE0 (0x00000000) +#define PORTSCX_LINE_STATUS_JSTATE (0x00000400) +#define PORTSCX_LINE_STATUS_KSTATE (0x00000800) +#define PORTSCX_LINE_STATUS_UNDEF (0x00000C00) +#define PORTSCX_LINE_STATUS_BIT_POS (10) + +/* bit 15-14 are port indicator control */ +#define PORTSCX_PIC_OFF (0x00000000) +#define PORTSCX_PIC_AMBER (0x00004000) +#define PORTSCX_PIC_GREEN (0x00008000) +#define PORTSCX_PIC_UNDEF (0x0000C000) +#define PORTSCX_PIC_BIT_POS (14) + +/* bit 19-16 are port test control */ +#define PORTSCX_PTC_DISABLE (0x00000000) +#define PORTSCX_PTC_JSTATE (0x00010000) +#define PORTSCX_PTC_KSTATE (0x00020000) +#define PORTSCX_PTC_SEQNAK (0x00030000) +#define PORTSCX_PTC_PACKET (0x00040000) +#define PORTSCX_PTC_FORCE_EN (0x00050000) +#define PORTSCX_PTC_BIT_POS (16) + +/* bit 27-26 are port speed */ +#define PORTSCX_PORT_SPEED_FULL (0x00000000) +#define PORTSCX_PORT_SPEED_LOW (0x04000000) +#define PORTSCX_PORT_SPEED_HIGH (0x08000000) +#define PORTSCX_PORT_SPEED_UNDEF (0x0C000000) +#define PORTSCX_SPEED_BIT_POS (26) + +/* OTGSC Register Bit Masks */ +#define OTGSC_B_SESSION_VALID_IRQ_EN (1 << 27) +#define OTGSC_B_SESSION_VALID_IRQ_STS (1 << 19) +#define OTGSC_B_SESSION_VALID (1 << 11) + +/* bit 28 is parallel transceiver width for UTMI interface */ +#define PORTSCX_PTW (0x10000000) +#define PORTSCX_PTW_8BIT (0x00000000) +#define PORTSCX_PTW_16BIT (0x10000000) + +/* bit 31-30 are port transceiver select */ +#define PORTSCX_PTS_UTMI (0x00000000) +#define PORTSCX_PTS_ULPI (0x80000000) +#define PORTSCX_PTS_FSLS (0xC0000000) +#define PORTSCX_PTS_BIT_POS (30) + +/* USB MODE Register Bit Masks */ +#define USB_MODE_CTRL_MODE_IDLE (0x00000000) +#define USB_MODE_CTRL_MODE_DEVICE (0x00000002) +#define USB_MODE_CTRL_MODE_HOST (0x00000003) +#define USB_MODE_CTRL_MODE_MASK 0x00000003 +#define USB_MODE_CTRL_MODE_RSV (0x00000001) +#define USB_MODE_ES 0x00000004 /* (big) Endian Sel */ +#define USB_MODE_SETUP_LOCK_OFF (0x00000008) +#define USB_MODE_STREAM_DISABLE (0x00000010) +/* Endpoint Flush Register */ +#define EPFLUSH_TX_OFFSET (0x00010000) +#define EPFLUSH_RX_OFFSET (0x00000000) + +/* Endpoint Setup Status bit masks */ +#define EP_SETUP_STATUS_MASK (0x0000003F) +#define EP_SETUP_STATUS_EP0 (0x00000001) + +/* ENDPOINTCTRLx Register Bit Masks */ +#define EPCTRL_TX_ENABLE (0x00800000) +#define EPCTRL_TX_DATA_TOGGLE_RST (0x00400000) /* Not EP0 */ +#define EPCTRL_TX_DATA_TOGGLE_INH (0x00200000) /* Not EP0 */ +#define EPCTRL_TX_TYPE (0x000C0000) +#define EPCTRL_TX_DATA_SOURCE (0x00020000) /* Not EP0 */ +#define EPCTRL_TX_EP_STALL (0x00010000) +#define EPCTRL_RX_ENABLE (0x00000080) +#define EPCTRL_RX_DATA_TOGGLE_RST (0x00000040) /* Not EP0 */ +#define EPCTRL_RX_DATA_TOGGLE_INH (0x00000020) /* Not EP0 */ +#define EPCTRL_RX_TYPE (0x0000000C) +#define EPCTRL_RX_DATA_SINK (0x00000002) /* Not EP0 */ +#define EPCTRL_RX_EP_STALL (0x00000001) + +/* bit 19-18 and 3-2 are endpoint type */ +#define EPCTRL_EP_TYPE_CONTROL (0) +#define EPCTRL_EP_TYPE_ISO (1) +#define EPCTRL_EP_TYPE_BULK (2) +#define EPCTRL_EP_TYPE_INTERRUPT (3) +#define EPCTRL_TX_EP_TYPE_SHIFT (18) +#define EPCTRL_RX_EP_TYPE_SHIFT (2) + +/* SNOOPn Register Bit Masks */ +#define SNOOP_ADDRESS_MASK (0xFFFFF000) +#define SNOOP_SIZE_ZERO (0x00) /* snooping disable */ +#define SNOOP_SIZE_4KB (0x0B) /* 4KB snoop size */ +#define SNOOP_SIZE_8KB (0x0C) +#define SNOOP_SIZE_16KB (0x0D) +#define SNOOP_SIZE_32KB (0x0E) +#define SNOOP_SIZE_64KB (0x0F) +#define SNOOP_SIZE_128KB (0x10) +#define SNOOP_SIZE_256KB (0x11) +#define SNOOP_SIZE_512KB (0x12) +#define SNOOP_SIZE_1MB (0x13) +#define SNOOP_SIZE_2MB (0x14) +#define SNOOP_SIZE_4MB (0x15) +#define SNOOP_SIZE_8MB (0x16) +#define SNOOP_SIZE_16MB (0x17) +#define SNOOP_SIZE_32MB (0x18) +#define SNOOP_SIZE_64MB (0x19) +#define SNOOP_SIZE_128MB (0x1A) +#define SNOOP_SIZE_256MB (0x1B) +#define SNOOP_SIZE_512MB (0x1C) +#define SNOOP_SIZE_1GB (0x1D) +#define SNOOP_SIZE_2GB (0x1E) /* 2GB snoop size */ + +/* pri_ctrl Register Bit Masks */ +#define PRI_CTRL_PRI_LVL1 (0x0000000C) +#define PRI_CTRL_PRI_LVL0 (0x00000003) + +/* si_ctrl Register Bit Masks */ +#define SI_CTRL_ERR_DISABLE (0x00000010) +#define SI_CTRL_IDRC_DISABLE (0x00000008) +#define SI_CTRL_RD_SAFE_EN (0x00000004) +#define SI_CTRL_RD_PREFETCH_DISABLE (0x00000002) +#define SI_CTRL_RD_PREFEFETCH_VAL (0x00000001) + +/* control Register Bit Masks */ +#define USB_CTRL_IOENB (0x00000004) +#define USB_CTRL_ULPI_INT0EN (0x00000001) +#define USB_CTRL_OTG_WUIR (0x80000000) +#define USB_CTRL_OTG_WUIE (0x08000000) +#define USB_CTRL_OTG_VWUE (0x00001000) +#define USB_CTRL_OTG_IWUE (0x00100000) + +/* PHY control0 Register Bit Masks */ +#define PHY_CTRL0_CONF2 (1 << 26) +#define PHY_CTRL0_USBEN (1 << 24) /* USB UTMI PHY Enable */ + +/* USB UH2 CTRL Register Bits */ +#define USB_UH2_OVBWK_EN (1 << 6) /* OTG VBUS Wakeup Enable */ +#define USB_UH2_OIDWK_EN (1 << 5) /* OTG ID Wakeup Enable */ +/*! + * Endpoint Queue Head data struct + * Rem: all the variables of qh are LittleEndian Mode + * and NEXT_POINTER_MASK should operate on a LittleEndian, Phy Addr + */ +struct ep_queue_head { + /*! + * Mult(31-30) , Zlt(29) , Max Pkt len and IOS(15) + */ + u32 max_pkt_length; + + /*! + * Current dTD Pointer(31-5) + */ + u32 curr_dtd_ptr; + + /*! + * Next dTD Pointer(31-5), T(0) + */ + u32 next_dtd_ptr; + + /*! + * Total bytes (30-16), IOC (15), MultO(11-10), STS (7-0) + */ + u32 size_ioc_int_sts; + + /*! + * Buffer pointer Page 0 (31-12) + */ + u32 buff_ptr0; + + /*! + * Buffer pointer Page 1 (31-12) + */ + u32 buff_ptr1; + + /*! + * Buffer pointer Page 2 (31-12) + */ + u32 buff_ptr2; + + /*! + * Buffer pointer Page 3 (31-12) + */ + u32 buff_ptr3; + + /*! + * Buffer pointer Page 4 (31-12) + */ + u32 buff_ptr4; + + /*! + * reserved field 1 + */ + u32 res1; + /*! + * Setup data 8 bytes + */ + u8 setup_buffer[8]; /* Setup data 8 bytes */ + + /*! + * reserved field 2,pad out to 64 bytes + */ + u32 res2[4]; +}; + +/* Endpoint Queue Head Bit Masks */ +#define EP_QUEUE_HEAD_MULT_POS (30) +#define EP_QUEUE_HEAD_ZLT_SEL (0x20000000) +#define EP_QUEUE_HEAD_MAX_PKT_LEN_POS (16) +#define EP_QUEUE_HEAD_MAX_PKT_LEN(ep_info) (((ep_info)>>16)&0x07ff) +#define EP_QUEUE_HEAD_IOS (0x00008000) +#define EP_QUEUE_HEAD_NEXT_TERMINATE (0x00000001) +#define EP_QUEUE_HEAD_IOC (0x00008000) +#define EP_QUEUE_HEAD_MULTO (0x00000C00) +#define EP_QUEUE_HEAD_STATUS_HALT (0x00000040) +#define EP_QUEUE_HEAD_STATUS_ACTIVE (0x00000080) +#define EP_QUEUE_CURRENT_OFFSET_MASK (0x00000FFF) +#define EP_QUEUE_HEAD_NEXT_POINTER_MASK 0xFFFFFFE0 +#define EP_QUEUE_FRINDEX_MASK (0x000007FF) +#define EP_MAX_LENGTH_TRANSFER (0x4000) + +/*! + * Endpoint Transfer Descriptor data struct + * Rem: all the variables of td are LittleEndian Mode + * must be 32-byte aligned + */ +struct ep_td_struct { + /*! + * Next TD pointer(31-5), T(0) set indicate invalid + */ + u32 next_td_ptr; + + /*! + * Total bytes (30-16), IOC (15),MultO(11-10), STS (7-0) + */ + u32 size_ioc_sts; + + /*! + * Buffer pointer Page 0 + */ + u32 buff_ptr0; + + /*! + * Buffer pointer Page 1 + */ + u32 buff_ptr1; + + /*! + * Buffer pointer Page 2 + */ + u32 buff_ptr2; + + /*! + * Buffer pointer Page 3 + */ + u32 buff_ptr3; + + /*! + * Buffer pointer Page 4 + */ + u32 buff_ptr4; + + /*! + * dma address of this td + * */ + dma_addr_t td_dma; + + /*! + * virtual address of next td + * */ + struct ep_td_struct *next_td_virt; + + /*! + * make it an even 16 words + * */ + u32 res[7]; +}; + +/*! + * Endpoint Transfer Descriptor bit Masks + */ +#define DTD_NEXT_TERMINATE (0x00000001) +#define DTD_IOC (0x00008000) +#define DTD_STATUS_ACTIVE (0x00000080) +#define DTD_STATUS_HALTED (0x00000040) +#define DTD_STATUS_DATA_BUFF_ERR (0x00000020) +#define DTD_STATUS_TRANSACTION_ERR (0x00000008) +#define DTD_RESERVED_FIELDS (0x80007300) +#define DTD_ADDR_MASK 0xFFFFFFE0 +#define DTD_PACKET_SIZE (0x7FFF0000) +#define DTD_LENGTH_BIT_POS (16) +#define DTD_ERROR_MASK (DTD_STATUS_HALTED | \ + DTD_STATUS_DATA_BUFF_ERR | \ + DTD_STATUS_TRANSACTION_ERR) +/* Alignment requirements; must be a power of two */ +#define DTD_ALIGNMENT 0x20 +#define QH_ALIGNMENT 2048 + +/* Controller dma boundary */ +#define UDC_DMA_BOUNDARY 0x1000 + +/* -----------------------------------------------------------------------*/ +/* ##### enum data +*/ +typedef enum { + e_ULPI, + e_UTMI_8BIT, + e_UTMI_16BIT, + e_SERIAL +} e_PhyInterface; + +/*-------------------------------------------------------------------------*/ + +struct fsl_req { + struct usb_request req; + struct list_head queue; + /* ep_queue() func will add + a request->queue into a udc_ep->queue 'd tail */ + struct fsl_ep *ep; + unsigned mapped; + + struct ep_td_struct *head, *tail; /* For dTD List + this is a BigEndian Virtual addr */ + unsigned int dtd_count; + /* just for IRAM patch */ + dma_addr_t oridma; /* original dma */ + size_t buffer_offset; /* offset of user buffer */ + int last_one; /* mark if reach to last packet */ + struct ep_td_struct *cur; /* current tranfer dtd */ +}; + +#define REQ_UNCOMPLETE (1) + +struct fsl_ep { + struct usb_ep ep; + struct list_head queue; + struct fsl_udc *udc; + struct ep_queue_head *qh; + const struct usb_endpoint_descriptor *desc; + struct usb_gadget *gadget; + + char name[14]; + unsigned stopped:1; +}; + +#define EP_DIR_IN 1 +#define EP_DIR_OUT 0 + +struct fsl_udc { + struct usb_gadget gadget; + struct usb_gadget_driver *driver; + struct fsl_usb2_platform_data *pdata; + struct fsl_ep *eps; + unsigned int max_ep; + unsigned int irq; + + struct usb_ctrlrequest local_setup_buff; + spinlock_t lock; + u32 xcvr_type; + struct otg_transceiver *transceiver; + unsigned softconnect:1; + unsigned vbus_active:1; + unsigned stopped:1; + unsigned remote_wakeup:1; + unsigned already_stopped:1; + + struct ep_queue_head *ep_qh; /* Endpoints Queue-Head */ + struct fsl_req *status_req; /* ep0 status request */ + struct fsl_req *data_req; /* ep0 data request */ + struct dma_pool *td_pool; /* dma pool for DTD */ + enum fsl_usb2_phy_modes phy_mode; + + size_t ep_qh_size; /* size after alignment adjustment*/ + dma_addr_t ep_qh_dma; /* dma address of QH */ + + u32 max_pipes; /* Device max pipes */ + u32 max_use_endpts; /* Max endpointes to be used */ + u32 bus_reset; /* Device is bus reseting */ + u32 resume_state; /* USB state to resume */ + u32 usb_state; /* USB current state */ + u32 usb_next_state; /* USB next state */ + u32 ep0_dir; /* Endpoint zero direction: can be + USB_DIR_IN or USB_DIR_OUT */ + u32 usb_sof_count; /* SOF count */ + u32 errors; /* USB ERRORs count */ + u8 device_address; /* Device USB address */ + + struct completion *done; /* to make sure release() is done */ + u32 iram_buffer[IRAM_PPH_NTD]; + void *iram_buffer_v[IRAM_PPH_NTD]; +}; + +/*-------------------------------------------------------------------------*/ + +#ifdef DEBUG +#define DBG(fmt, args...) printk(KERN_DEBUG "[%s] " fmt "\n", \ + __func__, ## args) +#else +#define DBG(fmt, args...) do {} while (0) +#endif + +#if 0 +static void dump_msg(const char *label, const u8 * buf, unsigned int length) +{ + unsigned int start, num, i; + char line[52], *p; + + if (length >= 512) + return; + pr_debug("udc: %s, length %u:\n", label, length); + start = 0; + while (length > 0) { + num = min(length, 16u); + p = line; + for (i = 0; i < num; ++i) { + if (i == 8) + *p++ = ' '; + sprintf(p, " %02x", buf[i]); + p += 3; + } + *p = 0; + printk(KERN_DEBUG "%6x: %s\n", start, line); + buf += num; + start += num; + length -= num; + } +} +#endif + +#ifdef VERBOSE +#define VDBG DBG +#else +#define VDBG(stuff...) do {} while (0) +#endif + +#define ERR(stuff...) printk(KERN_ERR "udc: " stuff) +#define INFO(stuff...) printk(KERN_INFO "udc: " stuff) + +/*-------------------------------------------------------------------------*/ + +/* ### Add board specific defines here + */ + +/* + * ### pipe direction macro from device view + */ +#define USB_RECV (0) /* OUT EP */ +#define USB_SEND (1) /* IN EP */ + +/* + * ### internal used help routines. + */ +#define ep_index(EP) ((EP)->desc->bEndpointAddress&0xF) +#define ep_maxpacket(EP) ((EP)->ep.maxpacket) + +#define ep_is_in(EP) ((ep_index(EP) == 0) ? (EP->udc->ep0_dir == \ + USB_DIR_IN) : ((EP)->desc->bEndpointAddress \ + & USB_DIR_IN) == USB_DIR_IN) + +#define get_ep_by_pipe(udc, pipe) ((pipe == 1) ? &udc->eps[0] : \ + &udc->eps[pipe]) +#define get_pipe_by_windex(windex) ((windex & USB_ENDPOINT_NUMBER_MASK) \ + * 2 + ((windex & USB_DIR_IN) ? 1 : 0)) + +/* Bulk only class request */ +#define USB_BULK_RESET_REQUEST 0xff + +#if defined(CONFIG_ARCH_MXC) || defined(CONFIG_ARCH_STMP3XXX) || \ + defined(CONFIG_ARCH_MXS) +#include +#elif CONFIG_PPC32 +#include +#endif + +#endif /* __ARCOTG_UDC_H */ diff --git a/drivers/usb/gadget/fsl_udc_core.c b/drivers/usb/gadget/fsl_udc_core.c index 08a9a62a39e3..7d0e7fbceabf 100644 --- a/drivers/usb/gadget/fsl_udc_core.c +++ b/drivers/usb/gadget/fsl_udc_core.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2004-2007 Freescale Semicondutor, Inc. All rights reserved. + * Copyright (C) 2004-2010 Freescale Semicondutor, Inc. All rights reserved. * * Author: Li Yang * Jiang Bo @@ -2475,8 +2475,11 @@ static int __init udc_init(void) return platform_driver_probe(&udc_driver, fsl_udc_probe); } -module_init(udc_init); - +#ifdef CONFIG_MXS_VBUS_CURRENT_DRAW + fs_initcall(udc_init); +#else + module_init(udc_init); +#endif static void __exit udc_exit(void) { platform_driver_unregister(&udc_driver); diff --git a/drivers/usb/gadget/fsl_updater.c b/drivers/usb/gadget/fsl_updater.c index 8b4b54f8cca7..50acce441a90 100644 --- a/drivers/usb/gadget/fsl_updater.c +++ b/drivers/usb/gadget/fsl_updater.c @@ -29,6 +29,7 @@ static int utp_init(struct fsg_dev *fsg) INIT_LIST_HEAD(&utp_context.write); mutex_init(&utp_context.lock); + /* the max message is 64KB */ utp_context.buffer = vmalloc(0x10000); if (!utp_context.buffer) return -EIO; @@ -63,6 +64,7 @@ static void utp_user_data_free(struct utp_user_data *uud) kfree(uud); } +/* Get the number of element for list */ static u32 count_list(struct list_head *l) { u32 count = 0; @@ -74,10 +76,11 @@ static u32 count_list(struct list_head *l) return count; } - +/* The routine will not go on if utp_context.queue is empty */ #define WAIT_ACTIVITY(queue) \ wait_event_interruptible(utp_context.wq, !list_empty(&utp_context.queue)) +/* Called by userspace program (uuc) */ static ssize_t utp_file_read(struct file *file, char __user *buf, size_t size, @@ -109,12 +112,15 @@ static ssize_t utp_file_read(struct file *file, "need to put %d\n", size, size_to_put); } + /* + * The user program has already finished data process, + * go on getting data from the host + */ wake_up(&utp_context.list_full_wq); return size_to_put; } - static ssize_t utp_file_write(struct file *file, const char __user *buf, size_t size, loff_t *off) { @@ -127,11 +133,13 @@ static ssize_t utp_file_write(struct file *file, const char __user *buf, return -EACCES; mutex_lock(&utp_context.lock); list_add_tail(&uud->link, &utp_context.write); + /* Go on EXEC routine process */ wake_up(&utp_context.wq); mutex_unlock(&utp_context.lock); return size; } +/* Will be called when the host wants to get the sense data */ static int utp_get_sense(struct fsg_dev *fsg) { if (UTP_CTX(fsg)->processed == 0) @@ -186,6 +194,7 @@ static int utp_do_read(struct fsg_dev *fsg, void *data, size_t size) /* Perform the read */ pr_info("Copied to %p, %d bytes started from %d\n", bh->buf, amount, size - amount_left); + /* from upt buffer to file_storeage buffer */ memcpy(bh->buf, data + size - amount_left, amount); amount_left -= amount; fsg->residue -= amount; @@ -196,6 +205,7 @@ static int utp_do_read(struct fsg_dev *fsg, void *data, size_t size) /* Send this buffer and go read some more */ bh->inreq->zero = 0; + /* USB Physical transfer: Data from device to host */ start_transfer(fsg, fsg->bulk_in, bh->inreq, &bh->inreq_busy, &bh->state); @@ -326,8 +336,8 @@ static void utp_poll(struct fsg_dev *fsg) if (uud) { if (uud->data.flags & UTP_FLAG_STATUS) { - pr_debug("%s: exit with status %d\n", __func__, - uud->data.status); + printk(KERN_WARNING "%s: exit with status %d\n", + __func__, uud->data.status); UTP_SS_EXIT(fsg, uud->data.status); } else { pr_debug("%s: pass\n", __func__); @@ -356,11 +366,16 @@ static int utp_exec(struct fsg_dev *fsg, mutex_lock(&ctx->lock); list_add_tail(&uud2r->link, &ctx->read); mutex_unlock(&ctx->lock); + /* wake up the read routine */ wake_up(&ctx->wq); if (command[0] == '!') /* there will be no response */ return 0; + /* + * the user program (uuc) will return utp_message + * and add list to write list + */ WAIT_ACTIVITY(write); mutex_lock(&ctx->lock); @@ -382,21 +397,19 @@ static int utp_exec(struct fsg_dev *fsg, if (uud->data.flags & UTP_FLAG_DATA) { memcpy(ctx->buffer, uud->data.data, uud->data.bufsize); UTP_SS_SIZE(fsg, uud->data.bufsize); - utp_user_data_free(uud); - return 0; - } - - if (uud->data.flags & UTP_FLAG_REPORT_BUSY) { - utp_user_data_free(uud); + } else if (uud->data.flags & UTP_FLAG_REPORT_BUSY) { ctx->counter = 0xFFFF; UTP_SS_BUSY(fsg, ctx->counter); - return 0; + } else if (uud->data.flags & UTP_FLAG_STATUS) { + printk(KERN_WARNING "%s: exit with status %d\n", __func__, + uud->data.status); + UTP_SS_EXIT(fsg, uud->data.status); + } else { + pr_debug("%s: pass\n", __func__); + UTP_SS_PASS(fsg); } - utp_user_data_free(uud); - UTP_SS_PASS(fsg); - - return -1; + return 0; } static int utp_send_status(struct fsg_dev *fsg) @@ -470,16 +483,17 @@ static int utp_handle_message(struct fsg_dev *fsg, case UTP_EXEC: pr_debug("%s: EXEC\n", __func__); data = kzalloc(fsg->data_size, GFP_KERNEL); + /* copy data from usb buffer to utp buffer */ utp_do_write(fsg, data, fsg->data_size); utp_exec(fsg, data, fsg->data_size, param); kfree(data); break; - case UTP_GET: + case UTP_GET: /* data from device to host */ pr_debug("%s: GET, %d bytes\n", __func__, fsg->data_size); r = utp_do_read(fsg, UTP_CTX(fsg)->buffer, fsg->data_size); UTP_SS_PASS(fsg); break; - case UTP_PUT: + case UTP_PUT: /* data from host to device */ pr_debug("%s: PUT, %d bytes\n", __func__, fsg->data_size); uud2r = utp_user_data_alloc(fsg->data_size); uud2r->data.bufsize = fsg->data_size; @@ -490,6 +504,37 @@ static int utp_handle_message(struct fsg_dev *fsg, list_add_tail(&uud2r->link, &UTP_CTX(fsg)->read); mutex_unlock(&UTP_CTX(fsg)->lock); wake_up(&UTP_CTX(fsg)->wq); + /* + * Return PASS or FAIL according to uuc's status + * Please open it if need to check uuc's status + * and use another version uuc + */ +#if 0 + struct utp_user_data *uud = NULL; + struct utp_context *ctx; + WAIT_ACTIVITY(write); + ctx = UTP_CTX(fsg); + mutex_lock(&ctx->lock); + + if (!list_empty(&ctx->write)) + uud = list_first_entry(&ctx->write, + struct utp_user_data, link); + + mutex_unlock(&ctx->lock); + if (uud) { + if (uud->data.flags & UTP_FLAG_STATUS) { + printk(KERN_WARNING "%s: exit with status %d\n", + __func__, uud->data.status); + UTP_SS_EXIT(fsg, uud->data.status); + } else { + pr_debug("%s: pass\n", __func__); + UTP_SS_PASS(fsg); + } + utp_user_data_free(uud); + } else{ + UTP_SS_PASS(fsg); + } +#endif UTP_SS_PASS(fsg); wait_event_interruptible(UTP_CTX(fsg)->list_full_wq, diff --git a/drivers/usb/gadget/fsl_updater.h b/drivers/usb/gadget/fsl_updater.h index 44329a9af58a..70e4defa1a9c 100644 --- a/drivers/usb/gadget/fsl_updater.h +++ b/drivers/usb/gadget/fsl_updater.h @@ -59,6 +59,7 @@ static int utp_handle_message(struct fsg_dev *fsg, #define UTP_SS_BUSY(fsg, r) utp_set_sense(fsg, UTP_REPLY_BUSY, (u64)r) #define UTP_SS_SIZE(fsg, r) utp_set_sense(fsg, UTP_REPLY_SIZE, (u64)r) +/* the structure of utp message which is mapped to 16-byte SCSI CBW's CDB */ #pragma pack(1) struct utp_msg { u8 f0; diff --git a/drivers/usb/gadget/stmp_updater.c b/drivers/usb/gadget/stmp_updater.c new file mode 100644 index 000000000000..63c22f98eacf --- /dev/null +++ b/drivers/usb/gadget/stmp_updater.c @@ -0,0 +1,504 @@ +/* + * Freescale STMP378X UUT driver + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + * Copyright 2008-2009 Embedded Alley Solutions, Inc All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include + +static u64 get_be64(u8 *buf) +{ + return ((u64)get_unaligned_be32(buf) << 32) | get_unaligned_be32(buf + 4); +} + +static int utp_init(struct fsg_dev *fsg) +{ + init_waitqueue_head(&utp_context.wq); + init_waitqueue_head(&utp_context.list_full_wq); + + INIT_LIST_HEAD(&utp_context.read); + INIT_LIST_HEAD(&utp_context.write); + mutex_init(&utp_context.lock); + + utp_context.buffer = vmalloc(0x10000); + if (!utp_context.buffer) + return -EIO; + utp_context.utp_version = 0x1ull; + fsg->utp = &utp_context; + return misc_register(&utp_dev); +} + +static void utp_exit(struct fsg_dev *fsg) +{ + vfree(utp_context.buffer); + misc_deregister(&utp_dev); +} + +static struct utp_user_data *utp_user_data_alloc(size_t size) +{ + struct utp_user_data *uud; + + uud = kzalloc(size + sizeof(*uud), GFP_KERNEL); + if (!uud) + return uud; + uud->data.size = size + sizeof(uud->data); + INIT_LIST_HEAD(&uud->link); + return uud; +} + +static void utp_user_data_free(struct utp_user_data *uud) +{ + mutex_lock(&utp_context.lock); + list_del(&uud->link); + mutex_unlock(&utp_context.lock); + kfree(uud); +} + +static u32 count_list(struct list_head *l) +{ + u32 count = 0; + struct list_head *tmp; + + list_for_each(tmp, l) { + count++; + } + + return count; +} + +#define WAIT_ACTIVITY(queue) \ + wait_event_interruptible(utp_context.wq, !list_empty(&utp_context.queue)) + +static ssize_t utp_file_read(struct file *file, + char __user *buf, + size_t size, + loff_t *off) +{ + struct utp_user_data *uud; + size_t size_to_put; + int free = 0; + + WAIT_ACTIVITY(read); + + mutex_lock(&utp_context.lock); + uud = list_first_entry(&utp_context.read, struct utp_user_data, link); + mutex_unlock(&utp_context.lock); + size_to_put = uud->data.size; + + if (size >= size_to_put) + free = !0; + if (copy_to_user(buf, &uud->data, size_to_put)) + return -EACCES; + if (free) + utp_user_data_free(uud); + else { + pr_info("sizeof = %d, size = %d\n", + sizeof(uud->data), + uud->data.size); + + pr_err("Will not free utp_user_data, because buffer size = %d," + "need to put %d\n", size, size_to_put); + } + + wake_up(&utp_context.list_full_wq); + + return size_to_put; +} + + +static ssize_t utp_file_write(struct file *file, const char __user *buf, + size_t size, loff_t *off) +{ + struct utp_user_data *uud; + + if (size < sizeof(uud->data)) + return -EINVAL; + uud = utp_user_data_alloc(size); + if (copy_from_user(&uud->data, buf, size)) + return -EACCES; + mutex_lock(&utp_context.lock); + list_add_tail(&uud->link, &utp_context.write); + wake_up(&utp_context.wq); + mutex_unlock(&utp_context.lock); + return size; +} + +static int utp_get_sense(struct fsg_dev *fsg) +{ + if (UTP_CTX(fsg)->processed == 0) + return -1; + + UTP_CTX(fsg)->processed = 0; + return 0; +} + +static int utp_do_read(struct fsg_dev *fsg, void *data, size_t size) +{ + struct fsg_buffhd *bh; + int rc; + u32 amount_left; + unsigned int amount; + + /* Get the starting Logical Block Address and check that it's + * not too big */ + + amount_left = size; + if (unlikely(amount_left == 0)) + return -EIO; /* No default reply*/ + + pr_debug("%s: sending %d\n", __func__, size); + for (;;) { + /* Figure out how much we need to read: + * Try to read the remaining amount. + * But don't read more than the buffer size. + * And don't try to read past the end of the file. + * Finally, if we're not at a page boundary, don't read past + * the next page. + * If this means reading 0 then we were asked to read past + * the end of file. */ + amount = min((unsigned int) amount_left, mod_data.buflen); + + /* Wait for the next buffer to become available */ + bh = fsg->next_buffhd_to_fill; + while (bh->state != BUF_STATE_EMPTY) { + rc = sleep_thread(fsg); + if (rc) + return rc; + } + + /* If we were asked to read past the end of file, + * end with an empty buffer. */ + if (amount == 0) { + bh->inreq->length = 0; + bh->state = BUF_STATE_FULL; + break; + } + + /* Perform the read */ + pr_info("Copied to %p, %d bytes started from %d\n", + bh->buf, amount, size - amount_left); + memcpy(bh->buf, data + size - amount_left, amount); + amount_left -= amount; + fsg->residue -= amount; + + bh->inreq->length = amount; + bh->state = BUF_STATE_FULL; + + /* Send this buffer and go read some more */ + bh->inreq->zero = 0; + + start_transfer(fsg, fsg->bulk_in, bh->inreq, + &bh->inreq_busy, &bh->state); + + fsg->next_buffhd_to_fill = bh->next; + + if (amount_left <= 0) + break; + } + + return size - amount_left; +} + +static int utp_do_write(struct fsg_dev *fsg, void *data, size_t size) +{ + struct fsg_buffhd *bh; + int get_some_more; + u32 amount_left_to_req, amount_left_to_write; + unsigned int amount; + int rc; + loff_t offset; + + /* Carry out the file writes */ + get_some_more = 1; + amount_left_to_req = amount_left_to_write = size; + + if (unlikely(amount_left_to_write == 0)) + return -EIO; + + offset = 0; + while (amount_left_to_write > 0) { + + /* Queue a request for more data from the host */ + bh = fsg->next_buffhd_to_fill; + if (bh->state == BUF_STATE_EMPTY && get_some_more) { + + /* Figure out how much we want to get: + * Try to get the remaining amount. + * But don't get more than the buffer size. + * And don't try to go past the end of the file. + * If we're not at a page boundary, + * don't go past the next page. + * If this means getting 0, then we were asked + * to write past the end of file. + * Finally, round down to a block boundary. */ + amount = min(amount_left_to_req, mod_data.buflen); + + if (amount == 0) { + get_some_more = 0; + /* cry now */ + continue; + } + + /* Get the next buffer */ + amount_left_to_req -= amount; + if (amount_left_to_req == 0) + get_some_more = 0; + + /* amount is always divisible by 512, hence by + * the bulk-out maxpacket size */ + bh->outreq->length = bh->bulk_out_intended_length = + amount; + bh->outreq->short_not_ok = 1; + start_transfer(fsg, fsg->bulk_out, bh->outreq, + &bh->outreq_busy, &bh->state); + fsg->next_buffhd_to_fill = bh->next; + continue; + } + + /* Write the received data to the backing file */ + bh = fsg->next_buffhd_to_drain; + if (bh->state == BUF_STATE_EMPTY && !get_some_more) + break; /* We stopped early */ + if (bh->state == BUF_STATE_FULL) { + smp_rmb(); + fsg->next_buffhd_to_drain = bh->next; + bh->state = BUF_STATE_EMPTY; + + /* Did something go wrong with the transfer? */ + if (bh->outreq->status != 0) + /* cry again, COMMUNICATION_FAILURE */ + break; + + amount = bh->outreq->actual; + + /* Perform the write */ + memcpy(data + offset, bh->buf, amount); + + offset += amount; + if (signal_pending(current)) + return -EINTR; /* Interrupted!*/ + amount_left_to_write -= amount; + fsg->residue -= amount; + + /* Did the host decide to stop early? */ + if (bh->outreq->actual != bh->outreq->length) { + fsg->short_packet_received = 1; + break; + } + continue; + } + + /* Wait for something to happen */ + rc = sleep_thread(fsg); + if (rc) + return rc; + } + + return -EIO; +} + +static inline void utp_set_sense(struct fsg_dev *fsg, u16 code, u64 reply) +{ + UTP_CTX(fsg)->processed = true; + UTP_CTX(fsg)->sdinfo = reply & 0xFFFFFFFF; + UTP_CTX(fsg)->sdinfo_h = (reply >> 32) & 0xFFFFFFFF; + UTP_CTX(fsg)->sd = (UTP_SENSE_KEY << 16) | code; +} + +static void utp_poll(struct fsg_dev *fsg) +{ + struct utp_context *ctx = UTP_CTX(fsg); + struct utp_user_data *uud = NULL; + + mutex_lock(&ctx->lock); + if (!list_empty(&ctx->write)) + uud = list_first_entry(&ctx->write, struct utp_user_data, link); + mutex_unlock(&ctx->lock); + + if (uud) { + if (uud->data.flags & UTP_FLAG_STATUS) { + pr_debug("%s: exit with status %d\n", __func__, + uud->data.status); + UTP_SS_EXIT(fsg, uud->data.status); + } else { + pr_debug("%s: pass\n", __func__); + UTP_SS_PASS(fsg); + } + utp_user_data_free(uud); + } else { + pr_debug("%s: still busy...\n", __func__); + UTP_SS_BUSY(fsg, --ctx->counter); + } +} + +static int utp_exec(struct fsg_dev *fsg, + char *command, + int cmdsize, + unsigned long long payload) +{ + struct utp_user_data *uud = NULL, *uud2r; + struct utp_context *ctx = UTP_CTX(fsg); + + uud2r = utp_user_data_alloc(cmdsize + 1); + uud2r->data.flags = UTP_FLAG_COMMAND; + uud2r->data.payload = payload; + strncpy(uud2r->data.command, command, cmdsize); + + mutex_lock(&ctx->lock); + list_add_tail(&uud2r->link, &ctx->read); + mutex_unlock(&ctx->lock); + wake_up(&ctx->wq); + + if (command[0] == '!') /* there will be no response */ + return 0; + + WAIT_ACTIVITY(write); + + mutex_lock(&ctx->lock); + if (!list_empty(&ctx->write)) { + uud = list_first_entry(&ctx->write, struct utp_user_data, link); +#ifdef DEBUG + pr_info("UUD:\n\tFlags = %02X\n", uud->data.flags); + if (uud->data.flags & UTP_FLAG_DATA) { + pr_info("\tbufsize = %d\n", uud->data.bufsize); + print_hex_dump(KERN_DEBUG, "\t", DUMP_PREFIX_NONE, + 16, 2, uud->data.data, uud->data.bufsize, true); + } + if (uud->data.flags & UTP_FLAG_REPORT_BUSY) + pr_info("\tBUSY\n"); +#endif + } + mutex_unlock(&ctx->lock); + + if (uud->data.flags & UTP_FLAG_DATA) { + memcpy(ctx->buffer, uud->data.data, uud->data.bufsize); + UTP_SS_SIZE(fsg, uud->data.bufsize); + utp_user_data_free(uud); + return 0; + } + + if (uud->data.flags & UTP_FLAG_REPORT_BUSY) { + utp_user_data_free(uud); + ctx->counter = 0xFFFF; + UTP_SS_BUSY(fsg, ctx->counter); + return 0; + } + + utp_user_data_free(uud); + UTP_SS_PASS(fsg); + + return -1; +} + +static int utp_send_status(struct fsg_dev *fsg) +{ + struct fsg_buffhd *bh; + u8 status = USB_STATUS_PASS; + struct bulk_cs_wrap *csw; + int rc; + + /* Wait for the next buffer to become available */ + bh = fsg->next_buffhd_to_fill; + while (bh->state != BUF_STATE_EMPTY) { + rc = sleep_thread(fsg); + if (rc) + return rc; + } + + if (fsg->phase_error) { + DBG(fsg, "sending phase-error status\n"); + status = USB_STATUS_PHASE_ERROR; + + } else if ((UTP_CTX(fsg)->sd & 0xFFFF) != UTP_REPLY_PASS) { + status = USB_STATUS_FAIL; + } + + csw = bh->buf; + + /* Store and send the Bulk-only CSW */ + csw->Signature = __constant_cpu_to_le32(USB_BULK_CS_SIG); + csw->Tag = fsg->tag; + csw->Residue = cpu_to_le32(fsg->residue); + csw->Status = status; + + bh->inreq->length = USB_BULK_CS_WRAP_LEN; + bh->inreq->zero = 0; + start_transfer(fsg, fsg->bulk_in, bh->inreq, + &bh->inreq_busy, &bh->state); + fsg->next_buffhd_to_fill = bh->next; + return 0; +} + +static int utp_handle_message(struct fsg_dev *fsg, + char *cdb_data, + int default_reply) +{ + struct utp_msg *m = (struct utp_msg *)cdb_data; + void *data = NULL; + int r; + struct utp_user_data *uud2r; + unsigned long long param; + unsigned long tag; + + if (m->f0 != 0xF0) + return default_reply; + + tag = get_unaligned_be32((void *)&m->utp_msg_tag); + param = get_be64((void *)&m->param); + pr_debug("Type 0x%x, tag 0x%08lx, param %llx\n", + m->utp_msg_type, tag, param); + + switch ((enum utp_msg_type)m->utp_msg_type) { + + case UTP_POLL: + if (get_be64((void *)&m->param) == 1) { + pr_debug("%s: version request\n", __func__); + UTP_SS_EXIT(fsg, UTP_CTX(fsg)->utp_version); + break; + } + utp_poll(fsg); + break; + case UTP_EXEC: + pr_debug("%s: EXEC\n", __func__); + data = kzalloc(fsg->data_size, GFP_KERNEL); + utp_do_write(fsg, data, fsg->data_size); + utp_exec(fsg, data, fsg->data_size, param); + kfree(data); + break; + case UTP_GET: + pr_debug("%s: GET, %d bytes\n", __func__, fsg->data_size); + r = utp_do_read(fsg, UTP_CTX(fsg)->buffer, fsg->data_size); + UTP_SS_PASS(fsg); + break; + case UTP_PUT: + pr_debug("%s: PUT, %d bytes\n", __func__, fsg->data_size); + uud2r = utp_user_data_alloc(fsg->data_size); + uud2r->data.bufsize = fsg->data_size; + uud2r->data.flags = UTP_FLAG_DATA; + utp_do_write(fsg, uud2r->data.data, fsg->data_size); + /* don't know what will be written */ + mutex_lock(&UTP_CTX(fsg)->lock); + list_add_tail(&uud2r->link, &UTP_CTX(fsg)->read); + mutex_unlock(&UTP_CTX(fsg)->lock); + wake_up(&UTP_CTX(fsg)->wq); + UTP_SS_PASS(fsg); + + wait_event_interruptible(UTP_CTX(fsg)->list_full_wq, + count_list(&UTP_CTX(fsg)->read) < 7); + break; + } + + utp_send_status(fsg); + return -1; +} + diff --git a/drivers/usb/gadget/stmp_updater.h b/drivers/usb/gadget/stmp_updater.h new file mode 100644 index 000000000000..810e5f92aeb8 --- /dev/null +++ b/drivers/usb/gadget/stmp_updater.h @@ -0,0 +1,140 @@ +/* + * Freescale STMP378X UUT driver + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + * Copyright 2008-2009 Embedded Alley Solutions, Inc All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#ifndef __STMP_UPDATER_H +#define __STMP_UPDATER_H + +#include +#include +#include + +static int utp_init(struct fsg_dev *fsg); +static void utp_exit(struct fsg_dev *fsg); +static ssize_t utp_file_read(struct file *file, + char __user *buf, + size_t size, + loff_t *off); + +static ssize_t utp_file_write(struct file *file, + const char __user *buf, + size_t size, + loff_t *off); + +static struct utp_user_data *utp_user_data_alloc(size_t size); +static void utp_user_data_free(struct utp_user_data *uud); +static int utp_get_sense(struct fsg_dev *fsg); +static int utp_do_read(struct fsg_dev *fsg, void *data, size_t size); +static int utp_do_write(struct fsg_dev *fsg, void *data, size_t size); +static inline void utp_set_sense(struct fsg_dev *fsg, u16 code, u64 reply); +static int utp_handle_message(struct fsg_dev *fsg, + char *cdb_data, + int default_reply); + +#define UTP_REPLY_PASS 0 +#define UTP_REPLY_EXIT 0x8001 +#define UTP_REPLY_BUSY 0x8002 +#define UTP_REPLY_SIZE 0x8003 +#define UTP_SENSE_KEY 9 + +#define UTP_MINOR 222 +/* MISC_DYNAMIC_MINOR would be better, but... */ + +#define UTP_COMMAND_SIZE 80 + +#define UTP_SS_EXIT(fsg, r) utp_set_sense(fsg, UTP_REPLY_EXIT, (u64)r) +#define UTP_SS_PASS(fsg) utp_set_sense(fsg, UTP_REPLY_PASS, 0) +#define UTP_SS_BUSY(fsg, r) utp_set_sense(fsg, UTP_REPLY_BUSY, (u64)r) +#define UTP_SS_SIZE(fsg, r) utp_set_sense(fsg, UTP_REPLY_SIZE, (u64)r) + +#pragma pack(1) +struct utp_msg { + u8 f0; + u8 utp_msg_type; + u32 utp_msg_tag; + union { + struct { + u32 param_lsb; + u32 param_msb; + }; + u64 param; + }; +}; + +enum utp_msg_type { + UTP_POLL = 0, + UTP_EXEC, + UTP_GET, + UTP_PUT, +}; + +static struct utp_context { + wait_queue_head_t wq; + wait_queue_head_t list_full_wq; + struct mutex lock; + struct list_head read; + struct list_head write; + u32 sd, sdinfo, sdinfo_h; /* sense data */ + int processed; + u8 *buffer; + u32 counter; + u64 utp_version; +} utp_context; + +static const struct file_operations utp_fops = { + .open = nonseekable_open, + .read = utp_file_read, + .write = utp_file_write, +}; + +static struct miscdevice utp_dev = { + .minor = UTP_MINOR, + .name = "utp", + .fops = &utp_fops, +}; + +#define UTP_FLAG_COMMAND 0x00000001 +#define UTP_FLAG_DATA 0x00000002 +#define UTP_FLAG_STATUS 0x00000004 +#define UTP_FLAG_REPORT_BUSY 0x10000000 +struct utp_message { + u32 flags; + size_t size; + union { + struct { + u64 payload; + char command[1]; + }; + struct { + size_t bufsize; + u8 data[1]; + }; + u32 status; + }; +}; + +struct utp_user_data { + struct list_head link; + struct utp_message data; +}; +#pragma pack() + +static inline struct utp_context *UTP_CTX(struct fsg_dev *fsg) +{ + return (struct utp_context *)fsg->utp; +} + +#endif /* __STMP_UPDATER_H */ + diff --git a/drivers/usb/host/Kconfig b/drivers/usb/host/Kconfig index f865be2276d4..f90afd30a70c 100644 --- a/drivers/usb/host/Kconfig +++ b/drivers/usb/host/Kconfig @@ -59,9 +59,101 @@ config USB_EHCI_HCD To compile this driver as a module, choose M here: the module will be called ehci-hcd. +config USB_EHCI_ARC + bool "Support for Freescale controller" + depends on USB_EHCI_HCD && (ARCH_MXC || ARCH_STMP3XXX || ARCH_MXS) + select USB_OTG_UTILS + ---help--- + Some Freescale processors have an integrated High Speed + USBOTG controller, which supports EHCI host mode. + + Say "y" here to add support for this controller + to the EHCI HCD driver. + +config USB_EHCI_ARC_H1 + bool "Support for Host1 port on Freescale controller" + depends on USB_EHCI_ARC && (ARCH_MX27 || ARCH_MX3 || ARCH_MX28) + ---help--- + Enable support for the USB Host1 port. + +config USB_EHCI_ARC_H2 + bool "Support for Host2 port on Freescale controller" + depends on USB_EHCI_ARC && \ + (ARCH_MX25 || ARCH_MX27 || ARCH_MX3 || ARCH_MX35) + ---help--- + Enable support for the USB Host2 port. + +config USB_EHCI_ARC_OTG + bool "Support for DR host port on Freescale controller" + depends on USB_EHCI_ARC + default y + ---help--- + Enable support for the USB OTG port in HS/FS Host mode. + +config USB_STATIC_IRAM + bool "Use IRAM for USB" + depends on USB_EHCI_ARC + ---help--- + Enable this option to use IRAM instead of DRAM for USB + structures and buffers. This option will reduce bus + contention on systems with large (VGA+) framebuffer + devices and heavy USB activity. There are performance + penalties and usage restrictions when using this option. + + If in doubt, say N. + +choice + prompt "Select transceiver for DR port" + depends on USB_EHCI_ARC_OTG + default USB_EHCI_FSL_1504 if ARCH_MX3 + default USB_EHCI_FSL_1301 if ARCH_MX27 + default USB_EHCI_FSL_UTMI if (ARCH_MX25 || ARCH_MX35 || ARCH_MX37 || ARCH_MX51 || ARCH_STMP3XXX || ARCH_MXS) + ---help--- + Choose the transceiver to use with the Freescale DR port. + +config USB_EHCI_FSL_MC13783 + bool "Freescale MC13783" + depends on !MACH_MX25_3DS + ---help--- + Enable support for the Full Speed Freescale MC13783 transceiver. + + The mx27ads, mx31ads and mx32ads boards require modifications + to support this transceiver. + +config USB_EHCI_FSL_1301 + bool "Philips ISP1301" + depends on !MACH_MX25_3DS + ---help--- + Enable support for the Full Speed Philips ISP1301 transceiver. + + This is the factory default for the mx27ads board. + The mx31ads and mx32ads boards require modifications + to support this transceiver. + +config USB_EHCI_FSL_1504 + bool "Philips ISP1504" + depends on MACH_MX27ADS || MACH_MX31ADS || MACH_MX32ADS ||MACH_MX31_3DS + ---help--- + Enable support for the High Speed Philips ISP1504 transceiver. + + This is the factory default for the mx31ads and mx32ads boards. + The mx27ads board requires modifications to support this transceiver. + +config USB_EHCI_FSL_UTMI + bool "Internal UTMI" + depends on (ARCH_MX25 || ARCH_MX35 || ARCH_MX37 || ARCH_MX51 || ARCH_STMP3XXX || ARCH_MXS) + ---help--- + Enable support for the on-chip High Speed UTMI transceiver. + + This is the factory default for the mx35ads board. + +endchoice + + config USB_EHCI_ROOT_HUB_TT bool "Root Hub Transaction Translators" depends on USB_EHCI_HCD + default y if USB_EHCI_ARC ---help--- Some EHCI chips have vendor-specific extensions to integrate transaction translators, so that no OHCI or UHCI companion diff --git a/drivers/usb/host/ehci-arc.c b/drivers/usb/host/ehci-arc.c new file mode 100644 index 000000000000..fe7989586cee --- /dev/null +++ b/drivers/usb/host/ehci-arc.c @@ -0,0 +1,709 @@ +/* + * Copyright (c) 2005 MontaVista Software + * Copyright (C) 2010 Freescale Semiconductor + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * + * Ported to 834x by Randy Vinson using code provided + * by Hunter Wu. + */ + +#include +#include +#include + +#include "ehci-fsl.h" +#include + +#undef EHCI_PROC_PTC +#ifdef EHCI_PROC_PTC /* /proc PORTSC:PTC support */ +/* + * write a PORTSC:PTC value to /proc/driver/ehci-ptc + * to put the controller into test mode. + */ +#include +#include +#define EFPSL 3 /* ehci fsl proc string length */ + +static int ehci_fsl_proc_read(char *page, char **start, off_t off, int count, + int *eof, void *data) +{ + return 0; +} + +static int ehci_fsl_proc_write(struct file *file, const char __user *buffer, + unsigned long count, void *data) +{ + int ptc; + u32 portsc; + struct ehci_hcd *ehci = (struct ehci_hcd *) data; + char str[EFPSL] = {0}; + + if (count > EFPSL-1) + return -EINVAL; + + if (copy_from_user(str, buffer, count)) + return -EFAULT; + + str[count] = '\0'; + + ptc = simple_strtoul(str, NULL, 0); + + portsc = ehci_readl(ehci, &ehci->regs->port_status[0]); + portsc &= ~(0xf << 16); + portsc |= (ptc << 16); + printk(KERN_INFO "PTC %x portsc %08x\n", ptc, portsc); + + ehci_writel(ehci, portsc, &ehci->regs->port_status[0]); + + return count; +} + +static int ehci_testmode_init(struct ehci_hcd *ehci) +{ + struct proc_dir_entry *entry; + + entry = create_proc_read_entry("driver/ehci-ptc", 0644, NULL, + ehci_fsl_proc_read, ehci); + if (!entry) + return -ENODEV; + + entry->write_proc = ehci_fsl_proc_write; + return 0; +} +#else +static int ehci_testmode_init(struct ehci_hcd *ehci) +{ + return 0; +} +#endif /* /proc PORTSC:PTC support */ + + +/* configure so an HC device and id are always provided */ +/* always called with process context; sleeping is OK */ + +/** + * usb_hcd_fsl_probe - initialize FSL-based HCDs + * @drvier: Driver to be used for this HCD + * @pdev: USB Host Controller being probed + * Context: !in_interrupt() + * + * Allocates basic resources for this USB host controller. + * + */ +int usb_hcd_fsl_probe(const struct hc_driver *driver, + struct platform_device *pdev) +{ + struct fsl_usb2_platform_data *pdata; + struct usb_hcd *hcd; + struct resource *res; + int irq; + int retval; + + pr_debug("initializing FSL-SOC USB Controller\n"); + + /* Need platform data for setup */ + pdata = (struct fsl_usb2_platform_data *)pdev->dev.platform_data; + if (!pdata) { + dev_err(&pdev->dev, + "No platform data for %s.\n", dev_name(&pdev->dev)); + return -ENODEV; + } + + /* + * This is a host mode driver, verify that we're supposed to be + * in host mode. + */ + if (!((pdata->operating_mode == FSL_USB2_DR_HOST) || + (pdata->operating_mode == FSL_USB2_MPH_HOST) || + (pdata->operating_mode == FSL_USB2_DR_OTG))) { + dev_err(&pdev->dev, + "Non Host Mode configured for %s. Wrong driver linked.\n", + dev_name(&pdev->dev)); + return -ENODEV; + } + + hcd = usb_create_hcd(driver, &pdev->dev, dev_name(&pdev->dev)); + if (!hcd) { + retval = -ENOMEM; + goto err1; + } + + res = platform_get_resource(pdev, IORESOURCE_IRQ, 0); + if (!res) { + dev_err(&pdev->dev, + "Found HC with no IRQ. Check %s setup!\n", + dev_name(&pdev->dev)); + return -ENODEV; + } + irq = res->start; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + hcd->rsrc_start = res->start; + hcd->rsrc_len = resource_size(res); + + if (pdata->operating_mode != FSL_USB2_DR_OTG) { + if (!request_mem_region(hcd->rsrc_start, hcd->rsrc_len, + driver->description)) { + dev_dbg(&pdev->dev, "controller already in use\n"); + retval = -EBUSY; + goto err2; + } + } + + hcd->regs = ioremap(hcd->rsrc_start, hcd->rsrc_len); + + if (hcd->regs == NULL) { + dev_dbg(&pdev->dev, "error mapping memory\n"); + retval = -EFAULT; + goto err3; + } + pdata->regs = hcd->regs; + + /* + * do platform specific init: check the clock, grab/config pins, etc. + */ + if (pdata->platform_init && pdata->platform_init(pdev)) { + retval = -ENODEV; + goto err3; + } + + fsl_platform_set_host_mode(hcd); + hcd->power_budget = pdata->power_budget; + + retval = usb_add_hcd(hcd, irq, IRQF_DISABLED | IRQF_SHARED); + if (retval != 0) + goto err4; + + fsl_platform_set_vbus_power(pdata, 1); + + if (pdata->operating_mode == FSL_USB2_DR_OTG) { + struct ehci_hcd *ehci = hcd_to_ehci(hcd); + + dbg("pdev=0x%p hcd=0x%p ehci=0x%p\n", pdev, hcd, ehci); + + ehci->transceiver = otg_get_transceiver(); + dbg("ehci->transceiver=0x%p\n", ehci->transceiver); + + if (!ehci->transceiver) { + printk(KERN_ERR "can't find transceiver\n"); + retval = -ENODEV; + goto err4; + } + + retval = otg_set_host(ehci->transceiver, &ehci_to_hcd(ehci)->self); + if (retval) + otg_put_transceiver(ehci->transceiver); + } + + if (pdata->suspended) { + pdata->suspended = 0; + if (pdata->already_suspended) + pdata->already_suspended = 0; + } + + fsl_platform_set_ahb_burst(hcd); + ehci_testmode_init(hcd_to_ehci(hcd)); + return retval; + +err4: + iounmap(hcd->regs); +err3: + if (pdata->operating_mode != FSL_USB2_DR_OTG) + release_mem_region(hcd->rsrc_start, hcd->rsrc_len); +err2: + usb_put_hcd(hcd); +err1: + dev_err(&pdev->dev, "init %s fail, %d\n", dev_name(&pdev->dev), retval); + if (pdata->platform_uninit) + pdata->platform_uninit(pdata); + return retval; +} + +/* may be called without controller electrically present */ +/* may be called with controller, bus, and devices active */ + +/** + * usb_hcd_fsl_remove - shutdown processing for FSL-based HCDs + * @dev: USB Host Controller being removed + * Context: !in_interrupt() + * + * Reverses the effect of usb_hcd_fsl_probe(). + * + */ +static void usb_hcd_fsl_remove(struct usb_hcd *hcd, + struct platform_device *pdev) +{ + struct ehci_hcd *ehci = hcd_to_ehci(hcd); + struct fsl_usb2_platform_data *pdata = pdev->dev.platform_data; + u32 tmp; + + if (!test_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags)) { + /* Need open clock for register access */ + if (pdata->usb_clock_for_pm) + pdata->usb_clock_for_pm(true); + + tmp = ehci_readl(ehci, &ehci->regs->port_status[0]); + if (tmp & PORT_PTS_PHCD) { + tmp &= ~PORT_PTS_PHCD; + ehci_writel(ehci, tmp, &ehci->regs->port_status[0]); + msleep(100); + + if (pdata->usb_clock_for_pm) + pdata->usb_clock_for_pm(false); + } + } + + /* DDD shouldn't we turn off the power here? */ + fsl_platform_set_vbus_power(pdata, 0); + + if (ehci->transceiver) { + (void)otg_set_host(ehci->transceiver, 0); + otg_put_transceiver(ehci->transceiver); + } else { + release_mem_region(hcd->rsrc_start, hcd->rsrc_len); + } + + usb_remove_hcd(hcd); + usb_put_hcd(hcd); + + /* + * do platform specific un-initialization: + * release iomux pins, etc. + */ + if (pdata->platform_uninit) + pdata->platform_uninit(pdata); + + iounmap(hcd->regs); +} + +static void fsl_setup_phy(struct ehci_hcd *ehci, + enum fsl_usb2_phy_modes phy_mode, int port_offset) +{ + u32 portsc; + + portsc = ehci_readl(ehci, &ehci->regs->port_status[port_offset]); + portsc &= ~(PORT_PTS_MSK | PORT_PTS_PTW); + + switch (phy_mode) { + case FSL_USB2_PHY_ULPI: + portsc |= PORT_PTS_ULPI; + break; + case FSL_USB2_PHY_SERIAL: + portsc |= PORT_PTS_SERIAL; + break; + case FSL_USB2_PHY_UTMI_WIDE: + portsc |= PORT_PTS_PTW; + /* fall through */ + case FSL_USB2_PHY_UTMI: + portsc |= PORT_PTS_UTMI; + break; + case FSL_USB2_PHY_NONE: + break; + } + ehci_writel(ehci, portsc, &ehci->regs->port_status[port_offset]); +} + +/* called after powerup, by probe or system-pm "wakeup" */ +static int ehci_fsl_reinit(struct ehci_hcd *ehci) +{ + fsl_platform_usb_setup(ehci); + ehci_port_power(ehci, 0); + + return 0; +} + +/* called during probe() after chip reset completes */ +static int ehci_fsl_setup(struct usb_hcd *hcd) +{ + struct ehci_hcd *ehci = hcd_to_ehci(hcd); + int retval; + + /* EHCI registers start at offset 0x100 */ + ehci->caps = hcd->regs + 0x100; + ehci->regs = hcd->regs + 0x100 + + HC_LENGTH(ehci_readl(ehci, &ehci->caps->hc_capbase)); + dbg_hcs_params(ehci, "reset"); + dbg_hcc_params(ehci, "reset"); + + /* cache this readonly data; minimize chip reads */ + ehci->hcs_params = ehci_readl(ehci, &ehci->caps->hcs_params); + + retval = ehci_halt(ehci); + if (retval) + return retval; + + /* data structure init */ + retval = ehci_init(hcd); + if (retval) + return retval; + + hcd->has_tt = 1; + + ehci->sbrn = 0x20; + + ehci_reset(ehci); + + retval = ehci_fsl_reinit(ehci); + return retval; +} + +static int ehci_fsl_bus_suspend(struct usb_hcd *hcd) +{ + u32 temp; + int rc; + struct fsl_usb2_platform_data *pdata = hcd->self.controller->platform_data; + + if ((pdata->operating_mode == FSL_USB2_DR_OTG) || + (pdata->operating_mode == FSL_USB2_DR_DEVICE)) + return -EBUSY; + + rc = ehci_bus_suspend(hcd); + + if (!rc && device_may_wakeup(hcd->self.controller)) { + clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags); + /* enable remote wake up irq */ + if (pdata->wake_up_enable) + pdata->wake_up_enable(pdata, true); + + /* Put PHY into low power mode */ + temp = readl(hcd->regs + 0x184); + writel(temp | (1 << 23), (hcd->regs + 0x184)); + + if (pdata->usb_clock_for_pm) + pdata->usb_clock_for_pm(false); + } + return rc; +} + +static int ehci_fsl_bus_resume(struct usb_hcd *hcd) +{ + u32 temp; + + if (device_may_wakeup(hcd->self.controller)) { + temp = readl(hcd->regs + 0x184); + writel(temp & (~(1 << 23)), (hcd->regs + 0x184)); + } + return ehci_bus_resume(hcd); +} + +int usb_host_wakeup_irq(struct device *wkup_dev); + +static irqreturn_t ehci_fsl_irq(struct usb_hcd *hcd) +{ + struct fsl_usb2_platform_data *pdata = hcd->self.controller->platform_data; + + if (pdata->usb_clock_for_pm) + pdata->usb_clock_for_pm(true); + + /* if receive a remote wakeup interrrupt after suspend */ + if (usb_host_wakeup_irq(hcd->self.controller)) { + /* disable remote wake up irq */ + if (pdata->wake_up_enable) + pdata->wake_up_enable(pdata, false); + + set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags); + } + + return ehci_irq(hcd); +} + +#ifdef CONFIG_USB_OTG +static int ehci_start_port_reset(struct usb_hcd *hcd, unsigned port) +{ + struct ehci_hcd *ehci = hcd_to_ehci(hcd); + u32 status; + + if (!port) + return -EINVAL; + port--; + + /* start port reset before HNP protocol time out */ + status = readl(&ehci->regs->port_status[port]); + if (!(status & PORT_CONNECT)) + return -ENODEV; + + /* khubd will finish the reset later */ + if (ehci_is_TDI(ehci)) + writel(PORT_RESET | (status & ~(PORT_CSC | PORT_PEC + | PORT_OCC)), &ehci->regs->port_status[port]); + else + writel(PORT_RESET, &ehci->regs->port_status[port]); + + return 0; +} +#else +static int ehci_start_port_reset(struct usb_hcd *hcd, unsigned port) +{ + return 0; +} +#endif /* CONFIG_USB_OTG */ + +static const struct hc_driver ehci_fsl_hc_driver = { + .description = hcd_name, + .product_desc = "Freescale On-Chip EHCI Host Controller", + .hcd_priv_size = sizeof(struct ehci_hcd), + + /* + * generic hardware linkage + */ + .irq = ehci_fsl_irq, + .flags = HCD_USB2, + + /* + * basic lifecycle operations + */ + .reset = ehci_fsl_setup, + .start = ehci_run, + .stop = ehci_stop, + .shutdown = ehci_shutdown, + + /* + * managing i/o requests and associated device resources + */ + .urb_enqueue = ehci_urb_enqueue, + .urb_dequeue = ehci_urb_dequeue, + .endpoint_disable = ehci_endpoint_disable, + .endpoint_reset = ehci_endpoint_reset, + + /* + * scheduling support + */ + .get_frame_number = ehci_get_frame, + + /* + * root hub support + */ + .hub_status_data = ehci_hub_status_data, + .hub_control = ehci_hub_control, + .bus_suspend = ehci_fsl_bus_suspend, + .bus_resume = ehci_fsl_bus_resume, + .start_port_reset = ehci_start_port_reset, + .relinquish_port = ehci_relinquish_port, + .port_handed_over = ehci_port_handed_over, + + .clear_tt_buffer_complete = ehci_clear_tt_buffer_complete, +}; + +static int ehci_fsl_drv_probe(struct platform_device *pdev) +{ + if (usb_disabled()) + return -ENODEV; + + /* FIXME we only want one one probe() not two */ + return usb_hcd_fsl_probe(&ehci_fsl_hc_driver, pdev); +} + +static int ehci_fsl_drv_remove(struct platform_device *pdev) +{ + struct usb_hcd *hcd = platform_get_drvdata(pdev); + + /* FIXME we only want one one remove() not two */ + usb_hcd_fsl_remove(hcd, pdev); + return 0; +} + +#ifdef CONFIG_PM +/* suspend/resume, section 4.3 */ + +/* These routines rely on the bus (pci, platform, etc) + * to handle powerdown and wakeup, and currently also on + * transceivers that don't need any software attention to set up + * the right sort of wakeup. + * + * They're also used for turning on/off the port when doing OTG. + */ +static int ehci_fsl_drv_suspend(struct platform_device *pdev, + pm_message_t message) +{ + struct usb_hcd *hcd = platform_get_drvdata(pdev); + struct ehci_hcd *ehci = hcd_to_ehci(hcd); + u32 tmp, port_status; + struct fsl_usb2_platform_data *pdata = pdev->dev.platform_data; + + if (device_may_wakeup(&(pdev->dev))) { + /* Need open clock for register access */ + if (pdata->usb_clock_for_pm) + pdata->usb_clock_for_pm(true); + } + +#ifdef DEBUG + u32 mode = ehci_readl(ehci, hcd->regs + FSL_SOC_USB_USBMODE); + mode &= USBMODE_CM_MASK; + tmp = ehci_readl(ehci, hcd->regs + 0x140); /* usbcmd */ + + printk(KERN_DEBUG "%s('%s'): suspend=%d already_suspended=%d " + "mode=%d usbcmd %08x\n", __func__, pdata->name, + pdata->suspended, pdata->already_suspended, mode, tmp); +#endif + + /* + * If the controller is already suspended, then this must be a + * PM suspend. Remember this fact, so that we will leave the + * controller suspended at PM resume time. + */ + if (pdata->suspended) { + pr_debug("%s: already suspended, leaving early\n", __func__); + pdata->already_suspended = 1; + goto err1; + } + + pr_debug("%s: suspending...\n", __func__); + + printk(KERN_INFO "USB Host suspended\n"); + + port_status = ehci_readl(ehci, &ehci->regs->port_status[0]); + pdev->dev.power.power_state = PMSG_SUSPEND; + + /* save EHCI registers */ + pdata->pm_command = ehci_readl(ehci, &ehci->regs->command); + pdata->pm_command &= ~CMD_RUN; + pdata->pm_status = ehci_readl(ehci, &ehci->regs->status); + pdata->pm_intr_enable = ehci_readl(ehci, &ehci->regs->intr_enable); + pdata->pm_frame_index = ehci_readl(ehci, &ehci->regs->frame_index); + pdata->pm_segment = ehci_readl(ehci, &ehci->regs->segment); + pdata->pm_frame_list = ehci_readl(ehci, &ehci->regs->frame_list); + pdata->pm_async_next = ehci_readl(ehci, &ehci->regs->async_next); + pdata->pm_configured_flag = + ehci_readl(ehci, &ehci->regs->configured_flag); + pdata->pm_portsc = ehci_readl(ehci, &ehci->regs->port_status[0]); + + /* clear the W1C bits */ + pdata->pm_portsc &= cpu_to_hc32(ehci, ~PORT_RWC_BITS); + + /* clear PHCD bit */ + pdata->pm_portsc &= ~PORT_PTS_PHCD; + + pdata->suspended = 1; + + if (!device_may_wakeup(&(pdev->dev))) { + /* ignore non-host interrupts */ + clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags); + + /* clear PP to cut power to the port */ + tmp = ehci_readl(ehci, &ehci->regs->port_status[0]); + tmp &= ~PORT_POWER; + ehci_writel(ehci, tmp, &ehci->regs->port_status[0]); + goto err1; + } + + tmp = ehci_readl(ehci, &ehci->regs->port_status[0]); + + if (pdata->platform_suspend) + pdata->platform_suspend(pdata); +err1: + if (device_may_wakeup(&(pdev->dev))) { + if (pdata->usb_clock_for_pm) + pdata->usb_clock_for_pm(false); + } + return 0; +} + +static int ehci_fsl_drv_resume(struct platform_device *pdev) +{ + struct usb_hcd *hcd = platform_get_drvdata(pdev); + struct ehci_hcd *ehci = hcd_to_ehci(hcd); + u32 tmp; + struct fsl_usb2_platform_data *pdata = pdev->dev.platform_data; + + pr_debug("%s('%s'): suspend=%d already_suspended=%d\n", __func__, + pdata->name, pdata->suspended, pdata->already_suspended); + + /* + * If the controller was already suspended at suspend time, + * then don't resume it now. + */ + if (pdata->already_suspended) { + pr_debug("already suspended, leaving early\n"); + pdata->already_suspended = 0; + return 0; + } + + if (!pdata->suspended) { + pr_debug("not suspended, leaving early\n"); + return 0; + } + + /* If hcd is resumed by non-usb wakeup events, + * then usb clocks are still not open when come here */ + if (device_may_wakeup(&(pdev->dev))) { + /* Need open clock for register access */ + if (pdata->usb_clock_for_pm) + pdata->usb_clock_for_pm(true); + } + + tmp = ehci_readl(ehci, &ehci->regs->port_status[0]); + + pdata->suspended = 0; + + pr_debug("%s resuming...\n", __func__); + + /* set host mode */ + fsl_platform_set_host_mode(hcd); + + if (pdata->platform_resume) + pdata->platform_resume(pdata); + + /* restore EHCI registers */ + ehci_writel(ehci, pdata->pm_portsc, &ehci->regs->port_status[0]); + ehci_writel(ehci, pdata->pm_command, &ehci->regs->command); + ehci_writel(ehci, pdata->pm_intr_enable, &ehci->regs->intr_enable); + ehci_writel(ehci, pdata->pm_frame_index, &ehci->regs->frame_index); + ehci_writel(ehci, pdata->pm_segment, &ehci->regs->segment); + ehci_writel(ehci, pdata->pm_frame_list, &ehci->regs->frame_list); + ehci_writel(ehci, pdata->pm_async_next, &ehci->regs->async_next); + ehci_writel(ehci, pdata->pm_configured_flag, + &ehci->regs->configured_flag); + + /* set bit should be done by wakeup irq routine if may wakeup */ + if (!device_may_wakeup(&(pdev->dev))) + set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags); + else + while (!test_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags)) + msleep(1); + + pdev->dev.power.power_state = PMSG_ON; + + tmp = ehci_readl(ehci, &ehci->regs->command); + tmp |= CMD_RUN; + ehci_writel(ehci, tmp, &ehci->regs->command); + + usb_hcd_resume_root_hub(hcd); + + printk(KERN_INFO "USB Host resumed\n"); + + if (device_may_wakeup(&(pdev->dev))) { + if (pdata->usb_clock_for_pm) + pdata->usb_clock_for_pm(false); + } + + return 0; +} +#endif /* CONFIG_USB_OTG */ + +MODULE_ALIAS("platform:fsl-ehci"); + +static struct platform_driver ehci_fsl_driver = { + .probe = ehci_fsl_drv_probe, + .remove = ehci_fsl_drv_remove, + .shutdown = usb_hcd_platform_shutdown, +#ifdef CONFIG_PM + .suspend = ehci_fsl_drv_suspend, + .resume = ehci_fsl_drv_resume, +#endif + .driver = { + .name = "fsl-ehci", + }, +}; diff --git a/drivers/usb/host/ehci-fsl.h b/drivers/usb/host/ehci-fsl.h index b5e59db53347..8a12eec68a90 100644 --- a/drivers/usb/host/ehci-fsl.h +++ b/drivers/usb/host/ehci-fsl.h @@ -19,6 +19,9 @@ #define _EHCI_FSL_H /* offsets for the non-ehci registers in the FSL SOC USB controller */ +#define FSL_SOC_USB_SBUSCFG 0x90 +#define FSL_SOC_USB_BURSTSIZE 0x160 +#define FSL_SOC_USB_TXFILLTUNING 0x164 #define FSL_SOC_USB_ULPIVP 0x170 #define FSL_SOC_USB_PORTSC1 0x184 #define PORT_PTS_MSK (3<<30) @@ -26,8 +29,12 @@ #define PORT_PTS_ULPI (2<<30) #define PORT_PTS_SERIAL (3<<30) #define PORT_PTS_PTW (1<<28) +#define PORT_PTS_PHCD (1<<23) #define FSL_SOC_USB_PORTSC2 0x188 #define FSL_SOC_USB_USBMODE 0x1a8 +#define USBMODE_CM_HOST (3 << 0) /* controller mode: host */ +#define USBMODE_ES (1 << 2) /* (Big) Endian Select */ + #define FSL_SOC_USB_SNOOP1 0x400 /* NOTE: big-endian */ #define FSL_SOC_USB_SNOOP2 0x404 /* NOTE: big-endian */ #define FSL_SOC_USB_AGECNTTHRSH 0x408 /* NOTE: big-endian */ diff --git a/drivers/usb/otg/Kconfig b/drivers/usb/otg/Kconfig index 3d2d3e549bd1..283e1b73d2dd 100644 --- a/drivers/usb/otg/Kconfig +++ b/drivers/usb/otg/Kconfig @@ -69,4 +69,11 @@ config NOP_USB_XCEIV built-in with usb ip or which are autonomous and doesn't require any phy programming such as ISP1x04 etc. +config MXC_OTG + tristate "USB OTG pin detect support" + select USB_OTG + depends on USB_GADGET_ARC && USB_EHCI_HCD + help + Support for USB OTG PIN detect on MXC platforms. + endif # USB || OTG diff --git a/drivers/usb/otg/Makefile b/drivers/usb/otg/Makefile index aeb49a8ec412..7b18165652dc 100644 --- a/drivers/usb/otg/Makefile +++ b/drivers/usb/otg/Makefile @@ -11,6 +11,8 @@ obj-$(CONFIG_ISP1301_OMAP) += isp1301_omap.o obj-$(CONFIG_TWL4030_USB) += twl4030-usb.o obj-$(CONFIG_NOP_USB_XCEIV) += nop-usb-xceiv.o obj-$(CONFIG_USB_ULPI) += ulpi.o +fsl_otg_arc-objs := fsl_otg.o otg_fsm.o +obj-$(CONFIG_MXC_OTG) += fsl_otg_arc.o ccflags-$(CONFIG_USB_DEBUG) += -DDEBUG ccflags-$(CONFIG_USB_GADGET_DEBUG) += -DDEBUG diff --git a/drivers/usb/otg/fsl_otg.c b/drivers/usb/otg/fsl_otg.c new file mode 100644 index 000000000000..656b95014187 --- /dev/null +++ b/drivers/usb/otg/fsl_otg.c @@ -0,0 +1,1300 @@ +/* + * Copyright (C) 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + * + * Author: Li Yang + * Jerry Huang + * + * Initialization based on code from Shlomi Gridish. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include "fsl_otg.h" + +#define CONFIG_USB_OTG_DEBUG_FILES +#define DRIVER_VERSION "$Revision: 1.55 $" +#define DRIVER_AUTHOR "Jerry Huang/Li Yang" +#define DRIVER_DESC "Freescale USB OTG Driver" +#define DRIVER_INFO DRIVER_VERSION " " DRIVER_DESC + + +MODULE_DESCRIPTION("Freescale USB OTG Transceiver Driver"); + +static const char driver_name[] = "fsl-usb2-otg"; + +const pm_message_t otg_suspend_state = { + .event = 1, +}; + +#define HA_DATA_PULSE 1 + +volatile static struct usb_dr_mmap *usb_dr_regs; +static struct fsl_otg *fsl_otg_dev; +static int srp_wait_done; +static int gpio_id; +/* FSM timers */ +struct fsl_otg_timer *a_wait_vrise_tmr, *a_wait_bcon_tmr, *a_aidl_bdis_tmr, + *b_ase0_brst_tmr, *b_se0_srp_tmr; + +/* Driver specific timers */ +struct fsl_otg_timer *b_data_pulse_tmr, *b_vbus_pulse_tmr, *b_srp_fail_tmr, + *b_srp_wait_tmr, *a_wait_enum_tmr; + +static struct list_head active_timers; + +static struct fsl_otg_config fsl_otg_initdata = { + .otg_port = 1, +}; + +int write_ulpi(u8 addr, u8 data) +{ + u32 temp; + temp = 0x60000000 | (addr << 16) | data; + temp = cpu_to_le32(temp); + usb_dr_regs->ulpiview = temp; + return 0; +} + +/* prototype declaration */ +void fsl_otg_add_timer(void *timer); +void fsl_otg_del_timer(void *timer); + +/* -------------------------------------------------------------*/ +/* Operations that will be called from OTG Finite State Machine */ + +/* Charge vbus for vbus pulsing in SRP */ +void fsl_otg_chrg_vbus(int on) +{ + if (on) + usb_dr_regs->otgsc = + cpu_to_le32((le32_to_cpu(usb_dr_regs->otgsc) & + ~OTGSC_INTSTS_MASK & + ~OTGSC_CTRL_VBUS_DISCHARGE) | + OTGSC_CTRL_VBUS_CHARGE); + else + usb_dr_regs->otgsc = + cpu_to_le32((le32_to_cpu(usb_dr_regs->otgsc) & + ~OTGSC_INTSTS_MASK & ~OTGSC_CTRL_VBUS_CHARGE)); +} + +/* Discharge vbus through a resistor to ground */ +void fsl_otg_dischrg_vbus(int on) +{ + if (on) + usb_dr_regs->otgsc = + cpu_to_le32((le32_to_cpu(usb_dr_regs->otgsc) & + ~OTGSC_INTSTS_MASK) + | OTGSC_CTRL_VBUS_DISCHARGE); + else + usb_dr_regs->otgsc = + cpu_to_le32((le32_to_cpu(usb_dr_regs->otgsc) & + ~OTGSC_INTSTS_MASK & + ~OTGSC_CTRL_VBUS_DISCHARGE)); +} + +/* A-device driver vbus, controlled through PP bit in PORTSC */ +void fsl_otg_drv_vbus(struct fsl_usb2_platform_data *pdata, int on) +{ +/* if (on) + usb_dr_regs->portsc = + cpu_to_le32((le32_to_cpu(usb_dr_regs->portsc) & + ~PORTSC_W1C_BITS) | PORTSC_PORT_POWER); + else + usb_dr_regs->portsc = + cpu_to_le32(le32_to_cpu(usb_dr_regs->portsc) & + ~PORTSC_W1C_BITS & ~PORTSC_PORT_POWER); +*/ + if (pdata->xcvr_ops && pdata->xcvr_ops->set_vbus_power) + pdata->xcvr_ops->set_vbus_power(pdata->xcvr_ops, pdata, on); +} + +/* + * Pull-up D+, signalling connect by periperal. Also used in + * data-line pulsing in SRP + */ +void fsl_otg_loc_conn(int on) +{ + if (on) + usb_dr_regs->otgsc = + cpu_to_le32((le32_to_cpu(usb_dr_regs->otgsc) & + ~OTGSC_INTSTS_MASK) | OTGSC_CTRL_DATA_PULSING); + else + usb_dr_regs->otgsc = + cpu_to_le32(le32_to_cpu(usb_dr_regs->otgsc) & + ~OTGSC_INTSTS_MASK & ~OTGSC_CTRL_DATA_PULSING); +} + +/* Generate SOF by host. This is controlled through suspend/resume the + * port. In host mode, controller will automatically send SOF. + * Suspend will block the data on the port. + */ +void fsl_otg_loc_sof(int on) +{ + u32 tmpval; + + tmpval = readl(&fsl_otg_dev->dr_mem_map->portsc) & ~PORTSC_W1C_BITS; + if (on) + tmpval |= PORTSC_PORT_FORCE_RESUME; + else + tmpval |= PORTSC_PORT_SUSPEND; + writel(tmpval, &fsl_otg_dev->dr_mem_map->portsc); + +} + +/* Start SRP pulsing by data-line pulsing, followed with v-bus pulsing. */ +void fsl_otg_start_pulse(void) +{ + srp_wait_done = 0; +#ifdef HA_DATA_PULSE + usb_dr_regs->otgsc = + cpu_to_le32((le32_to_cpu(usb_dr_regs->otgsc) & ~OTGSC_INTSTS_MASK) + | OTGSC_HA_DATA_PULSE); +#else + fsl_otg_loc_conn(1); +#endif + + fsl_otg_add_timer(b_data_pulse_tmr); +} + +void fsl_otg_pulse_vbus(void); + +void b_data_pulse_end(unsigned long foo) +{ +#ifdef HA_DATA_PULSE +#else + fsl_otg_loc_conn(0); +#endif + + /* Do VBUS pulse after data pulse */ + fsl_otg_pulse_vbus(); +} + +void fsl_otg_pulse_vbus(void) +{ + srp_wait_done = 0; + fsl_otg_chrg_vbus(1); + /* start the timer to end vbus charge */ + fsl_otg_add_timer(b_vbus_pulse_tmr); +} + +void b_vbus_pulse_end(unsigned long foo) +{ + fsl_otg_chrg_vbus(0); + + /* As USB3300 using the same a_sess_vld and b_sess_vld voltage + * we need to discharge the bus for a while to distinguish + * residual voltage of vbus pulsing and A device pull up */ + fsl_otg_dischrg_vbus(1); + fsl_otg_add_timer(b_srp_wait_tmr); +} + +void b_srp_end(unsigned long foo) +{ + fsl_otg_dischrg_vbus(0); + srp_wait_done = 1; + + if ((fsl_otg_dev->otg.state == OTG_STATE_B_SRP_INIT) && + fsl_otg_dev->fsm.b_sess_vld) + fsl_otg_dev->fsm.b_srp_done = 1; +} + +/* Workaround for a_host suspending too fast. When a_bus_req=0, + * a_host will start by SRP. It needs to set b_hnp_enable before + * actually suspending to start HNP + */ +void a_wait_enum(unsigned long foo) +{ + VDBG("a_wait_enum timeout\n"); + if (!fsl_otg_dev->otg.host->b_hnp_enable) + fsl_otg_add_timer(a_wait_enum_tmr); + else + otg_statemachine(&fsl_otg_dev->fsm); +} + +/* ------------------------------------------------------*/ + +/* The timeout callback function to set time out bit */ +void set_tmout(unsigned long indicator) +{ + *(int *)indicator = 1; +} + +/* Initialize timers */ +int fsl_otg_init_timers(struct otg_fsm *fsm) +{ + /* FSM used timers */ + a_wait_vrise_tmr = otg_timer_initializer(&set_tmout, TA_WAIT_VRISE, + (unsigned long)&fsm->a_wait_vrise_tmout); + if (a_wait_vrise_tmr == NULL) + return -ENOMEM; + + a_wait_bcon_tmr = otg_timer_initializer(&set_tmout, TA_WAIT_BCON, + (unsigned long)&fsm->a_wait_bcon_tmout); + if (a_wait_bcon_tmr == NULL) + return -ENOMEM; + + a_aidl_bdis_tmr = otg_timer_initializer(&set_tmout, TA_AIDL_BDIS, + (unsigned long)&fsm->a_aidl_bdis_tmout); + if (a_aidl_bdis_tmr == NULL) + return -ENOMEM; + + b_ase0_brst_tmr = otg_timer_initializer(&set_tmout, TB_ASE0_BRST, + (unsigned long)&fsm->b_ase0_brst_tmout); + if (b_ase0_brst_tmr == NULL) + return -ENOMEM; + + b_se0_srp_tmr = otg_timer_initializer(&set_tmout, TB_SE0_SRP, + (unsigned long)&fsm->b_se0_srp); + if (b_se0_srp_tmr == NULL) + return -ENOMEM; + + b_srp_fail_tmr = otg_timer_initializer(&set_tmout, TB_SRP_FAIL, + (unsigned long)&fsm->b_srp_done); + if (b_srp_fail_tmr == NULL) + return -ENOMEM; + + a_wait_enum_tmr = otg_timer_initializer(&a_wait_enum, 10, + (unsigned long)&fsm); + if (a_wait_enum_tmr == NULL) + return -ENOMEM; + + /* device driver used timers */ + b_srp_wait_tmr = otg_timer_initializer(&b_srp_end, TB_SRP_WAIT, 0); + if (b_srp_wait_tmr == NULL) + return -ENOMEM; + + b_data_pulse_tmr = otg_timer_initializer(&b_data_pulse_end, + TB_DATA_PLS, 0); + if (b_data_pulse_tmr == NULL) + return -ENOMEM; + + b_vbus_pulse_tmr = otg_timer_initializer(&b_vbus_pulse_end, + TB_VBUS_PLS, 0); + if (b_vbus_pulse_tmr == NULL) + return -ENOMEM; + + return 0; +} + +/* Uninitialize timers */ +void fsl_otg_uninit_timers(void) +{ + /* FSM used timers */ + if (a_wait_vrise_tmr != NULL) + kfree(a_wait_vrise_tmr); + if (a_wait_bcon_tmr != NULL) + kfree(a_wait_bcon_tmr); + if (a_aidl_bdis_tmr != NULL) + kfree(a_aidl_bdis_tmr); + if (b_ase0_brst_tmr != NULL) + kfree(b_ase0_brst_tmr); + if (b_se0_srp_tmr != NULL) + kfree(b_se0_srp_tmr); + if (b_srp_fail_tmr != NULL) + kfree(b_srp_fail_tmr); + if (a_wait_enum_tmr != NULL) + kfree(a_wait_enum_tmr); + + /* device driver used timers */ + if (b_srp_wait_tmr != NULL) + kfree(b_srp_wait_tmr); + if (b_data_pulse_tmr != NULL) + kfree(b_data_pulse_tmr); + if (b_vbus_pulse_tmr != NULL) + kfree(b_vbus_pulse_tmr); +} + +/* Add timer to timer list */ +void fsl_otg_add_timer(void *gtimer) +{ + struct fsl_otg_timer *timer = (struct fsl_otg_timer *)gtimer; + struct fsl_otg_timer *tmp_timer; + + /* Check if the timer is already in the active list, + * if so update timer count + */ + list_for_each_entry(tmp_timer, &active_timers, list) + if (tmp_timer == timer) { + timer->count = timer->expires; + return; + } + timer->count = timer->expires; + list_add_tail(&timer->list, &active_timers); +} + +/* Remove timer from the timer list; clear timeout status */ +void fsl_otg_del_timer(void *gtimer) +{ + struct fsl_otg_timer *timer = (struct fsl_otg_timer *)gtimer; + struct fsl_otg_timer *tmp_timer, *del_tmp; + + list_for_each_entry_safe(tmp_timer, del_tmp, &active_timers, list) + if (tmp_timer == timer) + list_del(&timer->list); +} + +/* Reduce timer count by 1, and find timeout conditions. + * Called by fsl_otg 1ms timer interrupt + */ +int fsl_otg_tick_timer(void) +{ + struct fsl_otg_timer *tmp_timer, *del_tmp; + int expired = 0; + + list_for_each_entry_safe(tmp_timer, del_tmp, &active_timers, list) { + tmp_timer->count--; + /* check if timer expires */ + if (!tmp_timer->count) { + list_del(&tmp_timer->list); + tmp_timer->function(tmp_timer->data); + expired = 1; + } + } + + return expired; +} + +/* Reset controller, not reset the bus */ +void otg_reset_controller(void) +{ + u32 command; + + command = readl(&usb_dr_regs->usbcmd); + command |= (1 << 1); + writel(command, &usb_dr_regs->usbcmd); + while (readl(&usb_dr_regs->usbcmd) & (1 << 1)) + ; +} + +/* Call suspend/resume routines in host driver */ +int fsl_otg_start_host(struct otg_fsm *fsm, int on) +{ + struct otg_transceiver *xceiv = fsm->transceiver; + struct device *dev; + struct fsl_otg *otg_dev = container_of(xceiv, struct fsl_otg, otg); + struct platform_driver *host_pdrv; + struct platform_device *host_pdev; + u32 retval = 0; + + if (!xceiv->host) + return -ENODEV; + dev = xceiv->host->controller; + host_pdrv = container_of((dev->driver), struct platform_driver, driver); + host_pdev = to_platform_device(dev); + + /* Update a_vbus_vld state as a_vbus_vld int is disabled + * in device mode + */ + fsm->a_vbus_vld = + (le32_to_cpu(usb_dr_regs->otgsc) & OTGSC_STS_A_VBUS_VALID) ? 1 : 0; + if (on) { + /* start fsl usb host controller */ + if (otg_dev->host_working) + goto end; + else { + otg_reset_controller(); + VDBG("host on......\n"); + if (host_pdrv->resume) { + retval = host_pdrv->resume(host_pdev); + if (fsm->id) { + /* default-b */ + fsl_otg_drv_vbus(dev->platform_data, 1); + /* Workaround: b_host can't driver + * vbus, but PP in PORTSC needs to + * be 1 for host to work. + * So we set drv_vbus bit in + * transceiver to 0 thru ULPI. */ +#if defined(CONFIG_ISP1504_MXC) + write_ulpi(0x0c, 0x20); +#endif + } + } + + otg_dev->host_working = 1; + } + } else { + /* stop fsl usb host controller */ + if (!otg_dev->host_working) + goto end; + else { + VDBG("host off......\n"); + if (host_pdrv->suspend) { + retval = host_pdrv->suspend(host_pdev, + otg_suspend_state); + if (fsm->id) + /* default-b */ + fsl_otg_drv_vbus(dev->platform_data, 0); + } + otg_dev->host_working = 0; + } + } +end: + return retval; +} + +/* Call suspend and resume function in udc driver + * to stop and start udc driver. + */ +int fsl_otg_start_gadget(struct otg_fsm *fsm, int on) +{ + struct otg_transceiver *xceiv = fsm->transceiver; + struct device *dev; + struct platform_driver *gadget_pdrv; + struct platform_device *gadget_pdev; + + if (!xceiv->gadget || !xceiv->gadget->dev.parent) + return -ENODEV; + + VDBG("gadget %s \n", on ? "on" : "off"); + dev = xceiv->gadget->dev.parent; + + gadget_pdrv = container_of((dev->driver), + struct platform_driver, driver); + gadget_pdev = to_platform_device(dev); + + if (on) + gadget_pdrv->resume(gadget_pdev); + else + gadget_pdrv->suspend(gadget_pdev, otg_suspend_state); + + return 0; +} + +/* Called by initialization code of host driver. Register host controller + * to the OTG. Suspend host for OTG role detection. + */ +static int fsl_otg_set_host(struct otg_transceiver *otg_p, struct usb_bus *host) +{ + struct fsl_otg *otg_dev = container_of(otg_p, struct fsl_otg, otg); + + if (!otg_p || otg_dev != fsl_otg_dev) + return -ENODEV; + + otg_p->host = host; + + otg_dev->fsm.a_bus_drop = 0; + otg_dev->fsm.a_bus_req = 1; + + if (host) { + VDBG("host off......\n"); + + otg_p->host->otg_port = fsl_otg_initdata.otg_port; + otg_p->host->is_b_host = otg_dev->fsm.id; + /* must leave time for khubd to finish its thing + * before yanking the host driver out from under it, + * so suspend the host after a short delay. + */ + otg_dev->host_working = 1; + schedule_delayed_work(&otg_dev->otg_event, 100); + return 0; + } else { /* host driver going away */ + + if (!(le32_to_cpu(otg_dev->dr_mem_map->otgsc) & + OTGSC_STS_USB_ID)) { + /* Mini-A cable connected */ + struct otg_fsm *fsm = &otg_dev->fsm; + + otg_p->state = OTG_STATE_UNDEFINED; + fsm->protocol = PROTO_UNDEF; + } + if (gpio_id) { + if (gpio_get_value(gpio_id)) { + struct otg_fsm *fsm = &otg_dev->fsm; + otg_p->state = OTG_STATE_UNDEFINED; + fsm->protocol = PROTO_UNDEF; + } + } + } + + otg_dev->host_working = 0; + + otg_statemachine(&otg_dev->fsm); + + return 0; +} + +/* Called by initialization code of udc. Register udc to OTG.*/ +static int fsl_otg_set_peripheral(struct otg_transceiver *otg_p, + struct usb_gadget *gadget) +{ + struct fsl_otg *otg_dev = container_of(otg_p, struct fsl_otg, otg); + + VDBG("otg_dev 0x%x\n", (int)otg_dev); + VDBG("fsl_otg_dev 0x%x\n", (int)fsl_otg_dev); + + if (!otg_p || otg_dev != fsl_otg_dev) + return -ENODEV; + + if (!gadget) { + if (!otg_dev->otg.default_a) + otg_p->gadget->ops->vbus_draw(otg_p->gadget, 0); + usb_gadget_vbus_disconnect(otg_dev->otg.gadget); + otg_dev->otg.gadget = 0; + otg_dev->fsm.b_bus_req = 0; + otg_statemachine(&otg_dev->fsm); + return 0; + } +#ifdef DEBUG + /* + * debug the initial state of the ID pin when only + * the gadget driver is loaded and no cable is connected. + * sometimes, we get an ID irq right + * after the udc driver's otg_get_transceiver() call + * that indicates that IDpin=0, which means a Mini-A + * connector is attached. not good. + */ + DBG("before: fsm.id ID pin=%d", otg_dev->fsm.id); + otg_dev->fsm.id = (otg_dev->dr_mem_map->otgsc & OTGSC_STS_USB_ID) ? + 1 : 0; + DBG("after: fsm.id ID pin=%d", otg_dev->fsm.id); + /*if (!otg_dev->fsm.id) { + printk("OTG Control = 0x%x\n", + isp1504_read(ISP1504_OTGCTL, + &otg_dev->dr_mem_map->ulpiview)); + } */ +#endif + + otg_p->gadget = gadget; + otg_p->gadget->is_a_peripheral = !otg_dev->fsm.id; + + otg_dev->fsm.b_bus_req = 1; + + /* start the gadget right away if the ID pin says Mini-B */ + DBG("ID pin=%d\n", otg_dev->fsm.id); + if (otg_dev->fsm.id == 1) { + fsl_otg_start_host(&otg_dev->fsm, 0); + otg_drv_vbus(&otg_dev->fsm, 0); + fsl_otg_start_gadget(&otg_dev->fsm, 1); + } + + return 0; +} + +/* Set OTG port power, only for B-device */ +static int fsl_otg_set_power(struct otg_transceiver *otg_p, unsigned mA) +{ + if (!fsl_otg_dev) + return -ENODEV; + if (otg_p->state == OTG_STATE_B_PERIPHERAL) + printk(KERN_INFO "FSL OTG:Draw %d mA\n", mA); + + return 0; +} + +/* Delayed pin detect interrupt processing. + * + * When the Mini-A cable is disconnected from the board, + * the pin-detect interrupt happens before the disconnnect + * interrupts for the connected device(s). In order to + * process the disconnect interrupt(s) prior to switching + * roles, the pin-detect interrupts are delayed, and handled + * by this routine. + */ +static void fsl_otg_event(struct work_struct *work) +{ + struct fsl_otg *og = container_of(work, struct fsl_otg, otg_event.work); + struct otg_fsm *fsm = &og->fsm; + + if (fsm->id) { /* switch to gadget */ + fsl_otg_start_host(fsm, 0); + otg_drv_vbus(fsm, 0); + fsl_otg_start_gadget(fsm, 1); + } +} + +/* B-device start SRP */ +static int fsl_otg_start_srp(struct otg_transceiver *otg_p) +{ + struct fsl_otg *otg_dev = container_of(otg_p, struct fsl_otg, otg); + + if (!otg_p || otg_dev != fsl_otg_dev + || otg_p->state != OTG_STATE_B_IDLE) + return -ENODEV; + + otg_dev->fsm.b_bus_req = 1; + otg_statemachine(&otg_dev->fsm); + + return 0; +} + +/* A_host suspend will call this function to start hnp */ +static int fsl_otg_start_hnp(struct otg_transceiver *otg_p) +{ + struct fsl_otg *otg_dev = container_of(otg_p, struct fsl_otg, otg); + + if (!otg_p || otg_dev != fsl_otg_dev) + return -ENODEV; + + /* printk("start_hnp.............\n"); */ + /* clear a_bus_req to enter a_suspend state */ + otg_dev->fsm.a_bus_req = 0; + otg_statemachine(&otg_dev->fsm); + + return 0; +} +/* Interrupt handler for gpio id pin */ +irqreturn_t fsl_otg_isr_gpio(int irq, void *dev_id) +{ + struct otg_fsm *fsm; + struct fsl_usb2_platform_data *pdata = + (struct fsl_usb2_platform_data *)dev_id; + struct fsl_otg *p_otg; + struct otg_transceiver *otg_trans = otg_get_transceiver(); + p_otg = container_of(otg_trans, struct fsl_otg, otg); + fsm = &p_otg->fsm; + int value; + + if (pdata->id_gpio == 0) + return IRQ_NONE; + + value = gpio_get_value(pdata->id_gpio) ? 1 : 0; + + if (value) + set_irq_type(gpio_to_irq(pdata->id_gpio), IRQ_TYPE_LEVEL_LOW); + else + set_irq_type(gpio_to_irq(pdata->id_gpio), IRQ_TYPE_LEVEL_HIGH); + + + if (value == p_otg->fsm.id) + return IRQ_HANDLED; + + p_otg->fsm.id = value; + + otg_trans->default_a = (fsm->id == 0); + /* clear conn information */ + if (fsm->id) + fsm->b_conn = 0; + else + fsm->a_conn = 0; + + if (otg_trans->host) + otg_trans->host->is_b_host = fsm->id; + if (otg_trans->gadget) + otg_trans->gadget->is_a_peripheral = !fsm->id; + + VDBG("ID int (ID is %d)\n", fsm->id); + if (fsm->id) { /* switch to gadget */ + schedule_delayed_work(&p_otg->otg_event, 100); + + } else { /* switch to host */ + cancel_delayed_work(&p_otg->otg_event); + fsl_otg_start_gadget(fsm, 0); + otg_drv_vbus(fsm, 1); + fsl_otg_start_host(fsm, 1); + } + return IRQ_HANDLED; +} +/* Interrupt handler. OTG/host/peripheral share the same int line. + * OTG driver clears OTGSC interrupts and leaves USB interrupts + * intact. It needs to have knowledge of some USB interrupts + * such as port change. + */ +irqreturn_t fsl_otg_isr(int irq, void *dev_id) +{ + struct otg_fsm *fsm = &((struct fsl_otg *)dev_id)->fsm; + struct otg_transceiver *otg = &((struct fsl_otg *)dev_id)->otg; + u32 otg_int_src, otg_sc; + + otg_sc = le32_to_cpu(usb_dr_regs->otgsc); + otg_int_src = otg_sc & OTGSC_INTSTS_MASK & (otg_sc >> 8); + + /* Only clear otg interrupts */ + usb_dr_regs->otgsc |= cpu_to_le32(otg_sc & OTGSC_INTSTS_MASK); + + /*FIXME: ID change not generate when init to 0 */ + fsm->id = (otg_sc & OTGSC_STS_USB_ID) ? 1 : 0; + otg->default_a = (fsm->id == 0); + + /* process OTG interrupts */ + if (otg_int_src) { + if (otg_int_src & OTGSC_INTSTS_USB_ID) { + fsm->id = (otg_sc & OTGSC_STS_USB_ID) ? 1 : 0; + otg->default_a = (fsm->id == 0); + /* clear conn information */ + if (fsm->id) + fsm->b_conn = 0; + else + fsm->a_conn = 0; + + if (otg->host) + otg->host->is_b_host = fsm->id; + if (otg->gadget) + otg->gadget->is_a_peripheral = !fsm->id; + VDBG("ID int (ID is %d)\n", fsm->id); + + if (fsm->id) { /* switch to gadget */ + schedule_delayed_work(&((struct fsl_otg *) + dev_id)->otg_event, + 100); + } else { /* switch to host */ + cancel_delayed_work(& + ((struct fsl_otg *)dev_id)-> + otg_event); + fsl_otg_start_gadget(fsm, 0); + otg_drv_vbus(fsm, 1); + fsl_otg_start_host(fsm, 1); + } + + return IRQ_HANDLED; + } + } + + return IRQ_NONE; +} + +static void fsl_otg_fsm_drv_vbus(int on) +{ + struct otg_fsm *fsm = &(fsl_otg_dev->fsm); + struct otg_transceiver *xceiv = fsm->transceiver; + struct device *dev = xceiv->host->controller; + + fsl_otg_drv_vbus(dev->platform_data, on); + +} + +static struct otg_fsm_ops fsl_otg_ops = { + .chrg_vbus = fsl_otg_chrg_vbus, + .drv_vbus = fsl_otg_fsm_drv_vbus, + .loc_conn = fsl_otg_loc_conn, + .loc_sof = fsl_otg_loc_sof, + .start_pulse = fsl_otg_start_pulse, + + .add_timer = fsl_otg_add_timer, + .del_timer = fsl_otg_del_timer, + + .start_host = fsl_otg_start_host, + .start_gadget = fsl_otg_start_gadget, +}; + +/* Initialize the global variable fsl_otg_dev and request IRQ for OTG */ +static int fsl_otg_conf(struct platform_device *pdev) +{ + int status; + struct fsl_otg *fsl_otg_tc; + struct fsl_usb2_platform_data *pdata; + + pdata = pdev->dev.platform_data; + + DBG(); + + if (fsl_otg_dev) + return 0; + + /* allocate space to fsl otg device */ + fsl_otg_tc = kzalloc(sizeof(struct fsl_otg), GFP_KERNEL); + if (!fsl_otg_tc) + return -ENODEV; + + INIT_DELAYED_WORK(&fsl_otg_tc->otg_event, fsl_otg_event); + + INIT_LIST_HEAD(&active_timers); + status = fsl_otg_init_timers(&fsl_otg_tc->fsm); + if (status) { + printk(KERN_INFO "Couldn't init OTG timers\n"); + fsl_otg_uninit_timers(); + kfree(fsl_otg_tc); + return status; + } + spin_lock_init(&fsl_otg_tc->fsm.lock); + + /* Set OTG state machine operations */ + fsl_otg_tc->fsm.ops = &fsl_otg_ops; + + /* initialize the otg structure */ + fsl_otg_tc->otg.label = DRIVER_DESC; + fsl_otg_tc->otg.set_host = fsl_otg_set_host; + fsl_otg_tc->otg.set_peripheral = fsl_otg_set_peripheral; + fsl_otg_tc->otg.set_power = fsl_otg_set_power; + fsl_otg_tc->otg.start_hnp = fsl_otg_start_hnp; + fsl_otg_tc->otg.start_srp = fsl_otg_start_srp; + + fsl_otg_dev = fsl_otg_tc; + + /* Store the otg transceiver */ + status = otg_set_transceiver(&fsl_otg_tc->otg); + if (status) { + printk(KERN_WARNING ": unable to register OTG transceiver.\n"); + return status; + } + + return 0; +} + +/* OTG Initialization*/ +int usb_otg_start(struct platform_device *pdev) +{ + struct fsl_otg *p_otg; + struct otg_transceiver *otg_trans = otg_get_transceiver(); + struct otg_fsm *fsm; + volatile unsigned long *p; + int status; + struct resource *res; + u32 temp; + struct fsl_usb2_platform_data *pdata = pdev->dev.platform_data; + + p_otg = container_of(otg_trans, struct fsl_otg, otg); + fsm = &p_otg->fsm; + + /* Initialize the state machine structure with default values */ + SET_OTG_STATE(otg_trans, OTG_STATE_UNDEFINED); + fsm->transceiver = &p_otg->otg; + + /* We don't require predefined MEM/IRQ resource index */ + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!res) + return -ENXIO; + + /* We don't request_mem_region here to enable resource sharing + * with host/device */ + + usb_dr_regs = ioremap(res->start, sizeof(struct usb_dr_mmap)); + p_otg->dr_mem_map = (struct usb_dr_mmap *)usb_dr_regs; + pdata->regs = (void *)usb_dr_regs; + + gpio_id = pdata->id_gpio; + /* request irq */ + if (pdata->id_gpio == 0) { + p_otg->irq = platform_get_irq(pdev, 0); + status = request_irq(p_otg->irq, fsl_otg_isr, + IRQF_SHARED, driver_name, p_otg); + } else { + status = request_irq(gpio_to_irq(pdata->id_gpio), + fsl_otg_isr_gpio, + IRQF_SHARED, driver_name, pdata); + } + if (status) { + dev_dbg(p_otg->otg.dev, "can't get IRQ %d, error %d\n", + p_otg->irq, status); + iounmap(p_otg->dr_mem_map); + kfree(p_otg); + return status; + } + + if (pdata->platform_init && pdata->platform_init(pdev) != 0) + return -EINVAL; + + /* stop the controller */ + temp = readl(&p_otg->dr_mem_map->usbcmd); + temp &= ~USB_CMD_RUN_STOP; + writel(temp, &p_otg->dr_mem_map->usbcmd); + + /* reset the controller */ + temp = readl(&p_otg->dr_mem_map->usbcmd); + temp |= USB_CMD_CTRL_RESET; + writel(temp, &p_otg->dr_mem_map->usbcmd); + + /* wait reset completed */ + while (readl(&p_otg->dr_mem_map->usbcmd) & USB_CMD_CTRL_RESET) + ; + + /* configure the VBUSHS as IDLE(both host and device) */ + temp = USB_MODE_STREAM_DISABLE | (pdata->es ? USB_MODE_ES : 0); + writel(temp, &p_otg->dr_mem_map->usbmode); + + /* configure PHY interface */ + temp = readl(&p_otg->dr_mem_map->portsc); + temp &= ~(PORTSC_PHY_TYPE_SEL | PORTSC_PTW); + switch (pdata->phy_mode) { + case FSL_USB2_PHY_ULPI: + temp |= PORTSC_PTS_ULPI; + break; + case FSL_USB2_PHY_UTMI_WIDE: + temp |= PORTSC_PTW_16BIT; + /* fall through */ + case FSL_USB2_PHY_UTMI: + temp |= PORTSC_PTS_UTMI; + /* fall through */ + default: + break; + } + writel(temp, &p_otg->dr_mem_map->portsc); + + if (pdata->have_sysif_regs) { + /* configure control enable IO output, big endian register */ + p = (volatile unsigned long *)(&p_otg->dr_mem_map->control); + temp = *p; + temp |= USB_CTRL_IOENB; + *p = temp; + } + + /* disable all interrupt and clear all OTGSC status */ + temp = readl(&p_otg->dr_mem_map->otgsc); + temp &= ~OTGSC_INTERRUPT_ENABLE_BITS_MASK; + temp |= OTGSC_INTERRUPT_STATUS_BITS_MASK | OTGSC_CTRL_VBUS_DISCHARGE; + writel(temp, &p_otg->dr_mem_map->otgsc); + + + /* + * The identification (id) input is FALSE when a Mini-A plug is inserted + * in the devices Mini-AB receptacle. Otherwise, this input is TRUE. + * Also: record initial state of ID pin + */ + if (le32_to_cpu(p_otg->dr_mem_map->otgsc) & OTGSC_STS_USB_ID) { + p_otg->fsm.id = 1; + } else { + p_otg->fsm.id = 0; + } + + if (pdata->id_gpio != 0) { + p_otg->fsm.id = gpio_get_value(pdata->id_gpio) ? 1 : 0; + if (p_otg->fsm.id) + set_irq_type(gpio_to_irq(pdata->id_gpio), + IRQ_TYPE_LEVEL_LOW); + else + set_irq_type(gpio_to_irq(pdata->id_gpio), + IRQ_TYPE_LEVEL_HIGH); + } + p_otg->otg.state = p_otg->fsm.id ? OTG_STATE_UNDEFINED : + OTG_STATE_A_IDLE; + + DBG("initial ID pin=%d\n", p_otg->fsm.id); + + /* enable OTG ID pin interrupt */ + temp = readl(&p_otg->dr_mem_map->otgsc); + if (!pdata->id_gpio) + temp |= OTGSC_INTR_USB_ID_EN; + temp &= ~(OTGSC_CTRL_VBUS_DISCHARGE | OTGSC_INTR_1MS_TIMER_EN); + + writel(temp, &p_otg->dr_mem_map->otgsc); + + return 0; +} + +/*------------------------------------------------------------------------- + PROC File System Support +-------------------------------------------------------------------------*/ +#ifdef CONFIG_USB_OTG_DEBUG_FILES + +#include + +static const char proc_filename[] = "driver/isp1504_otg"; + +static int otg_proc_read(char *page, char **start, off_t off, int count, + int *eof, void *_dev) +{ + struct otg_fsm *fsm = &fsl_otg_dev->fsm; + char *buf = page; + char *next = buf; + unsigned size = count; + unsigned long flags; + int t; + u32 tmp_reg; + + if (off != 0) + return 0; + + spin_lock_irqsave(&fsm->lock, flags); + + /* ------basic driver infomation ---- */ + t = scnprintf(next, size, + DRIVER_DESC "\n" "fsl_usb2_otg version: %s\n\n", + DRIVER_VERSION); + size -= t; + next += t; + + /* ------ Registers ----- */ + tmp_reg = le32_to_cpu(usb_dr_regs->otgsc); + t = scnprintf(next, size, "OTGSC reg: %08x\n", tmp_reg); + size -= t; + next += t; + + tmp_reg = le32_to_cpu(usb_dr_regs->portsc); + t = scnprintf(next, size, "PORTSC reg: %08x\n", tmp_reg); + size -= t; + next += t; + + tmp_reg = le32_to_cpu(usb_dr_regs->usbmode); + t = scnprintf(next, size, "USBMODE reg: %08x\n", tmp_reg); + size -= t; + next += t; + + tmp_reg = le32_to_cpu(usb_dr_regs->usbcmd); + t = scnprintf(next, size, "USBCMD reg: %08x\n", tmp_reg); + size -= t; + next += t; + + tmp_reg = le32_to_cpu(usb_dr_regs->usbsts); + t = scnprintf(next, size, "USBSTS reg: %08x\n", tmp_reg); + size -= t; + next += t; + + /* ------ State ----- */ + t = scnprintf(next, size, + "OTG state: %s\n\n", + state_string(fsl_otg_dev->otg.state)); + size -= t; + next += t; + +#if 1 || defined DEBUG + /* ------ State Machine Variables ----- */ + t = scnprintf(next, size, "a_bus_req: %d\n", fsm->a_bus_req); + size -= t; + next += t; + + t = scnprintf(next, size, "b_bus_req: %d\n", fsm->b_bus_req); + size -= t; + next += t; + + t = scnprintf(next, size, "a_bus_resume: %d\n", fsm->a_bus_resume); + size -= t; + next += t; + + t = scnprintf(next, size, "a_bus_suspend: %d\n", fsm->a_bus_suspend); + size -= t; + next += t; + + t = scnprintf(next, size, "a_conn: %d\n", fsm->a_conn); + size -= t; + next += t; + + t = scnprintf(next, size, "a_sess_vld: %d\n", fsm->a_sess_vld); + size -= t; + next += t; + + t = scnprintf(next, size, "a_srp_det: %d\n", fsm->a_srp_det); + size -= t; + next += t; + + t = scnprintf(next, size, "a_vbus_vld: %d\n", fsm->a_vbus_vld); + size -= t; + next += t; + + t = scnprintf(next, size, "b_bus_resume: %d\n", fsm->b_bus_resume); + size -= t; + next += t; + + t = scnprintf(next, size, "b_bus_suspend: %d\n", fsm->b_bus_suspend); + size -= t; + next += t; + + t = scnprintf(next, size, "b_conn: %d\n", fsm->b_conn); + size -= t; + next += t; + + t = scnprintf(next, size, "b_se0_srp: %d\n", fsm->b_se0_srp); + size -= t; + next += t; + + t = scnprintf(next, size, "b_sess_end: %d\n", fsm->b_sess_end); + size -= t; + next += t; + + t = scnprintf(next, size, "b_sess_vld: %d\n", fsm->b_sess_vld); + size -= t; + next += t; + + t = scnprintf(next, size, "id: %d\n", fsm->id); + size -= t; + next += t; +#endif + + spin_unlock_irqrestore(&fsm->lock, flags); + + *eof = 1; + return count - size; +} + +#define create_proc_file() create_proc_read_entry(proc_filename, \ + 0, NULL, otg_proc_read, NULL) + +#define remove_proc_file() remove_proc_entry(proc_filename, NULL) + +#else /* !CONFIG_USB_OTG_DEBUG_FILES */ + +#define create_proc_file() do {} while (0) +#define remove_proc_file() do {} while (0) + +#endif /*CONFIG_USB_OTG_DEBUG_FILES */ + +/*----------------------------------------------------------*/ +/* Char driver interface to control some OTG input */ + +/* This function handle some ioctl command,such as get otg + * status and set host suspend + */ +static int fsl_otg_ioctl(struct inode *inode, struct file *file, + unsigned int cmd, unsigned long arg) +{ + u32 retval = 0; + + switch (cmd) { + case GET_OTG_STATUS: + retval = fsl_otg_dev->host_working; + break; + + case SET_A_SUSPEND_REQ: + fsl_otg_dev->fsm.a_suspend_req = arg; + break; + + case SET_A_BUS_DROP: + fsl_otg_dev->fsm.a_bus_drop = arg; + break; + + case SET_A_BUS_REQ: + fsl_otg_dev->fsm.a_bus_req = arg; + break; + + case SET_B_BUS_REQ: + fsl_otg_dev->fsm.b_bus_req = arg; + break; + + default: + break; + } + + otg_statemachine(&fsl_otg_dev->fsm); + + return retval; +} + +static int fsl_otg_open(struct inode *inode, struct file *file) +{ + + return 0; +} + +static int fsl_otg_release(struct inode *inode, struct file *file) +{ + + return 0; +} + +static struct file_operations otg_fops = { + .owner = THIS_MODULE, + .llseek = NULL, + .read = NULL, + .write = NULL, + .ioctl = fsl_otg_ioctl, + .open = fsl_otg_open, + .release = fsl_otg_release, +}; + +static int __init fsl_otg_probe(struct platform_device *pdev) +{ + int status; + struct fsl_usb2_platform_data *pdata; + + DBG("pdev=0x%p\n", pdev); + + if (!pdev) + return -ENODEV; + + if (!pdev->dev.platform_data) + return -ENOMEM; + + pdata = pdev->dev.platform_data; + + /* configure the OTG */ + status = fsl_otg_conf(pdev); + if (status) { + printk(KERN_INFO "Couldn't init OTG module\n"); + return -status; + } + + /* start OTG */ + status = usb_otg_start(pdev); + + if (register_chrdev(FSL_OTG_MAJOR, FSL_OTG_NAME, &otg_fops)) { + printk(KERN_WARNING FSL_OTG_NAME + ": unable to register FSL OTG device\n"); + return -EIO; + } + + create_proc_file(); + return status; +} + +static int fsl_otg_remove(struct platform_device *pdev) +{ + struct fsl_usb2_platform_data *pdata = pdev->dev.platform_data; + + otg_set_transceiver(NULL); + free_irq(fsl_otg_dev->irq, fsl_otg_dev); + + iounmap((void *)usb_dr_regs); + + kfree(fsl_otg_dev); + + remove_proc_file(); + + unregister_chrdev(FSL_OTG_MAJOR, FSL_OTG_NAME); + + if (pdata->platform_uninit) + pdata->platform_uninit(pdata); + + return 0; +} + +struct platform_driver fsl_otg_driver = { + .probe = fsl_otg_probe, + .remove = fsl_otg_remove, + .driver = { + .name = driver_name, + .owner = THIS_MODULE, + }, +}; + +/*-------------------------------------------------------------------------*/ + +static int __init fsl_usb_otg_init(void) +{ + printk(KERN_INFO DRIVER_DESC " loaded, %s\n", DRIVER_VERSION); + return platform_driver_register(&fsl_otg_driver); +} + +static void __exit fsl_usb_otg_exit(void) +{ + platform_driver_unregister(&fsl_otg_driver); + printk(KERN_INFO DRIVER_DESC " unloaded\n"); +} + +subsys_initcall(fsl_usb_otg_init); +module_exit(fsl_usb_otg_exit); + +MODULE_DESCRIPTION(DRIVER_INFO); +MODULE_AUTHOR(DRIVER_AUTHOR); +MODULE_LICENSE("GPL"); diff --git a/drivers/usb/otg/fsl_otg.h b/drivers/usb/otg/fsl_otg.h new file mode 100644 index 000000000000..0b7446192767 --- /dev/null +++ b/drivers/usb/otg/fsl_otg.h @@ -0,0 +1,412 @@ +/* Copyright (C) 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include "otg_fsm.h" +#include +#include + + /* USB Command Register Bit Masks */ +#define USB_CMD_RUN_STOP (0x1<<0) +#define USB_CMD_CTRL_RESET (0x1<<1) +#define USB_CMD_PERIODIC_SCHEDULE_EN (0x1<<4) +#define USB_CMD_ASYNC_SCHEDULE_EN (0x1<<5) +#define USB_CMD_INT_AA_DOORBELL (0x1<<6) +#define USB_CMD_ASP (0x3<<8) +#define USB_CMD_ASYNC_SCH_PARK_EN (0x1<<11) +#define USB_CMD_SUTW (0x1<<13) +#define USB_CMD_ATDTW (0x1<<14) +#define USB_CMD_ITC (0xFF<<16) + +/* bit 15,3,2 are frame list size */ +#define USB_CMD_FRAME_SIZE_1024 (0x0<<15 | 0x0<<2) +#define USB_CMD_FRAME_SIZE_512 (0x0<<15 | 0x1<<2) +#define USB_CMD_FRAME_SIZE_256 (0x0<<15 | 0x2<<2) +#define USB_CMD_FRAME_SIZE_128 (0x0<<15 | 0x3<<2) +#define USB_CMD_FRAME_SIZE_64 (0x1<<15 | 0x0<<2) +#define USB_CMD_FRAME_SIZE_32 (0x1<<15 | 0x1<<2) +#define USB_CMD_FRAME_SIZE_16 (0x1<<15 | 0x2<<2) +#define USB_CMD_FRAME_SIZE_8 (0x1<<15 | 0x3<<2) + +/* bit 9-8 are async schedule park mode count */ +#define USB_CMD_ASP_00 (0x0<<8) +#define USB_CMD_ASP_01 (0x1<<8) +#define USB_CMD_ASP_10 (0x2<<8) +#define USB_CMD_ASP_11 (0x3<<8) +#define USB_CMD_ASP_BIT_POS (8) + +/* bit 23-16 are interrupt threshold control */ +#define USB_CMD_ITC_NO_THRESHOLD (0x00<<16) +#define USB_CMD_ITC_1_MICRO_FRM (0x01<<16) +#define USB_CMD_ITC_2_MICRO_FRM (0x02<<16) +#define USB_CMD_ITC_4_MICRO_FRM (0x04<<16) +#define USB_CMD_ITC_8_MICRO_FRM (0x08<<16) +#define USB_CMD_ITC_16_MICRO_FRM (0x10<<16) +#define USB_CMD_ITC_32_MICRO_FRM (0x20<<16) +#define USB_CMD_ITC_64_MICRO_FRM (0x40<<16) +#define USB_CMD_ITC_BIT_POS (16) + +/* USB Status Register Bit Masks */ +#define USB_STS_INT (0x1<<0) +#define USB_STS_ERR (0x1<<1) +#define USB_STS_PORT_CHANGE (0x1<<2) +#define USB_STS_FRM_LST_ROLL (0x1<<3) +#define USB_STS_SYS_ERR (0x1<<4) +#define USB_STS_IAA (0x1<<5) +#define USB_STS_RESET_RECEIVED (0x1<<6) +#define USB_STS_SOF (0x1<<7) +#define USB_STS_DCSUSPEND (0x1<<8) +#define USB_STS_HC_HALTED (0x1<<12) +#define USB_STS_RCL (0x1<<13) +#define USB_STS_PERIODIC_SCHEDULE (0x1<<14) +#define USB_STS_ASYNC_SCHEDULE (0x1<<15) + +/* USB Interrupt Enable Register Bit Masks */ +#define USB_INTR_INT_EN (0x1<<0) +#define USB_INTR_ERR_INT_EN (0x1<<1) +#define USB_INTR_PC_DETECT_EN (0x1<<2) +#define USB_INTR_FRM_LST_ROLL_EN (0x1<<3) +#define USB_INTR_SYS_ERR_EN (0x1<<4) +#define USB_INTR_ASYN_ADV_EN (0x1<<5) +#define USB_INTR_RESET_EN (0x1<<6) +#define USB_INTR_SOF_EN (0x1<<7) +#define USB_INTR_DEVICE_SUSPEND (0x1<<8) + +/* Device Address bit masks */ +#define USB_DEVICE_ADDRESS_MASK (0x7F<<25) +#define USB_DEVICE_ADDRESS_BIT_POS (25) +/* PORTSC Register Bit Masks,Only one PORT in OTG mode*/ +#define PORTSC_CURRENT_CONNECT_STATUS (0x1<<0) +#define PORTSC_CONNECT_STATUS_CHANGE (0x1<<1) +#define PORTSC_PORT_ENABLE (0x1<<2) +#define PORTSC_PORT_EN_DIS_CHANGE (0x1<<3) +#define PORTSC_OVER_CURRENT_ACT (0x1<<4) +#define PORTSC_OVER_CUURENT_CHG (0x1<<5) +#define PORTSC_PORT_FORCE_RESUME (0x1<<6) +#define PORTSC_PORT_SUSPEND (0x1<<7) +#define PORTSC_PORT_RESET (0x1<<8) +#define PORTSC_LINE_STATUS_BITS (0x3<<10) +#define PORTSC_PORT_POWER (0x1<<12) +#define PORTSC_PORT_INDICTOR_CTRL (0x3<<14) +#define PORTSC_PORT_TEST_CTRL (0xF<<16) +#define PORTSC_WAKE_ON_CONNECT_EN (0x1<<20) +#define PORTSC_WAKE_ON_CONNECT_DIS (0x1<<21) +#define PORTSC_WAKE_ON_OVER_CURRENT (0x1<<22) +#define PORTSC_PHY_LOW_POWER_SPD (0x1<<23) +#define PORTSC_PORT_FORCE_FULL_SPEED (0x1<<24) +#define PORTSC_PORT_SPEED_MASK (0x3<<26) +#define PORTSC_TRANSCEIVER_WIDTH (0x1<<28) +#define PORTSC_PHY_TYPE_SEL (0x3<<30) +/* bit 11-10 are line status */ +#define PORTSC_LINE_STATUS_SE0 (0x0<<10) +#define PORTSC_LINE_STATUS_JSTATE (0x1<<10) +#define PORTSC_LINE_STATUS_KSTATE (0x2<<10) +#define PORTSC_LINE_STATUS_UNDEF (0x3<<10) +#define PORTSC_LINE_STATUS_BIT_POS (10) + +/* bit 15-14 are port indicator control */ +#define PORTSC_PIC_OFF (0x0<<14) +#define PORTSC_PIC_AMBER (0x1<<14) +#define PORTSC_PIC_GREEN (0x2<<14) +#define PORTSC_PIC_UNDEF (0x3<<14) +#define PORTSC_PIC_BIT_POS (14) + +/* bit 19-16 are port test control */ +#define PORTSC_PTC_DISABLE (0x0<<16) +#define PORTSC_PTC_JSTATE (0x1<<16) +#define PORTSC_PTC_KSTATE (0x2<<16) +#define PORTSC_PTC_SEQNAK (0x3<<16) +#define PORTSC_PTC_PACKET (0x4<<16) +#define PORTSC_PTC_FORCE_EN (0x5<<16) +#define PORTSC_PTC_BIT_POS (16) + +/* bit 27-26 are port speed */ +#define PORTSC_PORT_SPEED_FULL (0x0<<26) +#define PORTSC_PORT_SPEED_LOW (0x1<<26) +#define PORTSC_PORT_SPEED_HIGH (0x2<<26) +#define PORTSC_PORT_SPEED_UNDEF (0x3<<26) +#define PORTSC_SPEED_BIT_POS (26) + +/* bit 28 is parallel transceiver width for UTMI interface */ +#define PORTSC_PTW (0x1<<28) +#define PORTSC_PTW_8BIT (0x0<<28) +#define PORTSC_PTW_16BIT (0x1<<28) + +/* bit 31-30 are port transceiver select */ +#define PORTSC_PTS_UTMI (0x0<<30) +#define PORTSC_PTS_ULPI (0x2<<30) +#define PORTSC_PTS_FSLS_SERIAL (0x3<<30) +#define PORTSC_PTS_BIT_POS (30) + +#define PORTSC_W1C_BITS \ + (PORTSC_CONNECT_STATUS_CHANGE | \ + PORTSC_PORT_EN_DIS_CHANGE | \ + PORTSC_OVER_CUURENT_CHG) + +/* OTG Status Control Register Bit Masks */ +#define OTGSC_CTRL_VBUS_DISCHARGE (0x1<<0) +#define OTGSC_CTRL_VBUS_CHARGE (0x1<<1) +#define OTGSC_CTRL_OTG_TERMINATION (0x1<<3) +#define OTGSC_CTRL_DATA_PULSING (0x1<<4) +#define OTGSC_CTRL_ID_PULL_EN (0x1<<5) +#define OTGSC_HA_DATA_PULSE (0x1<<6) +#define OTGSC_HA_BA (0x1<<7) +#define OTGSC_STS_USB_ID (0x1<<8) +#define OTGSC_STS_A_VBUS_VALID (0x1<<9) +#define OTGSC_STS_A_SESSION_VALID (0x1<<10) +#define OTGSC_STS_B_SESSION_VALID (0x1<<11) +#define OTGSC_STS_B_SESSION_END (0x1<<12) +#define OTGSC_STS_1MS_TOGGLE (0x1<<13) +#define OTGSC_STS_DATA_PULSING (0x1<<14) +#define OTGSC_INTSTS_USB_ID (0x1<<16) +#define OTGSC_INTSTS_A_VBUS_VALID (0x1<<17) +#define OTGSC_INTSTS_A_SESSION_VALID (0x1<<18) +#define OTGSC_INTSTS_B_SESSION_VALID (0x1<<19) +#define OTGSC_INTSTS_B_SESSION_END (0x1<<20) +#define OTGSC_INTSTS_1MS (0x1<<21) +#define OTGSC_INTSTS_DATA_PULSING (0x1<<22) +#define OTGSC_INTR_USB_ID_EN (0x1<<24) +#define OTGSC_INTR_A_VBUS_VALID_EN (0x1<<25) +#define OTGSC_INTR_A_SESSION_VALID_EN (0x1<<26) +#define OTGSC_INTR_B_SESSION_VALID_EN (0x1<<27) +#define OTGSC_INTR_B_SESSION_END_EN (0x1<<28) +#define OTGSC_INTR_1MS_TIMER_EN (0x1<<29) +#define OTGSC_INTR_DATA_PULSING_EN (0x1<<30) +#define OTGSC_INTSTS_MASK (0x00ff0000) + +/* USB MODE Register Bit Masks */ +#define USB_MODE_CTRL_MODE_IDLE (0x0<<0) +#define USB_MODE_CTRL_MODE_DEVICE (0x2<<0) +#define USB_MODE_CTRL_MODE_HOST (0x3<<0) +#define USB_MODE_CTRL_MODE_RSV (0x1<<0) +#define USB_MODE_SETUP_LOCK_OFF (0x1<<3) +#define USB_MODE_STREAM_DISABLE (0x1<<4) +#define USB_MODE_ES (0x1<<2) /* (big) Endian Select */ + +#define MPC8349_OTG_IRQ (38) +#define CFG_IMMR_BASE (0xfe000000) +#define MPC83xx_USB_DR_BASE (CFG_IMMR_BASE + 0x23000) + +/* control Register Bit Masks */ +#define USB_CTRL_IOENB (0x1<<2) +#define USB_CTRL_ULPI_INT0EN (0x1<<0) + +/* BCSR5 */ +#define BCSR5_INT_USB (0x02) + +/* USB module clk cfg */ +#define SCCR_OFFS (0xA08) +#define SCCR_USB_CLK_DISABLE (0x00000000) /* USB clk disable */ +#define SCCR_USB_MPHCM_11 (0x00c00000) +#define SCCR_USB_MPHCM_01 (0x00400000) +#define SCCR_USB_MPHCM_10 (0x00800000) +#define SCCR_USB_DRCM_11 (0x00300000) +#define SCCR_USB_DRCM_01 (0x00100000) +#define SCCR_USB_DRCM_10 (0x00200000) + +#define SICRL_OFFS (0x114) +#define SICRL_USB0 (0x40000000) +#define SICRL_USB1 (0x20000000) + +#define SICRH_OFFS (0x118) +#define SICRH_USB_UTMI (0x00020000) + +/* OTG interrupt enable bit masks */ +#define OTGSC_INTERRUPT_ENABLE_BITS_MASK \ + (OTGSC_INTR_USB_ID_EN | \ + OTGSC_INTR_1MS_TIMER_EN | \ + OTGSC_INTR_A_VBUS_VALID_EN | \ + OTGSC_INTR_A_SESSION_VALID_EN | \ + OTGSC_INTR_B_SESSION_VALID_EN | \ + OTGSC_INTR_B_SESSION_END_EN | \ + OTGSC_INTR_DATA_PULSING_EN) + +/* OTG interrupt status bit masks */ +#define OTGSC_INTERRUPT_STATUS_BITS_MASK \ + (OTGSC_INTSTS_USB_ID | \ + OTGSC_INTR_1MS_TIMER_EN | \ + OTGSC_INTSTS_A_VBUS_VALID | \ + OTGSC_INTSTS_A_SESSION_VALID | \ + OTGSC_INTSTS_B_SESSION_VALID | \ + OTGSC_INTSTS_B_SESSION_END | \ + OTGSC_INTSTS_DATA_PULSING) + +/* + * A-DEVICE timing constants + */ + +/* Wait for VBUS Rise */ +#define TA_WAIT_VRISE (100) /* a_wait_vrise 100 ms, section: 6.6.5.1 */ + +/* Wait for B-Connect */ +#define TA_WAIT_BCON (10000) /* a_wait_bcon > 1 sec, section: 6.6.5.2 + * This is only used to get out of + * OTG_STATE_A_WAIT_BCON state if there was + * no connection for these many milliseconds + */ + +/* A-Idle to B-Disconnect */ +/* It is necessary for this timer to be more than 750 ms because of a bug in OPT + * test 5.4 in which B OPT disconnects after 750 ms instead of 75ms as stated + * in the test description + */ +#define TA_AIDL_BDIS (5000) /* a_suspend minimum 200 ms, section: 6.6.5.3 */ + +/* B-Idle to A-Disconnect */ +#define TA_BIDL_ADIS (12) /* 3 to 200 ms */ + +/* B-device timing constants */ + + +/* Data-Line Pulse Time*/ +#define TB_DATA_PLS (10) /* b_srp_init,continue 5~10ms, section:5.3.3 */ +#define TB_DATA_PLS_MIN (5) /* minimum 5 ms */ +#define TB_DATA_PLS_MAX (10) /* maximum 10 ms */ + +/* SRP Initiate Time */ +#define TB_SRP_INIT (100) /* b_srp_init,maximum 100 ms, section:5.3.8 */ + +/* SRP Fail Time */ +#define TB_SRP_FAIL (7000) /* b_srp_init,Fail time 5~30s, section:6.8.2.2*/ + +/* SRP result wait time */ +#define TB_SRP_WAIT (60) + +/* VBus time */ +#define TB_VBUS_PLS (30) /* time to keep vbus pulsing asserted */ + +/* Discharge time */ +/* This time should be less than 10ms. It varies from system to system. */ +#define TB_VBUS_DSCHRG (8) + +/* A-SE0 to B-Reset */ +#define TB_ASE0_BRST (20) /* b_wait_acon, mini 3.125 ms,section:6.8.2.4 */ + +/* A bus suspend timer before we can switch to b_wait_aconn */ +#define TB_A_SUSPEND (7) +#define TB_BUS_RESUME (12) + +/* SE0 Time Before SRP */ +#define TB_SE0_SRP (2) /* b_idle,minimum 2 ms, section:5.3.2 */ + + +#define SET_OTG_STATE(otg_ptr, newstate) ((otg_ptr)->state = newstate) + +struct usb_dr_mmap { + /* Capability register */ + u8 res1[256]; + u16 caplength; /* Capability Register Length */ + u16 hciversion; /* Host Controller Interface Version */ + u32 hcsparams; /* Host Controller Structual Parameters */ + u32 hccparams; /* Host Controller Capability Parameters */ + u8 res2[20]; + u32 dciversion; /* Device Controller Interface Version */ + u32 dccparams; /* Device Controller Capability Parameters */ + u8 res3[24]; + /* Operation register */ + u32 usbcmd; /* USB Command Register */ + u32 usbsts; /* USB Status Register */ + u32 usbintr; /* USB Interrupt Enable Register */ + u32 frindex; /* Frame Index Register */ + u8 res4[4]; + u32 deviceaddr; /* Device Address */ + u32 endpointlistaddr; /* Endpoint List Address Register */ + u8 res5[4]; + u32 burstsize; /* Master Interface Data Burst Size Register */ + u32 txttfilltuning; /* Transmit FIFO Tuning Controls Register */ + u8 res6[8]; + u32 ulpiview; /* ULPI register access */ + u8 res7[12]; + u32 configflag; /* Configure Flag Register */ + u32 portsc; /* Port 1 Status and Control Register */ + u8 res8[28]; + u32 otgsc; /* On-The-Go Status and Control */ + u32 usbmode; /* USB Mode Register */ + u32 endptsetupstat; /* Endpoint Setup Status Register */ + u32 endpointprime; /* Endpoint Initialization Register */ + u32 endptflush; /* Endpoint Flush Register */ + u32 endptstatus; /* Endpoint Status Register */ + u32 endptcomplete; /* Endpoint Complete Register */ + u32 endptctrl[6]; /* Endpoint Control Registers */ + u8 res9[552]; + u32 snoop1; + u32 snoop2; + u32 age_cnt_thresh; /* Age Count Threshold Register */ + u32 pri_ctrl; /* Priority Control Register */ + u32 si_ctrl; /* System Interface Control Register */ + u8 res10[236]; +#ifdef CONFIG_ARCH_MX5 + u32 res11[128]; +#endif + u32 control; /* General Purpose Control Register */ +}; + + +struct fsl_otg_timer { + unsigned long expires; /* Number of count increase to timeout */ + unsigned long count; /* Tick counter */ + void (*function)(unsigned long); /* Timeout function */ + unsigned long data; /* Data passed to function */ + struct list_head list; +}; + +struct inline fsl_otg_timer * otg_timer_initializer +(void (*function)(unsigned long), unsigned long expires, unsigned long data) +{ + struct fsl_otg_timer *timer; + timer = kmalloc(sizeof(struct fsl_otg_timer), GFP_KERNEL); + if (timer == NULL) + return NULL; + timer->function = function; + timer->expires = expires; + timer->data = data; + return timer; +} + +struct fsl_otg { + struct otg_transceiver otg; + struct otg_fsm fsm; + struct usb_dr_mmap *dr_mem_map; + struct delayed_work otg_event; + + /*used for usb host */ + struct work_struct work_wq; + u8 host_working; + + int irq; +}; + +struct fsl_otg_config { + u8 otg_port; +}; + +/*For SRP and HNP handle*/ +#define FSL_OTG_MAJOR 66 +#define FSL_OTG_NAME "fsl-usb2-otg" +/*Command to OTG driver(ioctl)*/ +#define OTG_IOCTL_MAGIC FSL_OTG_MAJOR +/*if otg work as host,it should return 1,otherwise it return 0*/ +#define GET_OTG_STATUS _IOR(OTG_IOCTL_MAGIC, 1, int) +#define SET_A_SUSPEND_REQ _IOW(OTG_IOCTL_MAGIC, 2, int) +#define SET_A_BUS_DROP _IOW(OTG_IOCTL_MAGIC, 3, int) +#define SET_A_BUS_REQ _IOW(OTG_IOCTL_MAGIC, 4, int) +#define SET_B_BUS_REQ _IOW(OTG_IOCTL_MAGIC, 5, int) +#define GET_A_SUSPEND_REQ _IOR(OTG_IOCTL_MAGIC, 6, int) +#define GET_A_BUS_DROP _IOR(OTG_IOCTL_MAGIC, 7, int) +#define GET_A_BUS_REQ _IOR(OTG_IOCTL_MAGIC, 8, int) +#define GET_B_BUS_REQ _IOR(OTG_IOCTL_MAGIC, 9, int) + +extern const char *state_string(enum usb_otg_state state); diff --git a/drivers/usb/otg/otg_fsm.c b/drivers/usb/otg/otg_fsm.c new file mode 100644 index 000000000000..cfd2a404f0bd --- /dev/null +++ b/drivers/usb/otg/otg_fsm.c @@ -0,0 +1,371 @@ +/* OTG Finite State Machine from OTG spec + * + * Copyright (C) 2006-2010 Freescale Semiconductor, Inc. + * + * Author: Li Yang + * Jerry Huang + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include "otg_fsm.h" + + +/* Defined by device specific driver, for different timer implementation */ +extern void *a_wait_vrise_tmr, *a_wait_bcon_tmr, *a_aidl_bdis_tmr, + *b_ase0_brst_tmr, *b_se0_srp_tmr, *b_srp_fail_tmr, *a_wait_enum_tmr; + +const char *state_string(enum usb_otg_state state) +{ + switch (state) { + case OTG_STATE_A_IDLE: return "a_idle"; + case OTG_STATE_A_WAIT_VRISE: return "a_wait_vrise"; + case OTG_STATE_A_WAIT_BCON: return "a_wait_bcon"; + case OTG_STATE_A_HOST: return "a_host"; + case OTG_STATE_A_SUSPEND: return "a_suspend"; + case OTG_STATE_A_PERIPHERAL: return "a_peripheral"; + case OTG_STATE_A_WAIT_VFALL: return "a_wait_vfall"; + case OTG_STATE_A_VBUS_ERR: return "a_vbus_err"; + case OTG_STATE_B_IDLE: return "b_idle"; + case OTG_STATE_B_SRP_INIT: return "b_srp_init"; + case OTG_STATE_B_PERIPHERAL: return "b_peripheral"; + case OTG_STATE_B_WAIT_ACON: return "b_wait_acon"; + case OTG_STATE_B_HOST: return "b_host"; + default: return "UNDEFINED"; + } +} + +/* Change USB protocol when there is a protocol change */ +static int otg_set_protocol(struct otg_fsm *fsm, int protocol) +{ + int ret = 0; + + if (fsm->protocol != protocol) { + VDBG("Changing role fsm->protocol= %d; new protocol= %d\n", + fsm->protocol, protocol); + /* stop old protocol */ + if (fsm->protocol == PROTO_HOST) + ret = fsm->ops->start_host(fsm, 0); + else if (fsm->protocol == PROTO_GADGET) + ret = fsm->ops->start_gadget(fsm, 0); + if (ret) + return ret; + + /* start new protocol */ + if (protocol == PROTO_HOST) + ret = fsm->ops->start_host(fsm, 1); + else if (protocol == PROTO_GADGET) + ret = fsm->ops->start_gadget(fsm, 1); + if (ret) + return ret; + + fsm->protocol = protocol; + return 0; + } + + return 0; +} + +static int state_changed; + +/* Called when leaving a state. Do state clean up jobs here */ +void otg_leave_state(struct otg_fsm *fsm, enum usb_otg_state old_state) +{ + switch (old_state) { + case OTG_STATE_B_IDLE: + otg_del_timer(fsm, b_se0_srp_tmr); + fsm->b_se0_srp = 0; + break; + case OTG_STATE_B_SRP_INIT: + fsm->b_srp_done = 0; + break; + case OTG_STATE_B_PERIPHERAL: + break; + case OTG_STATE_B_WAIT_ACON: + otg_del_timer(fsm, b_ase0_brst_tmr); + fsm->b_ase0_brst_tmout = 0; + break; + case OTG_STATE_B_HOST: + break; + case OTG_STATE_A_IDLE: + break; + case OTG_STATE_A_WAIT_VRISE: + otg_del_timer(fsm, a_wait_vrise_tmr); + fsm->a_wait_vrise_tmout = 0; + break; + case OTG_STATE_A_WAIT_BCON: + otg_del_timer(fsm, a_wait_bcon_tmr); + fsm->a_wait_bcon_tmout = 0; + break; + case OTG_STATE_A_HOST: + otg_del_timer(fsm, a_wait_enum_tmr); + break; + case OTG_STATE_A_SUSPEND: + otg_del_timer(fsm, a_aidl_bdis_tmr); + fsm->a_aidl_bdis_tmout = 0; + fsm->a_suspend_req = 0; + break; + case OTG_STATE_A_PERIPHERAL: + break; + case OTG_STATE_A_WAIT_VFALL: + otg_del_timer(fsm, a_wait_vrise_tmr); + break; + case OTG_STATE_A_VBUS_ERR: + break; + default: + break; + } +} + +/* Called when entering a state */ +int otg_set_state(struct otg_fsm *fsm, enum usb_otg_state new_state) +{ + state_changed = 1; + if (fsm->transceiver->state == new_state) + return 0; + VDBG("Set state: %s \n", state_string(new_state)); + otg_leave_state(fsm, fsm->transceiver->state); + switch (new_state) { + case OTG_STATE_B_IDLE: + otg_drv_vbus(fsm, 0); + otg_chrg_vbus(fsm, 0); + otg_loc_conn(fsm, 0); + otg_loc_sof(fsm, 0); + otg_set_protocol(fsm, PROTO_UNDEF); + otg_add_timer(fsm, b_se0_srp_tmr); + break; + case OTG_STATE_B_SRP_INIT: + otg_start_pulse(fsm); + otg_loc_sof(fsm, 0); + otg_set_protocol(fsm, PROTO_UNDEF); + otg_add_timer(fsm, b_srp_fail_tmr); + break; + case OTG_STATE_B_PERIPHERAL: + otg_chrg_vbus(fsm, 0); + otg_loc_conn(fsm, 1); + otg_loc_sof(fsm, 0); + otg_set_protocol(fsm, PROTO_GADGET); + break; + case OTG_STATE_B_WAIT_ACON: + otg_chrg_vbus(fsm, 0); + otg_loc_conn(fsm, 0); + otg_loc_sof(fsm, 0); + otg_set_protocol(fsm, PROTO_HOST); + otg_add_timer(fsm, b_ase0_brst_tmr); + fsm->a_bus_suspend = 0; + break; + case OTG_STATE_B_HOST: + otg_chrg_vbus(fsm, 0); + otg_loc_conn(fsm, 0); + otg_loc_sof(fsm, 1); + otg_set_protocol(fsm, PROTO_HOST); + usb_bus_start_enum(fsm->transceiver->host, + fsm->transceiver->host->otg_port); + break; + case OTG_STATE_A_IDLE: + otg_drv_vbus(fsm, 0); + otg_chrg_vbus(fsm, 0); + otg_loc_conn(fsm, 0); + otg_loc_sof(fsm, 0); + otg_set_protocol(fsm, PROTO_HOST); + break; + case OTG_STATE_A_WAIT_VRISE: + otg_drv_vbus(fsm, 1); + otg_loc_conn(fsm, 0); + otg_loc_sof(fsm, 0); + otg_set_protocol(fsm, PROTO_HOST); + otg_add_timer(fsm, a_wait_vrise_tmr); + break; + case OTG_STATE_A_WAIT_BCON: + otg_drv_vbus(fsm, 1); + otg_loc_conn(fsm, 0); + otg_loc_sof(fsm, 0); + otg_set_protocol(fsm, PROTO_HOST); + otg_add_timer(fsm, a_wait_bcon_tmr); + break; + case OTG_STATE_A_HOST: + otg_drv_vbus(fsm, 1); + otg_loc_conn(fsm, 0); + otg_loc_sof(fsm, 1); + otg_set_protocol(fsm, PROTO_HOST); + /* When HNP is triggered while a_bus_req = 0, a_host will + * suspend too fast to complete a_set_b_hnp_en */ + if (!fsm->a_bus_req || fsm->a_suspend_req) + otg_add_timer(fsm, a_wait_enum_tmr); + break; + case OTG_STATE_A_SUSPEND: + otg_drv_vbus(fsm, 1); + otg_loc_conn(fsm, 0); + otg_loc_sof(fsm, 0); + otg_set_protocol(fsm, PROTO_HOST); + otg_add_timer(fsm, a_aidl_bdis_tmr); + + break; + case OTG_STATE_A_PERIPHERAL: + otg_loc_conn(fsm, 1); + otg_loc_sof(fsm, 0); + otg_set_protocol(fsm, PROTO_GADGET); + otg_drv_vbus(fsm, 1); + break; + case OTG_STATE_A_WAIT_VFALL: + otg_drv_vbus(fsm, 0); + otg_loc_conn(fsm, 0); + otg_loc_sof(fsm, 0); + otg_set_protocol(fsm, PROTO_HOST); + break; + case OTG_STATE_A_VBUS_ERR: + otg_drv_vbus(fsm, 0); + otg_loc_conn(fsm, 0); + otg_loc_sof(fsm, 0); + otg_set_protocol(fsm, PROTO_UNDEF); + break; + default: + break; + } + + fsm->transceiver->state = new_state; + return 0; +} + +/* State change judgement */ +int otg_statemachine(struct otg_fsm *fsm) +{ + enum usb_otg_state state; + unsigned long flags; + + spin_lock_irqsave(&fsm->lock, flags); + + state = fsm->transceiver->state; + state_changed = 0; + /* State machine state change judgement */ + + switch (state) { + case OTG_STATE_UNDEFINED: + VDBG("fsm->id = %d \n", fsm->id); + if (fsm->id) + otg_set_state(fsm, OTG_STATE_B_IDLE); + else + otg_set_state(fsm, OTG_STATE_A_IDLE); + break; + case OTG_STATE_B_IDLE: + if (!fsm->id) + otg_set_state(fsm, OTG_STATE_A_IDLE); + else if (fsm->b_sess_vld && fsm->transceiver->gadget) + otg_set_state(fsm, OTG_STATE_B_PERIPHERAL); + else if (fsm->b_bus_req && fsm->b_sess_end && fsm->b_se0_srp) + otg_set_state(fsm, OTG_STATE_B_SRP_INIT); + break; + case OTG_STATE_B_SRP_INIT: + if (!fsm->id || fsm->b_srp_done) + otg_set_state(fsm, OTG_STATE_B_IDLE); + break; + case OTG_STATE_B_PERIPHERAL: + if (!fsm->id || !fsm->b_sess_vld) + otg_set_state(fsm, OTG_STATE_B_IDLE); + else if (fsm->b_bus_req && fsm->transceiver-> + gadget->b_hnp_enable && fsm->a_bus_suspend) + otg_set_state(fsm, OTG_STATE_B_WAIT_ACON); + break; + case OTG_STATE_B_WAIT_ACON: + if (fsm->a_conn) + otg_set_state(fsm, OTG_STATE_B_HOST); + else if (!fsm->id || !fsm->b_sess_vld) + otg_set_state(fsm, OTG_STATE_B_IDLE); + else if (fsm->a_bus_resume || fsm->b_ase0_brst_tmout) { + fsm->b_ase0_brst_tmout = 0; + otg_set_state(fsm, OTG_STATE_B_PERIPHERAL); + } + break; + case OTG_STATE_B_HOST: + if (!fsm->id || !fsm->b_sess_vld) + otg_set_state(fsm, OTG_STATE_B_IDLE); + else if (!fsm->b_bus_req || !fsm->a_conn) + otg_set_state(fsm, OTG_STATE_B_PERIPHERAL); + break; + case OTG_STATE_A_IDLE: + if (fsm->id) + otg_set_state(fsm, OTG_STATE_B_IDLE); + else if (!fsm->a_bus_drop && (fsm->a_bus_req || fsm->a_srp_det)) + otg_set_state(fsm, OTG_STATE_A_WAIT_VRISE); + break; + case OTG_STATE_A_WAIT_VRISE: + if (fsm->id || fsm->a_bus_drop || fsm->a_vbus_vld || + fsm->a_wait_vrise_tmout) { + otg_set_state(fsm, OTG_STATE_A_WAIT_BCON); + } + break; + case OTG_STATE_A_WAIT_BCON: + if (!fsm->a_vbus_vld) + otg_set_state(fsm, OTG_STATE_A_VBUS_ERR); + else if (fsm->b_conn) + otg_set_state(fsm, OTG_STATE_A_HOST); + else if (fsm->id | fsm->a_bus_drop | fsm->a_wait_bcon_tmout) + otg_set_state(fsm, OTG_STATE_A_WAIT_VFALL); + break; + case OTG_STATE_A_HOST: + if ((!fsm->a_bus_req || fsm->a_suspend_req) && + fsm->transceiver->host->b_hnp_enable) + otg_set_state(fsm, OTG_STATE_A_SUSPEND); + else if (fsm->id || !fsm->b_conn || fsm->a_bus_drop) + otg_set_state(fsm, OTG_STATE_A_WAIT_BCON); + else if (!fsm->a_vbus_vld) + otg_set_state(fsm, OTG_STATE_A_VBUS_ERR); + break; + case OTG_STATE_A_SUSPEND: + if (!fsm->b_conn && fsm->transceiver->host->b_hnp_enable) + otg_set_state(fsm, OTG_STATE_A_PERIPHERAL); + else if (!fsm->b_conn && !fsm->transceiver->host->b_hnp_enable) + otg_set_state(fsm, OTG_STATE_A_WAIT_BCON); + else if (fsm->a_bus_req || fsm->b_bus_resume) + otg_set_state(fsm, OTG_STATE_A_HOST); + else if (fsm->id || fsm->a_bus_drop || fsm->a_aidl_bdis_tmout) + otg_set_state(fsm, OTG_STATE_A_WAIT_VFALL); + else if (!fsm->a_vbus_vld) + otg_set_state(fsm, OTG_STATE_A_VBUS_ERR); + break; + case OTG_STATE_A_PERIPHERAL: + if (fsm->id || fsm->a_bus_drop) + otg_set_state(fsm, OTG_STATE_A_WAIT_VFALL); + else if (fsm->b_bus_suspend) + otg_set_state(fsm, OTG_STATE_A_WAIT_BCON); + else if (!fsm->a_vbus_vld) + otg_set_state(fsm, OTG_STATE_A_VBUS_ERR); + break; + case OTG_STATE_A_WAIT_VFALL: + if (fsm->id || fsm->a_bus_req || (!fsm->a_sess_vld && + !fsm->b_conn)) + otg_set_state(fsm, OTG_STATE_A_IDLE); + break; + case OTG_STATE_A_VBUS_ERR: + if (fsm->id || fsm->a_bus_drop || fsm->a_clr_err) + otg_set_state(fsm, OTG_STATE_A_WAIT_VFALL); + break; + default: + break; + } + spin_unlock_irqrestore(&fsm->lock, flags); + + /* VDBG("quit statemachine, changed = %d \n", state_changed); */ + return state_changed; +} diff --git a/drivers/usb/otg/otg_fsm.h b/drivers/usb/otg/otg_fsm.h new file mode 100644 index 000000000000..8fb6764b959e --- /dev/null +++ b/drivers/usb/otg/otg_fsm.h @@ -0,0 +1,151 @@ +/* Copyright (C) 2006-2010 Freescale Semiconductor, Inc. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#if 0 +#define DEBUG 1 +#define VERBOSE 1 +#endif + +#ifdef DEBUG +#define DBG(fmt, args...) printk(KERN_DEBUG "j=%lu [%s] " fmt "\n", jiffies, \ + __func__, ## args) +#else +#define DBG(fmt, args...) do {} while (0) +#endif + +#ifdef VERBOSE +#define VDBG DBG +#else +#define VDBG(stuff...) do {} while (0) +#endif + +#ifdef VERBOSE +#define MPC_LOC printk("Current Location [%s]:[%d]\n", __FILE__, __LINE__) +#else +#define MPC_LOC do {} while (0) +#endif + +#define PROTO_UNDEF (0) +#define PROTO_HOST (1) +#define PROTO_GADGET (2) + +/* OTG state machine according to the OTG spec */ +struct otg_fsm { + /* Input */ + int a_bus_resume; + int a_bus_suspend; + int a_conn; + int a_sess_vld; + int a_srp_det; + int a_vbus_vld; + int b_bus_resume; + int b_bus_suspend; + int b_conn; + int b_se0_srp; + int b_sess_end; + int b_sess_vld; + int id; + + /* Internal variables */ + int a_set_b_hnp_en; + int b_srp_done; + int b_hnp_enable; + + /* Timeout indicator for timers */ + int a_wait_vrise_tmout; + int a_wait_bcon_tmout; + int a_aidl_bdis_tmout; + int b_ase0_brst_tmout; + + /* Informative variables */ + int a_bus_drop; + int a_bus_req; + int a_clr_err; + int a_suspend_req; + int b_bus_req; + + /* Output */ + int drv_vbus; + int loc_conn; + int loc_sof; + + struct otg_fsm_ops *ops; + struct otg_transceiver *transceiver; + + /* Current usb protocol used: 0:undefine; 1:host; 2:client */ + int protocol; + spinlock_t lock; +}; + +struct otg_fsm_ops { + void (*chrg_vbus)(int on); + void (*drv_vbus)(int on); + void (*loc_conn)(int on); + void (*loc_sof)(int on); + void (*start_pulse)(void); + void (*add_timer)(void *timer); + void (*del_timer)(void *timer); + int (*start_host)(struct otg_fsm *fsm, int on); + int (*start_gadget)(struct otg_fsm *fsm, int on); +}; + + +static inline void otg_chrg_vbus(struct otg_fsm *fsm, int on) +{ + fsm->ops->chrg_vbus(on); +} + +static inline void otg_drv_vbus(struct otg_fsm *fsm, int on) +{ + if (fsm->drv_vbus != on) { + fsm->drv_vbus = on; + fsm->ops->drv_vbus(on); + } +} + +static inline void otg_loc_conn(struct otg_fsm *fsm, int on) +{ + if (fsm->loc_conn != on) { + fsm->loc_conn = on; + fsm->ops->loc_conn(on); + } +} + +static inline void otg_loc_sof(struct otg_fsm *fsm, int on) +{ + if (fsm->loc_sof != on) { + fsm->loc_sof = on; + fsm->ops->loc_sof(on); + } +} + +static inline void otg_start_pulse(struct otg_fsm *fsm) +{ + fsm->ops->start_pulse(); +} + +static inline void otg_add_timer(struct otg_fsm *fsm, void *timer) +{ + fsm->ops->add_timer(timer); +} + +static inline void otg_del_timer(struct otg_fsm *fsm, void *timer) +{ + fsm->ops->del_timer(timer); +} + +int otg_statemachine(struct otg_fsm *fsm); diff --git a/drivers/video/Kconfig b/drivers/video/Kconfig index 3d94a1471724..cff7be3ca1b1 100644 --- a/drivers/video/Kconfig +++ b/drivers/video/Kconfig @@ -389,6 +389,14 @@ config FB_CLPS711X Say Y to enable the Framebuffer driver for the CLPS7111 and EP7212 processors. +if ARCH_MXC +source "drivers/video/mxc/Kconfig" +endif + +if ARCH_MXS +source "drivers/video/mxs/Kconfig" +endif + config FB_SA1100 bool "SA-1100 LCD support" depends on (FB = y) && ARM && ARCH_SA1100 diff --git a/drivers/video/Makefile b/drivers/video/Makefile index ddc2af2ba45b..2d95727f0415 100644 --- a/drivers/video/Makefile +++ b/drivers/video/Makefile @@ -119,6 +119,8 @@ obj-$(CONFIG_FB_FSL_DIU) += fsl-diu-fb.o obj-$(CONFIG_FB_COBALT) += cobalt_lcdfb.o obj-$(CONFIG_FB_PNX4008_DUM) += pnx4008/ obj-$(CONFIG_FB_PNX4008_DUM_RGB) += pnx4008/ +obj-$(CONFIG_FB_MXC) += mxc/ +obj-$(CONFIG_FB_MXS) += mxs/ obj-$(CONFIG_FB_IBM_GXT4500) += gxt4500.o obj-$(CONFIG_FB_PS3) += ps3fb.o obj-$(CONFIG_FB_SM501) += sm501fb.o diff --git a/drivers/video/backlight/Kconfig b/drivers/video/backlight/Kconfig index e54a337227ea..2f5ed05b6ffa 100644 --- a/drivers/video/backlight/Kconfig +++ b/drivers/video/backlight/Kconfig @@ -307,6 +307,39 @@ config BACKLIGHT_PCF50633 If you have a backlight driven by a NXP PCF50633 MFD, say Y here to enable its driver. +config BACKLIGHT_MXC_IPU + tristate "IPU PWM Backlight Driver" + depends on MXC_IPU_V1 + default y + +config BACKLIGHT_MXC_LCDC + tristate "LCDC PWM Backlight Driver" + depends on (ARCH_MX21 || ARCH_MX27 || ARCH_MX25) + default y + +config BACKLIGHT_MXC_PMIC + tristate "PMIC Backlight Driver" + depends on MXC_MC13783_LIGHT + depends on MXC_MC13783_POWER + default y + +config BACKLIGHT_MXC_MC13892 + tristate "Mc13892 Backlight Driver" + depends on MXC_MC13892_LIGHT + default y + +config BACKLIGHT_MXS + tristate "Freescale MXS Backlight Driver" + depends on ARCH_MXS + default y + help + If you have a MXS, say y to enable the backlight driver. + +config BACKLIGHT_WM8350 + tristate "WM8350 Backlight Driver" + depends on REGULATOR_WM8350 + default y + endif # BACKLIGHT_CLASS_DEVICE endif # BACKLIGHT_LCD_SUPPORT diff --git a/drivers/video/backlight/Makefile b/drivers/video/backlight/Makefile index 44c0f81ad85d..97c87cb5ad02 100644 --- a/drivers/video/backlight/Makefile +++ b/drivers/video/backlight/Makefile @@ -36,3 +36,9 @@ obj-$(CONFIG_BACKLIGHT_ADP8860) += adp8860_bl.o obj-$(CONFIG_BACKLIGHT_88PM860X) += 88pm860x_bl.o obj-$(CONFIG_BACKLIGHT_PCF50633) += pcf50633-backlight.o +obj-$(CONFIG_BACKLIGHT_MXC_LCDC) += mxc_lcdc_bl.o +obj-$(CONFIG_BACKLIGHT_MXC_IPU) += mxc_ipu_bl.o +obj-$(CONFIG_BACKLIGHT_MXC_PMIC) += mxc_pmic_bl.o +obj-$(CONFIG_BACKLIGHT_WM8350) += wm8350_bl.o +obj-$(CONFIG_BACKLIGHT_MXC_MC13892) += mxc_mc13892_bl.o +obj-$(CONFIG_BACKLIGHT_MXS) += mxs_bl.o diff --git a/drivers/video/backlight/mxc_ipu_bl.c b/drivers/video/backlight/mxc_ipu_bl.c new file mode 100644 index 000000000000..fd6ea227989f --- /dev/null +++ b/drivers/video/backlight/mxc_ipu_bl.c @@ -0,0 +1,158 @@ +/* + * Copyright 2007-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +/*! + * @defgroup IPU_BL MXC IPU Backlight Driver + */ +/*! + * @file mxc_ipu_bl.c + * + * @brief Backlight Driver for IPU PWM on Freescale MXC/i.MX platforms. + * + * This file contains API defined in include/linux/clk.h for setting up and + * retrieving clocks. + * + * Based on Sharp's Corgi Backlight Driver + * + * @ingroup IPU_BL + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MXC_MAX_INTENSITY 255 +#define MXC_DEFAULT_INTENSITY 127 +#define MXC_INTENSITY_OFF 0 + +struct mxcbl_dev_data { + int intensity; +}; + +static int fb_id; + +static int mxcbl_send_intensity(struct backlight_device *bd) +{ + int intensity = bd->props.brightness; + struct mxcbl_dev_data *devdata = dev_get_drvdata(&bd->dev); + + if (bd->props.power != FB_BLANK_UNBLANK) + intensity = 0; + if (bd->props.fb_blank != FB_BLANK_UNBLANK) + intensity = 0; + + ipu_sdc_set_brightness(intensity); + + devdata->intensity = intensity; + return 0; +} + +static int mxcbl_get_intensity(struct backlight_device *bd) +{ + struct mxcbl_dev_data *devdata = dev_get_drvdata(&bd->dev); + return devdata->intensity; +} + +static int mxcbl_check_fb(struct backlight_device *bldev, struct fb_info *info) +{ + int id = info->fix.id[4] - '0'; + if (id == fb_id) { + if ((id == 3) && !strcmp(info->fix.id, "DISP3 FG")) { + return 0; + } + return 1; + } + return 0; +} + +static struct backlight_ops mxcbl_ops = { + .get_brightness = mxcbl_get_intensity, + .update_status = mxcbl_send_intensity, + .check_fb = mxcbl_check_fb, +}; + +static int __init mxcbl_probe(struct platform_device *pdev) +{ + struct backlight_device *bd; + struct mxcbl_dev_data *devdata; + struct backlight_properties props; + int ret = 0; + + devdata = kzalloc(sizeof(struct mxcbl_dev_data), GFP_KERNEL); + if (!devdata) + return -ENOMEM; + fb_id = (int)pdev->dev.platform_data; + + memset(&props, 0, sizeof(struct backlight_properties)); + props.max_brightness = MXC_MAX_INTENSITY; + bd = backlight_device_register(dev_name(&pdev->dev), &pdev->dev, devdata, + &mxcbl_ops, &props); + if (IS_ERR(bd)) { + ret = PTR_ERR(bd); + goto err0; + } + platform_set_drvdata(pdev, bd); + + bd->props.brightness = MXC_DEFAULT_INTENSITY; + bd->props.power = FB_BLANK_UNBLANK; + bd->props.fb_blank = FB_BLANK_UNBLANK; + backlight_update_status(bd); + + printk("MXC Backlight Device %s Initialized.\n", dev_name(&pdev->dev)); + return 0; + err0: + kfree(devdata); + return ret; +} + +static int mxcbl_remove(struct platform_device *pdev) +{ + struct backlight_device *bd = platform_get_drvdata(pdev); + + bd->props.brightness = MXC_INTENSITY_OFF; + backlight_update_status(bd); + + backlight_device_unregister(bd); + + return 0; +} + +static struct platform_driver mxcbl_driver = { + .probe = mxcbl_probe, + .remove = mxcbl_remove, + .driver = { + .name = "mxc_ipu_bl", + }, +}; + +static int __init mxcbl_init(void) +{ + return platform_driver_register(&mxcbl_driver); +} + +static void __exit mxcbl_exit(void) +{ + platform_driver_unregister(&mxcbl_driver); +} + +late_initcall(mxcbl_init); +module_exit(mxcbl_exit); + +MODULE_DESCRIPTION("Freescale MXC/i.MX IPU PWM Backlight Driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/video/backlight/mxc_lcdc_bl.c b/drivers/video/backlight/mxc_lcdc_bl.c new file mode 100644 index 000000000000..9dfbca102530 --- /dev/null +++ b/drivers/video/backlight/mxc_lcdc_bl.c @@ -0,0 +1,161 @@ +/* + * Copyright 2007-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +/*! + * @defgroup LCDC_BL MXC LCDC Backlight Driver + */ +/*! + * @file mxc_lcdc_bl.c + * + * @brief Backlight Driver for LCDC PWM on Freescale MXC/i.MX platforms. + * + * This file contains API defined in include/linux/clk.h for setting up and + * retrieving clocks. + * + * Based on Sharp's Corgi Backlight Driver + * + * @ingroup LCDC_BL + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MXC_MAX_INTENSITY 255 +#define MXC_DEFAULT_INTENSITY 127 +#define MXC_INTENSITY_OFF 0 + +extern void mx2fb_set_brightness(uint8_t); + +struct mxcbl_dev_data { + struct clk *clk; + int intensity; +}; + +static int mxcbl_send_intensity(struct backlight_device *bd) +{ + int intensity = bd->props.brightness; + struct mxcbl_dev_data *devdata = dev_get_drvdata(&bd->dev); + + if (bd->props.power != FB_BLANK_UNBLANK) + intensity = 0; + if (bd->props.fb_blank != FB_BLANK_UNBLANK) + intensity = 0; + + if ((devdata->intensity == 0) && (intensity != 0)) + clk_enable(devdata->clk); + + /* PWM contrast control register */ + mx2fb_set_brightness(intensity); + + if ((devdata->intensity != 0) && (intensity == 0)) + clk_disable(devdata->clk); + + devdata->intensity = intensity; + return 0; +} + +static int mxcbl_get_intensity(struct backlight_device *bd) +{ + struct mxcbl_dev_data *devdata = dev_get_drvdata(&bd->dev); + return devdata->intensity; +} + +static int mxcbl_check_fb(struct fb_info *info) +{ + if (strcmp(info->fix.id, "DISP0 BG") == 0) { + return 1; + } + return 0; +} + +static struct backlight_ops mxcbl_ops = { + .get_brightness = mxcbl_get_intensity, + .update_status = mxcbl_send_intensity, + .check_fb = mxcbl_check_fb, +}; + +static int __init mxcbl_probe(struct platform_device *pdev) +{ + struct backlight_device *bd; + struct mxcbl_dev_data *devdata; + int ret = 0; + + devdata = kzalloc(sizeof(struct mxcbl_dev_data), GFP_KERNEL); + if (!devdata) + return -ENOMEM; + + devdata->clk = clk_get(NULL, "lcdc_clk"); + + bd = backlight_device_register(dev_name(&pdev->dev), &pdev->dev, devdata, + &mxcbl_ops); + if (IS_ERR(bd)) { + ret = PTR_ERR(bd); + goto err0; + } + platform_set_drvdata(pdev, bd); + + bd->props.brightness = MXC_DEFAULT_INTENSITY; + bd->props.max_brightness = MXC_MAX_INTENSITY; + bd->props.power = FB_BLANK_UNBLANK; + bd->props.fb_blank = FB_BLANK_UNBLANK; + mx2fb_set_brightness(MXC_DEFAULT_INTENSITY); + + printk("MXC Backlight Device %s Initialized.\n", dev_name(&pdev->dev)); + return 0; + err0: + kfree(devdata); + return ret; +} + +static int mxcbl_remove(struct platform_device *pdev) +{ + struct backlight_device *bd = platform_get_drvdata(pdev); + + bd->props.brightness = MXC_INTENSITY_OFF; + backlight_update_status(bd); + + backlight_device_unregister(bd); + + return 0; +} + +static struct platform_driver mxcbl_driver = { + .probe = mxcbl_probe, + .remove = mxcbl_remove, + .driver = { + .name = "mxc_lcdc_bl", + }, +}; + +static int __init mxcbl_init(void) +{ + return platform_driver_register(&mxcbl_driver); +} + +static void __exit mxcbl_exit(void) +{ + platform_driver_unregister(&mxcbl_driver); +} + +module_init(mxcbl_init); +module_exit(mxcbl_exit); + +MODULE_DESCRIPTION("Freescale MXC/i.MX LCDC PWM Backlight Driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/video/backlight/mxc_mc13892_bl.c b/drivers/video/backlight/mxc_mc13892_bl.c new file mode 100644 index 000000000000..752cae445c5a --- /dev/null +++ b/drivers/video/backlight/mxc_mc13892_bl.c @@ -0,0 +1,180 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +/* +#define MXC_MAX_INTENSITY 255 +#define MXC_DEFAULT_INTENSITY 127 +*/ +/* workaround for atlas hot issue */ +#define MXC_MAX_INTENSITY 128 +#define MXC_DEFAULT_INTENSITY 64 + +#define MXC_INTENSITY_OFF 0 + +struct mxcbl_dev_data { + int intensity; + int suspend; +}; + +static int mxcbl_set_intensity(struct backlight_device *bd) +{ + int brightness = bd->props.brightness; + struct mxcbl_dev_data *devdata = dev_get_drvdata(&bd->dev); + + if (bd->props.power != FB_BLANK_UNBLANK) + brightness = 0; + if (bd->props.fb_blank != FB_BLANK_UNBLANK) + brightness = 0; + if (devdata->suspend) + brightness = 0; + + brightness = brightness / 4; + mc13892_bklit_set_dutycycle(LIT_MAIN, brightness); + devdata->intensity = brightness; + + return 0; +} + +static int mxcbl_get_intensity(struct backlight_device *bd) +{ + struct mxcbl_dev_data *devdata = dev_get_drvdata(&bd->dev); + return devdata->intensity; +} + +static int mxcbl_check_fb(struct backlight_device *bldev, struct fb_info *info) +{ + char *id = info->fix.id; + + if (!strcmp(id, "DISP3 BG")) + return 1; + else + return 0; +} + +static struct backlight_ops bl_ops; + +static int __init mxcbl_probe(struct platform_device *pdev) +{ + int ret = 0; + struct backlight_device *bd; + struct mxcbl_dev_data *devdata; + struct backlight_properties props; + pmic_version_t pmic_version; + + pr_debug("mc13892 backlight start probe\n"); + + devdata = kzalloc(sizeof(struct mxcbl_dev_data), GFP_KERNEL); + if (!devdata) + return -ENOMEM; + + bl_ops.check_fb = mxcbl_check_fb; + bl_ops.get_brightness = mxcbl_get_intensity; + bl_ops.update_status = mxcbl_set_intensity; + memset(&props, 0, sizeof(struct backlight_properties)); + props.max_brightness = MXC_MAX_INTENSITY; + bd = backlight_device_register(dev_name(&pdev->dev), &pdev->dev, devdata, + &bl_ops, &props); + if (IS_ERR(bd)) { + ret = PTR_ERR(bd); + goto err0; + } + + platform_set_drvdata(pdev, bd); + + /* according to LCD spec, current should be 18mA */ + /* workaround for MC13892 TO1.1 crash issue, set current 6mA */ + pmic_version = pmic_get_version(); + if (pmic_version.revision < 20) + mc13892_bklit_set_current(LIT_MAIN, LIT_CURR_6); + else + mc13892_bklit_set_current(LIT_MAIN, LIT_CURR_18); + bd->props.brightness = MXC_DEFAULT_INTENSITY; + bd->props.power = FB_BLANK_UNBLANK; + bd->props.fb_blank = FB_BLANK_UNBLANK; + backlight_update_status(bd); + pr_debug("mc13892 backlight probed successfully\n"); + return 0; + + err0: + kfree(devdata); + return ret; +} + +static int mxcbl_remove(struct platform_device *pdev) +{ + struct backlight_device *bd = platform_get_drvdata(pdev); + struct mxcbl_dev_data *devdata = dev_get_drvdata(&bd->dev); + + kfree(devdata); + backlight_device_unregister(bd); + return 0; +} + +static int mxcbl_suspend(struct platform_device *pdev, pm_message_t state) +{ + struct backlight_device *bd = platform_get_drvdata(pdev); + struct mxcbl_dev_data *devdata = dev_get_drvdata(&bd->dev); + + devdata->suspend = 1; + backlight_update_status(bd); + return 0; +} + +static int mxcbl_resume(struct platform_device *pdev) +{ + struct backlight_device *bd = platform_get_drvdata(pdev); + struct mxcbl_dev_data *devdata = dev_get_drvdata(&bd->dev); + + devdata->suspend = 0; + backlight_update_status(bd); + return 0; +} + +static struct platform_driver mxcbl_driver = { + .probe = mxcbl_probe, + .remove = mxcbl_remove, + .suspend = mxcbl_suspend, + .resume = mxcbl_resume, + .driver = { + .name = "mxc_mc13892_bl", + }, +}; + +static int __init mxcbl_init(void) +{ + return platform_driver_register(&mxcbl_driver); +} + +static void __exit mxcbl_exit(void) +{ + platform_driver_unregister(&mxcbl_driver); +} + +module_init(mxcbl_init); +module_exit(mxcbl_exit); + +MODULE_DESCRIPTION("Freescale MXC/i.MX PMIC Backlight Driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/video/backlight/mxc_pmic_bl.c b/drivers/video/backlight/mxc_pmic_bl.c new file mode 100644 index 000000000000..b8ac44132bfa --- /dev/null +++ b/drivers/video/backlight/mxc_pmic_bl.c @@ -0,0 +1,200 @@ +/* + * Copyright 2007-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +/*! + * @defgroup PMIC_BL MXC PMIC Backlight Driver + */ +/*! + * @file mxc_pmic_bl.c + * + * @brief PMIC Backlight Driver for Freescale MXC/i.MX platforms. + * + * This file contains API defined in include/linux/clk.h for setting up and + * retrieving clocks. + * + * Based on Sharp's Corgi Backlight Driver + * + * @ingroup PMIC_BL + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#define MXC_MAX_INTENSITY 255 +#define MXC_DEFAULT_INTENSITY 127 +#define MXC_INTENSITY_OFF 0 + +struct mxcbl_dev_data { + int bl_id; + int intensity; + struct backlight_ops bl_ops; +}; + +static int pmic_bl_use_count; +static int main_fb_id; +static int sec_fb_id; + +static int mxcbl_send_intensity(struct backlight_device *bd) +{ + int intensity = bd->props.brightness; + struct mxcbl_dev_data *devdata = dev_get_drvdata(&bd->dev); + + if (bd->props.power != FB_BLANK_UNBLANK) + intensity = 0; + if (bd->props.fb_blank != FB_BLANK_UNBLANK) + intensity = 0; + + intensity = intensity / 16; + pmic_bklit_set_dutycycle(devdata->bl_id, intensity); + + devdata->intensity = intensity; + return 0; +} + +static int mxcbl_get_intensity(struct backlight_device *bd) +{ + struct mxcbl_dev_data *devdata = dev_get_drvdata(&bd->dev); + return devdata->intensity; +} + +static int mxcbl_check_main_fb(struct fb_info *info) +{ + int id = info->fix.id[4] - '0'; + + if (id == main_fb_id) { + return 1; + } else { + return 0; + } +} + +static int mxcbl_check_sec_fb(struct backlight_device *bldev, struct fb_info *info) +{ + int id = info->fix.id[4] - '0'; + + if (id == sec_fb_id) { + return 1; + } else { + return 0; + } +} + +static int __init mxcbl_probe(struct platform_device *pdev) +{ + int ret = 0; + struct backlight_device *bd; + struct mxcbl_dev_data *devdata; + struct backlight_properties props; + + devdata = kzalloc(sizeof(struct mxcbl_dev_data), GFP_KERNEL); + if (!devdata) + return -ENOMEM; + devdata->bl_id = pdev->id; + + if (pdev->id == 0) { + devdata->bl_ops.check_fb = mxcbl_check_main_fb; + main_fb_id = (int)pdev->dev.platform_data; + } else { + devdata->bl_ops.check_fb = mxcbl_check_sec_fb; + sec_fb_id = (int)pdev->dev.platform_data; + } + + devdata->bl_ops.get_brightness = mxcbl_get_intensity; + devdata->bl_ops.update_status = mxcbl_send_intensity, + memset(&props, 0, sizeof(struct backlight_properties)); + props.max_brightness = MXC_MAX_INTENSITY; + bd = + backlight_device_register(dev_name(&pdev->dev), &pdev->dev, devdata, + &devdata->bl_ops, &props); + if (IS_ERR(bd)) { + ret = PTR_ERR(bd); + goto err0; + } + + platform_set_drvdata(pdev, bd); + + if (pmic_bl_use_count++ == 0) { + pmic_power_regulator_on(SW_SW3); + pmic_power_regulator_set_lp_mode(SW_SW3, LOW_POWER_CTRL_BY_PIN); + + pmic_bklit_tcled_master_enable(); + pmic_bklit_enable_edge_slow(); + pmic_bklit_set_cycle_time(0); + } + + pmic_bklit_set_current(devdata->bl_id, 7); + bd->props.brightness = MXC_DEFAULT_INTENSITY; + bd->props.power = FB_BLANK_UNBLANK; + bd->props.fb_blank = FB_BLANK_UNBLANK; + backlight_update_status(bd); + + printk("MXC Backlight Device %s Initialized.\n", dev_name(&pdev->dev)); + return 0; + err0: + kfree(devdata); + return ret; +} + +static int mxcbl_remove(struct platform_device *pdev) +{ + struct backlight_device *bd = platform_get_drvdata(pdev); + + bd->props.brightness = MXC_INTENSITY_OFF; + backlight_update_status(bd); + + if (--pmic_bl_use_count == 0) { + pmic_bklit_tcled_master_disable(); + + pmic_power_regulator_off(SW_SW3); + pmic_power_regulator_set_lp_mode(SW_SW3, LOW_POWER_CTRL_BY_PIN); + } + + backlight_device_unregister(bd); + + printk("MXC Backlight Driver Unloaded\n"); + + return 0; +} + +static struct platform_driver mxcbl_driver = { + .probe = mxcbl_probe, + .remove = mxcbl_remove, + .driver = { + .name = "mxc_pmic_bl", + }, +}; + +static int __init mxcbl_init(void) +{ + return platform_driver_register(&mxcbl_driver); +} + +static void __exit mxcbl_exit(void) +{ + platform_driver_unregister(&mxcbl_driver); +} + +module_init(mxcbl_init); +module_exit(mxcbl_exit); + +MODULE_DESCRIPTION("Freescale MXC/i.MX PMIC Backlight Driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/drivers/video/backlight/mxs_bl.c b/drivers/video/backlight/mxs_bl.c new file mode 100644 index 000000000000..f793d330e172 --- /dev/null +++ b/drivers/video/backlight/mxs_bl.c @@ -0,0 +1,385 @@ +/* + * Backlight Driver for Freescale MXS + * + * Embedded Alley Solutions, Inc + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. + * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +struct mxs_bl_data { + struct notifier_block nb; + struct notifier_block reg_nb; + struct notifier_block reg_init_nb; + struct backlight_device *bd; + struct mxs_platform_bl_data *pdata; + int current_intensity; + int saved_intensity; + int mxsbl_suspended; + int mxsbl_constrained; +}; + +static int mxsbl_do_probe(struct mxs_bl_data *data, + struct mxs_platform_bl_data *pdata); +static int mxsbl_set_intensity(struct backlight_device *bd); +static inline void bl_register_reg(struct mxs_platform_bl_data *pdata, + struct mxs_bl_data *data); + + +/* + * If we got here init is done + */ +static int bl_init_reg_callback(struct notifier_block *self, + unsigned long event, void *data) +{ + struct mxs_bl_data *bdata; + struct mxs_platform_bl_data *pdata; + struct regulator *r = regulator_get(NULL, "mxs-bl-1"); + + bdata = container_of(self, struct mxs_bl_data, reg_init_nb); + pdata = bdata->pdata; + + if (r && !IS_ERR(r)) + regulator_put(r); + else + goto out; + + bl_register_reg(pdata, bdata); + + if (pdata->regulator) { + + printk(KERN_NOTICE"%s: setting intensity\n", __func__); + + bus_unregister_notifier(&platform_bus_type, + &bdata->reg_init_nb); + mutex_lock(&bdata->bd->ops_lock); + mxsbl_set_intensity(bdata->bd); + mutex_unlock(&bdata->bd->ops_lock); + } + +out: + return 0; +} + +static int bl_reg_callback(struct notifier_block *self, + unsigned long event, void *data) +{ + struct mxs_bl_data *bdata; + struct mxs_platform_bl_data *pdata; + bdata = container_of(self, struct mxs_bl_data, reg_nb); + pdata = bdata->pdata; + + mutex_lock(&bdata->bd->ops_lock); + + switch (event) { + case MXS_REG5V_IS_USB: + bdata->bd->props.max_brightness = pdata->bl_cons_intensity; + bdata->bd->props.brightness = pdata->bl_cons_intensity; + bdata->saved_intensity = bdata->current_intensity; + bdata->mxsbl_constrained = 1; + break; + case MXS_REG5V_NOT_USB: + bdata->bd->props.max_brightness = pdata->bl_max_intensity; + bdata->bd->props.brightness = bdata->saved_intensity; + bdata->mxsbl_constrained = 0; + break; + } + + mxsbl_set_intensity(bdata->bd); + mutex_unlock(&bdata->bd->ops_lock); + return 0; +} + +static inline void bl_unregister_reg(struct mxs_platform_bl_data *pdata, + struct mxs_bl_data *data) +{ + if (!pdata) + return; + if (pdata->regulator) + regulator_unregister_notifier(pdata->regulator, + &data->reg_nb); + if (pdata->regulator) + regulator_put(pdata->regulator); + pdata->regulator = NULL; +} + +static inline void bl_register_reg(struct mxs_platform_bl_data *pdata, + struct mxs_bl_data *data) +{ + pdata->regulator = regulator_get(NULL, "mxs-bl-1"); + if (pdata->regulator && !IS_ERR(pdata->regulator)) { + regulator_set_mode(pdata->regulator, REGULATOR_MODE_FAST); + if (pdata->regulator) { + data->reg_nb.notifier_call = bl_reg_callback; + regulator_register_notifier(pdata->regulator, + &data->reg_nb); + } + } else{ + printk(KERN_ERR "%s: failed to get regulator\n", __func__); + pdata->regulator = NULL; + } + +} + +static int bl_callback(struct notifier_block *self, + unsigned long event, void *data) +{ + struct mxs_platform_fb_entry *pentry = data; + struct mxs_bl_data *bdata; + struct mxs_platform_bl_data *pdata; + + switch (event) { + case MXS_LCDIF_PANEL_INIT: + bdata = container_of(self, struct mxs_bl_data, nb); + pdata = pentry->bl_data; + bdata->pdata = pdata; + if (pdata) { + bl_register_reg(pdata, bdata); + if (!pdata->regulator) { + /* wait for regulator to appear */ + bdata->reg_init_nb.notifier_call = + bl_init_reg_callback; + bus_register_notifier(&platform_bus_type, + &bdata->reg_init_nb); + } + return mxsbl_do_probe(bdata, pdata); + } + break; + + case MXS_LCDIF_PANEL_RELEASE: + bdata = container_of(self, struct mxs_bl_data, nb); + pdata = pentry->bl_data; + if (pdata) { + bus_unregister_notifier(&platform_bus_type, + &bdata->reg_init_nb); + bl_unregister_reg(pdata, bdata); + pdata->free_bl(pdata); + } + bdata->pdata = NULL; + break; + } + return 0; +} + +#ifdef CONFIG_PM +static int mxsbl_suspend(struct platform_device *pdev, pm_message_t state) +{ + struct mxs_bl_data *data = platform_get_drvdata(pdev); + struct mxs_platform_bl_data *pdata = data->pdata; + + data->mxsbl_suspended = 1; + if (pdata) { + dev_dbg(&pdev->dev, "real suspend\n"); + mxsbl_set_intensity(data->bd); + } + return 0; +} + +static int mxsbl_resume(struct platform_device *pdev) +{ + struct mxs_bl_data *data = platform_get_drvdata(pdev); + struct mxs_platform_bl_data *pdata = data->pdata; + int ret = 0; + + data->mxsbl_suspended = 0; + if (pdata) { + dev_dbg(&pdev->dev, "real resume\n"); + pdata->free_bl(pdata); + ret = pdata->init_bl(pdata); + if (ret) + goto out; + mxsbl_set_intensity(data->bd); + } +out: + return ret; +} +#else +#define mxsbl_suspend NULL +#define mxsbl_resume NULL +#endif +/* + * This function should be called with bd->ops_lock held + * Suspend/resume ? + */ +static int mxsbl_set_intensity(struct backlight_device *bd) +{ + struct platform_device *pdev = dev_get_drvdata(&bd->dev); + struct mxs_bl_data *data = platform_get_drvdata(pdev); + struct mxs_platform_bl_data *pdata = data->pdata; + + if (pdata) { + int ret; + + ret = pdata->set_bl_intensity(pdata, bd, + data->mxsbl_suspended); + if (ret) + bd->props.brightness = data->current_intensity; + else + data->current_intensity = bd->props.brightness; + return ret; + } else + return -ENODEV; +} + +static int mxsbl_get_intensity(struct backlight_device *bd) +{ + struct platform_device *pdev = dev_get_drvdata(&bd->dev); + struct mxs_bl_data *data = platform_get_drvdata(pdev); + + return data->current_intensity; +} + +static struct backlight_ops mxsbl_ops = { + .get_brightness = mxsbl_get_intensity, + .update_status = mxsbl_set_intensity, +}; + +static int mxsbl_do_probe(struct mxs_bl_data *data, + struct mxs_platform_bl_data *pdata) +{ + int ret = pdata->init_bl(pdata); + + if (ret) + goto out; + + data->bd->props.power = FB_BLANK_UNBLANK; + data->bd->props.fb_blank = FB_BLANK_UNBLANK; + if (data->mxsbl_constrained) { + data->bd->props.max_brightness = pdata->bl_cons_intensity; + data->bd->props.brightness = pdata->bl_cons_intensity; + } else { + data->bd->props.max_brightness = pdata->bl_max_intensity; + data->bd->props.brightness = pdata->bl_default_intensity; + } + + data->pdata = pdata; + mxsbl_set_intensity(data->bd); + +out: + return ret; +} + +static int __init mxsbl_probe(struct platform_device *pdev) +{ + struct mxs_bl_data *data; + struct mxs_platform_bl_data *pdata = pdev->dev.platform_data; + int ret = 0; + + data = kzalloc(sizeof(*data), GFP_KERNEL); + if (!data) { + ret = -ENOMEM; + goto out; + } + data->bd = backlight_device_register(pdev->name, &pdev->dev, pdev, + &mxsbl_ops); + if (IS_ERR(data->bd)) { + ret = PTR_ERR(data->bd); + goto out_1; + } + + get_device(&pdev->dev); + + data->nb.notifier_call = bl_callback; + mxs_lcdif_register_client(&data->nb); + platform_set_drvdata(pdev, data); + + if (pdata) { + ret = mxsbl_do_probe(data, pdata); + if (ret) + goto out_2; + } + + goto out; + +out_2: + put_device(&pdev->dev); +out_1: + kfree(data); +out: + return ret; +} + +static int mxsbl_remove(struct platform_device *pdev) +{ + struct mxs_platform_bl_data *pdata = pdev->dev.platform_data; + struct mxs_bl_data *data = platform_get_drvdata(pdev); + struct backlight_device *bd = data->bd; + + bd->props.power = FB_BLANK_POWERDOWN; + bd->props.fb_blank = FB_BLANK_POWERDOWN; + bd->props.brightness = 0; + data->current_intensity = bd->props.brightness; + + if (pdata) { + pdata->set_bl_intensity(pdata, bd, data->mxsbl_suspended); + if (pdata->free_bl) + pdata->free_bl(pdata); + } + backlight_device_unregister(bd); + if (pdata->regulator) + regulator_put(pdata->regulator); + put_device(&pdev->dev); + platform_set_drvdata(pdev, NULL); + mxs_lcdif_unregister_client(&data->nb); + kfree(data); + + return 0; +} + +static struct platform_driver mxsbl_driver = { + .probe = mxsbl_probe, + .remove = __devexit_p(mxsbl_remove), + .suspend = mxsbl_suspend, + .resume = mxsbl_resume, + .driver = { + .name = "mxs-bl", + .owner = THIS_MODULE, + }, +}; + +static int __init mxs_init(void) +{ + return platform_driver_register(&mxsbl_driver); +} + +static void __exit mxs_exit(void) +{ + platform_driver_unregister(&mxsbl_driver); +} + +module_init(mxs_init); +module_exit(mxs_exit); + +MODULE_AUTHOR("Embedded Alley Solutions, Inc "); +MODULE_DESCRIPTION("MXS Backlight Driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/video/backlight/wm8350_bl.c b/drivers/video/backlight/wm8350_bl.c new file mode 100644 index 000000000000..6865b753d8ce --- /dev/null +++ b/drivers/video/backlight/wm8350_bl.c @@ -0,0 +1,299 @@ +/* + * Backlight driver for DCDC2 on i.MX32ADS board + * + * Copyright(C) 2007 Wolfson Microelectronics PLC. + * Copyright (C) 2010 Freescale Semiconductor, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct wm8350_backlight { + struct backlight_properties props; + struct backlight_device *device; + struct regulator *dcdc; + struct regulator *isink; + struct notifier_block notifier; + struct work_struct work; + struct mutex mutex; + int intensity; + int suspend; + int retries; +}; + +/* hundredths of uA, 405 = 4.05 uA */ +static const int intensity_huA[] = { + 405, 482, 573, 681, 810, 963, 1146, 1362, 1620, 1927, 2291, 2725, + 3240, 3853, 4582, 5449, 6480, 7706, 9164, 10898, 12960, 15412, 18328, + 21796, 25920, 30824, 36656, 43592, 51840, 61648, 73313, 87184, + 103680, 123297, 146626, 174368, 207360, 246594, 293251, 348737, + 414720, 493188, 586503, 697473, 829440, 986376, 1173005, 1394946, + 1658880, 1972752, 2346011, 2789892, 3317760, 3945504, 4692021, + 5579785, 6635520, 7891008, 9384042, 11159570, 13271040, 15782015, + 18768085, 22319140, +}; + +static void bl_work(struct work_struct *work) +{ + struct wm8350_backlight *bl = + container_of(work, struct wm8350_backlight, work); + struct regulator *isink = bl->isink; + + mutex_lock(&bl->mutex); + if (bl->intensity >= 0 && + bl->intensity < ARRAY_SIZE(intensity_huA)) { + bl->retries = 0; + regulator_set_current_limit(isink, + 0, intensity_huA[bl->intensity] / 100); + } else + printk(KERN_ERR "wm8350: Backlight intensity error\n"); + mutex_unlock(&bl->mutex); +} + +static int wm8350_bl_notifier(struct notifier_block *self, + unsigned long event, void *data) +{ + struct wm8350_backlight *bl = + container_of(self, struct wm8350_backlight, notifier); + struct regulator *isink = bl->isink; + + if (event & REGULATOR_EVENT_UNDER_VOLTAGE) + printk(KERN_ERR "wm8350: BL DCDC undervoltage\n"); + if (event & REGULATOR_EVENT_REGULATION_OUT) + printk(KERN_ERR "wm8350: BL ISINK out of regulation\n"); + + mutex_lock(&bl->mutex); + if (bl->retries) { + bl->retries--; + regulator_disable(isink); + regulator_set_current_limit(isink, 0, bl->intensity); + regulator_enable(isink); + } else { + printk(KERN_ERR + "wm8350: BL regulation retry failure - disable\n"); + bl->intensity = 0; + regulator_disable(isink); + } + mutex_unlock(&bl->mutex); + return 0; +} + +static int wm8350_bl_send_intensity(struct backlight_device *bd) +{ + struct wm8350_backlight *bl = + (struct wm8350_backlight *)dev_get_drvdata(&bd->dev); + int intensity = bd->props.brightness; + + if (bd->props.power != FB_BLANK_UNBLANK) + intensity = 0; + if (bd->props.fb_blank != FB_BLANK_UNBLANK) + intensity = 0; + if (bl->suspend) + intensity = 0; + + mutex_lock(&bl->mutex); + bl->intensity = intensity; + mutex_unlock(&bl->mutex); + schedule_work(&bl->work); + + return 0; +} + +#ifdef CONFIG_PM +static int wm8350_bl_suspend(struct platform_device *pdev, pm_message_t state) +{ + struct wm8350_backlight *bl = + (struct wm8350_backlight *)platform_get_drvdata(pdev); + + bl->suspend = 1; + backlight_update_status(bl->device); + return 0; +} + +static int wm8350_bl_resume(struct platform_device *pdev) +{ + struct wm8350_backlight *bl = + (struct wm8350_backlight *)platform_get_drvdata(pdev); + + bl->suspend = 0; + backlight_update_status(bl->device); + return 0; +} +#else +#define wm8350_bl_suspend NULL +#define wm8350_bl_resume NULL +#endif + +static int wm8350_bl_get_intensity(struct backlight_device *bd) +{ + struct wm8350_backlight *bl = + (struct wm8350_backlight *)dev_get_drvdata(&bd->dev); + return bl->intensity; +} + +static struct backlight_ops wm8350_bl_ops = { + .get_brightness = wm8350_bl_get_intensity, + .update_status = wm8350_bl_send_intensity, +}; + +static int wm8350_bl_probe(struct platform_device *pdev) +{ + struct regulator *isink, *dcdc; + struct wm8350_backlight *bl; + struct wm8350_bl_platform_data *pdata = pdev->dev.platform_data; + struct wm8350 *pmic; + int ret; + + if (pdata == NULL) { + printk(KERN_ERR "%s: no platform data\n", __func__); + return -ENODEV; + } + + if (pdata->isink != WM8350_ISINK_A && pdata->isink != WM8350_ISINK_B) { + printk(KERN_ERR "%s: invalid ISINK\n", __func__); + return -EINVAL; + } + if (pdata->dcdc != WM8350_DCDC_2 && pdata->dcdc != WM8350_DCDC_5) { + printk(KERN_ERR "%s: invalid DCDC\n", __func__); + return -EINVAL; + } + + printk(KERN_INFO "wm8350: backlight using %s and %s\n", + pdata->isink == WM8350_ISINK_A ? "ISINKA" : "ISINKB", + pdata->dcdc == WM8350_DCDC_2 ? "DCDC2" : "DCDC5"); + + isink = regulator_get(&pdev->dev, + pdata->isink == WM8350_ISINK_A ? "ISINKA" : "ISINKB"); + if (IS_ERR(isink) || isink == NULL) { + printk(KERN_ERR "%s: cant get ISINK\n", __func__); + return PTR_ERR(isink); + } + + dcdc = regulator_get(&pdev->dev, + pdata->dcdc == WM8350_DCDC_2 ? "DCDC2" : "DCDC5"); + if (IS_ERR(dcdc) || dcdc == NULL) { + printk(KERN_ERR "%s: cant get DCDC\n", __func__); + regulator_put(isink); + return PTR_ERR(dcdc); + } + + bl = kzalloc(sizeof(*bl), GFP_KERNEL); + if (bl == NULL) { + regulator_put(isink); + regulator_put(dcdc); + return -ENOMEM; + } + + mutex_init(&bl->mutex); + INIT_WORK(&bl->work, bl_work); + bl->props.max_brightness = pdata->max_brightness; + bl->props.power = pdata->power; + bl->props.brightness = pdata->brightness; + bl->retries = pdata->retries; + bl->dcdc = dcdc; + bl->isink = isink; + platform_set_drvdata(pdev, bl); + pmic = regulator_get_drvdata(bl->isink); + + wm8350_bl_ops.check_fb = pdata->check_fb; + + bl->device = backlight_device_register(dev_name(&pdev->dev), &pdev->dev, + bl, &wm8350_bl_ops); + if (IS_ERR(bl->device)) { + ret = PTR_ERR(bl->device); + regulator_put(dcdc); + regulator_put(isink); + kfree(bl); + return ret; + } + + bl->notifier.notifier_call = wm8350_bl_notifier; + regulator_register_notifier(dcdc, &bl->notifier); + regulator_register_notifier(isink, &bl->notifier); + bl->device->props = bl->props; + + regulator_set_current_limit(isink, 0, 20000); + + wm8350_isink_set_flash(pmic, pdata->isink, + WM8350_ISINK_FLASH_DISABLE, + WM8350_ISINK_FLASH_TRIG_BIT, + WM8350_ISINK_FLASH_DUR_32MS, + WM8350_ISINK_FLASH_ON_1_00S, + WM8350_ISINK_FLASH_OFF_1_00S, + WM8350_ISINK_FLASH_MODE_EN); + + wm8350_dcdc25_set_mode(pmic, pdata->dcdc, + WM8350_ISINK_MODE_BOOST, WM8350_ISINK_ILIM_NORMAL, + pdata->voltage_ramp, pdata->isink == WM8350_ISINK_A ? + WM8350_DC5_FBSRC_ISINKA : WM8350_DC5_FBSRC_ISINKB); + + wm8350_dcdc_set_slot(pmic, pdata->dcdc, 15, 0, + pdata->dcdc == WM8350_DCDC_2 ? + WM8350_DC2_ERRACT_SHUTDOWN_CONV : WM8350_DC5_ERRACT_NONE); + + regulator_enable(isink); + backlight_update_status(bl->device); + return 0; +} + +static int wm8350_bl_remove(struct platform_device *pdev) +{ + struct wm8350_backlight *bl = + (struct wm8350_backlight *)platform_get_drvdata(pdev); + struct regulator *isink = bl->isink, *dcdc = bl->dcdc; + + bl->intensity = 0; + backlight_update_status(bl->device); + schedule_work(&bl->work); + flush_scheduled_work(); + backlight_device_unregister(bl->device); + + regulator_set_current_limit(isink, 0, 0); + regulator_disable(isink); + regulator_unregister_notifier(isink, &bl->notifier); + regulator_unregister_notifier(dcdc, &bl->notifier); + regulator_put(isink); + regulator_put(dcdc); + return 0; +} + +struct platform_driver imx32ads_backlight_driver = { + .driver = { + .name = "wm8350-bl", + .owner = THIS_MODULE, + }, + .probe = wm8350_bl_probe, + .remove = wm8350_bl_remove, + .suspend = wm8350_bl_suspend, + .resume = wm8350_bl_resume, +}; + +static int __devinit imx32ads_backlight_init(void) +{ + return platform_driver_register(&imx32ads_backlight_driver); +} + +static void imx32ads_backlight_exit(void) +{ + platform_driver_unregister(&imx32ads_backlight_driver); +} + +device_initcall_sync(imx32ads_backlight_init); +module_exit(imx32ads_backlight_exit); + +MODULE_AUTHOR("Liam Girdwood "); +MODULE_DESCRIPTION("WM8350 Backlight driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/video/mxc/Kconfig b/drivers/video/mxc/Kconfig new file mode 100644 index 000000000000..66a7f84c5656 --- /dev/null +++ b/drivers/video/mxc/Kconfig @@ -0,0 +1,103 @@ +config FB_MXC + tristate "MXC Framebuffer support" + depends on FB && (MXC_IPU || ARCH_MX21 || ARCH_MX27 || ARCH_MX25) + select FB_CFB_FILLRECT + select FB_CFB_COPYAREA + select FB_CFB_IMAGEBLIT + select FB_MODE_HELPERS + default y + help + This is a framebuffer device for the MXC LCD Controller. + See for information on framebuffer + devices. + + If you plan to use the LCD display with your MXC system, say + Y here. + +config FB_MXC_SYNC_PANEL + depends on FB_MXC + tristate "Synchronous Panel Framebuffer" + default y + +config FB_MXC_EPSON_VGA_SYNC_PANEL + depends on FB_MXC_SYNC_PANEL + tristate "Epson VGA Panel" + default n + +config FB_MXC_TVOUT_TVE + tristate "MXC TVE TV Out Encoder" + depends on FB_MXC_SYNC_PANEL + depends on MXC_IPU_V3 + +config FB_MXC_LDB + tristate "MXC LDB" + depends on FB_MXC_SYNC_PANEL + depends on MXC_IPU_V3 + +config FB_MXC_CLAA_WVGA_SYNC_PANEL + depends on FB_MXC_SYNC_PANEL + tristate "CLAA WVGA Panel" + +config FB_MXC_CH7026 + depends on FB_MXC_SYNC_PANEL + tristate "Chrontel CH7026 VGA Interface Chip" + +config FB_MXC_TVOUT_CH7024 + tristate "CH7024 TV Out Encoder" + depends on FB_MXC_SYNC_PANEL + +config FB_MXC_LOW_PWR_DISPLAY + bool "Low Power Display Refresh Mode" + depends on FB_MXC_SYNC_PANEL && MXC_FB_IRAM + default y + +config FB_MXC_INTERNAL_MEM + bool "Framebuffer in Internal RAM" + depends on FB_MXC_SYNC_PANEL && MXC_FB_IRAM + default y + +config FB_MXC_ASYNC_PANEL + depends on FB_MXC + bool "Asynchronous Panels" + default n + +menu "Asynchronous Panel Type" + depends on FB_MXC_ASYNC_PANEL && FB_MXC + +config FB_MXC_EPSON_PANEL + depends on FB_MXC_ASYNC_PANEL + default n + bool "Epson 176x220 Panel" + +endmenu + +config FB_MXC_EINK_PANEL + depends on FB_MXC + depends on DMA_ENGINE + select FB_DEFERRED_IO + tristate "E-Ink Panel Framebuffer" + +config FB_MXC_EINK_AUTO_UPDATE_MODE + bool "E-Ink Auto-update Mode Support" + default n + depends on FB_MXC_EINK_PANEL + +config FB_MXC_ELCDIF_FB + depends on FB && ARCH_MXC + tristate "Support MXC ELCDIF framebuffer" + +choice + prompt "Async Panel Interface Type" + depends on FB_MXC_ASYNC_PANEL && FB_MXC + default FB_MXC_ASYNC_PANEL_IFC_16_BIT + +config FB_MXC_ASYNC_PANEL_IFC_8_BIT + bool "8-bit Parallel Bus Interface" + +config FB_MXC_ASYNC_PANEL_IFC_16_BIT + bool "16-bit Parallel Bus Interface" + +config FB_MXC_ASYNC_PANEL_IFC_SERIAL + bool "Serial Bus Interface" + +endchoice diff --git a/drivers/video/mxc/Makefile b/drivers/video/mxc/Makefile new file mode 100644 index 000000000000..c428bb95a948 --- /dev/null +++ b/drivers/video/mxc/Makefile @@ -0,0 +1,24 @@ +ifeq ($(CONFIG_ARCH_MX21)$(CONFIG_ARCH_MX27)$(CONFIG_ARCH_MX25),y) + obj-$(CONFIG_FB_MXC_TVOUT) += fs453.o + obj-$(CONFIG_FB_MXC_SYNC_PANEL) += mx2fb.o mxcfb_modedb.o + obj-$(CONFIG_FB_MXC_EPSON_PANEL) += mx2fb_epson.o +else +ifeq ($(CONFIG_MXC_IPU_V1),y) + obj-$(CONFIG_FB_MXC_SYNC_PANEL) += mxcfb.o mxcfb_modedb.o +else + obj-$(CONFIG_FB_MXC_SYNC_PANEL) += mxc_ipuv3_fb.o +endif + obj-$(CONFIG_FB_MXC_EPSON_PANEL) += mxcfb_epson.o + obj-$(CONFIG_FB_MXC_EPSON_QVGA_PANEL) += mxcfb_epson_qvga.o + obj-$(CONFIG_FB_MXC_TOSHIBA_QVGA_PANEL) += mxcfb_toshiba_qvga.o + obj-$(CONFIG_FB_MXC_SHARP_128_PANEL) += mxcfb_sharp_128x128.o +endif +obj-$(CONFIG_FB_MXC_EPSON_VGA_SYNC_PANEL) += mxcfb_epson_vga.o +obj-$(CONFIG_FB_MXC_CLAA_WVGA_SYNC_PANEL) += mxcfb_claa_wvga.o +obj-$(CONFIG_FB_MXC_TVOUT_CH7024) += ch7024.o +obj-$(CONFIG_FB_MXC_TVOUT_TVE) += tve.o +obj-$(CONFIG_FB_MXC_LDB) += ldb.o +obj-$(CONFIG_FB_MXC_CH7026) += mxcfb_ch7026.o +#obj-$(CONFIG_FB_MODE_HELPERS) += mxc_edid.o +obj-$(CONFIG_FB_MXC_EINK_PANEL) += mxc_epdc_fb.o +obj-$(CONFIG_FB_MXC_ELCDIF_FB) += mxc_elcdif_fb.o diff --git a/drivers/video/mxc/ch7024.c b/drivers/video/mxc/ch7024.c new file mode 100644 index 000000000000..48e6b09feecb --- /dev/null +++ b/drivers/video/mxc/ch7024.c @@ -0,0 +1,866 @@ +/* + * Copyright 2007-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file ch7024.c + * @brief Driver for CH7024 TV encoder + * + * @ingroup Framebuffer + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/*! + * CH7024 registers + */ +#define CH7024_DEVID 0x00 +#define CH7024_REVID 0x01 +#define CH7024_PG 0x02 + +#define CH7024_RESET 0x03 +#define CH7024_POWER 0x04 +#define CH7024_TVHUE 0x05 +#define CH7024_TVSAT 0x06 +#define CH7024_TVCTA 0x07 +#define CH7024_TVBRI 0x08 +#define CH7024_TVSHARP 0x09 +#define CH7024_OUT_FMT 0x0A +#define CH7024_XTAL 0x0B +#define CH7024_IDF1 0x0C +#define CH7024_IDF2 0x0D +#define CH7024_SYNC 0x0E +#define CH7024_TVFILTER1 0x0F +#define CH7024_TVFILTER2 0x10 +#define CH7024_IN_TIMING1 0x11 +#define CH7024_IN_TIMING2 0x12 +#define CH7024_IN_TIMING3 0x13 +#define CH7024_IN_TIMING4 0x14 +#define CH7024_IN_TIMING5 0x15 +#define CH7024_IN_TIMING6 0x16 +#define CH7024_IN_TIMING7 0x17 +#define CH7024_IN_TIMING8 0x18 +#define CH7024_IN_TIMING9 0x19 +#define CH7024_IN_TIMING10 0x1A +#define CH7024_IN_TIMING11 0x1B +#define CH7024_ACIV 0x1C +#define CH7024_CLK_TREE 0x1D +#define CH7024_OUT_TIMING1 0x1E +#define CH7024_OUT_TIMING2 0x1F +#define CH7024_V_POS1 0x20 +#define CH7024_V_POS2 0x21 +#define CH7024_H_POS1 0x22 +#define CH7024_H_POS2 0x23 +#define CH7024_PCLK_A1 0x24 +#define CH7024_PCLK_A2 0x25 +#define CH7024_PCLK_A3 0x26 +#define CH7024_PCLK_A4 0x27 +#define CH7024_CLK_P1 0x28 +#define CH7024_CLK_P2 0x29 +#define CH7024_CLK_P3 0x2A +#define CH7024_CLK_N1 0x2B +#define CH7024_CLK_N2 0x2C +#define CH7024_CLK_N3 0x2D +#define CH7024_CLK_T 0x2E +#define CH7024_PLL1 0x2F +#define CH7024_PLL2 0x30 +#define CH7024_PLL3 0x31 +#define CH7024_SC_FREQ1 0x34 +#define CH7024_SC_FREQ2 0x35 +#define CH7024_SC_FREQ3 0x36 +#define CH7024_SC_FREQ4 0x37 +#define CH7024_DAC_TRIM 0x62 +#define CH7024_DATA_IO 0x63 +#define CH7024_ATT_DISP 0x7E + +/*! + * CH7024 register values + */ +/* video output formats */ +#define CH7024_VOS_NTSC_M 0x0 +#define CH7024_VOS_NTSC_J 0x1 +#define CH7024_VOS_NTSC_443 0x2 +#define CH7024_VOS_PAL_BDGHKI 0x3 +#define CH7024_VOS_PAL_M 0x4 +#define CH7024_VOS_PAL_N 0x5 +#define CH7024_VOS_PAL_NC 0x6 +#define CH7024_VOS_PAL_60 0x7 +/* crystal predefined */ +#define CH7024_XTAL_13MHZ 0x4 +#define CH7024_XTAL_26MHZ 0xB + +/* chip ID */ +#define CH7024_DEVICE_ID 0x45 + +/* clock source define */ +#define CLK_HIGH 0 +#define CLK_LOW 1 + +/* CH7024 presets structs */ +struct ch7024_clock { + u32 A; + u32 P; + u32 N; + u32 T; + u8 PLLN1; + u8 PLLN2; + u8 PLLN3; +}; + +struct ch7024_input_timing { + u32 HTI; + u32 VTI; + u32 HAI; + u32 VAI; + u32 HW; + u32 HO; + u32 VW; + u32 VO; + u32 VOS; +}; + +#define TVOUT_FMT_OFF 0 +#define TVOUT_FMT_NTSC 1 +#define TVOUT_FMT_PAL 2 + +static int enabled; /* enable power on or not */ +static int pm_status; /* status before suspend */ + +static struct i2c_client *ch7024_client; +static struct fb_info *ch7024_fbi; +static int ch7024_cur_mode; +static u32 detect_gpio; +static struct regulator *io_reg; +static struct regulator *core_reg; +static struct regulator *analog_reg; + +static void hp_detect_wq_handler(struct work_struct *); +DECLARE_DELAYED_WORK(ch7024_wq, hp_detect_wq_handler); + +static inline int ch7024_read_reg(u8 reg) +{ + return i2c_smbus_read_byte_data(ch7024_client, reg); +} + +static inline int ch7024_write_reg(u8 reg, u8 word) +{ + return i2c_smbus_write_byte_data(ch7024_client, reg, word); +} + +/** + * PAL B/D/G/H/K/I clock and timting structures + */ +static struct ch7024_clock ch7024_clk_pal = { + .A = 0x0, + .P = 0x36b00, + .N = 0x41eb00, + .T = 0x3f, + .PLLN1 = 0x0, + .PLLN2 = 0x1b, + .PLLN3 = 0x12, +}; + +static struct ch7024_input_timing ch7024_timing_pal = { + .HTI = 950, + .VTI = 560, + .HAI = 640, + .VAI = 480, + .HW = 60, + .HO = 250, + .VW = 40, + .VO = 40, + .VOS = CH7024_VOS_PAL_BDGHKI, +}; + +/** + * NTSC_M clock and timting structures + * TODO: change values to work well. + */ +static struct ch7024_clock ch7024_clk_ntsc = { + .A = 0x0, + .P = 0x2ac90, + .N = 0x36fc90, + .T = 0x3f, + .PLLN1 = 0x0, + .PLLN2 = 0x1b, + .PLLN3 = 0x12, +}; + +static struct ch7024_input_timing ch7024_timing_ntsc = { + .HTI = 801, + .VTI = 554, + .HAI = 640, + .VAI = 480, + .HW = 60, + .HO = 101, + .VW = 20, + .VO = 54, + .VOS = CH7024_VOS_NTSC_M, +}; + +static struct fb_videomode video_modes[] = { + { + /* NTSC TV output */ + "TV-NTSC", 60, 640, 480, 37594, + 0, 101, + 0, 54, + 60, 20, + FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, + FB_VMODE_NONINTERLACED, + 0,}, + { + /* PAL TV output */ + "TV-PAL", 50, 640, 480, 37594, + 0, 250, + 0, 40, + 60, 40, + FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, + FB_VMODE_NONINTERLACED, + 0,}, +}; + +/** + * ch7024_setup + * initial the CH7024 chipset by setting register + * @param: + * vos: output video format + * @return: + * 0 successful + * otherwise failed + */ +static int ch7024_setup(int vos) +{ + struct ch7024_input_timing *ch_timing; + struct ch7024_clock *ch_clk; +#ifdef DEBUG_CH7024 + int i, val; +#endif + + /* select output video format */ + if (vos == TVOUT_FMT_PAL) { + ch_timing = &ch7024_timing_pal; + ch_clk = &ch7024_clk_pal; + pr_debug("CH7024: change to PAL video\n"); + } else if (vos == TVOUT_FMT_NTSC) { + ch_timing = &ch7024_timing_ntsc; + ch_clk = &ch7024_clk_ntsc; + pr_debug("CH7024: change to NTSC video\n"); + } else { + + pr_debug("CH7024: no such video format.\n"); + return -EINVAL; + } + ch7024_write_reg(CH7024_RESET, 0x0); + ch7024_write_reg(CH7024_RESET, 0x3); + + ch7024_write_reg(CH7024_POWER, 0x0C); /* power on, disable DAC */ + ch7024_write_reg(CH7024_XTAL, CH7024_XTAL_26MHZ); + ch7024_write_reg(CH7024_SYNC, 0x0D); /* SLAVE mode, and TTL */ + ch7024_write_reg(CH7024_IDF1, 0x00); + ch7024_write_reg(CH7024_TVFILTER1, 0x00); /* set XCH=0 */ + ch7024_write_reg(CH7024_CLK_TREE, 0x9E); /* Invert input clk */ + + /* set input clock and divider */ + /* set PLL */ + ch7024_write_reg(CH7024_PLL1, ch_clk->PLLN1); + ch7024_write_reg(CH7024_PLL2, ch_clk->PLLN2); + ch7024_write_reg(CH7024_PLL3, ch_clk->PLLN3); + /* set A register */ + ch7024_write_reg(CH7024_PCLK_A1, (ch_clk->A >> 24) & 0xFF); + ch7024_write_reg(CH7024_PCLK_A2, (ch_clk->A >> 16) & 0xFF); + ch7024_write_reg(CH7024_PCLK_A3, (ch_clk->A >> 8) & 0xFF); + ch7024_write_reg(CH7024_PCLK_A4, ch_clk->A & 0xFF); + /* set P register */ + ch7024_write_reg(CH7024_CLK_P1, (ch_clk->P >> 16) & 0xFF); + ch7024_write_reg(CH7024_CLK_P2, (ch_clk->P >> 8) & 0xFF); + ch7024_write_reg(CH7024_CLK_P3, ch_clk->P & 0xFF); + /* set N register */ + ch7024_write_reg(CH7024_CLK_N1, (ch_clk->N >> 16) & 0xFF); + ch7024_write_reg(CH7024_CLK_N2, (ch_clk->N >> 8) & 0xFF); + ch7024_write_reg(CH7024_CLK_N3, ch_clk->N & 0xFF); + /* set T register */ + ch7024_write_reg(CH7024_CLK_T, ch_clk->T & 0xFF); + + /* set sub-carrier frequency generation method */ + ch7024_write_reg(CH7024_ACIV, 0x00); /* ACIV = 0, automatical SCF */ + /* TV out pattern and DAC switch */ + ch7024_write_reg(CH7024_OUT_FMT, (0x10 | ch_timing->VOS) & 0xFF); + + /* input settings */ + /* input format, RGB666 */ + ch7024_write_reg(CH7024_IDF2, 0x02); + /* HAI/HTI VAI */ + ch7024_write_reg(CH7024_IN_TIMING1, ((ch_timing->HTI >> 5) & 0x38) | + ((ch_timing->HAI >> 8) & 0x07)); + ch7024_write_reg(CH7024_IN_TIMING2, ch_timing->HAI & 0xFF); + ch7024_write_reg(CH7024_IN_TIMING8, ch_timing->VAI & 0xFF); + /* HTI VTI */ + ch7024_write_reg(CH7024_IN_TIMING3, ch_timing->HTI & 0xFF); + ch7024_write_reg(CH7024_IN_TIMING9, ch_timing->VTI & 0xFF); + /* HW/HO(h) VW */ + ch7024_write_reg(CH7024_IN_TIMING4, ((ch_timing->HW >> 5) & 0x18) | + ((ch_timing->HO >> 8) & 0x7)); + ch7024_write_reg(CH7024_IN_TIMING6, ch_timing->HW & 0xFF); + ch7024_write_reg(CH7024_IN_TIMING11, ch_timing->VW & 0x3F); + /* HO(l) VO/VAI/VTI */ + ch7024_write_reg(CH7024_IN_TIMING5, ch_timing->HO & 0xFF); + ch7024_write_reg(CH7024_IN_TIMING7, ((ch_timing->VO >> 4) & 0x30) | + ((ch_timing->VTI >> 6) & 0x0C) | + ((ch_timing->VAI >> 8) & 0x03)); + ch7024_write_reg(CH7024_IN_TIMING10, ch_timing->VO & 0xFF); + + /* adjust the brightness */ + ch7024_write_reg(CH7024_TVBRI, 0x90); + + ch7024_write_reg(CH7024_OUT_TIMING1, 0x4); + ch7024_write_reg(CH7024_OUT_TIMING2, 0xe0); + + if (vos == TVOUT_FMT_PAL) { + ch7024_write_reg(CH7024_V_POS1, 0x03); + ch7024_write_reg(CH7024_V_POS2, 0x7d); + } else { + ch7024_write_reg(CH7024_V_POS1, 0x02); + ch7024_write_reg(CH7024_V_POS2, 0x7b); + } + + ch7024_write_reg(CH7024_POWER, 0x00); + +#ifdef DEBUG_CH7024 + for (i = 0; i < CH7024_SC_FREQ4; i++) { + + val = ch7024_read_reg(i); + pr_debug("CH7024, reg[0x%x] = %x\n", i, val); + } +#endif + return 0; +} + +/** + * ch7024_enable + * Enable the ch7024 Power to begin TV encoder + */ +static int ch7024_enable(void) +{ + int en = enabled; + + if (!enabled) { + regulator_enable(core_reg); + regulator_enable(io_reg); + regulator_enable(analog_reg); + msleep(200); + enabled = 1; + ch7024_write_reg(CH7024_POWER, 0x00); + pr_debug("CH7024 power on.\n"); + } + return en; +} + +/** + * ch7024_disable + * Disable the ch7024 Power to stop TV encoder + */ +static void ch7024_disable(void) +{ + if (enabled) { + enabled = 0; + ch7024_write_reg(CH7024_POWER, 0x0D); + regulator_disable(analog_reg); + regulator_disable(io_reg); + regulator_disable(core_reg); + pr_debug("CH7024 power off.\n"); + } +} + +static int ch7024_detect(void) +{ + int en; + int detect = 0; + + if (gpio_get_value(detect_gpio) == 1) { + set_irq_type(ch7024_client->irq, IRQF_TRIGGER_FALLING); + + en = ch7024_enable(); + + ch7024_write_reg(CH7024_DAC_TRIM, 0xB4); + msleep(50); + detect = ch7024_read_reg(CH7024_ATT_DISP) & 0x3; + ch7024_write_reg(CH7024_DAC_TRIM, 0x34); + + if (!en) + ch7024_disable(); + } else { + set_irq_type(ch7024_client->irq, IRQF_TRIGGER_RISING); + } + dev_dbg(&ch7024_client->dev, "detect = %d\n", detect); + return detect; +} + +static irqreturn_t hp_detect_handler(int irq, void *data) +{ + disable_irq(irq); + schedule_delayed_work(&ch7024_wq, 50); + + return IRQ_HANDLED; +} + +static void hp_detect_wq_handler(struct work_struct *work) +{ + int detect; + struct mxc_hw_event event = { HWE_PHONEJACK_PLUG, 0 }; + + detect = ch7024_detect(); + + enable_irq(ch7024_client->irq); + + sysfs_notify(&ch7024_client->dev.kobj, NULL, "headphone"); + + /* send hw event by netlink */ + event.args = detect; + hw_event_send(1, &event); +} + +int ch7024_fb_event(struct notifier_block *nb, unsigned long val, void *v) +{ + struct fb_event *event = v; + struct fb_info *fbi = event->info; + + switch (val) { + case FB_EVENT_FB_REGISTERED: + if ((ch7024_fbi != NULL) || strcmp(fbi->fix.id, "DISP3 BG")) + break; + + ch7024_fbi = fbi; + fb_add_videomode(&video_modes[0], &ch7024_fbi->modelist); + fb_add_videomode(&video_modes[1], &ch7024_fbi->modelist); + break; + case FB_EVENT_MODE_CHANGE: + if (ch7024_fbi != fbi) + break; + + if (!fbi->mode) { + ch7024_disable(); + ch7024_cur_mode = TVOUT_FMT_OFF; + return 0; + } + + if (fb_mode_is_equal(fbi->mode, &video_modes[0])) { + ch7024_cur_mode = TVOUT_FMT_NTSC; + ch7024_enable(); + ch7024_setup(TVOUT_FMT_NTSC); + } else if (fb_mode_is_equal(fbi->mode, &video_modes[1])) { + ch7024_cur_mode = TVOUT_FMT_PAL; + ch7024_enable(); + ch7024_setup(TVOUT_FMT_PAL); + } else { + ch7024_disable(); + ch7024_cur_mode = TVOUT_FMT_OFF; + return 0; + } + break; + case FB_EVENT_BLANK: + if ((ch7024_fbi != fbi) || (ch7024_cur_mode == TVOUT_FMT_OFF)) + return 0; + + if (*((int *)event->data) == FB_BLANK_UNBLANK) { + ch7024_enable(); + ch7024_setup(ch7024_cur_mode); + } else { + ch7024_disable(); + } + break; + } + return 0; +} + +static struct notifier_block nb = { + .notifier_call = ch7024_fb_event, +}; + +static ssize_t show_headphone(struct device_driver *dev, char *buf) +{ + int detect; + + detect = ch7024_detect(); + + if (detect == 0) { + strcpy(buf, "none\n"); + } else if (detect == 1) { + strcpy(buf, "cvbs\n"); + } else { + strcpy(buf, "headset\n"); + } + + return strlen(buf); +} + +DRIVER_ATTR(headphone, 0644, show_headphone, NULL); + +static ssize_t show_brightness(struct device_driver *dev, char *buf) +{ + u32 reg; + reg = ch7024_read_reg(CH7024_TVBRI); + return snprintf(buf, PAGE_SIZE, "%u", reg); +} + +static ssize_t store_brightness(struct device_driver *dev, const char *buf, + size_t count) +{ + char *endp; + int brightness = simple_strtoul(buf, &endp, 0); + size_t size = endp - buf; + + if (*endp && isspace(*endp)) + size++; + if (size != count) + return -EINVAL; + + if (brightness > 255) + brightness = 255; + + ch7024_write_reg(CH7024_TVBRI, brightness); + + return count; +} + +DRIVER_ATTR(brightness, 0644, show_brightness, store_brightness); + +static ssize_t show_contrast(struct device_driver *dev, char *buf) +{ + u32 reg; + reg = ch7024_read_reg(CH7024_TVCTA); + + reg *= 2; /* Scale to 0 - 255 */ + + return snprintf(buf, PAGE_SIZE, "%u", reg); +} + +static ssize_t store_contrast(struct device_driver *dev, const char *buf, + size_t count) +{ + char *endp; + int contrast = simple_strtoul(buf, &endp, 0); + size_t size = endp - buf; + + if (*endp && isspace(*endp)) + size++; + if (size != count) + return -EINVAL; + + contrast /= 2; + if (contrast > 127) + contrast = 127; + + ch7024_write_reg(CH7024_TVCTA, contrast); + + return count; +} + +DRIVER_ATTR(contrast, 0644, show_contrast, store_contrast); + +static ssize_t show_hue(struct device_driver *dev, char *buf) +{ + u32 reg; + reg = ch7024_read_reg(CH7024_TVHUE); + + reg *= 2; /* Scale to 0 - 255 */ + + return snprintf(buf, PAGE_SIZE, "%u", reg); +} + +static ssize_t store_hue(struct device_driver *dev, const char *buf, + size_t count) +{ + char *endp; + int hue = simple_strtoul(buf, &endp, 0); + size_t size = endp - buf; + + if (*endp && isspace(*endp)) + size++; + if (size != count) + return -EINVAL; + + hue /= 2; + if (hue > 127) + hue = 127; + + ch7024_write_reg(CH7024_TVHUE, hue); + + return count; +} + +DRIVER_ATTR(hue, 0644, show_hue, store_hue); + +static ssize_t show_saturation(struct device_driver *dev, char *buf) +{ + u32 reg; + reg = ch7024_read_reg(CH7024_TVSAT); + + reg *= 2; /* Scale to 0 - 255 */ + + return snprintf(buf, PAGE_SIZE, "%u", reg); +} + +static ssize_t store_saturation(struct device_driver *dev, const char *buf, + size_t count) +{ + char *endp; + int saturation = simple_strtoul(buf, &endp, 0); + size_t size = endp - buf; + + if (*endp && isspace(*endp)) + size++; + if (size != count) + return -EINVAL; + + saturation /= 2; + if (saturation > 127) + saturation = 127; + + ch7024_write_reg(CH7024_TVSAT, saturation); + + return count; +} + +DRIVER_ATTR(saturation, 0644, show_saturation, store_saturation); + +static ssize_t show_sharpness(struct device_driver *dev, char *buf) +{ + u32 reg; + reg = ch7024_read_reg(CH7024_TVSHARP); + + reg *= 32; /* Scale to 0 - 255 */ + + return snprintf(buf, PAGE_SIZE, "%u", reg); +} + +static ssize_t store_sharpness(struct device_driver *dev, const char *buf, + size_t count) +{ + char *endp; + int sharpness = simple_strtoul(buf, &endp, 0); + size_t size = endp - buf; + + if (*endp && isspace(*endp)) + size++; + if (size != count) + return -EINVAL; + + sharpness /= 32; /* Scale to 0 - 7 */ + if (sharpness > 7) + sharpness = 7; + + ch7024_write_reg(CH7024_TVSHARP, sharpness); + + return count; +} + +DRIVER_ATTR(sharpness, 0644, show_sharpness, store_sharpness); + +static int ch7024_probe(struct i2c_client *client, const struct i2c_device_id *dev_id) +{ + int ret, i; + u32 id; + u32 irqtype; + struct mxc_tvout_platform_data *plat_data = client->dev.platform_data; + + ch7024_client = client; + + io_reg = regulator_get(&client->dev, plat_data->io_reg); + core_reg = regulator_get(&client->dev, plat_data->core_reg); + analog_reg = regulator_get(&client->dev, plat_data->analog_reg); + + regulator_enable(io_reg); + regulator_enable(core_reg); + regulator_enable(analog_reg); + msleep(200); + + id = ch7024_read_reg(CH7024_DEVID); + + regulator_disable(core_reg); + regulator_disable(io_reg); + regulator_disable(analog_reg); + + if (id < 0 || id != CH7024_DEVICE_ID) { + printk(KERN_ERR + "ch7024: TV encoder not present: id = %x\n", id); + return -ENODEV; + } + printk(KERN_ERR "ch7024: TV encoder present: id = %x\n", id); + + detect_gpio = plat_data->detect_line; + + if (client->irq > 0) { + if (ch7024_detect() == 0) + irqtype = IRQF_TRIGGER_RISING; + else + irqtype = IRQF_TRIGGER_FALLING; + + ret = request_irq(client->irq, hp_detect_handler, irqtype, + client->name, client); + if (ret < 0) + goto err0; + + ret = driver_create_file(&client->driver->driver, + &driver_attr_headphone); + if (ret < 0) + goto err1; + } + + ret = driver_create_file(&client->driver->driver, + &driver_attr_brightness); + if (ret) + goto err2; + + ret = driver_create_file(&client->driver->driver, + &driver_attr_contrast); + if (ret) + goto err3; + ret = driver_create_file(&client->driver->driver, &driver_attr_hue); + if (ret) + goto err4; + ret = driver_create_file(&client->driver->driver, + &driver_attr_saturation); + if (ret) + goto err5; + ret = driver_create_file(&client->driver->driver, + &driver_attr_sharpness); + if (ret) + goto err6; + + for (i = 0; i < num_registered_fb; i++) { + if (strcmp(registered_fb[i]->fix.id, "DISP3 BG") == 0) { + ch7024_fbi = registered_fb[i]; + break; + } + } + if (ch7024_fbi != NULL) { + fb_add_videomode(&video_modes[0], &ch7024_fbi->modelist); + fb_add_videomode(&video_modes[1], &ch7024_fbi->modelist); + } + fb_register_client(&nb); + + return 0; + err6: + driver_remove_file(&client->driver->driver, &driver_attr_saturation); + err5: + driver_remove_file(&client->driver->driver, &driver_attr_hue); + err4: + driver_remove_file(&client->driver->driver, &driver_attr_contrast); + err3: + driver_remove_file(&client->driver->driver, &driver_attr_brightness); + err2: + driver_remove_file(&client->driver->driver, &driver_attr_headphone); + err1: + free_irq(client->irq, client); + err0: + return ret; +} + +static int ch7024_remove(struct i2c_client *client) +{ + free_irq(client->irq, client); + + regulator_put(io_reg); + regulator_put(core_reg); + regulator_put(analog_reg); + + driver_remove_file(&client->driver->driver, &driver_attr_headphone); + driver_remove_file(&client->driver->driver, &driver_attr_brightness); + driver_remove_file(&client->driver->driver, &driver_attr_contrast); + driver_remove_file(&client->driver->driver, &driver_attr_hue); + driver_remove_file(&client->driver->driver, &driver_attr_saturation); + driver_remove_file(&client->driver->driver, &driver_attr_sharpness); + + fb_unregister_client(&nb); + + ch7024_client = 0; + + return 0; +} + +#ifdef CONFIG_PM +/*! + * PM suspend/resume routing + */ +static int ch7024_suspend(struct i2c_client *client, pm_message_t state) +{ + pr_debug("Ch7024 suspend routing..\n"); + if (enabled) { + ch7024_disable(); + pm_status = 1; + } else { + pm_status = 0; + } + return 0; +} + +static int ch7024_resume(struct i2c_client *client) +{ + pr_debug("Ch7024 resume routing..\n"); + if (pm_status) { + ch7024_enable(); + ch7024_setup(ch7024_cur_mode); + } + return 0; +} +#else +#define ch7024_suspend NULL +#define ch7024_resume NULL +#endif + +static const struct i2c_device_id ch7024_id[] = { + { "ch7024", 0 }, + {}, +}; +MODULE_DEVICE_TABLE(i2c, ch7024_id); + +static struct i2c_driver ch7024_driver = { + .driver = { + .name = "ch7024", + }, + .probe = ch7024_probe, + .remove = ch7024_remove, + .suspend = ch7024_suspend, + .resume = ch7024_resume, + .id_table = ch7024_id, +}; + +static int __init ch7024_init(void) +{ + return i2c_add_driver(&ch7024_driver); +} + +static void __exit ch7024_exit(void) +{ + i2c_del_driver(&ch7024_driver); +} + +module_init(ch7024_init); +module_exit(ch7024_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("CH7024 TV encoder driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/video/mxc/elcdif_regs.h b/drivers/video/mxc/elcdif_regs.h new file mode 100644 index 000000000000..2eceba5864e0 --- /dev/null +++ b/drivers/video/mxc/elcdif_regs.h @@ -0,0 +1,678 @@ +/* + * Copyright (C) 2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ +/* + * Based on arch/arm/mach-mx28/include/mach/regs-lcdif.h. + * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. + */ + +#ifndef __ELCDIF_REGS_INCLUDED_ +#define __ELCDIF_REGS_INCLUDED_ + +#define HW_ELCDIF_CTRL (0x00000000) +#define HW_ELCDIF_CTRL_SET (0x00000004) +#define HW_ELCDIF_CTRL_CLR (0x00000008) +#define HW_ELCDIF_CTRL_TOG (0x0000000c) + +#define BM_ELCDIF_CTRL_SFTRST 0x80000000 +#define BM_ELCDIF_CTRL_CLKGATE 0x40000000 +#define BM_ELCDIF_CTRL_YCBCR422_INPUT 0x20000000 +#define BM_ELCDIF_CTRL_READ_WRITEB 0x10000000 +#define BM_ELCDIF_CTRL_WAIT_FOR_VSYNC_EDGE 0x08000000 +#define BM_ELCDIF_CTRL_DATA_SHIFT_DIR 0x04000000 +#define BV_ELCDIF_CTRL_DATA_SHIFT_DIR__TXDATA_SHIFT_LEFT 0x0 +#define BV_ELCDIF_CTRL_DATA_SHIFT_DIR__TXDATA_SHIFT_RIGHT 0x1 +#define BP_ELCDIF_CTRL_SHIFT_NUM_BITS 21 +#define BM_ELCDIF_CTRL_SHIFT_NUM_BITS 0x03E00000 +#define BF_ELCDIF_CTRL_SHIFT_NUM_BITS(v) \ + (((v) << 21) & BM_ELCDIF_CTRL_SHIFT_NUM_BITS) +#define BM_ELCDIF_CTRL_DVI_MODE 0x00100000 +#define BM_ELCDIF_CTRL_BYPASS_COUNT 0x00080000 +#define BM_ELCDIF_CTRL_VSYNC_MODE 0x00040000 +#define BM_ELCDIF_CTRL_DOTCLK_MODE 0x00020000 +#define BM_ELCDIF_CTRL_DATA_SELECT 0x00010000 +#define BV_ELCDIF_CTRL_DATA_SELECT__CMD_MODE 0x0 +#define BV_ELCDIF_CTRL_DATA_SELECT__DATA_MODE 0x1 +#define BP_ELCDIF_CTRL_INPUT_DATA_SWIZZLE 14 +#define BM_ELCDIF_CTRL_INPUT_DATA_SWIZZLE 0x0000C000 +#define BF_ELCDIF_CTRL_INPUT_DATA_SWIZZLE(v) \ + (((v) << 14) & BM_ELCDIF_CTRL_INPUT_DATA_SWIZZLE) +#define BV_ELCDIF_CTRL_INPUT_DATA_SWIZZLE__NO_SWAP 0x0 +#define BV_ELCDIF_CTRL_INPUT_DATA_SWIZZLE__LITTLE_ENDIAN 0x0 +#define BV_ELCDIF_CTRL_INPUT_DATA_SWIZZLE__BIG_ENDIAN_SWAP 0x1 +#define BV_ELCDIF_CTRL_INPUT_DATA_SWIZZLE__SWAP_ALL_BYTES 0x1 +#define BV_ELCDIF_CTRL_INPUT_DATA_SWIZZLE__HWD_SWAP 0x2 +#define BV_ELCDIF_CTRL_INPUT_DATA_SWIZZLE__HWD_BYTE_SWAP 0x3 +#define BP_ELCDIF_CTRL_CSC_DATA_SWIZZLE 12 +#define BM_ELCDIF_CTRL_CSC_DATA_SWIZZLE 0x00003000 +#define BF_ELCDIF_CTRL_CSC_DATA_SWIZZLE(v) \ + (((v) << 12) & BM_ELCDIF_CTRL_CSC_DATA_SWIZZLE) +#define BV_ELCDIF_CTRL_CSC_DATA_SWIZZLE__NO_SWAP 0x0 +#define BV_ELCDIF_CTRL_CSC_DATA_SWIZZLE__LITTLE_ENDIAN 0x0 +#define BV_ELCDIF_CTRL_CSC_DATA_SWIZZLE__BIG_ENDIAN_SWAP 0x1 +#define BV_ELCDIF_CTRL_CSC_DATA_SWIZZLE__SWAP_ALL_BYTES 0x1 +#define BV_ELCDIF_CTRL_CSC_DATA_SWIZZLE__HWD_SWAP 0x2 +#define BV_ELCDIF_CTRL_CSC_DATA_SWIZZLE__HWD_BYTE_SWAP 0x3 +#define BP_ELCDIF_CTRL_LCD_DATABUS_WIDTH 10 +#define BM_ELCDIF_CTRL_LCD_DATABUS_WIDTH 0x00000C00 +#define BF_ELCDIF_CTRL_LCD_DATABUS_WIDTH(v) \ + (((v) << 10) & BM_ELCDIF_CTRL_LCD_DATABUS_WIDTH) +#define BV_ELCDIF_CTRL_LCD_DATABUS_WIDTH__16_BIT 0x0 +#define BV_ELCDIF_CTRL_LCD_DATABUS_WIDTH__8_BIT 0x1 +#define BV_ELCDIF_CTRL_LCD_DATABUS_WIDTH__18_BIT 0x2 +#define BV_ELCDIF_CTRL_LCD_DATABUS_WIDTH__24_BIT 0x3 +#define BP_ELCDIF_CTRL_WORD_LENGTH 8 +#define BM_ELCDIF_CTRL_WORD_LENGTH 0x00000300 +#define BF_ELCDIF_CTRL_WORD_LENGTH(v) \ + (((v) << 8) & BM_ELCDIF_CTRL_WORD_LENGTH) +#define BV_ELCDIF_CTRL_WORD_LENGTH__16_BIT 0x0 +#define BV_ELCDIF_CTRL_WORD_LENGTH__8_BIT 0x1 +#define BV_ELCDIF_CTRL_WORD_LENGTH__18_BIT 0x2 +#define BV_ELCDIF_CTRL_WORD_LENGTH__24_BIT 0x3 +#define BM_ELCDIF_CTRL_RGB_TO_YCBCR422_CSC 0x00000080 +#define BM_ELCDIF_CTRL_ENABLE_PXP_HANDSHAKE 0x00000040 +#define BM_ELCDIF_CTRL_ELCDIF_MASTER 0x00000020 +#define BM_ELCDIF_CTRL_RSRVD0 0x00000010 +#define BM_ELCDIF_CTRL_DATA_FORMAT_16_BIT 0x00000008 +#define BM_ELCDIF_CTRL_DATA_FORMAT_18_BIT 0x00000004 +#define BV_ELCDIF_CTRL_DATA_FORMAT_18_BIT__LOWER_18_BITS_VALID 0x0 +#define BV_ELCDIF_CTRL_DATA_FORMAT_18_BIT__UPPER_18_BITS_VALID 0x1 +#define BM_ELCDIF_CTRL_DATA_FORMAT_24_BIT 0x00000002 +#define BV_ELCDIF_CTRL_DATA_FORMAT_24_BIT__ALL_24_BITS_VALID 0x0 +#define BV_ELCDIF_CTRL_DATA_FORMAT_24_BIT__DROP_UPPER_2_BITS_PER_BYTE 0x1 +#define BM_ELCDIF_CTRL_RUN 0x00000001 + +#define HW_ELCDIF_CTRL1 (0x00000010) +#define HW_ELCDIF_CTRL1_SET (0x00000014) +#define HW_ELCDIF_CTRL1_CLR (0x00000018) +#define HW_ELCDIF_CTRL1_TOG (0x0000001c) + +#define BP_ELCDIF_CTRL1_RSRVD1 28 +#define BM_ELCDIF_CTRL1_RSRVD1 0xF0000000 +#define BF_ELCDIF_CTRL1_RSRVD1(v) \ + (((v) << 28) & BM_ELCDIF_CTRL1_RSRVD1) +#define BM_ELCDIF_CTRL1_COMBINE_MPU_WR_STRB 0x08000000 +#define BM_ELCDIF_CTRL1_BM_ERROR_IRQ_EN 0x04000000 +#define BM_ELCDIF_CTRL1_BM_ERROR_IRQ 0x02000000 +#define BV_ELCDIF_CTRL1_BM_ERROR_IRQ__NO_REQUEST 0x0 +#define BV_ELCDIF_CTRL1_BM_ERROR_IRQ__REQUEST 0x1 +#define BM_ELCDIF_CTRL1_RECOVER_ON_UNDERFLOW 0x01000000 +#define BM_ELCDIF_CTRL1_INTERLACE_FIELDS 0x00800000 +#define BM_ELCDIF_CTRL1_START_INTERLACE_FROM_SECOND_FIELD 0x00400000 +#define BM_ELCDIF_CTRL1_FIFO_CLEAR 0x00200000 +#define BM_ELCDIF_CTRL1_IRQ_ON_ALTERNATE_FIELDS 0x00100000 +#define BP_ELCDIF_CTRL1_BYTE_PACKING_FORMAT 16 +#define BM_ELCDIF_CTRL1_BYTE_PACKING_FORMAT 0x000F0000 +#define BF_ELCDIF_CTRL1_BYTE_PACKING_FORMAT(v) \ + (((v) << 16) & BM_ELCDIF_CTRL1_BYTE_PACKING_FORMAT) +#define BM_ELCDIF_CTRL1_OVERFLOW_IRQ_EN 0x00008000 +#define BM_ELCDIF_CTRL1_UNDERFLOW_IRQ_EN 0x00004000 +#define BM_ELCDIF_CTRL1_CUR_FRAME_DONE_IRQ_EN 0x00002000 +#define BM_ELCDIF_CTRL1_VSYNC_EDGE_IRQ_EN 0x00001000 +#define BM_ELCDIF_CTRL1_OVERFLOW_IRQ 0x00000800 +#define BV_ELCDIF_CTRL1_OVERFLOW_IRQ__NO_REQUEST 0x0 +#define BV_ELCDIF_CTRL1_OVERFLOW_IRQ__REQUEST 0x1 +#define BM_ELCDIF_CTRL1_UNDERFLOW_IRQ 0x00000400 +#define BV_ELCDIF_CTRL1_UNDERFLOW_IRQ__NO_REQUEST 0x0 +#define BV_ELCDIF_CTRL1_UNDERFLOW_IRQ__REQUEST 0x1 +#define BM_ELCDIF_CTRL1_CUR_FRAME_DONE_IRQ 0x00000200 +#define BV_ELCDIF_CTRL1_CUR_FRAME_DONE_IRQ__NO_REQUEST 0x0 +#define BV_ELCDIF_CTRL1_CUR_FRAME_DONE_IRQ__REQUEST 0x1 +#define BM_ELCDIF_CTRL1_VSYNC_EDGE_IRQ 0x00000100 +#define BV_ELCDIF_CTRL1_VSYNC_EDGE_IRQ__NO_REQUEST 0x0 +#define BV_ELCDIF_CTRL1_VSYNC_EDGE_IRQ__REQUEST 0x1 +#define BP_ELCDIF_CTRL1_RSRVD0 3 +#define BM_ELCDIF_CTRL1_RSRVD0 0x000000F8 +#define BF_ELCDIF_CTRL1_RSRVD0(v) \ + (((v) << 3) & BM_ELCDIF_CTRL1_RSRVD0) +#define BM_ELCDIF_CTRL1_BUSY_ENABLE 0x00000004 +#define BV_ELCDIF_CTRL1_BUSY_ENABLE__BUSY_DISABLED 0x0 +#define BV_ELCDIF_CTRL1_BUSY_ENABLE__BUSY_ENABLED 0x1 +#define BM_ELCDIF_CTRL1_MODE86 0x00000002 +#define BV_ELCDIF_CTRL1_MODE86__8080_MODE 0x0 +#define BV_ELCDIF_CTRL1_MODE86__6800_MODE 0x1 +#define BM_ELCDIF_CTRL1_RESET 0x00000001 +#define BV_ELCDIF_CTRL1_RESET__LCDRESET_LOW 0x0 +#define BV_ELCDIF_CTRL1_RESET__LCDRESET_HIGH 0x1 + +#define HW_ELCDIF_CTRL2 (0x00000020) +#define HW_ELCDIF_CTRL2_SET (0x00000024) +#define HW_ELCDIF_CTRL2_CLR (0x00000028) +#define HW_ELCDIF_CTRL2_TOG (0x0000002c) + +#define BP_ELCDIF_CTRL2_RSRVD5 24 +#define BM_ELCDIF_CTRL2_RSRVD5 0xFF000000 +#define BF_ELCDIF_CTRL2_RSRVD5(v) \ + (((v) << 24) & BM_ELCDIF_CTRL2_RSRVD5) +#define BP_ELCDIF_CTRL2_OUTSTANDING_REQS 21 +#define BM_ELCDIF_CTRL2_OUTSTANDING_REQS 0x00E00000 +#define BF_ELCDIF_CTRL2_OUTSTANDING_REQS(v) \ + (((v) << 21) & BM_ELCDIF_CTRL2_OUTSTANDING_REQS) +#define BV_ELCDIF_CTRL2_OUTSTANDING_REQS__REQ_1 0x0 +#define BV_ELCDIF_CTRL2_OUTSTANDING_REQS__REQ_2 0x1 +#define BV_ELCDIF_CTRL2_OUTSTANDING_REQS__REQ_4 0x2 +#define BV_ELCDIF_CTRL2_OUTSTANDING_REQS__REQ_8 0x3 +#define BV_ELCDIF_CTRL2_OUTSTANDING_REQS__REQ_16 0x4 +#define BM_ELCDIF_CTRL2_BURST_LEN_8 0x00100000 +#define BM_ELCDIF_CTRL2_RSRVD4 0x00080000 +#define BP_ELCDIF_CTRL2_ODD_LINE_PATTERN 16 +#define BM_ELCDIF_CTRL2_ODD_LINE_PATTERN 0x00070000 +#define BF_ELCDIF_CTRL2_ODD_LINE_PATTERN(v) \ + (((v) << 16) & BM_ELCDIF_CTRL2_ODD_LINE_PATTERN) +#define BV_ELCDIF_CTRL2_ODD_LINE_PATTERN__RGB 0x0 +#define BV_ELCDIF_CTRL2_ODD_LINE_PATTERN__RBG 0x1 +#define BV_ELCDIF_CTRL2_ODD_LINE_PATTERN__GBR 0x2 +#define BV_ELCDIF_CTRL2_ODD_LINE_PATTERN__GRB 0x3 +#define BV_ELCDIF_CTRL2_ODD_LINE_PATTERN__BRG 0x4 +#define BV_ELCDIF_CTRL2_ODD_LINE_PATTERN__BGR 0x5 +#define BM_ELCDIF_CTRL2_RSRVD3 0x00008000 +#define BP_ELCDIF_CTRL2_EVEN_LINE_PATTERN 12 +#define BM_ELCDIF_CTRL2_EVEN_LINE_PATTERN 0x00007000 +#define BF_ELCDIF_CTRL2_EVEN_LINE_PATTERN(v) \ + (((v) << 12) & BM_ELCDIF_CTRL2_EVEN_LINE_PATTERN) +#define BV_ELCDIF_CTRL2_EVEN_LINE_PATTERN__RGB 0x0 +#define BV_ELCDIF_CTRL2_EVEN_LINE_PATTERN__RBG 0x1 +#define BV_ELCDIF_CTRL2_EVEN_LINE_PATTERN__GBR 0x2 +#define BV_ELCDIF_CTRL2_EVEN_LINE_PATTERN__GRB 0x3 +#define BV_ELCDIF_CTRL2_EVEN_LINE_PATTERN__BRG 0x4 +#define BV_ELCDIF_CTRL2_EVEN_LINE_PATTERN__BGR 0x5 +#define BM_ELCDIF_CTRL2_RSRVD2 0x00000800 +#define BM_ELCDIF_CTRL2_READ_PACK_DIR 0x00000400 +#define BM_ELCDIF_CTRL2_READ_MODE_OUTPUT_IN_RGB_FORMAT 0x00000200 +#define BM_ELCDIF_CTRL2_READ_MODE_6_BIT_INPUT 0x00000100 +#define BM_ELCDIF_CTRL2_RSRVD1 0x00000080 +#define BP_ELCDIF_CTRL2_READ_MODE_NUM_PACKED_SUBWORDS 4 +#define BM_ELCDIF_CTRL2_READ_MODE_NUM_PACKED_SUBWORDS 0x00000070 +#define BF_ELCDIF_CTRL2_READ_MODE_NUM_PACKED_SUBWORDS(v) \ + (((v) << 4) & BM_ELCDIF_CTRL2_READ_MODE_NUM_PACKED_SUBWORDS) +#define BP_ELCDIF_CTRL2_INITIAL_DUMMY_READ 1 +#define BM_ELCDIF_CTRL2_INITIAL_DUMMY_READ 0x0000000E +#define BF_ELCDIF_CTRL2_INITIAL_DUMMY_READ(v) \ + (((v) << 1) & BM_ELCDIF_CTRL2_INITIAL_DUMMY_READ) +#define BM_ELCDIF_CTRL2_RSRVD0 0x00000001 + +#define HW_ELCDIF_TRANSFER_COUNT (0x00000030) + +#define BP_ELCDIF_TRANSFER_COUNT_V_COUNT 16 +#define BM_ELCDIF_TRANSFER_COUNT_V_COUNT 0xFFFF0000 +#define BF_ELCDIF_TRANSFER_COUNT_V_COUNT(v) \ + (((v) << 16) & BM_ELCDIF_TRANSFER_COUNT_V_COUNT) +#define BP_ELCDIF_TRANSFER_COUNT_H_COUNT 0 +#define BM_ELCDIF_TRANSFER_COUNT_H_COUNT 0x0000FFFF +#define BF_ELCDIF_TRANSFER_COUNT_H_COUNT(v) \ + (((v) << 0) & BM_ELCDIF_TRANSFER_COUNT_H_COUNT) + +#define HW_ELCDIF_CUR_BUF (0x00000040) + +#define BP_ELCDIF_CUR_BUF_ADDR 0 +#define BM_ELCDIF_CUR_BUF_ADDR 0xFFFFFFFF +#define BF_ELCDIF_CUR_BUF_ADDR(v) (v) + +#define HW_ELCDIF_NEXT_BUF (0x00000050) + +#define BP_ELCDIF_NEXT_BUF_ADDR 0 +#define BM_ELCDIF_NEXT_BUF_ADDR 0xFFFFFFFF +#define BF_ELCDIF_NEXT_BUF_ADDR(v) (v) + +#define HW_ELCDIF_TIMING (0x00000060) + +#define BP_ELCDIF_TIMING_CMD_HOLD 24 +#define BM_ELCDIF_TIMING_CMD_HOLD 0xFF000000 +#define BF_ELCDIF_TIMING_CMD_HOLD(v) \ + (((v) << 24) & BM_ELCDIF_TIMING_CMD_HOLD) +#define BP_ELCDIF_TIMING_CMD_SETUP 16 +#define BM_ELCDIF_TIMING_CMD_SETUP 0x00FF0000 +#define BF_ELCDIF_TIMING_CMD_SETUP(v) \ + (((v) << 16) & BM_ELCDIF_TIMING_CMD_SETUP) +#define BP_ELCDIF_TIMING_DATA_HOLD 8 +#define BM_ELCDIF_TIMING_DATA_HOLD 0x0000FF00 +#define BF_ELCDIF_TIMING_DATA_HOLD(v) \ + (((v) << 8) & BM_ELCDIF_TIMING_DATA_HOLD) +#define BP_ELCDIF_TIMING_DATA_SETUP 0 +#define BM_ELCDIF_TIMING_DATA_SETUP 0x000000FF +#define BF_ELCDIF_TIMING_DATA_SETUP(v) \ + (((v) << 0) & BM_ELCDIF_TIMING_DATA_SETUP) + +#define HW_ELCDIF_VDCTRL0 (0x00000070) +#define HW_ELCDIF_VDCTRL0_SET (0x00000074) +#define HW_ELCDIF_VDCTRL0_CLR (0x00000078) +#define HW_ELCDIF_VDCTRL0_TOG (0x0000007c) + +#define BP_ELCDIF_VDCTRL0_RSRVD2 30 +#define BM_ELCDIF_VDCTRL0_RSRVD2 0xC0000000 +#define BF_ELCDIF_VDCTRL0_RSRVD2(v) \ + (((v) << 30) & BM_ELCDIF_VDCTRL0_RSRVD2) +#define BM_ELCDIF_VDCTRL0_VSYNC_OEB 0x20000000 +#define BV_ELCDIF_VDCTRL0_VSYNC_OEB__VSYNC_OUTPUT 0x0 +#define BV_ELCDIF_VDCTRL0_VSYNC_OEB__VSYNC_INPUT 0x1 +#define BM_ELCDIF_VDCTRL0_ENABLE_PRESENT 0x10000000 +#define BM_ELCDIF_VDCTRL0_VSYNC_POL 0x08000000 +#define BM_ELCDIF_VDCTRL0_HSYNC_POL 0x04000000 +#define BM_ELCDIF_VDCTRL0_DOTCLK_POL 0x02000000 +#define BM_ELCDIF_VDCTRL0_ENABLE_POL 0x01000000 +#define BP_ELCDIF_VDCTRL0_RSRVD1 22 +#define BM_ELCDIF_VDCTRL0_RSRVD1 0x00C00000 +#define BF_ELCDIF_VDCTRL0_RSRVD1(v) \ + (((v) << 22) & BM_ELCDIF_VDCTRL0_RSRVD1) +#define BM_ELCDIF_VDCTRL0_VSYNC_PERIOD_UNIT 0x00200000 +#define BM_ELCDIF_VDCTRL0_VSYNC_PULSE_WIDTH_UNIT 0x00100000 +#define BM_ELCDIF_VDCTRL0_HALF_LINE 0x00080000 +#define BM_ELCDIF_VDCTRL0_HALF_LINE_MODE 0x00040000 +#define BP_ELCDIF_VDCTRL0_VSYNC_PULSE_WIDTH 0 +#define BM_ELCDIF_VDCTRL0_VSYNC_PULSE_WIDTH 0x0003FFFF +#define BF_ELCDIF_VDCTRL0_VSYNC_PULSE_WIDTH(v) \ + (((v) << 0) & BM_ELCDIF_VDCTRL0_VSYNC_PULSE_WIDTH) + +#define HW_ELCDIF_VDCTRL1 (0x00000080) + +#define BP_ELCDIF_VDCTRL1_VSYNC_PERIOD 0 +#define BM_ELCDIF_VDCTRL1_VSYNC_PERIOD 0xFFFFFFFF +#define BF_ELCDIF_VDCTRL1_VSYNC_PERIOD(v) (v) + +#define HW_ELCDIF_VDCTRL2 (0x00000090) + +#define BP_ELCDIF_VDCTRL2_HSYNC_PULSE_WIDTH 18 +#define BM_ELCDIF_VDCTRL2_HSYNC_PULSE_WIDTH 0xFFFC0000 +#define BF_ELCDIF_VDCTRL2_HSYNC_PULSE_WIDTH(v) \ + (((v) << 18) & BM_ELCDIF_VDCTRL2_HSYNC_PULSE_WIDTH) +#define BP_ELCDIF_VDCTRL2_HSYNC_PERIOD 0 +#define BM_ELCDIF_VDCTRL2_HSYNC_PERIOD 0x0003FFFF +#define BF_ELCDIF_VDCTRL2_HSYNC_PERIOD(v) \ + (((v) << 0) & BM_ELCDIF_VDCTRL2_HSYNC_PERIOD) + +#define HW_ELCDIF_VDCTRL3 (0x000000a0) + +#define BP_ELCDIF_VDCTRL3_RSRVD0 30 +#define BM_ELCDIF_VDCTRL3_RSRVD0 0xC0000000 +#define BF_ELCDIF_VDCTRL3_RSRVD0(v) \ + (((v) << 30) & BM_ELCDIF_VDCTRL3_RSRVD0) +#define BM_ELCDIF_VDCTRL3_MUX_SYNC_SIGNALS 0x20000000 +#define BM_ELCDIF_VDCTRL3_VSYNC_ONLY 0x10000000 +#define BP_ELCDIF_VDCTRL3_HORIZONTAL_WAIT_CNT 16 +#define BM_ELCDIF_VDCTRL3_HORIZONTAL_WAIT_CNT 0x0FFF0000 +#define BF_ELCDIF_VDCTRL3_HORIZONTAL_WAIT_CNT(v) \ + (((v) << 16) & BM_ELCDIF_VDCTRL3_HORIZONTAL_WAIT_CNT) +#define BP_ELCDIF_VDCTRL3_VERTICAL_WAIT_CNT 0 +#define BM_ELCDIF_VDCTRL3_VERTICAL_WAIT_CNT 0x0000FFFF +#define BF_ELCDIF_VDCTRL3_VERTICAL_WAIT_CNT(v) \ + (((v) << 0) & BM_ELCDIF_VDCTRL3_VERTICAL_WAIT_CNT) + +#define HW_ELCDIF_VDCTRL4 (0x000000b0) + +#define BP_ELCDIF_VDCTRL4_DOTCLK_DLY_SEL 29 +#define BM_ELCDIF_VDCTRL4_DOTCLK_DLY_SEL 0xE0000000 +#define BF_ELCDIF_VDCTRL4_DOTCLK_DLY_SEL(v) \ + (((v) << 29) & BM_ELCDIF_VDCTRL4_DOTCLK_DLY_SEL) +#define BP_ELCDIF_VDCTRL4_RSRVD0 19 +#define BM_ELCDIF_VDCTRL4_RSRVD0 0x1FF80000 +#define BF_ELCDIF_VDCTRL4_RSRVD0(v) \ + (((v) << 19) & BM_ELCDIF_VDCTRL4_RSRVD0) +#define BM_ELCDIF_VDCTRL4_SYNC_SIGNALS_ON 0x00040000 +#define BP_ELCDIF_VDCTRL4_DOTCLK_H_VALID_DATA_CNT 0 +#define BM_ELCDIF_VDCTRL4_DOTCLK_H_VALID_DATA_CNT 0x0003FFFF +#define BF_ELCDIF_VDCTRL4_DOTCLK_H_VALID_DATA_CNT(v) \ + (((v) << 0) & BM_ELCDIF_VDCTRL4_DOTCLK_H_VALID_DATA_CNT) + +#define HW_ELCDIF_DVICTRL0 (0x000000c0) + +#define BP_ELCDIF_DVICTRL0_RSRVD1 28 +#define BM_ELCDIF_DVICTRL0_RSRVD1 0xF0000000 +#define BF_ELCDIF_DVICTRL0_RSRVD1(v) \ + (((v) << 28) & BM_ELCDIF_DVICTRL0_RSRVD1) +#define BP_ELCDIF_DVICTRL0_H_ACTIVE_CNT 16 +#define BM_ELCDIF_DVICTRL0_H_ACTIVE_CNT 0x0FFF0000 +#define BF_ELCDIF_DVICTRL0_H_ACTIVE_CNT(v) \ + (((v) << 16) & BM_ELCDIF_DVICTRL0_H_ACTIVE_CNT) +#define BP_ELCDIF_DVICTRL0_RSRVD0 12 +#define BM_ELCDIF_DVICTRL0_RSRVD0 0x0000F000 +#define BF_ELCDIF_DVICTRL0_RSRVD0(v) \ + (((v) << 12) & BM_ELCDIF_DVICTRL0_RSRVD0) +#define BP_ELCDIF_DVICTRL0_H_BLANKING_CNT 0 +#define BM_ELCDIF_DVICTRL0_H_BLANKING_CNT 0x00000FFF +#define BF_ELCDIF_DVICTRL0_H_BLANKING_CNT(v) \ + (((v) << 0) & BM_ELCDIF_DVICTRL0_H_BLANKING_CNT) + +#define HW_ELCDIF_DVICTRL1 (0x000000d0) + +#define BP_ELCDIF_DVICTRL1_RSRVD0 30 +#define BM_ELCDIF_DVICTRL1_RSRVD0 0xC0000000 +#define BF_ELCDIF_DVICTRL1_RSRVD0(v) \ + (((v) << 30) & BM_ELCDIF_DVICTRL1_RSRVD0) +#define BP_ELCDIF_DVICTRL1_F1_START_LINE 20 +#define BM_ELCDIF_DVICTRL1_F1_START_LINE 0x3FF00000 +#define BF_ELCDIF_DVICTRL1_F1_START_LINE(v) \ + (((v) << 20) & BM_ELCDIF_DVICTRL1_F1_START_LINE) +#define BP_ELCDIF_DVICTRL1_F1_END_LINE 10 +#define BM_ELCDIF_DVICTRL1_F1_END_LINE 0x000FFC00 +#define BF_ELCDIF_DVICTRL1_F1_END_LINE(v) \ + (((v) << 10) & BM_ELCDIF_DVICTRL1_F1_END_LINE) +#define BP_ELCDIF_DVICTRL1_F2_START_LINE 0 +#define BM_ELCDIF_DVICTRL1_F2_START_LINE 0x000003FF +#define BF_ELCDIF_DVICTRL1_F2_START_LINE(v) \ + (((v) << 0) & BM_ELCDIF_DVICTRL1_F2_START_LINE) + +#define HW_ELCDIF_DVICTRL2 (0x000000e0) + +#define BP_ELCDIF_DVICTRL2_RSRVD0 30 +#define BM_ELCDIF_DVICTRL2_RSRVD0 0xC0000000 +#define BF_ELCDIF_DVICTRL2_RSRVD0(v) \ + (((v) << 30) & BM_ELCDIF_DVICTRL2_RSRVD0) +#define BP_ELCDIF_DVICTRL2_F2_END_LINE 20 +#define BM_ELCDIF_DVICTRL2_F2_END_LINE 0x3FF00000 +#define BF_ELCDIF_DVICTRL2_F2_END_LINE(v) \ + (((v) << 20) & BM_ELCDIF_DVICTRL2_F2_END_LINE) +#define BP_ELCDIF_DVICTRL2_V1_BLANK_START_LINE 10 +#define BM_ELCDIF_DVICTRL2_V1_BLANK_START_LINE 0x000FFC00 +#define BF_ELCDIF_DVICTRL2_V1_BLANK_START_LINE(v) \ + (((v) << 10) & BM_ELCDIF_DVICTRL2_V1_BLANK_START_LINE) +#define BP_ELCDIF_DVICTRL2_V1_BLANK_END_LINE 0 +#define BM_ELCDIF_DVICTRL2_V1_BLANK_END_LINE 0x000003FF +#define BF_ELCDIF_DVICTRL2_V1_BLANK_END_LINE(v) \ + (((v) << 0) & BM_ELCDIF_DVICTRL2_V1_BLANK_END_LINE) + +#define HW_ELCDIF_DVICTRL3 (0x000000f0) + +#define BP_ELCDIF_DVICTRL3_RSRVD0 30 +#define BM_ELCDIF_DVICTRL3_RSRVD0 0xC0000000 +#define BF_ELCDIF_DVICTRL3_RSRVD0(v) \ + (((v) << 30) & BM_ELCDIF_DVICTRL3_RSRVD0) +#define BP_ELCDIF_DVICTRL3_V2_BLANK_START_LINE 20 +#define BM_ELCDIF_DVICTRL3_V2_BLANK_START_LINE 0x3FF00000 +#define BF_ELCDIF_DVICTRL3_V2_BLANK_START_LINE(v) \ + (((v) << 20) & BM_ELCDIF_DVICTRL3_V2_BLANK_START_LINE) +#define BP_ELCDIF_DVICTRL3_V2_BLANK_END_LINE 10 +#define BM_ELCDIF_DVICTRL3_V2_BLANK_END_LINE 0x000FFC00 +#define BF_ELCDIF_DVICTRL3_V2_BLANK_END_LINE(v) \ + (((v) << 10) & BM_ELCDIF_DVICTRL3_V2_BLANK_END_LINE) +#define BP_ELCDIF_DVICTRL3_V_LINES_CNT 0 +#define BM_ELCDIF_DVICTRL3_V_LINES_CNT 0x000003FF +#define BF_ELCDIF_DVICTRL3_V_LINES_CNT(v) \ + (((v) << 0) & BM_ELCDIF_DVICTRL3_V_LINES_CNT) + +#define HW_ELCDIF_DVICTRL4 (0x00000100) + +#define BP_ELCDIF_DVICTRL4_Y_FILL_VALUE 24 +#define BM_ELCDIF_DVICTRL4_Y_FILL_VALUE 0xFF000000 +#define BF_ELCDIF_DVICTRL4_Y_FILL_VALUE(v) \ + (((v) << 24) & BM_ELCDIF_DVICTRL4_Y_FILL_VALUE) +#define BP_ELCDIF_DVICTRL4_CB_FILL_VALUE 16 +#define BM_ELCDIF_DVICTRL4_CB_FILL_VALUE 0x00FF0000 +#define BF_ELCDIF_DVICTRL4_CB_FILL_VALUE(v) \ + (((v) << 16) & BM_ELCDIF_DVICTRL4_CB_FILL_VALUE) +#define BP_ELCDIF_DVICTRL4_CR_FILL_VALUE 8 +#define BM_ELCDIF_DVICTRL4_CR_FILL_VALUE 0x0000FF00 +#define BF_ELCDIF_DVICTRL4_CR_FILL_VALUE(v) \ + (((v) << 8) & BM_ELCDIF_DVICTRL4_CR_FILL_VALUE) +#define BP_ELCDIF_DVICTRL4_H_FILL_CNT 0 +#define BM_ELCDIF_DVICTRL4_H_FILL_CNT 0x000000FF +#define BF_ELCDIF_DVICTRL4_H_FILL_CNT(v) \ + (((v) << 0) & BM_ELCDIF_DVICTRL4_H_FILL_CNT) + +#define HW_ELCDIF_CSC_COEFF0 (0x00000110) + +#define BP_ELCDIF_CSC_COEFF0_RSRVD1 26 +#define BM_ELCDIF_CSC_COEFF0_RSRVD1 0xFC000000 +#define BF_ELCDIF_CSC_COEFF0_RSRVD1(v) \ + (((v) << 26) & BM_ELCDIF_CSC_COEFF0_RSRVD1) +#define BP_ELCDIF_CSC_COEFF0_C0 16 +#define BM_ELCDIF_CSC_COEFF0_C0 0x03FF0000 +#define BF_ELCDIF_CSC_COEFF0_C0(v) \ + (((v) << 16) & BM_ELCDIF_CSC_COEFF0_C0) +#define BP_ELCDIF_CSC_COEFF0_RSRVD0 2 +#define BM_ELCDIF_CSC_COEFF0_RSRVD0 0x0000FFFC +#define BF_ELCDIF_CSC_COEFF0_RSRVD0(v) \ + (((v) << 2) & BM_ELCDIF_CSC_COEFF0_RSRVD0) +#define BP_ELCDIF_CSC_COEFF0_CSC_SUBSAMPLE_FILTER 0 +#define BM_ELCDIF_CSC_COEFF0_CSC_SUBSAMPLE_FILTER 0x00000003 +#define BF_ELCDIF_CSC_COEFF0_CSC_SUBSAMPLE_FILTER(v) \ + (((v) << 0) & BM_ELCDIF_CSC_COEFF0_CSC_SUBSAMPLE_FILTER) +#define BV_ELCDIF_CSC_COEFF0_CSC_SUBSAMPLE_FILTER__SAMPLE_AND_HOLD 0x0 +#define BV_ELCDIF_CSC_COEFF0_CSC_SUBSAMPLE_FILTER__RSRVD 0x1 +#define BV_ELCDIF_CSC_COEFF0_CSC_SUBSAMPLE_FILTER__INTERSTITIAL 0x2 +#define BV_ELCDIF_CSC_COEFF0_CSC_SUBSAMPLE_FILTER__COSITED 0x3 + +#define HW_ELCDIF_CSC_COEFF1 (0x00000120) + +#define BP_ELCDIF_CSC_COEFF1_RSRVD1 26 +#define BM_ELCDIF_CSC_COEFF1_RSRVD1 0xFC000000 +#define BF_ELCDIF_CSC_COEFF1_RSRVD1(v) \ + (((v) << 26) & BM_ELCDIF_CSC_COEFF1_RSRVD1) +#define BP_ELCDIF_CSC_COEFF1_C2 16 +#define BM_ELCDIF_CSC_COEFF1_C2 0x03FF0000 +#define BF_ELCDIF_CSC_COEFF1_C2(v) \ + (((v) << 16) & BM_ELCDIF_CSC_COEFF1_C2) +#define BP_ELCDIF_CSC_COEFF1_RSRVD0 10 +#define BM_ELCDIF_CSC_COEFF1_RSRVD0 0x0000FC00 +#define BF_ELCDIF_CSC_COEFF1_RSRVD0(v) \ + (((v) << 10) & BM_ELCDIF_CSC_COEFF1_RSRVD0) +#define BP_ELCDIF_CSC_COEFF1_C1 0 +#define BM_ELCDIF_CSC_COEFF1_C1 0x000003FF +#define BF_ELCDIF_CSC_COEFF1_C1(v) \ + (((v) << 0) & BM_ELCDIF_CSC_COEFF1_C1) + +#define HW_ELCDIF_CSC_COEFF2 (0x00000130) + +#define BP_ELCDIF_CSC_COEFF2_RSRVD1 26 +#define BM_ELCDIF_CSC_COEFF2_RSRVD1 0xFC000000 +#define BF_ELCDIF_CSC_COEFF2_RSRVD1(v) \ + (((v) << 26) & BM_ELCDIF_CSC_COEFF2_RSRVD1) +#define BP_ELCDIF_CSC_COEFF2_C4 16 +#define BM_ELCDIF_CSC_COEFF2_C4 0x03FF0000 +#define BF_ELCDIF_CSC_COEFF2_C4(v) \ + (((v) << 16) & BM_ELCDIF_CSC_COEFF2_C4) +#define BP_ELCDIF_CSC_COEFF2_RSRVD0 10 +#define BM_ELCDIF_CSC_COEFF2_RSRVD0 0x0000FC00 +#define BF_ELCDIF_CSC_COEFF2_RSRVD0(v) \ + (((v) << 10) & BM_ELCDIF_CSC_COEFF2_RSRVD0) +#define BP_ELCDIF_CSC_COEFF2_C3 0 +#define BM_ELCDIF_CSC_COEFF2_C3 0x000003FF +#define BF_ELCDIF_CSC_COEFF2_C3(v) \ + (((v) << 0) & BM_ELCDIF_CSC_COEFF2_C3) + +#define HW_ELCDIF_CSC_COEFF3 (0x00000140) + +#define BP_ELCDIF_CSC_COEFF3_RSRVD1 26 +#define BM_ELCDIF_CSC_COEFF3_RSRVD1 0xFC000000 +#define BF_ELCDIF_CSC_COEFF3_RSRVD1(v) \ + (((v) << 26) & BM_ELCDIF_CSC_COEFF3_RSRVD1) +#define BP_ELCDIF_CSC_COEFF3_C6 16 +#define BM_ELCDIF_CSC_COEFF3_C6 0x03FF0000 +#define BF_ELCDIF_CSC_COEFF3_C6(v) \ + (((v) << 16) & BM_ELCDIF_CSC_COEFF3_C6) +#define BP_ELCDIF_CSC_COEFF3_RSRVD0 10 +#define BM_ELCDIF_CSC_COEFF3_RSRVD0 0x0000FC00 +#define BF_ELCDIF_CSC_COEFF3_RSRVD0(v) \ + (((v) << 10) & BM_ELCDIF_CSC_COEFF3_RSRVD0) +#define BP_ELCDIF_CSC_COEFF3_C5 0 +#define BM_ELCDIF_CSC_COEFF3_C5 0x000003FF +#define BF_ELCDIF_CSC_COEFF3_C5(v) \ + (((v) << 0) & BM_ELCDIF_CSC_COEFF3_C5) + +#define HW_ELCDIF_CSC_COEFF4 (0x00000150) + +#define BP_ELCDIF_CSC_COEFF4_RSRVD1 26 +#define BM_ELCDIF_CSC_COEFF4_RSRVD1 0xFC000000 +#define BF_ELCDIF_CSC_COEFF4_RSRVD1(v) \ + (((v) << 26) & BM_ELCDIF_CSC_COEFF4_RSRVD1) +#define BP_ELCDIF_CSC_COEFF4_C8 16 +#define BM_ELCDIF_CSC_COEFF4_C8 0x03FF0000 +#define BF_ELCDIF_CSC_COEFF4_C8(v) \ + (((v) << 16) & BM_ELCDIF_CSC_COEFF4_C8) +#define BP_ELCDIF_CSC_COEFF4_RSRVD0 10 +#define BM_ELCDIF_CSC_COEFF4_RSRVD0 0x0000FC00 +#define BF_ELCDIF_CSC_COEFF4_RSRVD0(v) \ + (((v) << 10) & BM_ELCDIF_CSC_COEFF4_RSRVD0) +#define BP_ELCDIF_CSC_COEFF4_C7 0 +#define BM_ELCDIF_CSC_COEFF4_C7 0x000003FF +#define BF_ELCDIF_CSC_COEFF4_C7(v) \ + (((v) << 0) & BM_ELCDIF_CSC_COEFF4_C7) + +#define HW_ELCDIF_CSC_OFFSET (0x00000160) + +#define BP_ELCDIF_CSC_OFFSET_RSRVD1 25 +#define BM_ELCDIF_CSC_OFFSET_RSRVD1 0xFE000000 +#define BF_ELCDIF_CSC_OFFSET_RSRVD1(v) \ + (((v) << 25) & BM_ELCDIF_CSC_OFFSET_RSRVD1) +#define BP_ELCDIF_CSC_OFFSET_CBCR_OFFSET 16 +#define BM_ELCDIF_CSC_OFFSET_CBCR_OFFSET 0x01FF0000 +#define BF_ELCDIF_CSC_OFFSET_CBCR_OFFSET(v) \ + (((v) << 16) & BM_ELCDIF_CSC_OFFSET_CBCR_OFFSET) +#define BP_ELCDIF_CSC_OFFSET_RSRVD0 9 +#define BM_ELCDIF_CSC_OFFSET_RSRVD0 0x0000FE00 +#define BF_ELCDIF_CSC_OFFSET_RSRVD0(v) \ + (((v) << 9) & BM_ELCDIF_CSC_OFFSET_RSRVD0) +#define BP_ELCDIF_CSC_OFFSET_Y_OFFSET 0 +#define BM_ELCDIF_CSC_OFFSET_Y_OFFSET 0x000001FF +#define BF_ELCDIF_CSC_OFFSET_Y_OFFSET(v) \ + (((v) << 0) & BM_ELCDIF_CSC_OFFSET_Y_OFFSET) + +#define HW_ELCDIF_CSC_LIMIT (0x00000170) + +#define BP_ELCDIF_CSC_LIMIT_CBCR_MIN 24 +#define BM_ELCDIF_CSC_LIMIT_CBCR_MIN 0xFF000000 +#define BF_ELCDIF_CSC_LIMIT_CBCR_MIN(v) \ + (((v) << 24) & BM_ELCDIF_CSC_LIMIT_CBCR_MIN) +#define BP_ELCDIF_CSC_LIMIT_CBCR_MAX 16 +#define BM_ELCDIF_CSC_LIMIT_CBCR_MAX 0x00FF0000 +#define BF_ELCDIF_CSC_LIMIT_CBCR_MAX(v) \ + (((v) << 16) & BM_ELCDIF_CSC_LIMIT_CBCR_MAX) +#define BP_ELCDIF_CSC_LIMIT_Y_MIN 8 +#define BM_ELCDIF_CSC_LIMIT_Y_MIN 0x0000FF00 +#define BF_ELCDIF_CSC_LIMIT_Y_MIN(v) \ + (((v) << 8) & BM_ELCDIF_CSC_LIMIT_Y_MIN) +#define BP_ELCDIF_CSC_LIMIT_Y_MAX 0 +#define BM_ELCDIF_CSC_LIMIT_Y_MAX 0x000000FF +#define BF_ELCDIF_CSC_LIMIT_Y_MAX(v) \ + (((v) << 0) & BM_ELCDIF_CSC_LIMIT_Y_MAX) + +#define HW_ELCDIF_DATA (0x00000180) + +#define BP_ELCDIF_DATA_DATA_THREE 24 +#define BM_ELCDIF_DATA_DATA_THREE 0xFF000000 +#define BF_ELCDIF_DATA_DATA_THREE(v) \ + (((v) << 24) & BM_ELCDIF_DATA_DATA_THREE) +#define BP_ELCDIF_DATA_DATA_TWO 16 +#define BM_ELCDIF_DATA_DATA_TWO 0x00FF0000 +#define BF_ELCDIF_DATA_DATA_TWO(v) \ + (((v) << 16) & BM_ELCDIF_DATA_DATA_TWO) +#define BP_ELCDIF_DATA_DATA_ONE 8 +#define BM_ELCDIF_DATA_DATA_ONE 0x0000FF00 +#define BF_ELCDIF_DATA_DATA_ONE(v) \ + (((v) << 8) & BM_ELCDIF_DATA_DATA_ONE) +#define BP_ELCDIF_DATA_DATA_ZERO 0 +#define BM_ELCDIF_DATA_DATA_ZERO 0x000000FF +#define BF_ELCDIF_DATA_DATA_ZERO(v) \ + (((v) << 0) & BM_ELCDIF_DATA_DATA_ZERO) + +#define HW_ELCDIF_BM_ERROR_STAT (0x00000190) + +#define BP_ELCDIF_BM_ERROR_STAT_ADDR 0 +#define BM_ELCDIF_BM_ERROR_STAT_ADDR 0xFFFFFFFF +#define BF_ELCDIF_BM_ERROR_STAT_ADDR(v) (v) + +#define HW_ELCDIF_CRC_STAT (0x000001a0) + +#define BP_ELCDIF_CRC_STAT_CRC_VALUE 0 +#define BM_ELCDIF_CRC_STAT_CRC_VALUE 0xFFFFFFFF +#define BF_ELCDIF_CRC_STAT_CRC_VALUE(v) (v) + +#define HW_ELCDIF_STAT (0x000001b0) + +#define BM_ELCDIF_STAT_PRESENT 0x80000000 +#define BM_ELCDIF_STAT_DMA_REQ 0x40000000 +#define BM_ELCDIF_STAT_LFIFO_FULL 0x20000000 +#define BM_ELCDIF_STAT_LFIFO_EMPTY 0x10000000 +#define BM_ELCDIF_STAT_TXFIFO_FULL 0x08000000 +#define BM_ELCDIF_STAT_TXFIFO_EMPTY 0x04000000 +#define BM_ELCDIF_STAT_BUSY 0x02000000 +#define BM_ELCDIF_STAT_DVI_CURRENT_FIELD 0x01000000 +#define BP_ELCDIF_STAT_RSRVD0 9 +#define BM_ELCDIF_STAT_RSRVD0 0x00FFFE00 +#define BF_ELCDIF_STAT_RSRVD0(v) \ + (((v) << 9) & BM_ELCDIF_STAT_RSRVD0) +#define BP_ELCDIF_STAT_LFIFO_COUNT 0 +#define BM_ELCDIF_STAT_LFIFO_COUNT 0x000001FF +#define BF_ELCDIF_STAT_LFIFO_COUNT(v) \ + (((v) << 0) & BM_ELCDIF_STAT_LFIFO_COUNT) + +#define HW_ELCDIF_VERSION (0x000001c0) + +#define BP_ELCDIF_VERSION_MAJOR 24 +#define BM_ELCDIF_VERSION_MAJOR 0xFF000000 +#define BF_ELCDIF_VERSION_MAJOR(v) \ + (((v) << 24) & BM_ELCDIF_VERSION_MAJOR) +#define BP_ELCDIF_VERSION_MINOR 16 +#define BM_ELCDIF_VERSION_MINOR 0x00FF0000 +#define BF_ELCDIF_VERSION_MINOR(v) \ + (((v) << 16) & BM_ELCDIF_VERSION_MINOR) +#define BP_ELCDIF_VERSION_STEP 0 +#define BM_ELCDIF_VERSION_STEP 0x0000FFFF +#define BF_ELCDIF_VERSION_STEP(v) \ + (((v) << 0) & BM_ELCDIF_VERSION_STEP) + +#define HW_ELCDIF_DEBUG0 (0x000001d0) + +#define BM_ELCDIF_DEBUG0_STREAMING_END_DETECTED 0x80000000 +#define BM_ELCDIF_DEBUG0_WAIT_FOR_VSYNC_EDGE_OUT 0x40000000 +#define BM_ELCDIF_DEBUG0_SYNC_SIGNALS_ON_REG 0x20000000 +#define BM_ELCDIF_DEBUG0_DMACMDKICK 0x10000000 +#define BM_ELCDIF_DEBUG0_ENABLE 0x08000000 +#define BM_ELCDIF_DEBUG0_HSYNC 0x04000000 +#define BM_ELCDIF_DEBUG0_VSYNC 0x02000000 +#define BM_ELCDIF_DEBUG0_CUR_FRAME_TX 0x01000000 +#define BM_ELCDIF_DEBUG0_EMPTY_WORD 0x00800000 +#define BP_ELCDIF_DEBUG0_CUR_STATE 16 +#define BM_ELCDIF_DEBUG0_CUR_STATE 0x007F0000 +#define BF_ELCDIF_DEBUG0_CUR_STATE(v) \ + (((v) << 16) & BM_ELCDIF_DEBUG0_CUR_STATE) +#define BM_ELCDIF_DEBUG0_PXP_ELCDIF_B0_READY 0x00008000 +#define BM_ELCDIF_DEBUG0_ELCDIF_PXP_B0_DONE 0x00004000 +#define BM_ELCDIF_DEBUG0_PXP_ELCDIF_B1_READY 0x00002000 +#define BM_ELCDIF_DEBUG0_ELCDIF_PXP_B1_DONE 0x00001000 +#define BP_ELCDIF_DEBUG0_CUR_REQ_STATE 10 +#define BM_ELCDIF_DEBUG0_CUR_REQ_STATE 0x00000C00 +#define BF_ELCDIF_DEBUG0_CUR_REQ_STATE(v) \ + (((v) << 10) & BM_ELCDIF_DEBUG0_CUR_REQ_STATE) +#define BM_ELCDIF_DEBUG0_MST_AVALID 0x00000200 +#define BP_ELCDIF_DEBUG0_MST_OUTSTANDING_REQS 4 +#define BM_ELCDIF_DEBUG0_MST_OUTSTANDING_REQS 0x000001F0 +#define BF_ELCDIF_DEBUG0_MST_OUTSTANDING_REQS(v) \ + (((v) << 4) & BM_ELCDIF_DEBUG0_MST_OUTSTANDING_REQS) +#define BP_ELCDIF_DEBUG0_MST_WORDS 0 +#define BM_ELCDIF_DEBUG0_MST_WORDS 0x0000000F +#define BF_ELCDIF_DEBUG0_MST_WORDS(v) \ + (((v) << 0) & BM_ELCDIF_DEBUG0_MST_WORDS) + +#define HW_ELCDIF_DEBUG1 (0x000001e0) + +#define BP_ELCDIF_DEBUG1_H_DATA_COUNT 16 +#define BM_ELCDIF_DEBUG1_H_DATA_COUNT 0xFFFF0000 +#define BF_ELCDIF_DEBUG1_H_DATA_COUNT(v) \ + (((v) << 16) & BM_ELCDIF_DEBUG1_H_DATA_COUNT) +#define BP_ELCDIF_DEBUG1_V_DATA_COUNT 0 +#define BM_ELCDIF_DEBUG1_V_DATA_COUNT 0x0000FFFF +#define BF_ELCDIF_DEBUG1_V_DATA_COUNT(v) \ + (((v) << 0) & BM_ELCDIF_DEBUG1_V_DATA_COUNT) + +#define HW_ELCDIF_DEBUG2 (0x000001f0) + +#define BP_ELCDIF_DEBUG2_MST_ADDRESS 0 +#define BM_ELCDIF_DEBUG2_MST_ADDRESS 0xFFFFFFFF +#define BF_ELCDIF_DEBUG2_MST_ADDRESS(v) (v) +#endif /* __ELCDIF_REGS_INCLUDED_ */ diff --git a/drivers/video/mxc/epdc_regs.h b/drivers/video/mxc/epdc_regs.h new file mode 100644 index 000000000000..f9232d8a9a51 --- /dev/null +++ b/drivers/video/mxc/epdc_regs.h @@ -0,0 +1,301 @@ +/* + * Copyright (C) 2010 Freescale Semiconductor, Inc. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ +#ifndef __EPDC_REGS_INCLUDED__ +#define __EPDC_REGS_INCLUDED__ + +extern void __iomem *epdc_base; + +/************************************* + * Register addresses + **************************************/ + +#define EPDC_CTRL (epdc_base + 0x000) +#define EPDC_CTRL_SET (epdc_base + 0x004) +#define EPDC_CTRL_CLEAR (epdc_base + 0x008) +#define EPDC_CTRL_TOGGLE (epdc_base + 0x00C) +#define EPDC_WVADDR (epdc_base + 0x020) +#define EPDC_WB_ADDR (epdc_base + 0x030) +#define EPDC_RES (epdc_base + 0x040) +#define EPDC_FORMAT (epdc_base + 0x050) +#define EPDC_FORMAT_SET (epdc_base + 0x054) +#define EPDC_FORMAT_CLEAR (epdc_base + 0x058) +#define EPDC_FORMAT_TOGGLE (epdc_base + 0x05C) +#define EPDC_FIFOCTRL (epdc_base + 0x0A0) +#define EPDC_FIFOCTRL_SET (epdc_base + 0x0A4) +#define EPDC_FIFOCTRL_CLEAR (epdc_base + 0x0A8) +#define EPDC_FIFOCTRL_TOGGLE (epdc_base + 0x0AC) +#define EPDC_UPD_ADDR (epdc_base + 0x100) +#define EPDC_UPD_CORD (epdc_base + 0x120) +#define EPDC_UPD_SIZE (epdc_base + 0x140) +#define EPDC_UPD_CTRL (epdc_base + 0x160) +#define EPDC_UPD_FIXED (epdc_base + 0x180) +#define EPDC_TEMP (epdc_base + 0x1A0) +#define EPDC_TCE_CTRL (epdc_base + 0x200) +#define EPDC_TCE_SDCFG (epdc_base + 0x220) +#define EPDC_TCE_GDCFG (epdc_base + 0x240) +#define EPDC_TCE_HSCAN1 (epdc_base + 0x260) +#define EPDC_TCE_HSCAN2 (epdc_base + 0x280) +#define EPDC_TCE_VSCAN (epdc_base + 0x2A0) +#define EPDC_TCE_OE (epdc_base + 0x2C0) +#define EPDC_TCE_POLARITY (epdc_base + 0x2E0) +#define EPDC_TCE_TIMING1 (epdc_base + 0x300) +#define EPDC_TCE_TIMING2 (epdc_base + 0x310) +#define EPDC_TCE_TIMING3 (epdc_base + 0x320) +#define EPDC_IRQ_MASK (epdc_base + 0x400) +#define EPDC_IRQ_MASK_SET (epdc_base + 0x404) +#define EPDC_IRQ_MASK_CLEAR (epdc_base + 0x408) +#define EPDC_IRQ_MASK_TOGGLE (epdc_base + 0x40C) +#define EPDC_IRQ (epdc_base + 0x420) +#define EPDC_IRQ_SET (epdc_base + 0x424) +#define EPDC_IRQ_CLEAR (epdc_base + 0x428) +#define EPDC_IRQ_TOGGLE (epdc_base + 0x42C) +#define EPDC_STATUS_LUTS (epdc_base + 0x440) +#define EPDC_STATUS_LUTS_SET (epdc_base + 0x444) +#define EPDC_STATUS_LUTS_CLEAR (epdc_base + 0x448) +#define EPDC_STATUS_LUTS_TOGGLE (epdc_base + 0x44C) +#define EPDC_STATUS_NEXTLUT (epdc_base + 0x460) +#define EPDC_STATUS_COL (epdc_base + 0x480) +#define EPDC_STATUS (epdc_base + 0x4A0) +#define EPDC_STATUS_SET (epdc_base + 0x4A4) +#define EPDC_STATUS_CLEAR (epdc_base + 0x4A8) +#define EPDC_STATUS_TOGGLE (epdc_base + 0x4AC) +#define EPDC_DEBUG (epdc_base + 0x500) +#define EPDC_DEBUG_LUT0 (epdc_base + 0x540) +#define EPDC_DEBUG_LUT1 (epdc_base + 0x550) +#define EPDC_DEBUG_LUT2 (epdc_base + 0x560) +#define EPDC_DEBUG_LUT3 (epdc_base + 0x570) +#define EPDC_DEBUG_LUT4 (epdc_base + 0x580) +#define EPDC_DEBUG_LUT5 (epdc_base + 0x590) +#define EPDC_DEBUG_LUT6 (epdc_base + 0x5A0) +#define EPDC_DEBUG_LUT7 (epdc_base + 0x5B0) +#define EPDC_DEBUG_LUT8 (epdc_base + 0x5C0) +#define EPDC_DEBUG_LUT9 (epdc_base + 0x5D0) +#define EPDC_DEBUG_LUT10 (epdc_base + 0x5E0) +#define EPDC_DEBUG_LUT11 (epdc_base + 0x5F0) +#define EPDC_DEBUG_LUT12 (epdc_base + 0x600) +#define EPDC_DEBUG_LUT13 (epdc_base + 0x610) +#define EPDC_DEBUG_LUT14 (epdc_base + 0x620) +#define EPDC_DEBUG_LUT15 (epdc_base + 0x630) +#define EPDC_GPIO (epdc_base + 0x700) +#define EPDC_VERSION (epdc_base + 0x7F0) + +/* + * Register field definitions + */ + +enum { +/* EPDC_CTRL field values */ + EPDC_CTRL_SFTRST = 0x80000000, + EPDC_CTRL_CLKGATE = 0x40000000, + EPDC_CTRL_SRAM_POWERDOWN = 0x100, + EPDC_CTRL_UPD_DATA_SWIZZLE_MASK = 0xC0, + EPDC_CTRL_UPD_DATA_SWIZZLE_NO_SWAP = 0, + EPDC_CTRL_UPD_DATA_SWIZZLE_ALL_BYTES_SWAP = 0x40, + EPDC_CTRL_UPD_DATA_SWIZZLE_HWD_SWAP = 0x80, + EPDC_CTRL_UPD_DATA_SWIZZLE_HWD_BYTE_SWAP = 0xC0, + EPDC_CTRL_LUT_DATA_SWIZZLE_MASK = 0x30, + EPDC_CTRL_LUT_DATA_SWIZZLE_NO_SWAP = 0, + EPDC_CTRL_LUT_DATA_SWIZZLE_ALL_BYTES_SWAP = 0x10, + EPDC_CTRL_LUT_DATA_SWIZZLE_HWD_SWAP = 0x20, + EPDC_CTRL_LUT_DATA_SWIZZLE_HWD_BYTE_SWAP = 0x30, + EPDC_CTRL_BURST_LEN_8_8 = 0x1, + EPDC_CTRL_BURST_LEN_8_16 = 0, + +/* EPDC_RES field values */ + EPDC_RES_VERTICAL_MASK = 0x1FFF0000, + EPDC_RES_VERTICAL_OFFSET = 16, + EPDC_RES_HORIZONTAL_MASK = 0x1FFF, + EPDC_RES_HORIZONTAL_OFFSET = 0, + +/* EPDC_FORMAT field values */ + EPDC_FORMAT_BUF_PIXEL_SCALE_ROUND = 0x1000000, + EPDC_FORMAT_DEFAULT_TFT_PIXEL_MASK = 0xFF0000, + EPDC_FORMAT_DEFAULT_TFT_PIXEL_OFFSET = 16, + EPDC_FORMAT_BUF_PIXEL_FORMAT_P2N = 0x200, + EPDC_FORMAT_BUF_PIXEL_FORMAT_P3N = 0x300, + EPDC_FORMAT_BUF_PIXEL_FORMAT_P4N = 0x400, + EPDC_FORMAT_BUF_PIXEL_FORMAT_P5N = 0x500, + EPDC_FORMAT_TFT_PIXEL_FORMAT_2BIT = 0x0, + EPDC_FORMAT_TFT_PIXEL_FORMAT_2BIT_VCOM = 0x1, + EPDC_FORMAT_TFT_PIXEL_FORMAT_4BIT = 0x2, + EPDC_FORMAT_TFT_PIXEL_FORMAT_4BIT_VCOM = 0x3, + +/* EPDC_FIFOCTRL field values */ + EPDC_FIFOCTRL_ENABLE_PRIORITY = 0x80000000, + EPDC_FIFOCTRL_FIFO_INIT_LEVEL_MASK = 0xFF0000, + EPDC_FIFOCTRL_FIFO_INIT_LEVEL_OFFSET = 16, + EPDC_FIFOCTRL_FIFO_H_LEVEL_MASK = 0xFF00, + EPDC_FIFOCTRL_FIFO_H_LEVEL_OFFSET = 8, + EPDC_FIFOCTRL_FIFO_L_LEVEL_MASK = 0xFF, + EPDC_FIFOCTRL_FIFO_L_LEVEL_OFFSET = 0, + +/* EPDC_UPD_CORD field values */ + EPDC_UPD_CORD_YCORD_MASK = 0x1FFF0000, + EPDC_UPD_CORD_YCORD_OFFSET = 16, + EPDC_UPD_CORD_XCORD_MASK = 0x1FFF, + EPDC_UPD_CORD_XCORD_OFFSET = 0, + +/* EPDC_UPD_SIZE field values */ + EPDC_UPD_SIZE_HEIGHT_MASK = 0x1FFF0000, + EPDC_UPD_SIZE_HEIGHT_OFFSET = 16, + EPDC_UPD_SIZE_WIDTH_MASK = 0x1FFF, + EPDC_UPD_SIZE_WIDTH_OFFSET = 0, + +/* EPDC_UPD_CTRL field values */ + EPDC_UPD_CTRL_USE_FIXED = 0x80000000, + EPDC_UPD_CTRL_LUT_SEL_MASK = 0xF0000, + EPDC_UPD_CTRL_LUT_SEL_OFFSET = 16, + EPDC_UPD_CTRL_WAVEFORM_MODE_MASK = 0xFF00, + EPDC_UPD_CTRL_WAVEFORM_MODE_OFFSET = 8, + EPDC_UPD_CTRL_UPDATE_MODE_FULL = 0x1, + +/* EPDC_UPD_FIXED field values */ + EPDC_UPD_FIXED_FIXNP_EN = 0x80000000, + EPDC_UPD_FIXED_FIXCP_EN = 0x40000000, + EPDC_UPD_FIXED_FIXNP_MASK = 0xFF00, + EPDC_UPD_FIXED_FIXNP_OFFSET = 8, + EPDC_UPD_FIXED_FIXCP_MASK = 0xFF, + EPDC_UPD_FIXED_FIXCP_OFFSET = 0, + +/* EPDC_TCE_CTRL field values */ + EPDC_TCE_CTRL_VSCAN_HOLDOFF_MASK = 0x1FF0000, + EPDC_TCE_CTRL_VSCAN_HOLDOFF_OFFSET = 16, + EPDC_TCE_CTRL_VCOM_VAL_MASK = 0xC00, + EPDC_TCE_CTRL_VCOM_VAL_OFFSET = 10, + EPDC_TCE_CTRL_VCOM_MODE_AUTO = 0x200, + EPDC_TCE_CTRL_VCOM_MODE_MANUAL = 0x000, + EPDC_TCE_CTRL_DDR_MODE_ENABLE = 0x100, + EPDC_TCE_CTRL_LVDS_MODE_CE_ENABLE = 0x80, + EPDC_TCE_CTRL_LVDS_MODE_ENABLE = 0x40, + EPDC_TCE_CTRL_SCAN_DIR_1_UP = 0x20, + EPDC_TCE_CTRL_SCAN_DIR_0_UP = 0x10, + EPDC_TCE_CTRL_DUAL_SCAN_ENABLE = 0x8, + EPDC_TCE_CTRL_SDDO_WIDTH_16BIT = 0x4, + EPDC_TCE_CTRL_PIXELS_PER_SDCLK_2 = 1, + EPDC_TCE_CTRL_PIXELS_PER_SDCLK_4 = 2, + EPDC_TCE_CTRL_PIXELS_PER_SDCLK_8 = 3, + +/* EPDC_TCE_SDCFG field values */ + EPDC_TCE_SDCFG_SDCLK_HOLD = 0x200000, + EPDC_TCE_SDCFG_SDSHR = 0x100000, + EPDC_TCE_SDCFG_NUM_CE_MASK = 0xF0000, + EPDC_TCE_SDCFG_NUM_CE_OFFSET = 16, + EPDC_TCE_SDCFG_SDDO_REFORMAT_STANDARD = 0, + EPDC_TCE_SDCFG_SDDO_REFORMAT_FLIP_PIXELS = 0x4000, + EPDC_TCE_SDCFG_SDDO_INVERT_ENABLE = 0x2000, + EPDC_TCE_SDCFG_PIXELS_PER_CE_MASK = 0x1FFF, + EPDC_TCE_SDCFG_PIXELS_PER_CE_OFFSET = 0, + +/* EPDC_TCE_GDCFG field values */ + EPDC_TCE_SDCFG_GDRL = 0x10, + EPDC_TCE_SDCFG_GDOE_MODE_DELAYED_GDCLK = 0x2, + EPDC_TCE_SDCFG_GDSP_MODE_FRAME_SYNC = 0x1, + EPDC_TCE_SDCFG_GDSP_MODE_ONE_LINE = 0x0, + +/* EPDC_TCE_HSCAN1 field values */ + EPDC_TCE_HSCAN1_LINE_SYNC_WIDTH_MASK = 0xFFF0000, + EPDC_TCE_HSCAN1_LINE_SYNC_WIDTH_OFFSET = 16, + EPDC_TCE_HSCAN1_LINE_SYNC_MASK = 0xFFF, + EPDC_TCE_HSCAN1_LINE_SYNC_OFFSET = 0, + +/* EPDC_TCE_HSCAN2 field values */ + EPDC_TCE_HSCAN2_LINE_END_MASK = 0xFFF0000, + EPDC_TCE_HSCAN2_LINE_END_OFFSET = 16, + EPDC_TCE_HSCAN2_LINE_BEGIN_MASK = 0xFFF, + EPDC_TCE_HSCAN2_LINE_BEGIN_OFFSET = 0, + +/* EPDC_TCE_VSCAN field values */ + EPDC_TCE_VSCAN_FRAME_END_MASK = 0xFF0000, + EPDC_TCE_VSCAN_FRAME_END_OFFSET = 16, + EPDC_TCE_VSCAN_FRAME_BEGIN_MASK = 0xFF00, + EPDC_TCE_VSCAN_FRAME_BEGIN_OFFSET = 8, + EPDC_TCE_VSCAN_FRAME_SYNC_MASK = 0xFF, + EPDC_TCE_VSCAN_FRAME_SYNC_OFFSET = 0, + +/* EPDC_TCE_OE field values */ + EPDC_TCE_OE_SDOED_WIDTH_MASK = 0xFF000000, + EPDC_TCE_OE_SDOED_WIDTH_OFFSET = 24, + EPDC_TCE_OE_SDOED_DLY_MASK = 0xFF0000, + EPDC_TCE_OE_SDOED_DLY_OFFSET = 16, + EPDC_TCE_OE_SDOEZ_WIDTH_MASK = 0xFF00, + EPDC_TCE_OE_SDOEZ_WIDTH_OFFSET = 8, + EPDC_TCE_OE_SDOEZ_DLY_MASK = 0xFF, + EPDC_TCE_OE_SDOEZ_DLY_OFFSET = 0, + +/* EPDC_TCE_POLARITY field values */ + EPDC_TCE_POLARITY_GDSP_POL_ACTIVE_HIGH = 0x10, + EPDC_TCE_POLARITY_GDOE_POL_ACTIVE_HIGH = 0x8, + EPDC_TCE_POLARITY_SDOE_POL_ACTIVE_HIGH = 0x4, + EPDC_TCE_POLARITY_SDLE_POL_ACTIVE_HIGH = 0x2, + EPDC_TCE_POLARITY_SDCE_POL_ACTIVE_HIGH = 0x1, + +/* EPDC_TCE_TIMING1 field values */ + EPDC_TCE_TIMING1_SDLE_SHIFT_NONE = 0x00, + EPDC_TCE_TIMING1_SDLE_SHIFT_1 = 0x10, + EPDC_TCE_TIMING1_SDLE_SHIFT_2 = 0x20, + EPDC_TCE_TIMING1_SDLE_SHIFT_3 = 0x30, + EPDC_TCE_TIMING1_SDCLK_INVERT = 0x8, + EPDC_TCE_TIMING1_SDCLK_SHIFT_NONE = 0, + EPDC_TCE_TIMING1_SDCLK_SHIFT_1CYCLE = 1, + EPDC_TCE_TIMING1_SDCLK_SHIFT_2CYCLES = 2, + EPDC_TCE_TIMING1_SDCLK_SHIFT_3CYCLES = 3, + +/* EPDC_TCE_TIMING2 field values */ + EPDC_TCE_TIMING2_GDCLK_HP_MASK = 0xFFFF0000, + EPDC_TCE_TIMING2_GDCLK_HP_OFFSET = 16, + EPDC_TCE_TIMING2_GDSP_OFFSET_MASK = 0xFFFF, + EPDC_TCE_TIMING2_GDSP_OFFSET_OFFSET = 0, + +/* EPDC_TCE_TIMING3 field values */ + EPDC_TCE_TIMING3_GDOE_OFFSET_MASK = 0xFFFF0000, + EPDC_TCE_TIMING3_GDOE_OFFSET_OFFSET = 16, + EPDC_TCE_TIMING3_GDCLK_OFFSET_MASK = 0xFFFF, + EPDC_TCE_TIMING3_GDCLK_OFFSET_OFFSET = 0, + +/* EPDC_IRQ_MASK/EPDC_IRQ field values */ + EPDC_IRQ_WB_CMPLT_IRQ = 0x10000, + EPDC_IRQ_LUT_COL_IRQ = 0x20000, + EPDC_IRQ_TCE_UNDERRUN_IRQ = 0x40000, + EPDC_IRQ_FRAME_END_IRQ = 0x80000, + EPDC_IRQ_BUS_ERROR_IRQ = 0x100000, + EPDC_IRQ_TCE_IDLE_IRQ = 0x200000, + +/* EPDC_STATUS_NEXTLUT field values */ + EPDC_STATUS_NEXTLUT_NEXT_LUT_VALID = 0x100, + EPDC_STATUS_NEXTLUT_NEXT_LUT_MASK = 0xF, + EPDC_STATUS_NEXTLUT_NEXT_LUT_OFFSET = 0, + +/* EPDC_STATUS field values */ + EPDC_STATUS_LUTS_UNDERRUN = 0x4, + EPDC_STATUS_LUTS_BUSY = 0x2, + EPDC_STATUS_WB_BUSY = 0x1, + +/* EPDC_DEBUG field values */ + EPDC_DEBUG_UNDERRUN_RECOVER = 0x2, + EPDC_DEBUG_COLLISION_OFF = 0x1, + +/* EPDC_GPIO field values */ + EPDC_GPIO_PWRCOM = 0x40, + EPDC_GPIO_PWRCTRL_MASK = 0x3C, + EPDC_GPIO_PWRCTRL_OFFSET = 2, + EPDC_GPIO_BDR_MASK = 0x3, + EPDC_GPIO_BDR_OFFSET = 0, +}; + +#endif /* __EPDC_REGS_INCLUDED__ */ diff --git a/drivers/video/mxc/ldb.c b/drivers/video/mxc/ldb.c new file mode 100644 index 000000000000..7d8cba479385 --- /dev/null +++ b/drivers/video/mxc/ldb.c @@ -0,0 +1,1449 @@ +/* + * Copyright (C) 2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +/*! + * @file mxc_ldb.c + * + * @brief This file contains the LDB driver device interface and fops + * functions. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define LDB_BGREF_RMODE_MASK 0x00008000 +#define LDB_BGREF_RMODE_INT 0x00008000 +#define LDB_BGREF_RMODE_EXT 0x0 + +#define LDB_DI1_VS_POL_MASK 0x00000400 +#define LDB_DI1_VS_POL_ACT_LOW 0x00000400 +#define LDB_DI1_VS_POL_ACT_HIGH 0x0 +#define LDB_DI0_VS_POL_MASK 0x00000200 +#define LDB_DI0_VS_POL_ACT_LOW 0x00000200 +#define LDB_DI0_VS_POL_ACT_HIGH 0x0 + +#define LDB_BIT_MAP_CH1_MASK 0x00000100 +#define LDB_BIT_MAP_CH1_JEIDA 0x00000100 +#define LDB_BIT_MAP_CH1_SPWG 0x0 +#define LDB_BIT_MAP_CH0_MASK 0x00000040 +#define LDB_BIT_MAP_CH0_JEIDA 0x00000040 +#define LDB_BIT_MAP_CH0_SPWG 0x0 + +#define LDB_DATA_WIDTH_CH1_MASK 0x00000080 +#define LDB_DATA_WIDTH_CH1_24 0x00000080 +#define LDB_DATA_WIDTH_CH1_18 0x0 +#define LDB_DATA_WIDTH_CH0_MASK 0x00000020 +#define LDB_DATA_WIDTH_CH0_24 0x00000020 +#define LDB_DATA_WIDTH_CH0_18 0x0 + +#define LDB_CH1_MODE_MASK 0x0000000C +#define LDB_CH1_MODE_EN_TO_DI1 0x0000000C +#define LDB_CH1_MODE_EN_TO_DI0 0x00000004 +#define LDB_CH1_MODE_DISABLE 0x0 +#define LDB_CH0_MODE_MASK 0x00000003 +#define LDB_CH0_MODE_EN_TO_DI1 0x00000003 +#define LDB_CH0_MODE_EN_TO_DI0 0x00000001 +#define LDB_CH0_MODE_DISABLE 0x0 + +#define LDB_SPLIT_MODE_EN 0x00000010 + +enum ldb_chan_mode_opt { + LDB_SIN_DI0 = 0, + LDB_SIN_DI1 = 1, + LDB_SEP = 2, + LDB_DUL_DI0 = 3, + LDB_DUL_DI1 = 4, + LDB_SPL_DI0 = 5, + LDB_SPL_DI1 = 6, +}; + +static struct ldb_data { + struct fb_info *fbi[2]; + bool ch_working[2]; + uint32_t chan_mode_opt; + uint32_t chan_bit_map[2]; + uint32_t bgref_rmode; + uint32_t base_addr; + uint32_t *control_reg; + struct clk *ldb_di_clk[2]; + struct regulator *lvds_bg_reg; + struct list_head modelist; +} ldb; + +static struct device *g_ldb_dev; +static u32 *ldb_reg; +static bool enabled[2]; +static int g_chan_mode_opt; +static int g_chan_bit_map[2]; +static bool g_enable_ldb; +static bool g_boot_cmd; + +DEFINE_SPINLOCK(ldb_lock); + +struct fb_videomode mxcfb_ldb_modedb[] = { + { + "1080P60", 60, 1920, 1080, 7692, + 100, 40, + 30, 3, + 10, 2, + FB_SYNC_EXT, + FB_VMODE_NONINTERLACED, + 0,}, + { + "XGA", 60, 1024, 768, 15385, + 220, 40, + 21, 7, + 60, 10, + FB_SYNC_EXT, + FB_VMODE_NONINTERLACED, + 0,}, +}; +int mxcfb_ldb_modedb_sz = ARRAY_SIZE(mxcfb_ldb_modedb); + +static int bits_per_pixel(int pixel_fmt) +{ + switch (pixel_fmt) { + case IPU_PIX_FMT_BGR24: + case IPU_PIX_FMT_RGB24: + return 24; + break; + case IPU_PIX_FMT_BGR666: + case IPU_PIX_FMT_RGB666: + case IPU_PIX_FMT_LVDS666: + return 18; + break; + default: + break; + } + return 0; +} + +static int valid_mode(int pixel_fmt) +{ + return ((pixel_fmt == IPU_PIX_FMT_RGB24) || + (pixel_fmt == IPU_PIX_FMT_BGR24) || + (pixel_fmt == IPU_PIX_FMT_LVDS666) || + (pixel_fmt == IPU_PIX_FMT_RGB666) || + (pixel_fmt == IPU_PIX_FMT_BGR666)); +} + +static void ldb_disable(int ipu_di) +{ + uint32_t reg; + int i = 0; + + spin_lock(&ldb_lock); + + switch (ldb.chan_mode_opt) { + case LDB_SIN_DI0: + if (ipu_di != 0 || !ldb.ch_working[0] || !enabled[0]) { + spin_unlock(&ldb_lock); + return; + } + + reg = __raw_readl(ldb.control_reg); + __raw_writel((reg & ~LDB_CH0_MODE_MASK) | + LDB_CH0_MODE_DISABLE, + ldb.control_reg); + + ldb.ldb_di_clk[0] = clk_get(NULL, "ldb_di0_clk"); + clk_disable(ldb.ldb_di_clk[0]); + clk_put(ldb.ldb_di_clk[0]); + + ldb.ch_working[0] = false; + enabled[0] = false; + break; + case LDB_SIN_DI1: + if (ipu_di != 1 || !ldb.ch_working[1] || !enabled[1]) { + spin_unlock(&ldb_lock); + return; + } + + reg = __raw_readl(ldb.control_reg); + __raw_writel((reg & ~LDB_CH1_MODE_MASK) | + LDB_CH1_MODE_DISABLE, + ldb.control_reg); + + ldb.ldb_di_clk[1] = clk_get(NULL, "ldb_di1_clk"); + clk_disable(ldb.ldb_di_clk[1]); + clk_put(ldb.ldb_di_clk[1]); + + ldb.ch_working[1] = false; + enabled[1] = false; + break; + case LDB_SPL_DI0: + case LDB_DUL_DI0: + if (ipu_di != 0 || !enabled[0]) { + spin_unlock(&ldb_lock); + return; + } + + for (i = 0; i < 2; i++) { + if (ldb.ch_working[i]) { + reg = __raw_readl(ldb.control_reg); + if (i == 0) + __raw_writel((reg & ~LDB_CH0_MODE_MASK) | + LDB_CH0_MODE_DISABLE, + ldb.control_reg); + else + __raw_writel((reg & ~LDB_CH0_MODE_MASK) | + LDB_CH1_MODE_DISABLE, + ldb.control_reg); + + if (ldb.chan_mode_opt == LDB_SPL_DI0) { + reg = __raw_readl(ldb.control_reg); + __raw_writel(reg & ~LDB_SPLIT_MODE_EN, + ldb.control_reg); + } + + ldb.ldb_di_clk[i] = clk_get(NULL, i ? + "ldb_di1_clk" : + "ldb_di0_clk"); + clk_disable(ldb.ldb_di_clk[i]); + clk_put(ldb.ldb_di_clk[i]); + + ldb.ch_working[i] = false; + } + } + enabled[0] = false; + break; + case LDB_SPL_DI1: + case LDB_DUL_DI1: + if (ipu_di != 1 || !enabled[1]) { + spin_unlock(&ldb_lock); + return; + } + + for (i = 0; i < 2; i++) { + if (ldb.ch_working[i]) { + reg = __raw_readl(ldb.control_reg); + if (i == 0) + __raw_writel((reg & ~LDB_CH0_MODE_MASK) | + LDB_CH0_MODE_DISABLE, + ldb.control_reg); + else + __raw_writel((reg & ~LDB_CH0_MODE_MASK) | + LDB_CH1_MODE_DISABLE, + ldb.control_reg); + + if (ldb.chan_mode_opt == LDB_SPL_DI1) { + reg = __raw_readl(ldb.control_reg); + __raw_writel(reg & ~LDB_SPLIT_MODE_EN, + ldb.control_reg); + } + + ldb.ldb_di_clk[i] = clk_get(NULL, i ? + "ldb_di1_clk" : + "ldb_di0_clk"); + clk_disable(ldb.ldb_di_clk[i]); + clk_put(ldb.ldb_di_clk[i]); + + ldb.ch_working[i] = false; + } + } + enabled[1] = false; + break; + case LDB_SEP: + if (ldb.ch_working[ipu_di] && enabled[ipu_di]) { + reg = __raw_readl(ldb.control_reg); + if (ipu_di == 0) + __raw_writel((reg & ~LDB_CH0_MODE_MASK) | + LDB_CH0_MODE_DISABLE, + ldb.control_reg); + else + __raw_writel((reg & ~LDB_CH1_MODE_MASK) | + LDB_CH1_MODE_DISABLE, + ldb.control_reg); + + ldb.ldb_di_clk[ipu_di] = clk_get(NULL, ipu_di ? + "ldb_di1_clk" : + "ldb_di0_clk"); + clk_disable(ldb.ldb_di_clk[ipu_di]); + clk_put(ldb.ldb_di_clk[ipu_di]); + + ldb.ch_working[ipu_di] = false; + enabled[ipu_di] = false; + } + break; + default: + break; + } + + spin_unlock(&ldb_lock); + return; +} + +static void ldb_enable(int ipu_di) +{ + uint32_t reg; + + spin_lock(&ldb_lock); + + reg = __raw_readl(ldb.control_reg); + switch (ldb.chan_mode_opt) { + case LDB_SIN_DI0: + if (ldb.ch_working[0] || ipu_di != 0 || enabled[0]) { + spin_unlock(&ldb_lock); + return; + } + + ldb.ldb_di_clk[0] = clk_get(NULL, "ldb_di0_clk"); + clk_enable(ldb.ldb_di_clk[0]); + clk_put(ldb.ldb_di_clk[0]); + __raw_writel((reg & ~LDB_CH0_MODE_MASK) | + LDB_CH0_MODE_EN_TO_DI0, ldb.control_reg); + ldb.ch_working[0] = true; + enabled[0] = true; + break; + case LDB_SIN_DI1: + if (ldb.ch_working[1] || ipu_di != 1 || enabled[1]) { + spin_unlock(&ldb_lock); + return; + } + + ldb.ldb_di_clk[1] = clk_get(NULL, "ldb_di1_clk"); + clk_enable(ldb.ldb_di_clk[1]); + clk_put(ldb.ldb_di_clk[1]); + __raw_writel((reg & ~LDB_CH1_MODE_MASK) | + LDB_CH1_MODE_EN_TO_DI1, ldb.control_reg); + ldb.ch_working[1] = true; + enabled[1] = true; + break; + case LDB_SEP: + if (ldb.ch_working[ipu_di] || enabled[ipu_di]) { + spin_unlock(&ldb_lock); + return; + } + + if (ipu_di == 0) { + ldb.ldb_di_clk[0] = clk_get(NULL, "ldb_di0_clk"); + clk_enable(ldb.ldb_di_clk[0]); + clk_put(ldb.ldb_di_clk[0]); + __raw_writel((reg & ~LDB_CH0_MODE_MASK) | + LDB_CH0_MODE_EN_TO_DI0, + ldb.control_reg); + ldb.ch_working[0] = true; + } else { + ldb.ldb_di_clk[1] = clk_get(NULL, "ldb_di1_clk"); + clk_enable(ldb.ldb_di_clk[1]); + clk_put(ldb.ldb_di_clk[1]); + __raw_writel((reg & ~LDB_CH1_MODE_MASK) | + LDB_CH1_MODE_EN_TO_DI1, + ldb.control_reg); + ldb.ch_working[1] = true; + } + enabled[ipu_di] = true; + break; + case LDB_DUL_DI0: + case LDB_SPL_DI0: + if (ipu_di != 0 || enabled[0]) + return; + else + goto proc; + case LDB_DUL_DI1: + case LDB_SPL_DI1: + if (ipu_di != 1 || enabled[1]) + return; +proc: + if (ldb.ch_working[0] || ldb.ch_working[1]) { + spin_unlock(&ldb_lock); + return; + } + + ldb.ldb_di_clk[0] = clk_get(NULL, "ldb_di0_clk"); + ldb.ldb_di_clk[1] = clk_get(NULL, "ldb_di1_clk"); + clk_enable(ldb.ldb_di_clk[0]); + clk_enable(ldb.ldb_di_clk[1]); + clk_put(ldb.ldb_di_clk[0]); + clk_put(ldb.ldb_di_clk[1]); + + if (ldb.chan_mode_opt == LDB_DUL_DI0 || + ldb.chan_mode_opt == LDB_SPL_DI0) { + __raw_writel((reg & ~LDB_CH0_MODE_MASK) | + LDB_CH0_MODE_EN_TO_DI0, + ldb.control_reg); + reg = __raw_readl(ldb.control_reg); + __raw_writel((reg & ~LDB_CH1_MODE_MASK) | + LDB_CH1_MODE_EN_TO_DI0, + ldb.control_reg); + } else if (ldb.chan_mode_opt == LDB_DUL_DI1 || + ldb.chan_mode_opt == LDB_SPL_DI1) { + __raw_writel((reg & ~LDB_CH0_MODE_MASK) | + LDB_CH0_MODE_EN_TO_DI1, + ldb.control_reg); + reg = __raw_readl(ldb.control_reg); + __raw_writel((reg & ~LDB_CH1_MODE_MASK) | + LDB_CH1_MODE_EN_TO_DI1, + ldb.control_reg); + } + if (ldb.chan_mode_opt == LDB_SPL_DI0 || + ldb.chan_mode_opt == LDB_SPL_DI1) { + reg = __raw_readl(ldb.control_reg); + __raw_writel(reg | LDB_SPLIT_MODE_EN, + ldb.control_reg); + } + ldb.ch_working[0] = true; + ldb.ch_working[1] = true; + enabled[ipu_di] = true; + break; + default: + break; + } + spin_unlock(&ldb_lock); + return; +} + +int ldb_fb_event(struct notifier_block *nb, unsigned long val, void *v) +{ + struct fb_event *event = v; + struct fb_info *fbi = event->info; + mm_segment_t old_fs; + int ipu_di = 0; + + switch (val) { + case FB_EVENT_BLANK: + if (ldb.fbi[0] != fbi && ldb.fbi[1] != fbi) + return 0; + + if (fbi->fbops->fb_ioctl) { + old_fs = get_fs(); + set_fs(KERNEL_DS); + fbi->fbops->fb_ioctl(fbi, + MXCFB_GET_FB_IPU_DI, + (unsigned long)&ipu_di); + set_fs(old_fs); + } else + return 0; + + if (*((int *)event->data) == FB_BLANK_UNBLANK) + ldb_enable(ipu_di); + else + ldb_disable(ipu_di); + break; + default: + break; + } + return 0; +} + +static struct notifier_block nb = { + .notifier_call = ldb_fb_event, +}; + +static int mxc_ldb_ioctl(struct inode *inode, struct file *file, + unsigned int cmd, unsigned long arg) +{ + int ret = 0; + uint32_t reg; + + switch (cmd) { + case LDB_BGREF_RMODE: + { + ldb_bgref_parm parm; + + if (copy_from_user(&parm, (ldb_bgref_parm *) arg, + sizeof(ldb_bgref_parm))) + return -EFAULT; + + spin_lock(&ldb_lock); + reg = __raw_readl(ldb.control_reg); + if (parm.bgref_mode == LDB_EXT_REF) + __raw_writel((reg & ~LDB_BGREF_RMODE_MASK) | + LDB_BGREF_RMODE_EXT, ldb.control_reg); + else if (parm.bgref_mode == LDB_INT_REF) + __raw_writel((reg & ~LDB_BGREF_RMODE_MASK) | + LDB_BGREF_RMODE_INT, ldb.control_reg); + spin_unlock(&ldb_lock); + break; + } + case LDB_VSYNC_POL: + { + ldb_vsync_parm parm; + + if (copy_from_user(&parm, (ldb_vsync_parm *) arg, + sizeof(ldb_vsync_parm))) + return -EFAULT; + + spin_lock(&ldb_lock); + reg = __raw_readl(ldb.control_reg); + if (parm.vsync_mode == LDB_VS_ACT_H) { + if (parm.di == 0) + __raw_writel((reg & + ~LDB_DI0_VS_POL_MASK) | + LDB_DI0_VS_POL_ACT_HIGH, + ldb.control_reg); + else + __raw_writel((reg & + ~LDB_DI1_VS_POL_MASK) | + LDB_DI1_VS_POL_ACT_HIGH, + ldb.control_reg); + } else if (parm.vsync_mode == LDB_VS_ACT_L) { + if (parm.di == 0) + __raw_writel((reg & + ~LDB_DI0_VS_POL_MASK) | + LDB_DI0_VS_POL_ACT_LOW, + ldb.control_reg); + else + __raw_writel((reg & + ~LDB_DI1_VS_POL_MASK) | + LDB_DI1_VS_POL_ACT_LOW, + ldb.control_reg); + + } + spin_unlock(&ldb_lock); + break; + } + case LDB_BIT_MAP: + { + ldb_bitmap_parm parm; + + if (copy_from_user(&parm, (ldb_bitmap_parm *) arg, + sizeof(ldb_bitmap_parm))) + return -EFAULT; + + spin_lock(&ldb_lock); + reg = __raw_readl(ldb.control_reg); + if (parm.bitmap_mode == LDB_BIT_MAP_SPWG) { + if (parm.channel == 0) + __raw_writel((reg & ~LDB_BIT_MAP_CH0_MASK) | + LDB_BIT_MAP_CH0_SPWG, + ldb.control_reg); + else + __raw_writel((reg & ~LDB_BIT_MAP_CH0_MASK) | + LDB_BIT_MAP_CH1_SPWG, + ldb.control_reg); + } else if (parm.bitmap_mode == LDB_BIT_MAP_JEIDA) { + if (parm.channel == 0) + __raw_writel((reg & ~LDB_BIT_MAP_CH0_MASK) | + LDB_BIT_MAP_CH0_JEIDA, + ldb.control_reg); + else + __raw_writel((reg & ~LDB_BIT_MAP_CH0_MASK) | + LDB_BIT_MAP_CH1_JEIDA, + ldb.control_reg); + } + spin_unlock(&ldb_lock); + break; + } + case LDB_DATA_WIDTH: + { + ldb_data_width_parm parm; + + if (copy_from_user(&parm, (ldb_data_width_parm *) arg, + sizeof(ldb_data_width_parm))) + return -EFAULT; + + spin_lock(&ldb_lock); + reg = __raw_readl(ldb.control_reg); + if (parm.data_width == 24) { + if (parm.channel == 0) + __raw_writel((reg & ~LDB_DATA_WIDTH_CH0_MASK) | + LDB_DATA_WIDTH_CH0_24, + ldb.control_reg); + else + __raw_writel((reg & ~LDB_DATA_WIDTH_CH0_MASK) | + LDB_DATA_WIDTH_CH1_24, + ldb.control_reg); + } else if (parm.data_width == 18) { + if (parm.channel == 0) + __raw_writel((reg & ~LDB_DATA_WIDTH_CH0_MASK) | + LDB_DATA_WIDTH_CH0_18, + ldb.control_reg); + else + __raw_writel((reg & ~LDB_DATA_WIDTH_CH0_MASK) | + LDB_DATA_WIDTH_CH1_18, + ldb.control_reg); + } + spin_unlock(&ldb_lock); + break; + } + case LDB_CHAN_MODE: + { + ldb_chan_mode_parm parm; + struct clk *pll4_clk; + unsigned long pll4_rate = 0; + + if (copy_from_user(&parm, (ldb_chan_mode_parm *) arg, + sizeof(ldb_chan_mode_parm))) + return -EFAULT; + + spin_lock(&ldb_lock); + + /* TODO:Set the correct pll4 rate for all situations */ + pll4_clk = clk_get(NULL, "pll4"); + pll4_rate = clk_get_rate(pll4_clk); + pll4_rate = 455000000; + clk_set_rate(pll4_clk, pll4_rate); + clk_put(pll4_clk); + + reg = __raw_readl(ldb.control_reg); + switch (parm.channel_mode) { + case LDB_CHAN_MODE_SIN: + if (parm.di == 0) { + ldb.chan_mode_opt = LDB_SIN_DI0; + + ldb.ldb_di_clk[0] = clk_get(NULL, + "ldb_di0_clk"); + clk_set_rate(ldb.ldb_di_clk[0], pll4_rate/7); + clk_put(ldb.ldb_di_clk[0]); + + __raw_writel((reg & ~LDB_CH0_MODE_MASK) | + LDB_CH0_MODE_EN_TO_DI0, + ldb.control_reg); + } else { + ldb.chan_mode_opt = LDB_SIN_DI1; + + ldb.ldb_di_clk[1] = clk_get(NULL, + "ldb_di1_clk"); + clk_set_rate(ldb.ldb_di_clk[1], pll4_rate/7); + clk_put(ldb.ldb_di_clk[1]); + + __raw_writel((reg & ~LDB_CH1_MODE_MASK) | + LDB_CH1_MODE_EN_TO_DI1, + ldb.control_reg); + } + break; + case LDB_CHAN_MODE_SEP: + ldb.chan_mode_opt = LDB_SEP; + + ldb.ldb_di_clk[0] = clk_get(NULL, "ldb_di0_clk"); + clk_set_rate(ldb.ldb_di_clk[0], pll4_rate/7); + clk_put(ldb.ldb_di_clk[0]); + ldb.ldb_di_clk[1] = clk_get(NULL, "ldb_di1_clk"); + clk_set_rate(ldb.ldb_di_clk[1], pll4_rate/7); + clk_put(ldb.ldb_di_clk[1]); + + __raw_writel((reg & ~(LDB_CH0_MODE_MASK | + LDB_CH1_MODE_MASK)) | + LDB_CH0_MODE_EN_TO_DI0 | + LDB_CH1_MODE_EN_TO_DI1, + ldb.control_reg); + break; + case LDB_CHAN_MODE_DUL: + case LDB_CHAN_MODE_SPL: + ldb.ldb_di_clk[0] = clk_get(NULL, "ldb_di0_clk"); + ldb.ldb_di_clk[1] = clk_get(NULL, "ldb_di1_clk"); + if (parm.di == 0) { + if (parm.channel_mode == LDB_CHAN_MODE_DUL) { + ldb.chan_mode_opt = LDB_DUL_DI0; + clk_set_rate(ldb.ldb_di_clk[0], + pll4_rate/7); + } else { + ldb.chan_mode_opt = LDB_SPL_DI0; + clk_set_rate(ldb.ldb_di_clk[0], + 2*pll4_rate/7); + clk_set_rate(ldb.ldb_di_clk[1], + 2*pll4_rate/7); + reg = __raw_readl(ldb.control_reg); + __raw_writel(reg | LDB_SPLIT_MODE_EN, + ldb.control_reg); + } + + reg = __raw_readl(ldb.control_reg); + __raw_writel((reg & ~(LDB_CH0_MODE_MASK | + LDB_CH1_MODE_MASK)) | + LDB_CH0_MODE_EN_TO_DI0 | + LDB_CH1_MODE_EN_TO_DI0, + ldb.control_reg); + } else { + if (parm.channel_mode == LDB_CHAN_MODE_DUL) { + ldb.chan_mode_opt = LDB_DUL_DI1; + clk_set_rate(ldb.ldb_di_clk[1], + pll4_rate/7); + } else { + ldb.chan_mode_opt = LDB_SPL_DI1; + clk_set_rate(ldb.ldb_di_clk[0], + 2*pll4_rate/7); + clk_set_rate(ldb.ldb_di_clk[1], + 2*pll4_rate/7); + reg = __raw_readl(ldb.control_reg); + __raw_writel(reg | LDB_SPLIT_MODE_EN, + ldb.control_reg); + } + + reg = __raw_readl(ldb.control_reg); + __raw_writel((reg & ~(LDB_CH0_MODE_MASK | + LDB_CH1_MODE_MASK)) | + LDB_CH0_MODE_EN_TO_DI1 | + LDB_CH1_MODE_EN_TO_DI1, + ldb.control_reg); + } + clk_put(ldb.ldb_di_clk[0]); + clk_put(ldb.ldb_di_clk[1]); + break; + default: + ret = -EINVAL; + break; + } + spin_unlock(&ldb_lock); + break; + } + case LDB_ENABLE: + { + int ipu_di; + + if (copy_from_user(&ipu_di, (int *) arg, sizeof(int))) + return -EFAULT; + + ldb_enable(ipu_di); + break; + } + case LDB_DISABLE: + { + int ipu_di; + + if (copy_from_user(&ipu_di, (int *) arg, sizeof(int))) + return -EFAULT; + + ldb_disable(ipu_di); + break; + } + default: + ret = -EINVAL; + break; + } + + return ret; +} + +static int mxc_ldb_open(struct inode *inode, struct file *file) +{ + return 0; +} + +static int mxc_ldb_release(struct inode *inode, struct file *file) +{ + return 0; +} + +static int mxc_ldb_mmap(struct file *file, struct vm_area_struct *vma) +{ + return 0; +} + +static const struct file_operations mxc_ldb_fops = { + .owner = THIS_MODULE, + .open = mxc_ldb_open, + .mmap = mxc_ldb_mmap, + .release = mxc_ldb_release, + .ioctl = mxc_ldb_ioctl +}; + +/*! + * This function is called by the driver framework to initialize the LDB + * device. + * + * @param dev The device structure for the LDB passed in by the + * driver framework. + * + * @return Returns 0 on success or negative error code on error + */ +static int ldb_probe(struct platform_device *pdev) +{ + int ret = 0, i, ipu_di, ipu_di_pix_fmt[2]; + bool primary = false, find_1080p = false; + struct resource *res; + struct ldb_platform_data *plat_data = pdev->dev.platform_data; + mm_segment_t old_fs; + struct clk *ldb_clk_parent; + unsigned long ldb_clk_prate = 455000000; + struct fb_var_screeninfo *var[2]; + uint32_t reg; + struct device *temp; + int mxc_ldb_major; + const struct fb_videomode *mode; + struct class *mxc_ldb_class; + + if (g_enable_ldb == false) + return -ENODEV; + + spin_lock_init(&ldb_lock); + + g_ldb_dev = &pdev->dev; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (IS_ERR(res)) + return -ENODEV; + + memset(&ldb, 0, sizeof(struct ldb_data)); + enabled[0] = enabled[1] = false; + var[0] = var[1] = NULL; + if (g_boot_cmd) { + ldb.chan_mode_opt = g_chan_mode_opt; + ldb.chan_bit_map[0] = g_chan_bit_map[0]; + ldb.chan_bit_map[1] = g_chan_bit_map[1]; + } + + ldb.base_addr = res->start; + ldb_reg = ioremap(ldb.base_addr, res->end - res->start + 1); + ldb.control_reg = ldb_reg + 2; + + INIT_LIST_HEAD(&ldb.modelist); + for (i = 0; i < mxcfb_ldb_modedb_sz; i++) + fb_add_videomode(&mxcfb_ldb_modedb[i], &ldb.modelist); + + for (i = 0; i < num_registered_fb; i++) { + if ((registered_fb[i]->var.sync & FB_SYNC_EXT) && + (registered_fb[i]->var.vmode == FB_VMODE_NONINTERLACED)) { + ldb.fbi[i] = registered_fb[i]; + + mode = fb_match_mode(&ldb.fbi[i]->var, &ldb.modelist); + if (mode) { + dev_dbg(g_ldb_dev, "fb mode found\n"); + fb_videomode_to_var(&ldb.fbi[i]->var, mode); + } else { + dev_warn(g_ldb_dev, + "can't find video mode\n"); + goto err0; + } + /* + * Default ldb mode: + * 1080p: DI0 split, SPWG + * others: single, SPWG + */ + if (g_boot_cmd == false) { + ldb.chan_bit_map[0] = LDB_BIT_MAP_SPWG; + if (fb_mode_is_equal(mode, &mxcfb_ldb_modedb[0])) { + ldb.chan_mode_opt = LDB_SPL_DI0; + ldb.chan_bit_map[0] = LDB_BIT_MAP_SPWG; + ldb.chan_bit_map[1] = LDB_BIT_MAP_SPWG; + find_1080p = true; + dev_warn(g_ldb_dev, "default split mode\n"); + } else if (!find_1080p) { + if (strcmp(ldb.fbi[i]->fix.id, + "DISP3 BG") == 0) { + ldb.chan_mode_opt = LDB_SIN_DI0; + ldb.chan_bit_map[0] = LDB_BIT_MAP_SPWG; + dev_warn(g_ldb_dev, + "default di0 single mode\n"); + } else if (strcmp(ldb.fbi[i]->fix.id, + "DISP3 BG - DI1") == 0) { + ldb.chan_mode_opt = LDB_SIN_DI1; + ldb.chan_bit_map[1] = LDB_BIT_MAP_SPWG; + dev_warn(g_ldb_dev, + "default di1 single mode\n"); + } + } + } + + acquire_console_sem(); + fb_blank(ldb.fbi[i], FB_BLANK_POWERDOWN); + release_console_sem(); + + if (i == 0) + primary = true; + + if (ldb.fbi[1] != NULL) + break; + } + } + + /* + * We cannot support two LVDS panel with different pixel clock rates + * except that one's pixel clock rate is two times of the others'. + */ + if (ldb.fbi[1] && ldb.fbi[0] != NULL) { + if (ldb.fbi[0]->var.pixclock != ldb.fbi[1]->var.pixclock && + ldb.fbi[0]->var.pixclock != 2 * ldb.fbi[1]->var.pixclock && + ldb.fbi[1]->var.pixclock != 2 * ldb.fbi[0]->var.pixclock) + return -EINVAL; + } + + ldb.bgref_rmode = plat_data->ext_ref; + ldb.lvds_bg_reg = regulator_get(&pdev->dev, plat_data->lvds_bg_reg); + if (!IS_ERR(ldb.lvds_bg_reg)) { + regulator_set_voltage(ldb.lvds_bg_reg, 2500000, 2500000); + regulator_enable(ldb.lvds_bg_reg); + } + + for (i = 0; i < 2; i++) { + if (ldb.fbi[i] != NULL) { + if (strcmp(ldb.fbi[i]->fix.id, "DISP3 BG") == 0) + ipu_di = 0; + else if (strcmp(ldb.fbi[i]->fix.id, "DISP3 BG - DI1") + == 0) + ipu_di = 1; + else { + dev_err(g_ldb_dev, "Wrong framebuffer\n"); + goto err0; + } + + var[ipu_di] = &ldb.fbi[i]->var; + if (ldb.fbi[i]->fbops->fb_ioctl) { + old_fs = get_fs(); + set_fs(KERNEL_DS); + ldb.fbi[i]->fbops->fb_ioctl(ldb.fbi[i], + MXCFB_GET_DIFMT, + (unsigned long)&(ipu_di_pix_fmt[ipu_di])); + set_fs(old_fs); + } else { + dev_err(g_ldb_dev, "Can't get framebuffer " + "information\n"); + goto err0; + } + + if (!valid_mode(ipu_di_pix_fmt[ipu_di])) { + dev_err(g_ldb_dev, "Unsupport pixel format " + "for ldb input\n"); + goto err0; + } + + reg = __raw_readl(ldb.control_reg); + if (var[ipu_di]->sync & FB_SYNC_VERT_HIGH_ACT) { + if (ipu_di == 0) + __raw_writel((reg & + ~LDB_DI0_VS_POL_MASK) | + LDB_DI0_VS_POL_ACT_HIGH, + ldb.control_reg); + else + __raw_writel((reg & + ~LDB_DI1_VS_POL_MASK) | + LDB_DI1_VS_POL_ACT_HIGH, + ldb.control_reg); + } else { + if (ipu_di == 0) + __raw_writel((reg & + ~LDB_DI0_VS_POL_MASK) | + LDB_DI0_VS_POL_ACT_LOW, + ldb.control_reg); + else + __raw_writel((reg & + ~LDB_DI1_VS_POL_MASK) | + LDB_DI1_VS_POL_ACT_LOW, + ldb.control_reg); + } + + /* TODO:Set the correct pll4 rate for all situations */ + if (ipu_di == 1) { + ldb.ldb_di_clk[1] = + clk_get(&pdev->dev, "ldb_di1_clk"); + ldb_clk_parent = + clk_get_parent(ldb.ldb_di_clk[1]); + clk_set_rate(ldb_clk_parent, ldb_clk_prate); + clk_put(ldb.ldb_di_clk[1]); + } else { + ldb.ldb_di_clk[0] = + clk_get(&pdev->dev, "ldb_di0_clk"); + ldb_clk_parent = + clk_get_parent(ldb.ldb_di_clk[0]); + clk_set_rate(ldb_clk_parent, ldb_clk_prate); + clk_put(ldb.ldb_di_clk[0]); + } + } + } + + reg = __raw_readl(ldb.control_reg); + if (ldb.bgref_rmode == LDB_EXT_REF) + __raw_writel((reg & ~LDB_BGREF_RMODE_MASK) | + LDB_BGREF_RMODE_EXT, ldb.control_reg); + else + __raw_writel((reg & ~LDB_BGREF_RMODE_MASK) | + LDB_BGREF_RMODE_INT, ldb.control_reg); + + switch (ldb.chan_mode_opt) { + case LDB_SIN_DI0: + if (var[0] == NULL) { + dev_err(g_ldb_dev, "Can't find framebuffer on DI0\n"); + break; + } + + reg = __raw_readl(ldb.control_reg); + if (bits_per_pixel(ipu_di_pix_fmt[0]) == 24) + __raw_writel((reg & ~LDB_DATA_WIDTH_CH0_MASK) | + LDB_DATA_WIDTH_CH0_24, + ldb.control_reg); + else if (bits_per_pixel(ipu_di_pix_fmt[0]) == 18) + __raw_writel((reg & ~LDB_DATA_WIDTH_CH0_MASK) | + LDB_DATA_WIDTH_CH0_18, + ldb.control_reg); + + reg = __raw_readl(ldb.control_reg); + if (ldb.chan_bit_map[0] == LDB_BIT_MAP_SPWG) + __raw_writel((reg & ~LDB_BIT_MAP_CH0_MASK) | + LDB_BIT_MAP_CH0_SPWG, + ldb.control_reg); + else + __raw_writel((reg & ~LDB_BIT_MAP_CH0_MASK) | + LDB_BIT_MAP_CH0_JEIDA, + ldb.control_reg); + + ldb.ldb_di_clk[0] = clk_get(NULL, "ldb_di0_clk"); + clk_set_rate(ldb.ldb_di_clk[0], ldb_clk_prate/7); + clk_enable(ldb.ldb_di_clk[0]); + clk_put(ldb.ldb_di_clk[0]); + + reg = __raw_readl(ldb.control_reg); + __raw_writel((reg & ~LDB_CH0_MODE_MASK) | + LDB_CH0_MODE_EN_TO_DI0, ldb.control_reg); + ldb.ch_working[0] = true; + break; + case LDB_SIN_DI1: + if (var[1] == NULL) { + dev_err(g_ldb_dev, "Can't find framebuffer on DI1\n"); + break; + } + + reg = __raw_readl(ldb.control_reg); + if (bits_per_pixel(ipu_di_pix_fmt[1]) == 24) + __raw_writel((reg & ~LDB_DATA_WIDTH_CH1_MASK) | + LDB_DATA_WIDTH_CH1_24, + ldb.control_reg); + else if (bits_per_pixel(ipu_di_pix_fmt[1]) == 18) + __raw_writel((reg & ~LDB_DATA_WIDTH_CH1_MASK) | + LDB_DATA_WIDTH_CH1_18, + ldb.control_reg); + + reg = __raw_readl(ldb.control_reg); + if (ldb.chan_bit_map[1] == LDB_BIT_MAP_SPWG) + __raw_writel((reg & ~LDB_BIT_MAP_CH1_MASK) | + LDB_BIT_MAP_CH1_SPWG, + ldb.control_reg); + else + __raw_writel((reg & ~LDB_BIT_MAP_CH1_MASK) | + LDB_BIT_MAP_CH1_JEIDA, + ldb.control_reg); + + ldb.ldb_di_clk[1] = clk_get(NULL, "ldb_di1_clk"); + clk_set_rate(ldb.ldb_di_clk[1], ldb_clk_prate/7); + clk_enable(ldb.ldb_di_clk[1]); + clk_put(ldb.ldb_di_clk[1]); + + reg = __raw_readl(ldb.control_reg); + __raw_writel((reg & ~LDB_CH1_MODE_MASK) | + LDB_CH1_MODE_EN_TO_DI1, ldb.control_reg); + ldb.ch_working[1] = true; + break; + case LDB_SEP: + if (var[0] == NULL || var[1] == NULL) { + dev_err(g_ldb_dev, "Can't find framebuffers on DI0/1\n"); + break; + } + + reg = __raw_readl(ldb.control_reg); + if (bits_per_pixel(ipu_di_pix_fmt[0]) == 24) + __raw_writel((reg & ~LDB_DATA_WIDTH_CH0_MASK) | + LDB_DATA_WIDTH_CH0_24, + ldb.control_reg); + else if (bits_per_pixel(ipu_di_pix_fmt[0]) == 18) + __raw_writel((reg & ~LDB_DATA_WIDTH_CH0_MASK) | + LDB_DATA_WIDTH_CH0_18, + ldb.control_reg); + reg = __raw_readl(ldb.control_reg); + if (bits_per_pixel(ipu_di_pix_fmt[1]) == 24) + __raw_writel((reg & ~LDB_DATA_WIDTH_CH1_MASK) | + LDB_DATA_WIDTH_CH1_24, + ldb.control_reg); + else if (bits_per_pixel(ipu_di_pix_fmt[1]) == 18) + __raw_writel((reg & ~LDB_DATA_WIDTH_CH1_MASK) | + LDB_DATA_WIDTH_CH1_18, + ldb.control_reg); + + reg = __raw_readl(ldb.control_reg); + if (ldb.chan_bit_map[0] == LDB_BIT_MAP_SPWG) + __raw_writel((reg & ~LDB_BIT_MAP_CH0_MASK) | + LDB_BIT_MAP_CH0_SPWG, + ldb.control_reg); + else + __raw_writel((reg & ~LDB_BIT_MAP_CH0_MASK) | + LDB_BIT_MAP_CH0_JEIDA, + ldb.control_reg); + reg = __raw_readl(ldb.control_reg); + if (ldb.chan_bit_map[1] == LDB_BIT_MAP_SPWG) + __raw_writel((reg & ~LDB_BIT_MAP_CH1_MASK) | + LDB_BIT_MAP_CH1_SPWG, + ldb.control_reg); + else + __raw_writel((reg & ~LDB_BIT_MAP_CH1_MASK) | + LDB_BIT_MAP_CH1_JEIDA, + ldb.control_reg); + + ldb.ldb_di_clk[0] = clk_get(NULL, "ldb_di0_clk"); + clk_set_rate(ldb.ldb_di_clk[0], ldb_clk_prate/7); + clk_enable(ldb.ldb_di_clk[0]); + clk_put(ldb.ldb_di_clk[0]); + ldb.ldb_di_clk[1] = clk_get(NULL, "ldb_di1_clk"); + clk_set_rate(ldb.ldb_di_clk[1], ldb_clk_prate/7); + clk_enable(ldb.ldb_di_clk[1]); + clk_put(ldb.ldb_di_clk[1]); + + reg = __raw_readl(ldb.control_reg); + __raw_writel((reg & ~(LDB_CH0_MODE_MASK | + LDB_CH1_MODE_MASK)) | + LDB_CH0_MODE_EN_TO_DI0 | + LDB_CH1_MODE_EN_TO_DI1, ldb.control_reg); + ldb.ch_working[0] = true; + ldb.ch_working[1] = true; + break; + case LDB_DUL_DI0: + case LDB_SPL_DI0: + if (var[0] == NULL) { + dev_err(g_ldb_dev, "Can't find framebuffer on DI0\n"); + break; + } + + reg = __raw_readl(ldb.control_reg); + if (bits_per_pixel(ipu_di_pix_fmt[0]) == 24) + __raw_writel((reg & ~(LDB_DATA_WIDTH_CH0_MASK | + LDB_DATA_WIDTH_CH1_MASK)) | + LDB_DATA_WIDTH_CH0_24 | + LDB_DATA_WIDTH_CH1_24, + ldb.control_reg); + else if (bits_per_pixel(ipu_di_pix_fmt[0]) == 18) + __raw_writel((reg & ~(LDB_DATA_WIDTH_CH0_MASK | + LDB_DATA_WIDTH_CH1_MASK)) | + LDB_DATA_WIDTH_CH0_18 | + LDB_DATA_WIDTH_CH1_18, + ldb.control_reg); + + reg = __raw_readl(ldb.control_reg); + if (ldb.chan_bit_map[0] == LDB_BIT_MAP_SPWG) + __raw_writel((reg & ~LDB_BIT_MAP_CH0_MASK) | + LDB_BIT_MAP_CH0_SPWG, + ldb.control_reg); + else + __raw_writel((reg & ~LDB_BIT_MAP_CH0_MASK) | + LDB_BIT_MAP_CH0_JEIDA, + ldb.control_reg); + reg = __raw_readl(ldb.control_reg); + if (ldb.chan_bit_map[1] == LDB_BIT_MAP_SPWG) + __raw_writel((reg & ~LDB_BIT_MAP_CH1_MASK) | + LDB_BIT_MAP_CH1_SPWG, + ldb.control_reg); + else + __raw_writel((reg & ~LDB_BIT_MAP_CH1_MASK) | + LDB_BIT_MAP_CH1_JEIDA, + ldb.control_reg); + + reg = __raw_readl(ldb.control_reg); + if (ldb.chan_mode_opt == LDB_SPL_DI0) + __raw_writel(reg | LDB_SPLIT_MODE_EN, + ldb.control_reg); + + ldb.ldb_di_clk[0] = clk_get(NULL, "ldb_di0_clk"); + ldb.ldb_di_clk[1] = clk_get(NULL, "ldb_di1_clk"); + if (ldb.chan_mode_opt == LDB_DUL_DI0) { + clk_set_rate(ldb.ldb_di_clk[0], ldb_clk_prate/7); + } else { + clk_set_rate(ldb.ldb_di_clk[0], 2*ldb_clk_prate/7); + clk_set_rate(ldb.ldb_di_clk[1], 2*ldb_clk_prate/7); + } + clk_enable(ldb.ldb_di_clk[0]); + clk_enable(ldb.ldb_di_clk[1]); + clk_put(ldb.ldb_di_clk[0]); + clk_put(ldb.ldb_di_clk[1]); + + reg = __raw_readl(ldb.control_reg); + __raw_writel((reg & ~(LDB_CH0_MODE_MASK | + LDB_CH1_MODE_MASK)) | + LDB_CH0_MODE_EN_TO_DI0 | + LDB_CH1_MODE_EN_TO_DI0, ldb.control_reg); + ldb.ch_working[0] = true; + ldb.ch_working[1] = true; + break; + case LDB_DUL_DI1: + case LDB_SPL_DI1: + if (var[1] == NULL) { + dev_err(g_ldb_dev, "Can't find framebuffer on DI1\n"); + break; + } + + reg = __raw_readl(ldb.control_reg); + if (bits_per_pixel(ipu_di_pix_fmt[1]) == 24) + __raw_writel((reg & ~(LDB_DATA_WIDTH_CH0_MASK | + LDB_DATA_WIDTH_CH1_MASK)) | + LDB_DATA_WIDTH_CH0_24 | + LDB_DATA_WIDTH_CH1_24, + ldb.control_reg); + else if (bits_per_pixel(ipu_di_pix_fmt[1]) == 18) + __raw_writel((reg & ~(LDB_DATA_WIDTH_CH0_MASK | + LDB_DATA_WIDTH_CH1_MASK)) | + LDB_DATA_WIDTH_CH0_18 | + LDB_DATA_WIDTH_CH1_18, + ldb.control_reg); + + reg = __raw_readl(ldb.control_reg); + if (ldb.chan_bit_map[0] == LDB_BIT_MAP_SPWG) + __raw_writel((reg & ~LDB_BIT_MAP_CH0_MASK) | + LDB_BIT_MAP_CH0_SPWG, + ldb.control_reg); + else + __raw_writel((reg & ~LDB_BIT_MAP_CH0_MASK) | + LDB_BIT_MAP_CH0_JEIDA, + ldb.control_reg); + reg = __raw_readl(ldb.control_reg); + if (ldb.chan_bit_map[1] == LDB_BIT_MAP_SPWG) + __raw_writel((reg & ~LDB_BIT_MAP_CH1_MASK) | + LDB_BIT_MAP_CH1_SPWG, + ldb.control_reg); + else + __raw_writel((reg & ~LDB_BIT_MAP_CH1_MASK) | + LDB_BIT_MAP_CH1_JEIDA, + ldb.control_reg); + + reg = __raw_readl(ldb.control_reg); + if (ldb.chan_mode_opt == LDB_SPL_DI1) + __raw_writel(reg | LDB_SPLIT_MODE_EN, + ldb.control_reg); + + ldb.ldb_di_clk[0] = clk_get(NULL, "ldb_di0_clk"); + ldb.ldb_di_clk[1] = clk_get(NULL, "ldb_di1_clk"); + if (ldb.chan_mode_opt == LDB_DUL_DI1) { + clk_set_rate(ldb.ldb_di_clk[1], ldb_clk_prate/7); + } else { + clk_set_rate(ldb.ldb_di_clk[0], 2*ldb_clk_prate/7); + clk_set_rate(ldb.ldb_di_clk[1], 2*ldb_clk_prate/7); + } + clk_enable(ldb.ldb_di_clk[0]); + clk_enable(ldb.ldb_di_clk[1]); + clk_put(ldb.ldb_di_clk[0]); + clk_put(ldb.ldb_di_clk[1]); + + reg = __raw_readl(ldb.control_reg); + __raw_writel((reg & ~(LDB_CH0_MODE_MASK | + LDB_CH1_MODE_MASK)) | + LDB_CH0_MODE_EN_TO_DI1 | + LDB_CH1_MODE_EN_TO_DI1, ldb.control_reg); + ldb.ch_working[0] = true; + ldb.ch_working[1] = true; + break; + default: + break; + } + + mxc_ldb_major = register_chrdev(0, "mxc_ldb", &mxc_ldb_fops); + if (mxc_ldb_major < 0) { + dev_err(g_ldb_dev, "Unable to register MXC LDB as a char " + "device\n"); + ret = mxc_ldb_major; + goto err0; + } + + mxc_ldb_class = class_create(THIS_MODULE, "mxc_ldb"); + if (IS_ERR(mxc_ldb_class)) { + dev_err(g_ldb_dev, "Unable to create class for MXC LDB\n"); + ret = PTR_ERR(mxc_ldb_class); + goto err1; + } + + temp = device_create(mxc_ldb_class, NULL, MKDEV(mxc_ldb_major, 0), + NULL, "mxc_ldb"); + if (IS_ERR(temp)) { + dev_err(g_ldb_dev, "Unable to create class device for " + "MXC LDB\n"); + ret = PTR_ERR(temp); + goto err2; + } + + ret = fb_register_client(&nb); + if (ret < 0) + goto err2; + + if (primary && ldb.fbi[0] != NULL) { + acquire_console_sem(); + fb_blank(ldb.fbi[0], FB_BLANK_UNBLANK); + release_console_sem(); + fb_show_logo(ldb.fbi[0], 0); + } + + return ret; +err2: + class_destroy(mxc_ldb_class); +err1: + unregister_chrdev(mxc_ldb_major, "mxc_ldb"); +err0: + iounmap(ldb_reg); + return ret; +} + +static int ldb_remove(struct platform_device *pdev) +{ + int i; + + __raw_writel(0, ldb.control_reg); + + for (i = 0; i < 2; i++) { + if (ldb.ch_working[i]) { + ldb.ldb_di_clk[i] = clk_get(NULL, + i ? "ldb_di1_clk" : "ldb_di0_clk"); + clk_disable(ldb.ldb_di_clk[i]); + clk_put(ldb.ldb_di_clk[i]); + ldb.ch_working[i] = false; + } + } + + fb_unregister_client(&nb); + return 0; +} + +static int ldb_suspend(struct platform_device *pdev, pm_message_t state) +{ + switch (ldb.chan_mode_opt) { + case LDB_SIN_DI0: + case LDB_DUL_DI0: + case LDB_SPL_DI0: + ldb_disable(0); + break; + case LDB_SIN_DI1: + case LDB_DUL_DI1: + case LDB_SPL_DI1: + ldb_disable(1); + break; + case LDB_SEP: + ldb_disable(0); + ldb_disable(1); + break; + default: + break; + } + return 0; +} + +static int ldb_resume(struct platform_device *pdev) +{ + switch (ldb.chan_mode_opt) { + case LDB_SIN_DI0: + case LDB_DUL_DI0: + case LDB_SPL_DI0: + ldb_enable(0); + break; + case LDB_SIN_DI1: + case LDB_DUL_DI1: + case LDB_SPL_DI1: + ldb_enable(1); + break; + case LDB_SEP: + ldb_enable(0); + ldb_enable(1); + break; + default: + break; + } + return 0; +} + +static struct platform_driver mxcldb_driver = { + .driver = { + .name = "mxc_ldb", + }, + .probe = ldb_probe, + .remove = ldb_remove, + .suspend = ldb_suspend, + .resume = ldb_resume, +}; + +/* + * Parse user specified options (`lvds=') + * example: + * lvds=single(separate, dual or split),(di=0 or di=1), + * ch0_map=SPWG or JEIDA,ch1_map=SPWG or JEIDA + * + */ +static int __init ldb_setup(char *options) +{ + g_enable_ldb = true; + + if (!strlen(options)) + return 1; + else if (!strsep(&options, "=")) + return 1; + + if (!strncmp(options, "single", 6)) { + strsep(&options, ","); + if (!strncmp(options, "di=0", 4)) + g_chan_mode_opt = LDB_SIN_DI0; + else + g_chan_mode_opt = LDB_SIN_DI1; + } else if (!strncmp(options, "separate", 8)) { + g_chan_mode_opt = LDB_SEP; + } else if (!strncmp(options, "dual", 4)) { + strsep(&options, ","); + if (!strncmp(options, "di=", 3)) { + if (simple_strtoul(options + 3, NULL, 0) == 0) + g_chan_mode_opt = LDB_DUL_DI0; + else + g_chan_mode_opt = LDB_DUL_DI1; + } + } else if (!strncmp(options, "split", 5)) { + strsep(&options, ","); + if (!strncmp(options, "di=", 3)) { + if (simple_strtoul(options + 3, NULL, 0) == 0) + g_chan_mode_opt = LDB_SPL_DI0; + else + g_chan_mode_opt = LDB_SPL_DI1; + } + } else + return 1; + + if ((strsep(&options, ",") != NULL) && + !strncmp(options, "ch0_map=", 8)) { + if (!strncmp(options + 8, "SPWG", 4)) + g_chan_bit_map[0] = LDB_BIT_MAP_SPWG; + else + g_chan_bit_map[0] = LDB_BIT_MAP_JEIDA; + } + + if (!(g_chan_mode_opt == LDB_SIN_DI0 || + g_chan_mode_opt == LDB_SIN_DI1) && + (strsep(&options, ",") != NULL) && + !strncmp(options, "ch1_map=", 8)) { + if (!strncmp(options + 8, "SPWG", 4)) + g_chan_bit_map[1] = LDB_BIT_MAP_SPWG; + else + g_chan_bit_map[1] = LDB_BIT_MAP_JEIDA; + } + + g_boot_cmd = true; + + return 1; +} +__setup("ldb", ldb_setup); + +static int __init ldb_init(void) +{ + int ret; + + ret = platform_driver_register(&mxcldb_driver); + return 0; +} + +static void __exit ldb_uninit(void) +{ + platform_driver_unregister(&mxcldb_driver); +} + +module_init(ldb_init); +module_exit(ldb_uninit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MXC LDB driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/video/mxc/mxc_edid.c b/drivers/video/mxc/mxc_edid.c new file mode 100644 index 000000000000..9641b37a1edd --- /dev/null +++ b/drivers/video/mxc/mxc_edid.c @@ -0,0 +1,88 @@ +/* + * Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @defgroup Framebuffer Framebuffer Driver for SDC and ADC. + */ + +/*! + * @file mxc_edid.c + * + * @brief MXC EDID tools + * + * @ingroup Framebuffer + */ + +/*! + * Include files + */ +#include + +#define EDID_LENGTH 128 + +static u8 edid[EDID_LENGTH]; + +int read_edid(struct i2c_adapter *adp, + struct fb_var_screeninfo *einfo, + int *dvi) +{ + u8 buf0[2] = {0, 0}; + int dat = 0; + u16 addr = 0x50; + struct i2c_msg msg[2] = { + { + .addr = addr, + .flags = 0, + .len = 1, + .buf = buf0, + }, { + .addr = addr, + .flags = I2C_M_RD, + .len = EDID_LENGTH, + .buf = edid, + }, + }; + + if (adp == NULL || einfo == NULL) + return -EINVAL; + + buf0[0] = 0x00; + memset(&edid, 0, sizeof(edid)); + memset(einfo, 0, sizeof(struct fb_var_screeninfo)); + dat = i2c_transfer(adp, msg, 2); + + /* If 0x50 fails, try 0x37. */ + if (edid[1] == 0x00) { + msg[0].addr = msg[1].addr = 0x37; + dat = i2c_transfer(adp, msg, 2); + } + + if (edid[1] == 0x00) + return -ENOENT; + + *dvi = 0; + if ((edid[20] == 0x80) || (edid[20] == 0x88) || (edid[20] == 0)) + *dvi = 1; + + dat = fb_parse_edid(edid, einfo); + if (dat) + return -dat; + + /* This is valid for version 1.3 of the EDID */ + if ((edid[18] == 1) && (edid[19] == 3)) { + einfo->height = edid[21] * 10; + einfo->width = edid[22] * 10; + } + + return 0; +} diff --git a/drivers/video/mxc/mxc_elcdif_fb.c b/drivers/video/mxc/mxc_elcdif_fb.c new file mode 100644 index 000000000000..1619a6593f64 --- /dev/null +++ b/drivers/video/mxc/mxc_elcdif_fb.c @@ -0,0 +1,1436 @@ +/* + * Copyright (C) 2010 Freescale Semiconductor, Inc. + */ + +/* + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ +/* + * Based on drivers/video/mxc/mxc_ipuv3_fb.c, drivers/video/mxs/lcdif.c + * and arch/arm/mach-mx28/include/mach/lcdif.h. + * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "elcdif_regs.h" + +/* ELCDIF Pixel format definitions */ +/* Four-character-code (FOURCC) */ +#define fourcc(a, b, c, d) \ + (((__u32)(a)<<0)|((__u32)(b)<<8)|((__u32)(c)<<16)|((__u32)(d)<<24)) + +/* + * ELCDIF RGB Formats + */ +#define ELCDIF_PIX_FMT_RGB332 fourcc('R', 'G', 'B', '1') +#define ELCDIF_PIX_FMT_RGB555 fourcc('R', 'G', 'B', 'O') +#define ELCDIF_PIX_FMT_RGB565 fourcc('R', 'G', 'B', 'P') +#define ELCDIF_PIX_FMT_RGB666 fourcc('R', 'G', 'B', '6') +#define ELCDIF_PIX_FMT_BGR666 fourcc('B', 'G', 'R', '6') +#define ELCDIF_PIX_FMT_BGR24 fourcc('B', 'G', 'R', '3') +#define ELCDIF_PIX_FMT_RGB24 fourcc('R', 'G', 'B', '3') +#define ELCDIF_PIX_FMT_BGR32 fourcc('B', 'G', 'R', '4') +#define ELCDIF_PIX_FMT_BGRA32 fourcc('B', 'G', 'R', 'A') +#define ELCDIF_PIX_FMT_RGB32 fourcc('R', 'G', 'B', '4') +#define ELCDIF_PIX_FMT_RGBA32 fourcc('R', 'G', 'B', 'A') +#define ELCDIF_PIX_FMT_ABGR32 fourcc('A', 'B', 'G', 'R') + +struct mxc_elcdif_fb_data { + int cur_blank; + int next_blank; + int output_pix_fmt; + int elcdif_mode; + ssize_t mem_size; + ssize_t map_size; + dma_addr_t phys_start; + dma_addr_t cur_phys; + int dma_irq; + int err_irq; + void *virt_start; + struct completion vsync_complete; + struct semaphore flip_sem; + u32 pseudo_palette[16]; +}; + +struct elcdif_signal_cfg { + unsigned clk_pol:1; /* true = falling edge */ + unsigned enable_pol:1; /* true = active high */ + unsigned Hsync_pol:1; /* true = active high */ + unsigned Vsync_pol:1; /* true = active high */ +}; + +static int mxc_elcdif_fb_blank(int blank, struct fb_info *info); +static int mxc_elcdif_fb_map_video_memory(struct fb_info *info); +static int mxc_elcdif_fb_unmap_video_memory(struct fb_info *info); +static char *fb_mode; +static unsigned long default_bpp = 16; +static void __iomem *elcdif_base; +static struct device *g_elcdif_dev; +static bool g_elcdif_axi_clk_enable; +static bool g_elcdif_pix_clk_enable; +static struct clk *g_elcdif_axi_clk; +static struct clk *g_elcdif_pix_clk; + +static inline void setup_dotclk_panel(u32 pixel_clk, + u16 v_pulse_width, + u16 v_period, + u16 v_wait_cnt, + u16 v_active, + u16 h_pulse_width, + u16 h_period, + u16 h_wait_cnt, + u16 h_active, + int in_pixel_format, + int out_pixel_format, + struct elcdif_signal_cfg sig_cfg, + int enable_present) +{ + u32 val, rounded_pixel_clk; + + if (!g_elcdif_axi_clk_enable) { + clk_enable(g_elcdif_axi_clk); + g_elcdif_axi_clk_enable = true; + } + + dev_dbg(g_elcdif_dev, "pixel clk = %d\n", pixel_clk); + rounded_pixel_clk = clk_round_rate(g_elcdif_pix_clk, pixel_clk); + clk_set_rate(g_elcdif_pix_clk, rounded_pixel_clk); + + __raw_writel(BM_ELCDIF_CTRL_DATA_SHIFT_DIR, + elcdif_base + HW_ELCDIF_CTRL_CLR); + + __raw_writel(BM_ELCDIF_CTRL_SHIFT_NUM_BITS, + elcdif_base + HW_ELCDIF_CTRL_CLR); + + __raw_writel(BF_ELCDIF_CTRL2_OUTSTANDING_REQS + (BV_ELCDIF_CTRL2_OUTSTANDING_REQS__REQ_8), + elcdif_base + HW_ELCDIF_CTRL2_SET); + + /* Recover on underflow */ + __raw_writel(BM_ELCDIF_CTRL1_RECOVER_ON_UNDERFLOW, + elcdif_base + HW_ELCDIF_CTRL1_SET); + + /* Configure the input pixel format */ + __raw_writel(BM_ELCDIF_CTRL_WORD_LENGTH | + BM_ELCDIF_CTRL_INPUT_DATA_SWIZZLE | + BM_ELCDIF_CTRL_DATA_FORMAT_16_BIT | + BM_ELCDIF_CTRL_DATA_FORMAT_18_BIT | + BM_ELCDIF_CTRL_DATA_FORMAT_24_BIT, + elcdif_base + HW_ELCDIF_CTRL_CLR); + __raw_writel(BM_ELCDIF_CTRL1_BYTE_PACKING_FORMAT, + elcdif_base + HW_ELCDIF_CTRL1_CLR); + switch (in_pixel_format) { + case ELCDIF_PIX_FMT_RGB565: + __raw_writel(BF_ELCDIF_CTRL1_BYTE_PACKING_FORMAT(0xF), + elcdif_base + HW_ELCDIF_CTRL1_SET); + __raw_writel(BF_ELCDIF_CTRL_WORD_LENGTH(0) | + BF_ELCDIF_CTRL_INPUT_DATA_SWIZZLE(0), + elcdif_base + HW_ELCDIF_CTRL_SET); + break; + case ELCDIF_PIX_FMT_RGB24: + __raw_writel(BF_ELCDIF_CTRL1_BYTE_PACKING_FORMAT(0xF), + elcdif_base + HW_ELCDIF_CTRL1_SET); + __raw_writel(BF_ELCDIF_CTRL_WORD_LENGTH(3) | + BF_ELCDIF_CTRL_INPUT_DATA_SWIZZLE(0), + elcdif_base + HW_ELCDIF_CTRL_SET); + break; + case ELCDIF_PIX_FMT_RGB32: + __raw_writel(BF_ELCDIF_CTRL1_BYTE_PACKING_FORMAT(0x7), + elcdif_base + HW_ELCDIF_CTRL1_SET); + __raw_writel(BF_ELCDIF_CTRL_WORD_LENGTH(3) | + BF_ELCDIF_CTRL_INPUT_DATA_SWIZZLE(0), + elcdif_base + HW_ELCDIF_CTRL_SET); + break; + default: + dev_err(g_elcdif_dev, "ELCDIF unsupported input pixel format " + "%d\n", in_pixel_format); + break; + } + + /* Configure the output pixel format */ + __raw_writel(BM_ELCDIF_CTRL_LCD_DATABUS_WIDTH, + elcdif_base + HW_ELCDIF_CTRL_CLR); + switch (out_pixel_format) { + case ELCDIF_PIX_FMT_RGB565: + __raw_writel(BF_ELCDIF_CTRL_LCD_DATABUS_WIDTH(0), + elcdif_base + HW_ELCDIF_CTRL_SET); + break; + case ELCDIF_PIX_FMT_RGB666: + __raw_writel(BF_ELCDIF_CTRL_LCD_DATABUS_WIDTH(2), + elcdif_base + HW_ELCDIF_CTRL_SET); + break; + case ELCDIF_PIX_FMT_RGB24: + __raw_writel(BF_ELCDIF_CTRL_LCD_DATABUS_WIDTH(3), + elcdif_base + HW_ELCDIF_CTRL_SET); + break; + default: + dev_err(g_elcdif_dev, "ELCDIF unsupported output pixel format " + "%d\n", out_pixel_format); + break; + } + + val = __raw_readl(elcdif_base + HW_ELCDIF_TRANSFER_COUNT); + val &= ~(BM_ELCDIF_TRANSFER_COUNT_V_COUNT | + BM_ELCDIF_TRANSFER_COUNT_H_COUNT); + val |= BF_ELCDIF_TRANSFER_COUNT_H_COUNT(h_active) | + BF_ELCDIF_TRANSFER_COUNT_V_COUNT(v_active); + __raw_writel(val, elcdif_base + HW_ELCDIF_TRANSFER_COUNT); + + __raw_writel(BM_ELCDIF_CTRL_VSYNC_MODE, + elcdif_base + HW_ELCDIF_CTRL_CLR); + __raw_writel(BM_ELCDIF_CTRL_WAIT_FOR_VSYNC_EDGE, + elcdif_base + HW_ELCDIF_CTRL_CLR); + __raw_writel(BM_ELCDIF_CTRL_DVI_MODE, + elcdif_base + HW_ELCDIF_CTRL_CLR); + __raw_writel(BM_ELCDIF_CTRL_DOTCLK_MODE, + elcdif_base + HW_ELCDIF_CTRL_SET); + __raw_writel(BM_ELCDIF_CTRL_BYPASS_COUNT, + elcdif_base + HW_ELCDIF_CTRL_SET); + + val = __raw_readl(elcdif_base + HW_ELCDIF_VDCTRL0); + val &= ~(BM_ELCDIF_VDCTRL0_VSYNC_POL | + BM_ELCDIF_VDCTRL0_HSYNC_POL | + BM_ELCDIF_VDCTRL0_ENABLE_POL | + BM_ELCDIF_VDCTRL0_DOTCLK_POL); + if (sig_cfg.Vsync_pol) + val |= BM_ELCDIF_VDCTRL0_VSYNC_POL; + if (sig_cfg.Hsync_pol) + val |= BM_ELCDIF_VDCTRL0_HSYNC_POL; + if (sig_cfg.clk_pol) + val |= BM_ELCDIF_VDCTRL0_DOTCLK_POL; + if (sig_cfg.enable_pol) + val |= BM_ELCDIF_VDCTRL0_ENABLE_POL; + __raw_writel(val, elcdif_base + HW_ELCDIF_VDCTRL0); + + /* vsync is output */ + val = __raw_readl(elcdif_base + HW_ELCDIF_VDCTRL0); + val &= ~(BM_ELCDIF_VDCTRL0_VSYNC_OEB); + __raw_writel(val, elcdif_base + HW_ELCDIF_VDCTRL0); + + /* + * need enable sig for true RGB i/f. Or, if not true RGB, leave it + * zero. + */ + if (enable_present) { + val = __raw_readl(elcdif_base + HW_ELCDIF_VDCTRL0); + val |= BM_ELCDIF_VDCTRL0_ENABLE_PRESENT; + __raw_writel(val, elcdif_base + HW_ELCDIF_VDCTRL0); + } + + /* + * For DOTCLK mode, count VSYNC_PERIOD in terms of complete hz lines + */ + val = __raw_readl(elcdif_base + HW_ELCDIF_VDCTRL0); + val &= ~(BM_ELCDIF_VDCTRL0_VSYNC_PERIOD_UNIT | + BM_ELCDIF_VDCTRL0_VSYNC_PULSE_WIDTH_UNIT); + val |= BM_ELCDIF_VDCTRL0_VSYNC_PERIOD_UNIT | + BM_ELCDIF_VDCTRL0_VSYNC_PULSE_WIDTH_UNIT; + __raw_writel(val, elcdif_base + HW_ELCDIF_VDCTRL0); + + __raw_writel(BM_ELCDIF_VDCTRL0_VSYNC_PULSE_WIDTH, + elcdif_base + HW_ELCDIF_VDCTRL0_CLR); + __raw_writel(v_pulse_width, elcdif_base + HW_ELCDIF_VDCTRL0_SET); + + __raw_writel(BF_ELCDIF_VDCTRL1_VSYNC_PERIOD(v_period), + elcdif_base + HW_ELCDIF_VDCTRL1); + + __raw_writel(BF_ELCDIF_VDCTRL2_HSYNC_PULSE_WIDTH(h_pulse_width) | + BF_ELCDIF_VDCTRL2_HSYNC_PERIOD(h_period), + elcdif_base + HW_ELCDIF_VDCTRL2); + + val = __raw_readl(elcdif_base + HW_ELCDIF_VDCTRL4); + val &= ~BM_ELCDIF_VDCTRL4_DOTCLK_H_VALID_DATA_CNT; + val |= BF_ELCDIF_VDCTRL4_DOTCLK_H_VALID_DATA_CNT(h_active); + __raw_writel(val, elcdif_base + HW_ELCDIF_VDCTRL4); + + val = __raw_readl(elcdif_base + HW_ELCDIF_VDCTRL3); + val &= ~(BM_ELCDIF_VDCTRL3_HORIZONTAL_WAIT_CNT | + BM_ELCDIF_VDCTRL3_VERTICAL_WAIT_CNT); + val |= BF_ELCDIF_VDCTRL3_HORIZONTAL_WAIT_CNT(h_wait_cnt) | + BF_ELCDIF_VDCTRL3_VERTICAL_WAIT_CNT(v_wait_cnt); + __raw_writel(val, elcdif_base + HW_ELCDIF_VDCTRL3); + + val = __raw_readl(elcdif_base + HW_ELCDIF_VDCTRL4); + val |= BM_ELCDIF_VDCTRL4_SYNC_SIGNALS_ON; + __raw_writel(val, elcdif_base + HW_ELCDIF_VDCTRL4); + + return; +} + +static inline void release_dotclk_panel(void) +{ + if (!g_elcdif_axi_clk_enable) { + clk_enable(g_elcdif_axi_clk); + g_elcdif_axi_clk_enable = true; + } + + __raw_writel(BM_ELCDIF_CTRL_DOTCLK_MODE, + elcdif_base + HW_ELCDIF_CTRL_CLR); + __raw_writel(0, elcdif_base + HW_ELCDIF_VDCTRL0); + __raw_writel(0, elcdif_base + HW_ELCDIF_VDCTRL1); + __raw_writel(0, elcdif_base + HW_ELCDIF_VDCTRL2); + __raw_writel(0, elcdif_base + HW_ELCDIF_VDCTRL3); + + return; +} + +static inline void setup_dvi_panel(u16 h_active, u16 v_active, + u16 h_blanking, u16 v_lines, + u16 v1_blank_start, u16 v1_blank_end, + u16 v2_blank_start, u16 v2_blank_end, + u16 f1_start, u16 f1_end, + u16 f2_start, u16 f2_end) +{ + u32 val; + + if (!g_elcdif_axi_clk_enable) { + clk_enable(g_elcdif_axi_clk); + g_elcdif_axi_clk_enable = true; + } + + /* 32bit packed format (RGB) */ + __raw_writel(BM_ELCDIF_CTRL1_BYTE_PACKING_FORMAT, + elcdif_base + HW_ELCDIF_CTRL1_CLR); + __raw_writel(BF_ELCDIF_CTRL1_BYTE_PACKING_FORMAT(0x7) | + BM_ELCDIF_CTRL1_RECOVER_ON_UNDERFLOW, + elcdif_base + HW_ELCDIF_CTRL1_SET); + + val = __raw_readl(elcdif_base + HW_ELCDIF_TRANSFER_COUNT); + val &= ~(BM_ELCDIF_TRANSFER_COUNT_V_COUNT | + BM_ELCDIF_TRANSFER_COUNT_H_COUNT); + val |= BF_ELCDIF_TRANSFER_COUNT_H_COUNT(h_active) | + BF_ELCDIF_TRANSFER_COUNT_V_COUNT(v_active); + __raw_writel(val, elcdif_base + HW_ELCDIF_TRANSFER_COUNT); + + /* set elcdif to DVI mode */ + __raw_writel(BM_ELCDIF_CTRL_DVI_MODE, + elcdif_base + HW_ELCDIF_CTRL_SET); + __raw_writel(BM_ELCDIF_CTRL_VSYNC_MODE, + elcdif_base + HW_ELCDIF_CTRL_CLR); + __raw_writel(BM_ELCDIF_CTRL_DOTCLK_MODE, + elcdif_base + HW_ELCDIF_CTRL_CLR); + + __raw_writel(BM_ELCDIF_CTRL_BYPASS_COUNT, + elcdif_base + HW_ELCDIF_CTRL_SET); + /* convert input RGB -> YCbCr */ + __raw_writel(BM_ELCDIF_CTRL_RGB_TO_YCBCR422_CSC, + elcdif_base + HW_ELCDIF_CTRL_SET); + /* interlace odd and even fields */ + __raw_writel(BM_ELCDIF_CTRL1_INTERLACE_FIELDS, + elcdif_base + HW_ELCDIF_CTRL1_SET); + + __raw_writel(BM_ELCDIF_CTRL_WORD_LENGTH | + BM_ELCDIF_CTRL_INPUT_DATA_SWIZZLE | + BM_ELCDIF_CTRL_LCD_DATABUS_WIDTH, + elcdif_base + HW_ELCDIF_CTRL_CLR); + __raw_writel(BF_ELCDIF_CTRL_WORD_LENGTH(3) | /* 24 bit */ + BM_ELCDIF_CTRL_DATA_SELECT | /* data mode */ + BF_ELCDIF_CTRL_INPUT_DATA_SWIZZLE(0) | /* no swap */ + BF_ELCDIF_CTRL_LCD_DATABUS_WIDTH(1), /* 8 bit */ + elcdif_base + HW_ELCDIF_CTRL_SET); + + /* ELCDIF_DVI */ + /* set frame size */ + val = __raw_readl(elcdif_base + HW_ELCDIF_DVICTRL0); + __raw_writel(val, elcdif_base + HW_ELCDIF_DVICTRL0); + + /* set start/end of field-1 and start of field-2 */ + val = __raw_readl(elcdif_base + HW_ELCDIF_DVICTRL1); + val &= ~(BM_ELCDIF_DVICTRL1_F1_START_LINE | + BM_ELCDIF_DVICTRL1_F1_END_LINE | + BM_ELCDIF_DVICTRL1_F2_START_LINE); + val |= BF_ELCDIF_DVICTRL1_F1_START_LINE(f1_start) | + BF_ELCDIF_DVICTRL1_F1_END_LINE(f1_end) | + BF_ELCDIF_DVICTRL1_F2_START_LINE(f2_start); + __raw_writel(val, elcdif_base + HW_ELCDIF_DVICTRL1); + + /* set first vertical blanking interval and end of filed-2 */ + val = __raw_readl(elcdif_base + HW_ELCDIF_DVICTRL2); + val &= ~(BM_ELCDIF_DVICTRL2_F2_END_LINE | + BM_ELCDIF_DVICTRL2_V1_BLANK_START_LINE | + BM_ELCDIF_DVICTRL2_V1_BLANK_END_LINE); + val |= BF_ELCDIF_DVICTRL2_F2_END_LINE(f2_end) | + BF_ELCDIF_DVICTRL2_V1_BLANK_START_LINE(v1_blank_start) | + BF_ELCDIF_DVICTRL2_V1_BLANK_END_LINE(v1_blank_end); + __raw_writel(val, elcdif_base + HW_ELCDIF_DVICTRL2); + + /* set second vertical blanking interval */ + val = __raw_readl(elcdif_base + HW_ELCDIF_DVICTRL3); + val &= ~(BM_ELCDIF_DVICTRL3_V2_BLANK_START_LINE | + BM_ELCDIF_DVICTRL3_V2_BLANK_END_LINE); + val |= BF_ELCDIF_DVICTRL3_V2_BLANK_START_LINE(v2_blank_start) | + BF_ELCDIF_DVICTRL3_V2_BLANK_END_LINE(v2_blank_end); + __raw_writel(val, elcdif_base + HW_ELCDIF_DVICTRL3); + + /* fill the rest area black color if the input frame + * is not 720 pixels/line + */ + if (h_active != 720) { + /* the input frame can't be less then (720-256) pixels/line */ + if (720 - h_active > 0xff) + h_active = 720 - 0xff; + + val = __raw_readl(elcdif_base + HW_ELCDIF_DVICTRL4); + val &= ~(BM_ELCDIF_DVICTRL4_H_FILL_CNT | + BM_ELCDIF_DVICTRL4_Y_FILL_VALUE | + BM_ELCDIF_DVICTRL4_CB_FILL_VALUE | + BM_ELCDIF_DVICTRL4_CR_FILL_VALUE); + val |= BF_ELCDIF_DVICTRL4_H_FILL_CNT(720 - h_active) | + BF_ELCDIF_DVICTRL4_Y_FILL_VALUE(16) | + BF_ELCDIF_DVICTRL4_CB_FILL_VALUE(128) | + BF_ELCDIF_DVICTRL4_CR_FILL_VALUE(128); + __raw_writel(val, elcdif_base + HW_ELCDIF_DVICTRL4); + } + + /* Color Space Conversion RGB->YCbCr */ + val = __raw_readl(elcdif_base + HW_ELCDIF_CSC_COEFF0); + val &= ~(BM_ELCDIF_CSC_COEFF0_C0 | + BM_ELCDIF_CSC_COEFF0_CSC_SUBSAMPLE_FILTER); + val |= BF_ELCDIF_CSC_COEFF0_C0(0x41) | + BF_ELCDIF_CSC_COEFF0_CSC_SUBSAMPLE_FILTER(3); + __raw_writel(val, elcdif_base + HW_ELCDIF_CSC_COEFF0); + + val = __raw_readl(elcdif_base + HW_ELCDIF_CSC_COEFF1); + val &= ~(BM_ELCDIF_CSC_COEFF1_C1 | BM_ELCDIF_CSC_COEFF1_C2); + val |= BF_ELCDIF_CSC_COEFF1_C1(0x81) | + BF_ELCDIF_CSC_COEFF1_C2(0x19); + __raw_writel(val, elcdif_base + HW_ELCDIF_CSC_COEFF1); + + val = __raw_readl(elcdif_base + HW_ELCDIF_CSC_COEFF2); + val &= ~(BM_ELCDIF_CSC_COEFF2_C3 | BM_ELCDIF_CSC_COEFF2_C4); + val |= BF_ELCDIF_CSC_COEFF2_C3(0x3DB) | + BF_ELCDIF_CSC_COEFF2_C4(0x3B6); + __raw_writel(val, elcdif_base + HW_ELCDIF_CSC_COEFF2); + + val = __raw_readl(elcdif_base + HW_ELCDIF_CSC_COEFF3); + val &= ~(BM_ELCDIF_CSC_COEFF3_C5 | BM_ELCDIF_CSC_COEFF3_C6); + val |= BF_ELCDIF_CSC_COEFF3_C5(0x70) | + BF_ELCDIF_CSC_COEFF3_C6(0x70); + __raw_writel(val, elcdif_base + HW_ELCDIF_CSC_COEFF3); + + val = __raw_readl(elcdif_base + HW_ELCDIF_CSC_COEFF4); + val &= ~(BM_ELCDIF_CSC_COEFF4_C7 | BM_ELCDIF_CSC_COEFF4_C8); + val |= BF_ELCDIF_CSC_COEFF4_C7(0x3A2) | + BF_ELCDIF_CSC_COEFF4_C8(0x3EE); + __raw_writel(val, elcdif_base + HW_ELCDIF_CSC_COEFF4); + + val = __raw_readl(elcdif_base + HW_ELCDIF_CSC_OFFSET); + val &= ~(BM_ELCDIF_CSC_OFFSET_CBCR_OFFSET | + BM_ELCDIF_CSC_OFFSET_Y_OFFSET); + val |= BF_ELCDIF_CSC_OFFSET_CBCR_OFFSET(0x80) | + BF_ELCDIF_CSC_OFFSET_Y_OFFSET(0x10); + __raw_writel(val, elcdif_base + HW_ELCDIF_CSC_OFFSET); + + val = __raw_readl(elcdif_base + HW_ELCDIF_CSC_LIMIT); + val &= ~(BM_ELCDIF_CSC_LIMIT_CBCR_MIN | + BM_ELCDIF_CSC_LIMIT_CBCR_MAX | + BM_ELCDIF_CSC_LIMIT_Y_MIN | + BM_ELCDIF_CSC_LIMIT_Y_MAX); + val |= BF_ELCDIF_CSC_LIMIT_CBCR_MIN(16) | + BF_ELCDIF_CSC_LIMIT_CBCR_MAX(240) | + BF_ELCDIF_CSC_LIMIT_Y_MIN(16) | + BF_ELCDIF_CSC_LIMIT_Y_MAX(235); + __raw_writel(val, elcdif_base + HW_ELCDIF_CSC_LIMIT); + + return; +} + +static inline void release_dvi_panel(void) +{ + if (!g_elcdif_axi_clk_enable) { + clk_enable(g_elcdif_axi_clk); + g_elcdif_axi_clk_enable = true; + } + + __raw_writel(BM_ELCDIF_CTRL_DVI_MODE, + elcdif_base + HW_ELCDIF_CTRL_CLR); + return; +} + +static inline void mxc_init_elcdif(void) +{ + if (!g_elcdif_axi_clk_enable) { + clk_enable(g_elcdif_axi_clk); + g_elcdif_axi_clk_enable = true; + } + + __raw_writel(BM_ELCDIF_CTRL_CLKGATE, + elcdif_base + HW_ELCDIF_CTRL_CLR); + /* Reset controller */ + __raw_writel(BM_ELCDIF_CTRL_SFTRST, + elcdif_base + HW_ELCDIF_CTRL_SET); + udelay(10); + + /* Take controller out of reset */ + __raw_writel(BM_ELCDIF_CTRL_SFTRST | BM_ELCDIF_CTRL_CLKGATE, + elcdif_base + HW_ELCDIF_CTRL_CLR); + + /* Setup the bus protocol */ + __raw_writel(BM_ELCDIF_CTRL1_MODE86, + elcdif_base + HW_ELCDIF_CTRL1_CLR); + __raw_writel(BM_ELCDIF_CTRL1_BUSY_ENABLE, + elcdif_base + HW_ELCDIF_CTRL1_CLR); + + /* Take display out of reset */ + __raw_writel(BM_ELCDIF_CTRL1_RESET, + elcdif_base + HW_ELCDIF_CTRL1_SET); + + /* VSYNC is an input by default */ + __raw_writel(BM_ELCDIF_VDCTRL0_VSYNC_OEB, + elcdif_base + HW_ELCDIF_VDCTRL0_SET); + + /* Reset display */ + __raw_writel(BM_ELCDIF_CTRL1_RESET, + elcdif_base + HW_ELCDIF_CTRL1_CLR); + udelay(10); + __raw_writel(BM_ELCDIF_CTRL1_RESET, + elcdif_base + HW_ELCDIF_CTRL1_SET); + udelay(10); + + return; +} + +static inline int mxc_elcdif_dma_init(dma_addr_t phys) +{ + int ret = 0; + + if (!g_elcdif_axi_clk_enable) { + clk_enable(g_elcdif_axi_clk); + g_elcdif_axi_clk_enable = true; + } + + __raw_writel(BM_ELCDIF_CTRL_ELCDIF_MASTER, + elcdif_base + HW_ELCDIF_CTRL_SET); + + __raw_writel(phys, elcdif_base + HW_ELCDIF_CUR_BUF); + __raw_writel(phys, elcdif_base + HW_ELCDIF_NEXT_BUF); + return ret; +} + +static inline void mxc_elcdif_dma_release(void) +{ + if (!g_elcdif_axi_clk_enable) { + clk_enable(g_elcdif_axi_clk); + g_elcdif_axi_clk_enable = true; + } + + __raw_writel(BM_ELCDIF_CTRL_ELCDIF_MASTER, + elcdif_base + HW_ELCDIF_CTRL_CLR); + return; +} + +static inline void mxc_elcdif_run(void) +{ + if (!g_elcdif_axi_clk_enable) { + clk_enable(g_elcdif_axi_clk); + g_elcdif_axi_clk_enable = true; + } + + __raw_writel(BM_ELCDIF_CTRL_ELCDIF_MASTER, + elcdif_base + HW_ELCDIF_CTRL_SET); + __raw_writel(BM_ELCDIF_CTRL_RUN, + elcdif_base + HW_ELCDIF_CTRL_SET); + return; +} + +static inline void mxc_elcdif_stop(void) +{ + if (!g_elcdif_axi_clk_enable) { + clk_enable(g_elcdif_axi_clk); + g_elcdif_axi_clk_enable = true; + } + + __raw_writel(BM_ELCDIF_CTRL_RUN, + elcdif_base + HW_ELCDIF_CTRL_CLR); + __raw_writel(BM_ELCDIF_CTRL_ELCDIF_MASTER, + elcdif_base + HW_ELCDIF_CTRL_CLR); + msleep(1); + __raw_writel(BM_ELCDIF_CTRL_CLKGATE, elcdif_base + HW_ELCDIF_CTRL_SET); + return; +} + +static int mxc_elcdif_blank_panel(int blank) +{ + int ret = 0, count; + + if (!g_elcdif_axi_clk_enable) { + clk_enable(g_elcdif_axi_clk); + g_elcdif_axi_clk_enable = true; + } + + switch (blank) { + case FB_BLANK_NORMAL: + case FB_BLANK_VSYNC_SUSPEND: + case FB_BLANK_HSYNC_SUSPEND: + case FB_BLANK_POWERDOWN: + __raw_writel(BM_ELCDIF_CTRL_BYPASS_COUNT, + elcdif_base + HW_ELCDIF_CTRL_CLR); + for (count = 10000; count; count--) { + if (__raw_readl(elcdif_base + HW_ELCDIF_STAT) & + BM_ELCDIF_STAT_TXFIFO_EMPTY) + break; + msleep(1); + } + break; + + case FB_BLANK_UNBLANK: + __raw_writel(BM_ELCDIF_CTRL_BYPASS_COUNT, + elcdif_base + HW_ELCDIF_CTRL_SET); + break; + + default: + dev_err(g_elcdif_dev, "unknown blank parameter\n"); + ret = -EINVAL; + break; + } + return ret; +} + +static int mxc_elcdif_init_panel(void) +{ + if (!g_elcdif_axi_clk_enable) { + clk_enable(g_elcdif_axi_clk); + g_elcdif_axi_clk_enable = true; + } + + /* + * Make sure we do a high-to-low transition to reset the panel. + * First make it low for 100 msec, hi for 10 msec, low for 10 msec, + * then hi. + */ + __raw_writel(BM_ELCDIF_CTRL1_RESET, + elcdif_base + HW_ELCDIF_CTRL1_CLR); /* low */ + msleep(100); + __raw_writel(BM_ELCDIF_CTRL1_RESET, + elcdif_base + HW_ELCDIF_CTRL1_SET); /* high */ + msleep(10); + __raw_writel(BM_ELCDIF_CTRL1_RESET, + elcdif_base + HW_ELCDIF_CTRL1_CLR); /* low */ + + /* For the Samsung, Reset must be held low at least 30 uSec + * Therefore, we'll hold it low for about 10 mSec just to be sure. + * Then we'll wait 1 mSec afterwards. + */ + msleep(10); + __raw_writel(BM_ELCDIF_CTRL1_RESET, + elcdif_base + HW_ELCDIF_CTRL1_SET); /* high */ + msleep(1); + + return 0; +} + +static uint32_t bpp_to_pixfmt(struct fb_info *fbi) +{ + uint32_t pixfmt = 0; + + if (fbi->var.nonstd) + return fbi->var.nonstd; + + switch (fbi->var.bits_per_pixel) { + case 32: + pixfmt = ELCDIF_PIX_FMT_RGB32; + break; + case 24: + pixfmt = ELCDIF_PIX_FMT_RGB24; + break; + case 18: + pixfmt = ELCDIF_PIX_FMT_RGB666; + break; + case 16: + pixfmt = ELCDIF_PIX_FMT_RGB565; + break; + case 8: + pixfmt = ELCDIF_PIX_FMT_RGB332; + break; + } + return pixfmt; +} + +static int mxc_elcdif_fb_set_fix(struct fb_info *info) +{ + struct fb_fix_screeninfo *fix = &info->fix; + struct fb_var_screeninfo *var = &info->var; + + fix->line_length = var->xres_virtual * var->bits_per_pixel / 8; + + fix->type = FB_TYPE_PACKED_PIXELS; + fix->accel = FB_ACCEL_NONE; + fix->visual = FB_VISUAL_TRUECOLOR; + fix->xpanstep = 1; + fix->ypanstep = 1; + + return 0; +} + +static irqreturn_t lcd_irq_handler(int irq, void *dev_id) +{ + struct mxc_elcdif_fb_data *data = dev_id; + u32 status_lcd = __raw_readl(elcdif_base + HW_ELCDIF_CTRL1); + dev_dbg(g_elcdif_dev, "%s: irq %d\n", __func__, irq); + + if (status_lcd & BM_ELCDIF_CTRL1_VSYNC_EDGE_IRQ) { + dev_dbg(g_elcdif_dev, "%s: VSYNC irq\n", __func__); + __raw_writel(BM_ELCDIF_CTRL1_VSYNC_EDGE_IRQ, + elcdif_base + HW_ELCDIF_CTRL1_CLR); + complete(&data->vsync_complete); + } + if (status_lcd & BM_ELCDIF_CTRL1_CUR_FRAME_DONE_IRQ) { + dev_dbg(g_elcdif_dev, "%s: frame done irq\n", __func__); + __raw_writel(BM_ELCDIF_CTRL1_CUR_FRAME_DONE_IRQ, + elcdif_base + HW_ELCDIF_CTRL1_CLR); + up(&data->flip_sem); + } + if (status_lcd & BM_ELCDIF_CTRL1_UNDERFLOW_IRQ) { + dev_dbg(g_elcdif_dev, "%s: underflow irq\n", __func__); + __raw_writel(BM_ELCDIF_CTRL1_UNDERFLOW_IRQ, + elcdif_base + HW_ELCDIF_CTRL1_CLR); + } + if (status_lcd & BM_ELCDIF_CTRL1_OVERFLOW_IRQ) { + dev_dbg(g_elcdif_dev, "%s: overflow irq\n", __func__); + __raw_writel(BM_ELCDIF_CTRL1_OVERFLOW_IRQ, + elcdif_base + HW_ELCDIF_CTRL1_CLR); + } + return IRQ_HANDLED; +} + +static inline u_int _chan_to_field(u_int chan, struct fb_bitfield *bf) +{ + chan &= 0xffff; + chan >>= 16 - bf->length; + return chan << bf->offset; +} + +static int mxc_elcdif_fb_setcolreg(u_int regno, u_int red, u_int green, + u_int blue, u_int transp, + struct fb_info *fbi) +{ + unsigned int val; + int ret = 1; + + /* + * If greyscale is true, then we convert the RGB value + * to greyscale no matter what visual we are using. + */ + if (fbi->var.grayscale) + red = green = blue = (19595 * red + 38470 * green + + 7471 * blue) >> 16; + switch (fbi->fix.visual) { + case FB_VISUAL_TRUECOLOR: + /* + * 16-bit True Colour. We encode the RGB value + * according to the RGB bitfield information. + */ + if (regno < 16) { + u32 *pal = fbi->pseudo_palette; + + val = _chan_to_field(red, &fbi->var.red); + val |= _chan_to_field(green, &fbi->var.green); + val |= _chan_to_field(blue, &fbi->var.blue); + + pal[regno] = val; + ret = 0; + } + break; + + case FB_VISUAL_STATIC_PSEUDOCOLOR: + case FB_VISUAL_PSEUDOCOLOR: + break; + } + return ret; +} + +/* + * This routine actually sets the video mode. It's in here where we + * the hardware state info->par and fix which can be affected by the + * change in par. For this driver it doesn't do much. + * + */ +static int mxc_elcdif_fb_set_par(struct fb_info *fbi) +{ + struct mxc_elcdif_fb_data *data = (struct mxc_elcdif_fb_data *)fbi->par; + struct elcdif_signal_cfg sig_cfg; + int mem_len; + + dev_dbg(fbi->device, "Reconfiguring framebuffer\n"); + + sema_init(&data->flip_sem, 1); + + /* release prev panel */ + if (!g_elcdif_pix_clk_enable) { + clk_enable(g_elcdif_pix_clk); + g_elcdif_pix_clk_enable = true; + } + mxc_elcdif_blank_panel(FB_BLANK_POWERDOWN); + mxc_elcdif_stop(); + release_dotclk_panel(); + mxc_elcdif_dma_release(); + mxc_elcdif_fb_set_fix(fbi); + if (g_elcdif_pix_clk_enable) { + clk_disable(g_elcdif_pix_clk); + g_elcdif_pix_clk_enable = false; + } + + mem_len = fbi->var.yres_virtual * fbi->fix.line_length; + if (!fbi->fix.smem_start || (mem_len > fbi->fix.smem_len)) { + if (fbi->fix.smem_start) + mxc_elcdif_fb_unmap_video_memory(fbi); + + if (mxc_elcdif_fb_map_video_memory(fbi) < 0) + return -ENOMEM; + } + + if (data->next_blank != FB_BLANK_UNBLANK) + return 0; + + /* init next panel */ + if (!g_elcdif_pix_clk_enable) { + clk_enable(g_elcdif_pix_clk); + g_elcdif_pix_clk_enable = true; + } + mxc_init_elcdif(); + mxc_elcdif_init_panel(); + + dev_dbg(fbi->device, "pixclock = %ul Hz\n", + (u32) (PICOS2KHZ(fbi->var.pixclock) * 1000UL)); + + memset(&sig_cfg, 0, sizeof(sig_cfg)); + if (fbi->var.sync & FB_SYNC_HOR_HIGH_ACT) + sig_cfg.Hsync_pol = true; + if (fbi->var.sync & FB_SYNC_VERT_HIGH_ACT) + sig_cfg.Vsync_pol = true; + if (fbi->var.sync & FB_SYNC_CLK_LAT_FALL) + sig_cfg.clk_pol = true; + if (!(fbi->var.sync & FB_SYNC_OE_LOW_ACT)) + sig_cfg.enable_pol = true; + + setup_dotclk_panel((PICOS2KHZ(fbi->var.pixclock)) * 1000UL, + fbi->var.vsync_len, + fbi->var.upper_margin + + fbi->var.yres + fbi->var.lower_margin, + fbi->var.upper_margin, + fbi->var.yres, + fbi->var.hsync_len, + fbi->var.left_margin + + fbi->var.xres + fbi->var.right_margin, + fbi->var.left_margin, + fbi->var.xres, + bpp_to_pixfmt(fbi), + data->output_pix_fmt, + sig_cfg, + 1); + mxc_elcdif_dma_init(fbi->fix.smem_start); + mxc_elcdif_run(); + mxc_elcdif_blank_panel(FB_BLANK_UNBLANK); + + fbi->mode = (struct fb_videomode *)fb_match_mode(&fbi->var, + &fbi->modelist); + return 0; +} + +static int mxc_elcdif_fb_check_var(struct fb_var_screeninfo *var, + struct fb_info *info) +{ + if (var->xres_virtual < var->xres) + var->xres_virtual = var->xres; + if (var->yres_virtual < var->yres) + var->yres_virtual = var->yres; + + if ((var->bits_per_pixel != 32) && (var->bits_per_pixel != 24) && + (var->bits_per_pixel != 16) && (var->bits_per_pixel != 8)) + var->bits_per_pixel = default_bpp; + + switch (var->bits_per_pixel) { + case 8: + var->red.length = 3; + var->red.offset = 5; + var->red.msb_right = 0; + + var->green.length = 3; + var->green.offset = 2; + var->green.msb_right = 0; + + var->blue.length = 2; + var->blue.offset = 0; + var->blue.msb_right = 0; + + var->transp.length = 0; + var->transp.offset = 0; + var->transp.msb_right = 0; + break; + case 16: + var->red.length = 5; + var->red.offset = 11; + var->red.msb_right = 0; + + var->green.length = 6; + var->green.offset = 5; + var->green.msb_right = 0; + + var->blue.length = 5; + var->blue.offset = 0; + var->blue.msb_right = 0; + + var->transp.length = 0; + var->transp.offset = 0; + var->transp.msb_right = 0; + break; + case 24: + var->red.length = 8; + var->red.offset = 16; + var->red.msb_right = 0; + + var->green.length = 8; + var->green.offset = 8; + var->green.msb_right = 0; + + var->blue.length = 8; + var->blue.offset = 0; + var->blue.msb_right = 0; + + var->transp.length = 0; + var->transp.offset = 0; + var->transp.msb_right = 0; + break; + case 32: + var->red.length = 8; + var->red.offset = 16; + var->red.msb_right = 0; + + var->green.length = 8; + var->green.offset = 8; + var->green.msb_right = 0; + + var->blue.length = 8; + var->blue.offset = 0; + var->blue.msb_right = 0; + + var->transp.length = 8; + var->transp.offset = 24; + var->transp.msb_right = 0; + break; + } + + var->height = -1; + var->width = -1; + var->grayscale = 0; + + return 0; +} + +static int mxc_elcdif_fb_wait_for_vsync(u32 channel, struct fb_info *info) +{ + struct mxc_elcdif_fb_data *data = + (struct mxc_elcdif_fb_data *)info->par; + int ret = 0; + + if (data->cur_blank != FB_BLANK_UNBLANK) { + dev_err(info->device, "can't wait for VSYNC when fb " + "is blank\n"); + return -EINVAL; + } + + init_completion(&data->vsync_complete); + + __raw_writel(BM_ELCDIF_CTRL1_VSYNC_EDGE_IRQ_EN, + elcdif_base + HW_ELCDIF_CTRL1_SET); + ret = wait_for_completion_interruptible_timeout( + &data->vsync_complete, 1 * HZ); + if (ret == 0) { + dev_err(info->device, + "MXC ELCDIF wait for vsync: timeout %d\n", + ret); + ret = -ETIME; + } else if (ret > 0) { + ret = 0; + } + __raw_writel(BM_ELCDIF_CTRL1_VSYNC_EDGE_IRQ_EN, + elcdif_base + HW_ELCDIF_CTRL1_CLR); + if (!ret) { + dev_err(info->device, "wait for vsync timed out\n"); + ret = -ETIMEDOUT; + } + return ret; +} + +static int mxc_elcdif_fb_ioctl(struct fb_info *info, unsigned int cmd, + unsigned long arg) +{ + u32 channel = 0; + int ret = -EINVAL; + + switch (cmd) { + case MXCFB_WAIT_FOR_VSYNC: + if (!get_user(channel, (__u32 __user *) arg)) + ret = mxc_elcdif_fb_wait_for_vsync(channel, info); + break; + default: + break; + } + return ret; +} + +static int mxc_elcdif_fb_blank(int blank, struct fb_info *info) +{ + struct mxc_elcdif_fb_data *data = + (struct mxc_elcdif_fb_data *)info->par; + int ret = 0; + + if (data->cur_blank == blank) + return ret; + + data->next_blank = blank; + + if (!g_elcdif_pix_clk_enable) { + clk_enable(g_elcdif_pix_clk); + g_elcdif_pix_clk_enable = true; + } + ret = mxc_elcdif_blank_panel(blank); + if (ret == 0) + data->cur_blank = blank; + else + return ret; + + if (blank == FB_BLANK_UNBLANK) { + ret = mxc_elcdif_fb_set_par(info); + if (ret) + return ret; + } + + if (data->cur_blank != FB_BLANK_UNBLANK) { + if (g_elcdif_axi_clk_enable) { + clk_disable(g_elcdif_axi_clk); + g_elcdif_axi_clk_enable = false; + } + if (g_elcdif_pix_clk_enable) { + clk_disable(g_elcdif_pix_clk); + g_elcdif_pix_clk_enable = false; + } + } else { + if (!g_elcdif_axi_clk_enable) { + clk_enable(g_elcdif_axi_clk); + g_elcdif_axi_clk_enable = true; + } + if (!g_elcdif_pix_clk_enable) { + clk_enable(g_elcdif_pix_clk); + g_elcdif_pix_clk_enable = true; + } + } + + return ret; +} + +static int mxc_elcdif_fb_pan_display(struct fb_var_screeninfo *var, + struct fb_info *info) +{ + struct mxc_elcdif_fb_data *data = + (struct mxc_elcdif_fb_data *)info->par; + int ret = 0; + unsigned long base; + + if (data->cur_blank != FB_BLANK_UNBLANK) { + dev_err(info->device, "can't do pan display when fb " + "is blank\n"); + return -EINVAL; + } + + if (var->xoffset > 0) { + dev_dbg(info->device, "x panning not supported\n"); + return -EINVAL; + } + + if ((var->yoffset + var->yres > var->yres_virtual)) { + dev_err(info->device, "y panning exceeds\n"); + return -EINVAL; + } + + /* update framebuffer visual */ + base = (var->yoffset * var->xres_virtual + var->xoffset); + base *= (var->bits_per_pixel) / 8; + base += info->fix.smem_start; + + __raw_writel(base, elcdif_base + HW_ELCDIF_NEXT_BUF); + + init_completion(&data->vsync_complete); + + /* + * Wait for an interrupt or we will lose frame + * if we call pan-dislay too fast. + */ + __raw_writel(BM_ELCDIF_CTRL1_CUR_FRAME_DONE_IRQ, + elcdif_base + HW_ELCDIF_CTRL1_CLR); + __raw_writel(BM_ELCDIF_CTRL1_CUR_FRAME_DONE_IRQ_EN, + elcdif_base + HW_ELCDIF_CTRL1_SET); + down(&data->flip_sem); + __raw_writel(BM_ELCDIF_CTRL1_CUR_FRAME_DONE_IRQ_EN, + elcdif_base + HW_ELCDIF_CTRL1_CLR); + + return ret; +} + +static struct fb_ops mxc_elcdif_fb_ops = { + .owner = THIS_MODULE, + .fb_check_var = mxc_elcdif_fb_check_var, + .fb_set_par = mxc_elcdif_fb_set_par, + .fb_setcolreg = mxc_elcdif_fb_setcolreg, + .fb_ioctl = mxc_elcdif_fb_ioctl, + .fb_blank = mxc_elcdif_fb_blank, + .fb_pan_display = mxc_elcdif_fb_pan_display, + .fb_fillrect = cfb_fillrect, + .fb_copyarea = cfb_copyarea, + .fb_imageblit = cfb_imageblit, +}; + +/*! + * Allocates the DRAM memory for the frame buffer. This buffer is remapped + * into a non-cached, non-buffered, memory region to allow palette and pixel + * writes to occur without flushing the cache. Once this area is remapped, + * all virtual memory access to the video memory should occur at the new region. + * + * @param fbi framebuffer information pointer + * + * @return Error code indicating success or failure + */ +static int mxc_elcdif_fb_map_video_memory(struct fb_info *fbi) +{ + if (fbi->fix.smem_len < fbi->var.yres_virtual * fbi->fix.line_length) + fbi->fix.smem_len = fbi->var.yres_virtual * + fbi->fix.line_length; + + fbi->screen_base = dma_alloc_writecombine(fbi->device, + fbi->fix.smem_len, + (dma_addr_t *)&fbi->fix.smem_start, + GFP_DMA); + if (fbi->screen_base == 0) { + dev_err(fbi->device, "Unable to allocate framebuffer memory\n"); + fbi->fix.smem_len = 0; + fbi->fix.smem_start = 0; + return -EBUSY; + } + + dev_dbg(fbi->device, "allocated fb @ paddr=0x%08X, size=%d.\n", + (uint32_t) fbi->fix.smem_start, fbi->fix.smem_len); + + fbi->screen_size = fbi->fix.smem_len; + + /* Clear the screen */ + memset((char *)fbi->screen_base, 0, fbi->fix.smem_len); + + return 0; +} + +/*! + * De-allocates the DRAM memory for the frame buffer. + * + * @param fbi framebuffer information pointer + * + * @return Error code indicating success or failure + */ +static int mxc_elcdif_fb_unmap_video_memory(struct fb_info *fbi) +{ + dma_free_writecombine(fbi->device, fbi->fix.smem_len, + fbi->screen_base, fbi->fix.smem_start); + fbi->screen_base = 0; + fbi->fix.smem_start = 0; + fbi->fix.smem_len = 0; + return 0; +} + +static int mxc_elcdif_fb_probe(struct platform_device *pdev) +{ + int ret = 0; + struct mxc_elcdif_fb_data *data; + struct resource *res; + struct fb_info *fbi; + struct mxc_fb_platform_data *pdata = pdev->dev.platform_data; + + fbi = framebuffer_alloc(sizeof(struct mxc_elcdif_fb_data), &pdev->dev); + if (fbi == NULL) { + ret = -ENOMEM; + goto out; + } + + data = (struct mxc_elcdif_fb_data *)fbi->par; + data->cur_blank = data->next_blank = FB_BLANK_UNBLANK; + + fbi->var.activate = FB_ACTIVATE_NOW; + fbi->fbops = &mxc_elcdif_fb_ops; + fbi->flags = FBINFO_FLAG_DEFAULT; + fbi->pseudo_palette = data->pseudo_palette; + + ret = fb_alloc_cmap(&fbi->cmap, 16, 0); + if (ret) + goto out; + + g_elcdif_dev = &pdev->dev; + + res = platform_get_resource(pdev, IORESOURCE_IRQ, 0); + if (res == NULL) { + dev_err(&pdev->dev, "cannot get IRQ resource\n"); + ret = -ENODEV; + goto err0; + } + data->dma_irq = res->start; + + ret = request_irq(data->dma_irq, lcd_irq_handler, 0, + "mxc_elcdif_fb", data); + if (ret) { + dev_err(&pdev->dev, "request_irq (%d) failed with error %d\n", + data->dma_irq, ret); + goto err0; + } + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (res == NULL) { + ret = -ENODEV; + goto err1; + } + elcdif_base = ioremap(res->start, SZ_4K); + + res = platform_get_resource(pdev, IORESOURCE_MEM, 1); + if (res) { + fbi->fix.smem_len = res->end - res->start + 1; + fbi->fix.smem_start = res->start; + fbi->screen_base = ioremap(fbi->fix.smem_start, + fbi->fix.smem_len); + } + + strcpy(fbi->fix.id, "mxc_elcdif_fb"); + + fbi->var.xres = 800; + fbi->var.yres = 480; + + if (pdata && !data->output_pix_fmt) + data->output_pix_fmt = pdata->interface_pix_fmt; + + if (pdata && pdata->mode && pdata->num_modes) + fb_videomode_to_modelist(pdata->mode, pdata->num_modes, + &fbi->modelist); + + if (!fb_mode && pdata && pdata->mode_str) + fb_mode = pdata->mode_str; + + if (fb_mode) { + ret = fb_find_mode(&fbi->var, fbi, fb_mode, NULL, 0, NULL, + default_bpp); + if ((!ret || (ret > 2)) && pdata && pdata->mode && + pdata->num_modes) + fb_find_mode(&fbi->var, fbi, fb_mode, pdata->mode, + pdata->num_modes, NULL, default_bpp); + } + + mxc_elcdif_fb_check_var(&fbi->var, fbi); + + fbi->var.xres_virtual = fbi->var.xres; + fbi->var.yres_virtual = fbi->var.yres * 3; + + mxc_elcdif_fb_set_fix(fbi); + + if (!res || !res->end) + if (mxc_elcdif_fb_map_video_memory(fbi) < 0) { + ret = -ENOMEM; + goto err2; + } + + g_elcdif_axi_clk = clk_get(g_elcdif_dev, "elcdif_axi"); + if (g_elcdif_axi_clk == NULL) { + dev_err(&pdev->dev, "can't get ELCDIF axi clk\n"); + ret = -ENODEV; + goto err3; + } + g_elcdif_pix_clk = clk_get(g_elcdif_dev, "elcdif_pix"); + if (g_elcdif_pix_clk == NULL) { + dev_err(&pdev->dev, "can't get ELCDIF pix clk\n"); + ret = -ENODEV; + goto err3; + } + /* + * Set an appropriate pixel clk rate first, so that we can + * access ELCDIF registers. + */ + clk_set_rate(g_elcdif_pix_clk, 25000000); + + ret = register_framebuffer(fbi); + if (ret) + goto err3; + + platform_set_drvdata(pdev, fbi); + + return 0; +err3: + mxc_elcdif_fb_unmap_video_memory(fbi); +err2: + iounmap(elcdif_base); +err1: + free_irq(data->dma_irq, data); +err0: + fb_dealloc_cmap(&fbi->cmap); + framebuffer_release(fbi); +out: + return ret; +} + +static int mxc_elcdif_fb_remove(struct platform_device *pdev) +{ + struct fb_info *fbi = platform_get_drvdata(pdev); + struct mxc_elcdif_fb_data *data = (struct mxc_elcdif_fb_data *)fbi->par; + + mxc_elcdif_fb_blank(FB_BLANK_POWERDOWN, fbi); + mxc_elcdif_stop(); + release_dotclk_panel(); + mxc_elcdif_dma_release(); + + if (g_elcdif_axi_clk_enable) { + clk_disable(g_elcdif_axi_clk); + g_elcdif_axi_clk_enable = false; + } + if (g_elcdif_pix_clk_enable) { + clk_disable(g_elcdif_pix_clk); + g_elcdif_pix_clk_enable = false; + } + clk_put(g_elcdif_axi_clk); + clk_put(g_elcdif_pix_clk); + + free_irq(data->dma_irq, data); + mxc_elcdif_fb_unmap_video_memory(fbi); + + if (&fbi->cmap) + fb_dealloc_cmap(&fbi->cmap); + + unregister_framebuffer(fbi); + framebuffer_release(fbi); + + platform_set_drvdata(pdev, NULL); + return 0; +} + +#ifdef CONFIG_PM +static int mxc_elcdif_fb_suspend(struct platform_device *pdev, + pm_message_t state) +{ + struct fb_info *fbi = platform_get_drvdata(pdev); + struct mxc_elcdif_fb_data *data = (struct mxc_elcdif_fb_data *)fbi->par; + int saved_blank; + + acquire_console_sem(); + fb_set_suspend(fbi, 1); + saved_blank = data->cur_blank; + mxc_elcdif_fb_blank(FB_BLANK_POWERDOWN, fbi); + data->next_blank = saved_blank; + if (!g_elcdif_pix_clk_enable) { + clk_enable(g_elcdif_pix_clk); + g_elcdif_pix_clk_enable = true; + } + mxc_elcdif_stop(); + mxc_elcdif_dma_release(); + if (g_elcdif_pix_clk_enable) { + clk_disable(g_elcdif_pix_clk); + g_elcdif_pix_clk_enable = false; + } + if (g_elcdif_axi_clk_enable) { + clk_disable(g_elcdif_axi_clk); + g_elcdif_axi_clk_enable = false; + } + release_console_sem(); + return 0; +} + +static int mxc_elcdif_fb_resume(struct platform_device *pdev) +{ + struct fb_info *fbi = platform_get_drvdata(pdev); + struct mxc_elcdif_fb_data *data = (struct mxc_elcdif_fb_data *)fbi->par; + + acquire_console_sem(); + mxc_elcdif_fb_blank(data->next_blank, fbi); + fb_set_suspend(fbi, 0); + release_console_sem(); + + return 0; +} +#else +#define mxc_elcdif_fb_suspend NULL +#define mxc_elcdif_fb_resume NULL +#endif + +static struct platform_driver mxc_elcdif_fb_driver = { + .probe = mxc_elcdif_fb_probe, + .remove = mxc_elcdif_fb_remove, + .suspend = mxc_elcdif_fb_suspend, + .resume = mxc_elcdif_fb_resume, + .driver = { + .name = "mxc_elcdif_fb", + .owner = THIS_MODULE, + }, +}; + +/* + * Parse user specified options (`video=trident:') + * example: + * video=trident:800x600,bpp=16,noaccel + */ +int mxc_elcdif_fb_setup(char *options) +{ + char *opt; + if (!options || !*options) + return 0; + while ((opt = strsep(&options, ",")) != NULL) { + if (!*opt) + continue; + + if (!strncmp(opt, "bpp=", 4)) + default_bpp = simple_strtoul(opt + 4, NULL, 0); + else + fb_mode = opt; + } + return 0; +} + +static int __init mxc_elcdif_fb_init(void) +{ + char *option = NULL; + + if (fb_get_options("mxc_elcdif_fb", &option)) + return -ENODEV; + mxc_elcdif_fb_setup(option); + + return platform_driver_register(&mxc_elcdif_fb_driver); +} + +static void __exit mxc_elcdif_fb_exit(void) +{ + platform_driver_unregister(&mxc_elcdif_fb_driver); +} + +module_init(mxc_elcdif_fb_init); +module_exit(mxc_elcdif_fb_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MXC ELCDIF Framebuffer Driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/video/mxc/mxc_epdc_fb.c b/drivers/video/mxc/mxc_epdc_fb.c new file mode 100644 index 000000000000..d3dee60e5907 --- /dev/null +++ b/drivers/video/mxc/mxc_epdc_fb.c @@ -0,0 +1,3058 @@ +/* + * Copyright (C) 2010 Freescale Semiconductor, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ +/* + * Based on STMP378X LCDIF + * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. + */ + +/*#define NO_POWERDOWN*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "epdc_regs.h" + +/* + * Enable this define to have a default panel + * loaded during driver initialization + */ +/*#define DEFAULT_PANEL_HW_INIT*/ + +#define NUM_SCREENS 2 +#define EPDC_NUM_LUTS 16 +#define EPDC_MAX_NUM_UPDATES 20 +#define INVALID_LUT -1 +#define TEMP_USE_DEFAULT 8 +#define INIT_UPDATE_MARKER 0x12345678 +#define PAN_UPDATE_MARKER 0x12345679 + +#define LUT_UPDATE_NONE 0 +#define LUT_UPDATE_NEW 1 +#define LUT_UPDATE_COLLISION 2 + +#define POWER_STATE_OFF 0 +#define POWER_STATE_ON 1 + +static unsigned long default_bpp = 16; + +struct mxc_epdc_platform_fb_entry { + char name[16]; + u16 x_res; + u16 y_res; + u16 bpp; + u32 cycle_time_ns; + struct list_head link; +}; + +struct mxc_epdc_platform_fb_data { + struct list_head list; + struct mxc_epdc_platform_fb_entry *cur; +}; + +struct update_marker_data { + u32 update_marker; + struct completion update_completion; + int lut_num; +}; + +/* This structure represents a list node containing both + * a memory region allocated as an output buffer for the PxP + * update processing task, and the update description (mode, region, etc.) */ +struct update_data_list { + struct list_head list; + struct mxcfb_update_data upd_data; /* Update parameters */ + dma_addr_t phys_addr; /* Pointer to phys address of processed Y buf */ + void *virt_addr; + u32 epdc_offs; /* Add to buffer pointer to resolve alignment */ + u32 size; + int lut_num; /* Assigned before update is processed into working buffer */ + int collision_mask; /* Set when update results in collision */ + /* Represents other LUTs that we collide with */ + struct update_marker_data *upd_marker_data; + bool is_collision; +}; + +struct mxc_epdc_fb_data { + struct fb_info info; + u32 pseudo_palette[16]; + struct list_head list; + struct mxc_epdc_platform_fb_entry *cur; + int blank; + ssize_t mem_size; + ssize_t map_size; + dma_addr_t phys_start; + u32 fb_offset; + int native_width; + int native_height; + int epdc_irq; + struct device *dev; + wait_queue_head_t vsync_wait_q; + u32 vsync_count; + void *par; + int power_state; + struct clk *epdc_clk_axi; + struct clk *epdc_clk_pix; + struct regulator *display_regulator; + struct regulator *vcom_regulator; + + /* FB elements related to EPDC updates */ + bool in_init; + bool hw_ready; + bool waiting_for_idle; + u32 auto_mode; + struct update_data_list *upd_buf_queue; + struct update_data_list *upd_buf_free_list; + struct update_data_list *upd_buf_collision_list; + struct update_data_list *cur_update; + spinlock_t queue_lock; + int trt_entries; + u8 *temp_range_bounds; + struct mxcfb_waveform_modes wv_modes; + u32 *waveform_buffer_virt; + u32 waveform_buffer_phys; + u32 waveform_buffer_size; + u32 *working_buffer_virt; + u32 working_buffer_phys; + u32 working_buffer_size; + struct update_marker_data update_marker_array[EPDC_MAX_NUM_UPDATES]; + u32 lut_update_type[EPDC_NUM_LUTS]; + struct completion updates_done; + struct work_struct epdc_done_work; + struct mutex power_mutex; + bool powering_down; + + /* FB elements related to PxP DMA */ + struct completion pxp_tx_cmpl; + struct pxp_channel *pxp_chan; + struct pxp_config_data pxp_conf; + struct dma_async_tx_descriptor *txd; + dma_cookie_t cookie; + struct scatterlist sg[2]; + struct mutex pxp_mutex; /* protects access to PxP */ +}; + +struct waveform_data_header { + unsigned int wi0; + unsigned int wi1; + unsigned int wi2; + unsigned int wi3; + unsigned int wi4; + unsigned int wi5; + unsigned int wi6; + unsigned int xwia:24; + unsigned int cs1:8; + unsigned int wmta:24; + unsigned int fvsn:8; + unsigned int luts:8; + unsigned int mc:8; + unsigned int trc:8; + unsigned int reserved0_0:8; + unsigned int eb:8; + unsigned int sb:8; + unsigned int reserved0_1:8; + unsigned int reserved0_2:8; + unsigned int reserved0_3:8; + unsigned int reserved0_4:8; + unsigned int reserved0_5:8; + unsigned int cs2:8; +}; + +struct mxcfb_waveform_data_file { + struct waveform_data_header wdh; + u32 *data; /* Temperature Range Table + Waveform Data */ +}; + +void __iomem *epdc_base; + +#define NUM_PANELS 1 + +static struct fb_videomode panel_modes[NUM_PANELS] = { + { + /* 800x600 @ 60 Hz , pixel clk @ 20MHz */ + "E-INK SVGA", 60, 800, 600, 50000, 10, 217, 4, 10, 20, 4, + 0, + FB_VMODE_NONINTERLACED, + 0,}, +}; + +/* + * This is a temporary placeholder + * Ultimately, this declaration will be off in a panel-specific file, + * and will include implementations for all of the panel functions + */ +static struct mxc_epdc_platform_fb_entry ed060sc4_fb_entry = { + .name = "ed060sc4", + .x_res = 800, + .y_res = 600, + .bpp = 16, + .cycle_time_ns = 200, +}; + +/* forward declaration */ +static int mxc_epdc_fb_blank(int blank, struct fb_info *info); +static int mxc_epdc_fb_init_hw(struct fb_info *info); +static int pxp_process_update(struct mxc_epdc_fb_data *fb_data, + struct mxcfb_rect *update_region); +static int pxp_complete_update(struct mxc_epdc_fb_data *fb_data, u32 *hist_stat); + +static void draw_mode0(struct mxc_epdc_fb_data *fb_data); + +#ifdef DEBUG +static void dump_pxp_config(struct mxc_epdc_fb_data *fb_data, + struct pxp_config_data *pxp_conf) +{ + dev_err(fb_data->dev, "S0 fmt 0x%x", + pxp_conf->s0_param.pixel_fmt); + dev_err(fb_data->dev, "S0 width 0x%x", + pxp_conf->s0_param.width); + dev_err(fb_data->dev, "S0 height 0x%x", + pxp_conf->s0_param.height); + dev_err(fb_data->dev, "S0 ckey 0x%x", + pxp_conf->s0_param.color_key); + dev_err(fb_data->dev, "S0 ckey en 0x%x", + pxp_conf->s0_param.color_key_enable); + + dev_err(fb_data->dev, "OL0 combine en 0x%x", + pxp_conf->ol_param[0].combine_enable); + dev_err(fb_data->dev, "OL0 fmt 0x%x", + pxp_conf->ol_param[0].pixel_fmt); + dev_err(fb_data->dev, "OL0 width 0x%x", + pxp_conf->ol_param[0].width); + dev_err(fb_data->dev, "OL0 height 0x%x", + pxp_conf->ol_param[0].height); + dev_err(fb_data->dev, "OL0 ckey 0x%x", + pxp_conf->ol_param[0].color_key); + dev_err(fb_data->dev, "OL0 ckey en 0x%x", + pxp_conf->ol_param[0].color_key_enable); + dev_err(fb_data->dev, "OL0 alpha 0x%x", + pxp_conf->ol_param[0].global_alpha); + dev_err(fb_data->dev, "OL0 alpha en 0x%x", + pxp_conf->ol_param[0].global_alpha_enable); + dev_err(fb_data->dev, "OL0 local alpha en 0x%x", + pxp_conf->ol_param[0].local_alpha_enable); + + dev_err(fb_data->dev, "Out fmt 0x%x", + pxp_conf->out_param.pixel_fmt); + dev_err(fb_data->dev, "Out width 0x%x", + pxp_conf->out_param.width); + dev_err(fb_data->dev, "Out height 0x%x", + pxp_conf->out_param.height); + + dev_err(fb_data->dev, + "drect left 0x%x right 0x%x width 0x%x height 0x%x", + pxp_conf->proc_data.drect.left, pxp_conf->proc_data.drect.top, + pxp_conf->proc_data.drect.width, + pxp_conf->proc_data.drect.height); + dev_err(fb_data->dev, + "srect left 0x%x right 0x%x width 0x%x height 0x%x", + pxp_conf->proc_data.srect.left, pxp_conf->proc_data.srect.top, + pxp_conf->proc_data.srect.width, + pxp_conf->proc_data.srect.height); + dev_err(fb_data->dev, "Scaling en 0x%x", pxp_conf->proc_data.scaling); + dev_err(fb_data->dev, "HFlip en 0x%x", pxp_conf->proc_data.hflip); + dev_err(fb_data->dev, "VFlip en 0x%x", pxp_conf->proc_data.vflip); + dev_err(fb_data->dev, "Rotation 0x%x", pxp_conf->proc_data.rotate); + dev_err(fb_data->dev, "BG Color 0x%x", pxp_conf->proc_data.bgcolor); +} + +static void dump_epdc_reg(void) +{ + printk(KERN_DEBUG "\n\n"); + printk(KERN_DEBUG "EPDC_CTRL 0x%x\n", __raw_readl(EPDC_CTRL)); + printk(KERN_DEBUG "EPDC_WVADDR 0x%x\n", __raw_readl(EPDC_WVADDR)); + printk(KERN_DEBUG "EPDC_WB_ADDR 0x%x\n", __raw_readl(EPDC_WB_ADDR)); + printk(KERN_DEBUG "EPDC_RES 0x%x\n", __raw_readl(EPDC_RES)); + printk(KERN_DEBUG "EPDC_FORMAT 0x%x\n", __raw_readl(EPDC_FORMAT)); + printk(KERN_DEBUG "EPDC_FIFOCTRL 0x%x\n", __raw_readl(EPDC_FIFOCTRL)); + printk(KERN_DEBUG "EPDC_UPD_ADDR 0x%x\n", __raw_readl(EPDC_UPD_ADDR)); + printk(KERN_DEBUG "EPDC_UPD_FIXED 0x%x\n", __raw_readl(EPDC_UPD_FIXED)); + printk(KERN_DEBUG "EPDC_UPD_CORD 0x%x\n", __raw_readl(EPDC_UPD_CORD)); + printk(KERN_DEBUG "EPDC_UPD_SIZE 0x%x\n", __raw_readl(EPDC_UPD_SIZE)); + printk(KERN_DEBUG "EPDC_UPD_CTRL 0x%x\n", __raw_readl(EPDC_UPD_CTRL)); + printk(KERN_DEBUG "EPDC_TEMP 0x%x\n", __raw_readl(EPDC_TEMP)); + printk(KERN_DEBUG "EPDC_TCE_CTRL 0x%x\n", __raw_readl(EPDC_TCE_CTRL)); + printk(KERN_DEBUG "EPDC_TCE_SDCFG 0x%x\n", __raw_readl(EPDC_TCE_SDCFG)); + printk(KERN_DEBUG "EPDC_TCE_GDCFG 0x%x\n", __raw_readl(EPDC_TCE_GDCFG)); + printk(KERN_DEBUG "EPDC_TCE_HSCAN1 0x%x\n", __raw_readl(EPDC_TCE_HSCAN1)); + printk(KERN_DEBUG "EPDC_TCE_HSCAN2 0x%x\n", __raw_readl(EPDC_TCE_HSCAN2)); + printk(KERN_DEBUG "EPDC_TCE_VSCAN 0x%x\n", __raw_readl(EPDC_TCE_VSCAN)); + printk(KERN_DEBUG "EPDC_TCE_OE 0x%x\n", __raw_readl(EPDC_TCE_OE)); + printk(KERN_DEBUG "EPDC_TCE_POLARITY 0x%x\n", __raw_readl(EPDC_TCE_POLARITY)); + printk(KERN_DEBUG "EPDC_TCE_TIMING1 0x%x\n", __raw_readl(EPDC_TCE_TIMING1)); + printk(KERN_DEBUG "EPDC_TCE_TIMING2 0x%x\n", __raw_readl(EPDC_TCE_TIMING2)); + printk(KERN_DEBUG "EPDC_TCE_TIMING3 0x%x\n", __raw_readl(EPDC_TCE_TIMING3)); + printk(KERN_DEBUG "EPDC_IRQ_MASK 0x%x\n", __raw_readl(EPDC_IRQ_MASK)); + printk(KERN_DEBUG "EPDC_IRQ 0x%x\n", __raw_readl(EPDC_IRQ)); + printk(KERN_DEBUG "EPDC_STATUS_LUTS 0x%x\n", __raw_readl(EPDC_STATUS_LUTS)); + printk(KERN_DEBUG "EPDC_STATUS_NEXTLUT 0x%x\n", __raw_readl(EPDC_STATUS_NEXTLUT)); + printk(KERN_DEBUG "EPDC_STATUS_COL 0x%x\n", __raw_readl(EPDC_STATUS_COL)); + printk(KERN_DEBUG "EPDC_STATUS 0x%x\n", __raw_readl(EPDC_STATUS)); + printk(KERN_DEBUG "EPDC_DEBUG 0x%x\n", __raw_readl(EPDC_DEBUG)); + printk(KERN_DEBUG "EPDC_DEBUG_LUT0 0x%x\n", __raw_readl(EPDC_DEBUG_LUT0)); + printk(KERN_DEBUG "EPDC_DEBUG_LUT1 0x%x\n", __raw_readl(EPDC_DEBUG_LUT1)); + printk(KERN_DEBUG "EPDC_DEBUG_LUT2 0x%x\n", __raw_readl(EPDC_DEBUG_LUT2)); + printk(KERN_DEBUG "EPDC_DEBUG_LUT3 0x%x\n", __raw_readl(EPDC_DEBUG_LUT3)); + printk(KERN_DEBUG "EPDC_DEBUG_LUT4 0x%x\n", __raw_readl(EPDC_DEBUG_LUT4)); + printk(KERN_DEBUG "EPDC_DEBUG_LUT5 0x%x\n", __raw_readl(EPDC_DEBUG_LUT5)); + printk(KERN_DEBUG "EPDC_DEBUG_LUT6 0x%x\n", __raw_readl(EPDC_DEBUG_LUT6)); + printk(KERN_DEBUG "EPDC_DEBUG_LUT7 0x%x\n", __raw_readl(EPDC_DEBUG_LUT7)); + printk(KERN_DEBUG "EPDC_DEBUG_LUT8 0x%x\n", __raw_readl(EPDC_DEBUG_LUT8)); + printk(KERN_DEBUG "EPDC_DEBUG_LUT9 0x%x\n", __raw_readl(EPDC_DEBUG_LUT9)); + printk(KERN_DEBUG "EPDC_DEBUG_LUT10 0x%x\n", __raw_readl(EPDC_DEBUG_LUT10)); + printk(KERN_DEBUG "EPDC_DEBUG_LUT11 0x%x\n", __raw_readl(EPDC_DEBUG_LUT11)); + printk(KERN_DEBUG "EPDC_DEBUG_LUT12 0x%x\n", __raw_readl(EPDC_DEBUG_LUT12)); + printk(KERN_DEBUG "EPDC_DEBUG_LUT13 0x%x\n", __raw_readl(EPDC_DEBUG_LUT13)); + printk(KERN_DEBUG "EPDC_DEBUG_LUT14 0x%x\n", __raw_readl(EPDC_DEBUG_LUT14)); + printk(KERN_DEBUG "EPDC_DEBUG_LUT15 0x%x\n", __raw_readl(EPDC_DEBUG_LUT15)); + printk(KERN_DEBUG "EPDC_GPIO 0x%x\n", __raw_readl(EPDC_GPIO)); + printk(KERN_DEBUG "EPDC_VERSION 0x%x\n", __raw_readl(EPDC_VERSION)); + printk(KERN_DEBUG "\n\n"); +} + +static void dump_update_data(struct device *dev, + struct update_data_list *upd_data_list) +{ + dev_err(dev, + "X = %d, Y = %d, Width = %d, Height = %d, WaveMode = %d, LUT = %d, Coll Mask = %d\n", + upd_data_list->upd_data.update_region.left, + upd_data_list->upd_data.update_region.top, + upd_data_list->upd_data.update_region.width, + upd_data_list->upd_data.update_region.height, + upd_data_list->upd_data.waveform_mode, upd_data_list->lut_num, + upd_data_list->collision_mask); +} + +static void dump_collision_list(struct mxc_epdc_fb_data *fb_data) +{ + struct update_data_list *plist; + + dev_err(fb_data->dev, "Collision List:\n"); + if (list_empty(&fb_data->upd_buf_collision_list->list)) + dev_err(fb_data->dev, "Empty"); + list_for_each_entry(plist, &fb_data->upd_buf_collision_list->list, list) { + dev_err(fb_data->dev, "Virt Addr = 0x%x, Phys Addr = 0x%x ", + (u32)plist->virt_addr, plist->phys_addr); + dump_update_data(fb_data->dev, plist); + } +} + +static void dump_free_list(struct mxc_epdc_fb_data *fb_data) +{ + struct update_data_list *plist; + + dev_err(fb_data->dev, "Free List:\n"); + if (list_empty(&fb_data->upd_buf_free_list->list)) + dev_err(fb_data->dev, "Empty"); + list_for_each_entry(plist, &fb_data->upd_buf_free_list->list, list) { + dev_err(fb_data->dev, "Virt Addr = 0x%x, Phys Addr = 0x%x ", + (u32)plist->virt_addr, plist->phys_addr); + dump_update_data(fb_data->dev, plist); + } +} + +static void dump_queue(struct mxc_epdc_fb_data *fb_data) +{ + struct update_data_list *plist; + + dev_err(fb_data->dev, "Queue:\n"); + if (list_empty(&fb_data->upd_buf_queue->list)) + dev_err(fb_data->dev, "Empty"); + list_for_each_entry(plist, &fb_data->upd_buf_queue->list, list) { + dev_err(fb_data->dev, "Virt Addr = 0x%x, Phys Addr = 0x%x ", + (u32)plist->virt_addr, plist->phys_addr); + dump_update_data(fb_data->dev, plist); + } +} + +static void dump_all_updates(struct mxc_epdc_fb_data *fb_data) +{ + dump_free_list(fb_data); + dump_queue(fb_data); + dump_collision_list(fb_data); + dev_err(fb_data->dev, "Current update being processed:\n"); + if (fb_data->cur_update == NULL) + dev_err(fb_data->dev, "No current update\n"); + else + dump_update_data(fb_data->dev, fb_data->cur_update); +} +#else +static inline void dump_pxp_config(struct mxc_epdc_fb_data *fb_data, + struct pxp_config_data *pxp_conf) {} +static inline void dump_epdc_reg(void) {} +static inline void dump_update_data(struct device *dev, + struct update_data_list *upd_data_list) {} +static inline void dump_collision_list(struct mxc_epdc_fb_data *fb_data) {} +static inline void dump_free_list(struct mxc_epdc_fb_data *fb_data) {} +static inline void dump_queue(struct mxc_epdc_fb_data *fb_data) {} +static inline void dump_all_updates(struct mxc_epdc_fb_data *fb_data) {} + +#endif + +static struct fb_var_screeninfo mxc_epdc_fb_default __devinitdata = { + .activate = FB_ACTIVATE_TEST, + .height = -1, + .width = -1, + .pixclock = 20000, + .left_margin = 8, + .right_margin = 142, + .upper_margin = 4, + .lower_margin = 10, + .hsync_len = 20, + .vsync_len = 4, + .vmode = FB_VMODE_NONINTERLACED, +}; + +static struct fb_fix_screeninfo mxc_epdc_fb_fix __devinitdata = { + .id = "mxc_epdc_fb", + .type = FB_TYPE_PACKED_PIXELS, + .visual = FB_VISUAL_TRUECOLOR, + .xpanstep = 0, + .ypanstep = 0, + .ywrapstep = 0, + .accel = FB_ACCEL_NONE, + .line_length = 800 * 2, +}; + +/******************************************************** + * Start Low-Level EPDC Functions + ********************************************************/ + +static inline void epdc_lut_complete_intr(u32 lut_num, bool enable) +{ + if (enable) + __raw_writel(1 << lut_num, EPDC_IRQ_MASK_SET); + else + __raw_writel(1 << lut_num, EPDC_IRQ_MASK_CLEAR); +} + +static inline void epdc_working_buf_intr(bool enable) +{ + if (enable) + __raw_writel(EPDC_IRQ_WB_CMPLT_IRQ, EPDC_IRQ_MASK_SET); + else + __raw_writel(EPDC_IRQ_WB_CMPLT_IRQ, EPDC_IRQ_MASK_CLEAR); +} + +static inline void epdc_clear_working_buf_irq(void) +{ + __raw_writel(EPDC_IRQ_WB_CMPLT_IRQ | EPDC_IRQ_LUT_COL_IRQ, + EPDC_IRQ_CLEAR); +} + +static inline void epdc_set_temp(u32 temp) +{ + __raw_writel(temp, EPDC_TEMP); +} + +static inline void epdc_set_screen_res(u32 width, u32 height) +{ + u32 val = (height << EPDC_RES_VERTICAL_OFFSET) | width; + __raw_writel(val, EPDC_RES); +} + +static inline void epdc_set_update_addr(u32 addr) +{ + __raw_writel(addr, EPDC_UPD_ADDR); +} + +static inline void epdc_set_update_coord(u32 x, u32 y) +{ + u32 val = (y << EPDC_UPD_CORD_YCORD_OFFSET) | x; + __raw_writel(val, EPDC_UPD_CORD); +} + +static inline void epdc_set_update_dimensions(u32 width, u32 height) +{ + u32 val = (height << EPDC_UPD_SIZE_HEIGHT_OFFSET) | width; + __raw_writel(val, EPDC_UPD_SIZE); +} + +static void epdc_submit_update(u32 lut_num, u32 waveform_mode, u32 update_mode, + bool use_test_mode, u32 np_val) +{ + u32 reg_val = 0; + + if (use_test_mode) { + reg_val |= + ((np_val << EPDC_UPD_FIXED_FIXNP_OFFSET) & + EPDC_UPD_FIXED_FIXNP_MASK) | EPDC_UPD_FIXED_FIXNP_EN; + + __raw_writel(reg_val, EPDC_UPD_FIXED); + + reg_val = EPDC_UPD_CTRL_USE_FIXED; + } else { + __raw_writel(reg_val, EPDC_UPD_FIXED); + } + + reg_val |= + ((lut_num << EPDC_UPD_CTRL_LUT_SEL_OFFSET) & + EPDC_UPD_CTRL_LUT_SEL_MASK) | + ((waveform_mode << EPDC_UPD_CTRL_WAVEFORM_MODE_OFFSET) & + EPDC_UPD_CTRL_WAVEFORM_MODE_MASK) | + update_mode; + + __raw_writel(reg_val, EPDC_UPD_CTRL); +} + +static inline bool epdc_is_lut_complete(u32 lut_num) +{ + u32 val = __raw_readl(EPDC_IRQ); + bool is_compl = val & (1 << lut_num) ? true : false; + + return is_compl; +} + +static inline void epdc_clear_lut_complete_irq(u32 lut_num) +{ + __raw_writel(1 << lut_num, EPDC_IRQ_CLEAR); +} + +static inline bool epdc_is_lut_active(u32 lut_num) +{ + u32 val = __raw_readl(EPDC_STATUS_LUTS); + bool is_active = val & (1 << lut_num) ? true : false; + + return is_active; +} + +static inline bool epdc_any_luts_active(void) +{ + bool any_active = __raw_readl(EPDC_STATUS_LUTS) ? true : false; + + return any_active; +} + +static inline bool epdc_any_luts_available(void) +{ + bool luts_available = + (__raw_readl(EPDC_STATUS_NEXTLUT) & + EPDC_STATUS_NEXTLUT_NEXT_LUT_VALID) ? true : false; + return luts_available; +} + +static inline int epdc_get_next_lut(void) +{ + u32 val = + __raw_readl(EPDC_STATUS_NEXTLUT) & + EPDC_STATUS_NEXTLUT_NEXT_LUT_MASK; + return val; +} + +static inline bool epdc_is_working_buffer_busy(void) +{ + u32 val = __raw_readl(EPDC_STATUS); + bool is_busy = (val & EPDC_STATUS_WB_BUSY) ? true : false; + + return is_busy; +} + +static inline bool epdc_is_working_buffer_complete(void) +{ + u32 val = __raw_readl(EPDC_IRQ); + bool is_compl = (val & EPDC_IRQ_WB_CMPLT_IRQ) ? true : false; + + return is_compl; +} + +static inline bool epdc_is_collision(void) +{ + u32 val = __raw_readl(EPDC_IRQ); + return (val & EPDC_IRQ_LUT_COL_IRQ) ? true : false; +} + +static inline int epdc_get_colliding_luts(void) +{ + u32 val = __raw_readl(EPDC_STATUS_COL); + return val; +} + +static void epdc_set_horizontal_timing(u32 horiz_start, u32 horiz_end, + u32 hsync_width, u32 hsync_line_length) +{ + u32 reg_val = + ((hsync_width << EPDC_TCE_HSCAN1_LINE_SYNC_WIDTH_OFFSET) & + EPDC_TCE_HSCAN1_LINE_SYNC_WIDTH_MASK) + | ((hsync_line_length << EPDC_TCE_HSCAN1_LINE_SYNC_OFFSET) & + EPDC_TCE_HSCAN1_LINE_SYNC_MASK); + __raw_writel(reg_val, EPDC_TCE_HSCAN1); + + reg_val = + ((horiz_start << EPDC_TCE_HSCAN2_LINE_BEGIN_OFFSET) & + EPDC_TCE_HSCAN2_LINE_BEGIN_MASK) + | ((horiz_end << EPDC_TCE_HSCAN2_LINE_END_OFFSET) & + EPDC_TCE_HSCAN2_LINE_END_MASK); + __raw_writel(reg_val, EPDC_TCE_HSCAN2); +} + +static void epdc_set_vertical_timing(u32 vert_start, u32 vert_end, + u32 vsync_width) +{ + u32 reg_val = + ((vert_start << EPDC_TCE_VSCAN_FRAME_BEGIN_OFFSET) & + EPDC_TCE_VSCAN_FRAME_BEGIN_MASK) + | ((vert_end << EPDC_TCE_VSCAN_FRAME_END_OFFSET) & + EPDC_TCE_VSCAN_FRAME_END_MASK) + | ((vsync_width << EPDC_TCE_VSCAN_FRAME_SYNC_OFFSET) & + EPDC_TCE_VSCAN_FRAME_SYNC_MASK); + __raw_writel(reg_val, EPDC_TCE_VSCAN); +} + +void epdc_init_settings(struct mxc_epdc_fb_data *fb_data) +{ + struct mxc_epdc_platform_fb_entry *pentry = fb_data->cur; + struct fb_var_screeninfo *screeninfo = &fb_data->info.var; + u32 reg_val; + + /* Reset */ + __raw_writel(EPDC_CTRL_SFTRST, EPDC_CTRL_SET); + while (!(__raw_readl(EPDC_CTRL) & EPDC_CTRL_CLKGATE)) + ; + __raw_writel(EPDC_CTRL_SFTRST, EPDC_CTRL_CLEAR); + + /* Enable clock gating (clear to enable) */ + __raw_writel(EPDC_CTRL_CLKGATE, EPDC_CTRL_CLEAR); + while (__raw_readl(EPDC_CTRL) & (EPDC_CTRL_SFTRST | EPDC_CTRL_CLKGATE)) + ; + + /* EPDC_CTRL */ + reg_val = __raw_readl(EPDC_CTRL); + reg_val &= ~EPDC_CTRL_UPD_DATA_SWIZZLE_MASK; + reg_val |= EPDC_CTRL_UPD_DATA_SWIZZLE_NO_SWAP; + reg_val &= ~EPDC_CTRL_LUT_DATA_SWIZZLE_MASK; + reg_val |= EPDC_CTRL_LUT_DATA_SWIZZLE_NO_SWAP; + __raw_writel(reg_val, EPDC_CTRL_SET); + + /* EPDC_FORMAT - 2bit TFT and 4bit Buf pixel format */ + reg_val = EPDC_FORMAT_TFT_PIXEL_FORMAT_2BIT + | EPDC_FORMAT_BUF_PIXEL_FORMAT_P4N + | ((0x0 << EPDC_FORMAT_DEFAULT_TFT_PIXEL_OFFSET) & + EPDC_FORMAT_DEFAULT_TFT_PIXEL_MASK); + __raw_writel(reg_val, EPDC_FORMAT); + + /* EPDC_FIFOCTRL (disabled) */ + reg_val = + ((100 << EPDC_FIFOCTRL_FIFO_INIT_LEVEL_OFFSET) & + EPDC_FIFOCTRL_FIFO_INIT_LEVEL_MASK) + | ((200 << EPDC_FIFOCTRL_FIFO_H_LEVEL_OFFSET) & + EPDC_FIFOCTRL_FIFO_H_LEVEL_MASK) + | ((100 << EPDC_FIFOCTRL_FIFO_L_LEVEL_OFFSET) & + EPDC_FIFOCTRL_FIFO_L_LEVEL_MASK); + __raw_writel(reg_val, EPDC_FIFOCTRL); + + /* EPDC_TEMP - 8 for room temperature */ + epdc_set_temp(8); + + /* EPDC_RES */ + epdc_set_screen_res(pentry->x_res, pentry->y_res); + + /* + * EPDC_TCE_CTRL + * VSCAN_HOLDOFF = 4 + * VCOM_MODE = MANUAL + * VCOM_VAL = 0 + * DDR_MODE = DISABLED + * LVDS_MODE_CE = DISABLED + * LVDS_MODE = DISABLED + * DUAL_SCAN = DISABLED + * SDDO_WIDTH = 8bit + * PIXELS_PER_SDCLK = 4 + */ + reg_val = + ((4 << EPDC_TCE_CTRL_VSCAN_HOLDOFF_OFFSET) & + EPDC_TCE_CTRL_VSCAN_HOLDOFF_MASK) + | EPDC_TCE_CTRL_PIXELS_PER_SDCLK_4; + __raw_writel(reg_val, EPDC_TCE_CTRL); + + /* EPDC_TCE_HSCAN */ + epdc_set_horizontal_timing(screeninfo->left_margin, + screeninfo->right_margin, + screeninfo->hsync_len, + screeninfo->hsync_len); + + /* EPDC_TCE_VSCAN */ + epdc_set_vertical_timing(screeninfo->upper_margin, + screeninfo->lower_margin, + screeninfo->vsync_len); + + /* EPDC_TCE_OE */ + reg_val = + ((10 << EPDC_TCE_OE_SDOED_WIDTH_OFFSET) & + EPDC_TCE_OE_SDOED_WIDTH_MASK) + | ((20 << EPDC_TCE_OE_SDOED_DLY_OFFSET) & + EPDC_TCE_OE_SDOED_DLY_MASK) + | ((10 << EPDC_TCE_OE_SDOEZ_WIDTH_OFFSET) & + EPDC_TCE_OE_SDOEZ_WIDTH_MASK) + | ((20 << EPDC_TCE_OE_SDOEZ_DLY_OFFSET) & + EPDC_TCE_OE_SDOEZ_DLY_MASK); + __raw_writel(reg_val, EPDC_TCE_OE); + + /* EPDC_TCE_TIMING1 */ + __raw_writel(0x0, EPDC_TCE_TIMING1); + + /* EPDC_TCE_TIMING2 */ + reg_val = + ((480 << EPDC_TCE_TIMING2_GDCLK_HP_OFFSET) & + EPDC_TCE_TIMING2_GDCLK_HP_MASK) + | ((20 << EPDC_TCE_TIMING2_GDSP_OFFSET_OFFSET) & + EPDC_TCE_TIMING2_GDSP_OFFSET_MASK); + __raw_writel(reg_val, EPDC_TCE_TIMING2); + + /* EPDC_TCE_TIMING3 */ + reg_val = + ((0 << EPDC_TCE_TIMING3_GDOE_OFFSET_OFFSET) & + EPDC_TCE_TIMING3_GDOE_OFFSET_MASK) + | ((1 << EPDC_TCE_TIMING3_GDCLK_OFFSET_OFFSET) & + EPDC_TCE_TIMING3_GDCLK_OFFSET_MASK); + __raw_writel(reg_val, EPDC_TCE_TIMING3); + + /* + * EPDC_TCE_SDCFG + * SDCLK_HOLD = 1 + * SDSHR = 1 + * NUM_CE = 1 + * SDDO_REFORMAT = FLIP_PIXELS + * SDDO_INVERT = DISABLED + * PIXELS_PER_CE = display horizontal resolution + */ + reg_val = EPDC_TCE_SDCFG_SDCLK_HOLD | EPDC_TCE_SDCFG_SDSHR + | ((1 << EPDC_TCE_SDCFG_NUM_CE_OFFSET) & EPDC_TCE_SDCFG_NUM_CE_MASK) + | EPDC_TCE_SDCFG_SDDO_REFORMAT_FLIP_PIXELS + | ((pentry->x_res << EPDC_TCE_SDCFG_PIXELS_PER_CE_OFFSET) & + EPDC_TCE_SDCFG_PIXELS_PER_CE_MASK); + __raw_writel(reg_val, EPDC_TCE_SDCFG); + + /* + * EPDC_TCE_GDCFG + * GDRL = 1 + * GDOE_MODE = 0; + * GDSP_MODE = 0; + */ + reg_val = EPDC_TCE_SDCFG_GDRL; + __raw_writel(reg_val, EPDC_TCE_GDCFG); + + /* + * EPDC_TCE_POLARITY + * SDCE_POL = ACTIVE LOW + * SDLE_POL = ACTIVE HIGH + * SDOE_POL = ACTIVE HIGH + * GDOE_POL = ACTIVE HIGH + * GDSP_POL = ACTIVE LOW + */ + reg_val = EPDC_TCE_POLARITY_SDLE_POL_ACTIVE_HIGH + | EPDC_TCE_POLARITY_SDOE_POL_ACTIVE_HIGH + | EPDC_TCE_POLARITY_GDOE_POL_ACTIVE_HIGH; + __raw_writel(reg_val, EPDC_TCE_POLARITY); + + /* EPDC_IRQ_MASK */ + __raw_writel(EPDC_IRQ_TCE_UNDERRUN_IRQ, EPDC_IRQ_MASK); + + /* + * EPDC_GPIO + * PWRCOM = ? + * PWRCTRL = ? + * BDR = ? + */ + reg_val = ((0 << EPDC_GPIO_PWRCTRL_OFFSET) & EPDC_GPIO_PWRCTRL_MASK) + | ((0 << EPDC_GPIO_BDR_OFFSET) & EPDC_GPIO_BDR_MASK); + __raw_writel(reg_val, EPDC_GPIO); +} + +static void epdc_powerup(struct mxc_epdc_fb_data *fb_data) +{ + mutex_lock(&fb_data->power_mutex); + + /* + * If power down request is pending, clear + * powering_down to cancel the request. + */ + if (fb_data->powering_down) + fb_data->powering_down = false; + + if (fb_data->power_state == POWER_STATE_ON) { + mutex_unlock(&fb_data->power_mutex); + return; + } + + dev_dbg(fb_data->dev, "EPDC Powerup\n"); + + /* Enable clocks to EPDC */ + clk_enable(fb_data->epdc_clk_axi); + clk_enable(fb_data->epdc_clk_pix); + + __raw_writel(EPDC_CTRL_CLKGATE, EPDC_CTRL_CLEAR); + + /* Enable power to the EPD panel */ + regulator_enable(fb_data->display_regulator); + regulator_enable(fb_data->vcom_regulator); + + fb_data->power_state = POWER_STATE_ON; + + mutex_unlock(&fb_data->power_mutex); +} + +static void epdc_powerdown(struct mxc_epdc_fb_data *fb_data) +{ + mutex_lock(&fb_data->power_mutex); + + /* If powering_down has been cleared, a powerup + * request is pre-empting this powerdown request. + */ + if (!fb_data->powering_down + || (fb_data->power_state == POWER_STATE_OFF)) { + mutex_unlock(&fb_data->power_mutex); + return; + } + + dev_dbg(fb_data->dev, "EPDC Powerdown\n"); + + /* Disable power to the EPD panel */ + regulator_disable(fb_data->vcom_regulator); + regulator_disable(fb_data->display_regulator); + + /* Disable clocks to EPDC */ + __raw_writel(EPDC_CTRL_CLKGATE, EPDC_CTRL_SET); + clk_disable(fb_data->epdc_clk_pix); + clk_disable(fb_data->epdc_clk_axi); + + fb_data->power_state = POWER_STATE_OFF; + fb_data->powering_down = false; + + mutex_unlock(&fb_data->power_mutex); +} + +static void epdc_init_sequence(struct mxc_epdc_fb_data *fb_data) +{ + /* Initialize EPDC, passing pointer to EPDC registers */ + epdc_init_settings(fb_data); + __raw_writel(fb_data->waveform_buffer_phys, EPDC_WVADDR); + __raw_writel(fb_data->working_buffer_phys, EPDC_WB_ADDR); + epdc_powerup(fb_data); + draw_mode0(fb_data); + epdc_powerdown(fb_data); +} + +static int mxc_epdc_fb_mmap(struct fb_info *info, struct vm_area_struct *vma) +{ + u32 len; + unsigned long offset = vma->vm_pgoff << PAGE_SHIFT; + + if (offset < info->fix.smem_len) { + /* mapping framebuffer memory */ + len = info->fix.smem_len - offset; + vma->vm_pgoff = (info->fix.smem_start + offset) >> PAGE_SHIFT; + } else + return -EINVAL; + + len = PAGE_ALIGN(len); + if (vma->vm_end - vma->vm_start > len) + return -EINVAL; + + /* make buffers bufferable */ + vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot); + + vma->vm_flags |= VM_IO | VM_RESERVED; + + if (remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff, + vma->vm_end - vma->vm_start, vma->vm_page_prot)) { + dev_dbg(info->device, "mmap remap_pfn_range failed\n"); + return -ENOBUFS; + } + + return 0; +} + +static int mxc_epdc_fb_setcolreg(u_int regno, u_int red, u_int green, + u_int blue, u_int transp, struct fb_info *info) +{ + if (regno >= 256) /* no. of hw registers */ + return 1; + /* + * Program hardware... do anything you want with transp + */ + + /* grayscale works only partially under directcolor */ + if (info->var.grayscale) { + /* grayscale = 0.30*R + 0.59*G + 0.11*B */ + red = green = blue = (red * 77 + green * 151 + blue * 28) >> 8; + } + +#define CNVT_TOHW(val, width) ((((val)<<(width))+0x7FFF-(val))>>16) + switch (info->fix.visual) { + case FB_VISUAL_TRUECOLOR: + case FB_VISUAL_PSEUDOCOLOR: + red = CNVT_TOHW(red, info->var.red.length); + green = CNVT_TOHW(green, info->var.green.length); + blue = CNVT_TOHW(blue, info->var.blue.length); + transp = CNVT_TOHW(transp, info->var.transp.length); + break; + case FB_VISUAL_DIRECTCOLOR: + red = CNVT_TOHW(red, 8); /* expect 8 bit DAC */ + green = CNVT_TOHW(green, 8); + blue = CNVT_TOHW(blue, 8); + /* hey, there is bug in transp handling... */ + transp = CNVT_TOHW(transp, 8); + break; + } +#undef CNVT_TOHW + /* Truecolor has hardware independent palette */ + if (info->fix.visual == FB_VISUAL_TRUECOLOR) { + + if (regno >= 16) + return 1; + + ((u32 *) (info->pseudo_palette))[regno] = + (red << info->var.red.offset) | + (green << info->var.green.offset) | + (blue << info->var.blue.offset) | + (transp << info->var.transp.offset); + } + return 0; +} + +static void adjust_coordinates(struct mxc_epdc_fb_data *fb_data, struct mxcfb_rect *update_region) +{ + struct fb_var_screeninfo *screeninfo = &fb_data->info.var; + u32 rotation = fb_data->info.var.rotate; + u32 temp; + + switch (rotation) { + case FB_ROTATE_UR: + /* No adjustment needed */ + break; + case FB_ROTATE_CW: + temp = update_region->top; + update_region->top = update_region->left; + update_region->left = screeninfo->yres - (temp + update_region->height); + temp = update_region->width; + update_region->width = update_region->height; + update_region->height = temp; + break; + case FB_ROTATE_UD: + update_region->top = screeninfo->yres - (update_region->top + update_region->height); + update_region->left = screeninfo->xres - (update_region->left + update_region->width); + break; + case FB_ROTATE_CCW: + temp = update_region->left; + update_region->left = update_region->top; + update_region->top = screeninfo->xres - (temp + update_region->width); + temp = update_region->width; + update_region->width = update_region->height; + update_region->height = temp; + break; + } +} + +/* + * Set fixed framebuffer parameters based on variable settings. + * + * @param info framebuffer information pointer + */ +static int mxc_epdc_fb_set_fix(struct fb_info *info) +{ + struct fb_fix_screeninfo *fix = &info->fix; + struct fb_var_screeninfo *var = &info->var; + + fix->line_length = var->xres_virtual * var->bits_per_pixel / 8; + + fix->type = FB_TYPE_PACKED_PIXELS; + fix->accel = FB_ACCEL_NONE; + fix->visual = FB_VISUAL_TRUECOLOR; + fix->xpanstep = 1; + fix->ypanstep = 1; + + return 0; +} + +/* + * This routine actually sets the video mode. It's in here where we + * the hardware state info->par and fix which can be affected by the + * change in par. For this driver it doesn't do much. + * + */ +static int mxc_epdc_fb_set_par(struct fb_info *info) +{ + struct mxc_epdc_fb_data *fb_data = (struct mxc_epdc_fb_data *)info; + struct pxp_config_data *pxp_conf = &fb_data->pxp_conf; + struct pxp_proc_data *proc_data = &pxp_conf->proc_data; + struct fb_var_screeninfo *screeninfo = &fb_data->info.var; + int i; + int ret; + + /* + * Update PxP config data (used to process FB regions for updates) + * based on FB info and processing tasks required + */ + + /* Initialize non-channel-specific PxP parameters */ + proc_data->drect.left = proc_data->srect.left = 0; + proc_data->drect.top = proc_data->srect.top = 0; + proc_data->drect.width = proc_data->srect.width = screeninfo->xres; + proc_data->drect.height = proc_data->srect.height = screeninfo->yres; + proc_data->scaling = 0; + proc_data->hflip = 0; + proc_data->vflip = 0; + proc_data->rotate = screeninfo->rotate; + proc_data->bgcolor = 0; + proc_data->overlay_state = 0; + proc_data->lut_transform = PXP_LUT_NONE; + + /* + * configure S0 channel parameters + * Parameters should match FB format/width/height + */ + if (screeninfo->grayscale) { + pxp_conf->s0_param.pixel_fmt = PXP_PIX_FMT_GREY; + if (screeninfo->grayscale == GRAYSCALE_8BIT_INVERTED) + proc_data->lut_transform = PXP_LUT_INVERT; + } else { + switch (screeninfo->bits_per_pixel) { + case 16: + pxp_conf->s0_param.pixel_fmt = PXP_PIX_FMT_RGB565; + break; + case 24: + pxp_conf->s0_param.pixel_fmt = PXP_PIX_FMT_RGB24; + break; + case 32: + pxp_conf->s0_param.pixel_fmt = PXP_PIX_FMT_RGB32; + break; + default: + pxp_conf->s0_param.pixel_fmt = PXP_PIX_FMT_RGB565; + break; + } + } + pxp_conf->s0_param.width = screeninfo->xres; + pxp_conf->s0_param.height = screeninfo->yres; + pxp_conf->s0_param.color_key = -1; + pxp_conf->s0_param.color_key_enable = false; + + /* + * Initialize Output channel parameters + * Output is Y-only greyscale + * Output width/height will vary based on update region size + */ + pxp_conf->out_param.width = screeninfo->xres; + pxp_conf->out_param.height = screeninfo->yres; + pxp_conf->out_param.pixel_fmt = PXP_PIX_FMT_GREY; + + /* + * If HW not yet initialized, check to see if we are being sent + * an initialization request. + */ + if (!fb_data->hw_ready) { + for (i = 0; i < NUM_PANELS; i++) { + /* Check resolution for a match with supported panel types */ + if ((screeninfo->xres != panel_modes[i].xres) || + (screeninfo->yres != panel_modes[i].yres)) + continue; + + /* Found a match - Grab timing params */ + screeninfo->left_margin = panel_modes[i].left_margin; + screeninfo->right_margin = panel_modes[i].right_margin; + screeninfo->upper_margin = panel_modes[i].upper_margin; + screeninfo->lower_margin = panel_modes[i].lower_margin; + screeninfo->hsync_len = panel_modes[i].hsync_len; + screeninfo->vsync_len = panel_modes[i].vsync_len; + + /* Initialize EPDC settings and init panel */ + ret = + mxc_epdc_fb_init_hw((struct fb_info *)fb_data); + if (ret) { + dev_err(fb_data->dev, "Failed to load panel waveform data\n"); + return ret; + } + + break; + } + } + + mxc_epdc_fb_set_fix(info); + + return 0; +} + +static int mxc_epdc_fb_check_var(struct fb_var_screeninfo *var, + struct fb_info *info) +{ + struct mxc_epdc_fb_data *fb_data = (struct mxc_epdc_fb_data *)info; + + if (!var->xres) + var->xres = 1; + if (!var->yres) + var->yres = 1; + + if (var->xres_virtual < var->xoffset + var->xres) + var->xres_virtual = var->xoffset + var->xres; + if (var->yres_virtual < var->yoffset + var->yres) + var->yres_virtual = var->yoffset + var->yres; + + if ((var->bits_per_pixel != 32) && (var->bits_per_pixel != 24) && + (var->bits_per_pixel != 16) && (var->bits_per_pixel != 8)) + var->bits_per_pixel = default_bpp; + + switch (var->bits_per_pixel) { + case 8: + if (var->grayscale != 0) { + /* + * For 8-bit grayscale, R, G, and B offset are equal. + * + */ + var->red.length = 8; + var->red.offset = 0; + var->red.msb_right = 0; + + var->green.length = 8; + var->green.offset = 0; + var->green.msb_right = 0; + + var->blue.length = 8; + var->blue.offset = 0; + var->blue.msb_right = 0; + + var->transp.length = 0; + var->transp.offset = 0; + var->transp.msb_right = 0; + } else { + var->red.length = 3; + var->red.offset = 5; + var->red.msb_right = 0; + + var->green.length = 3; + var->green.offset = 2; + var->green.msb_right = 0; + + var->blue.length = 2; + var->blue.offset = 0; + var->blue.msb_right = 0; + + var->transp.length = 0; + var->transp.offset = 0; + var->transp.msb_right = 0; + } + break; + case 16: + var->red.length = 5; + var->red.offset = 11; + var->red.msb_right = 0; + + var->green.length = 6; + var->green.offset = 5; + var->green.msb_right = 0; + + var->blue.length = 5; + var->blue.offset = 0; + var->blue.msb_right = 0; + + var->transp.length = 0; + var->transp.offset = 0; + var->transp.msb_right = 0; + break; + case 24: + var->red.length = 8; + var->red.offset = 16; + var->red.msb_right = 0; + + var->green.length = 8; + var->green.offset = 8; + var->green.msb_right = 0; + + var->blue.length = 8; + var->blue.offset = 0; + var->blue.msb_right = 0; + + var->transp.length = 0; + var->transp.offset = 0; + var->transp.msb_right = 0; + break; + case 32: + var->red.length = 8; + var->red.offset = 16; + var->red.msb_right = 0; + + var->green.length = 8; + var->green.offset = 8; + var->green.msb_right = 0; + + var->blue.length = 8; + var->blue.offset = 0; + var->blue.msb_right = 0; + + var->transp.length = 8; + var->transp.offset = 24; + var->transp.msb_right = 0; + break; + } + + switch (var->rotate) { + case FB_ROTATE_UR: + case FB_ROTATE_UD: + var->xres = var->xres_virtual = fb_data->native_width; + var->yres = fb_data->native_height; + var->yres_virtual = var->yres * 2; + break; + case FB_ROTATE_CW: + case FB_ROTATE_CCW: + var->xres = var->xres_virtual = fb_data->native_height; + var->yres = fb_data->native_width; + var->yres_virtual = var->yres * 2; + break; + default: + /* Invalid rotation value */ + var->rotate = 0; + dev_dbg(fb_data->dev, "Invalid rotation request\n"); + return -EINVAL; + } + + var->height = -1; + var->width = -1; + + return 0; +} + +static int mxc_epdc_fb_get_temp_index(struct mxc_epdc_fb_data *fb_data, int temp) +{ + int i; + int index = -1; + + if (fb_data->trt_entries == 0) { + dev_err(fb_data->dev, + "No TRT exists...using default temp index\n"); + return TEMP_USE_DEFAULT; + } + + /* Search temperature ranges for a match */ + for (i = 0; i < fb_data->trt_entries - 1; i++) { + if ((temp >= fb_data->temp_range_bounds[i]) + && (temp < fb_data->temp_range_bounds[i+1])) { + index = i; + break; + } + } + + if (index < 0) { + dev_err(fb_data->dev, + "No TRT index match...using default temp index\n"); + return TEMP_USE_DEFAULT; + } + + dev_dbg(fb_data->dev, "Using temperature index %d\n", index); + + return index; +} + +static int mxc_epdc_fb_set_temperature(int temperature, struct fb_info *info) +{ + struct mxc_epdc_fb_data *fb_data = (struct mxc_epdc_fb_data *)info; + int temp_index; + + if (temperature != TEMP_USE_AMBIENT) { + temp_index = mxc_epdc_fb_get_temp_index(fb_data, temperature); + epdc_set_temp(temp_index); + } + + return 0; +} + +static int mxc_epdc_fb_set_auto_update(u32 auto_mode, struct fb_info *info) +{ + struct mxc_epdc_fb_data *fb_data = (struct mxc_epdc_fb_data *)info; + + dev_dbg(fb_data->dev, "Setting auto update mode to %d\n", auto_mode); + + if ((auto_mode == AUTO_UPDATE_MODE_AUTOMATIC_MODE) + || (auto_mode == AUTO_UPDATE_MODE_REGION_MODE)) + fb_data->auto_mode = auto_mode; + else { + dev_err(fb_data->dev, "Invalid auto update mode parameter.\n"); + return -EINVAL; + } + + return 0; +} + +static int mxc_epdc_fb_send_update(struct mxcfb_update_data *upd_data, + struct fb_info *info) +{ + struct mxc_epdc_fb_data *fb_data = (struct mxc_epdc_fb_data *)info; + struct update_data_list *upd_data_list = NULL; + struct mxcfb_rect *screen_upd_region; /* Region on screen to update */ + struct mxcfb_rect *src_upd_region; /* Region of src buffer for update */ + struct mxcfb_rect pxp_upd_region; + u32 src_width; + unsigned long flags; + int i; + u32 offset_from_8, bytes_per_pixel; + u32 post_rotation_xcoord, post_rotation_ycoord, width_pxp_blocks; + u32 pxp_input_offs, pxp_output_offs, pxp_output_shift; + int adj_left, adj_top; + u32 hist_stat = 0; + int temp_index; + bool wait_for_power = false; + + int ret; + + /* Has EPDC HW been initialized? */ + if (!fb_data->hw_ready) { + dev_err(fb_data->dev, "Display HW not properly initialized. Aborting update.\n"); + return -EPERM; + } + + /* Check validity of update params */ + if ((upd_data->update_mode != UPDATE_MODE_PARTIAL) && + (upd_data->update_mode != UPDATE_MODE_FULL)) { + dev_err(fb_data->dev, + "Update mode 0x%x is invalid. Aborting update.\n", + upd_data->update_mode); + return -EINVAL; + } + if ((upd_data->waveform_mode > 255) && + (upd_data->waveform_mode != WAVEFORM_MODE_AUTO)) { + dev_err(fb_data->dev, + "Update waveform mode 0x%x is invalid. Aborting update.\n", + upd_data->waveform_mode); + return -EINVAL; + } + if ((upd_data->update_region.left + upd_data->update_region.width > fb_data->info.var.xres) || + (upd_data->update_region.top + upd_data->update_region.height > fb_data->info.var.yres)) { + dev_err(fb_data->dev, + "Update region is outside bounds of framebuffer. Aborting update.\n"); + return -EINVAL; + } + if (upd_data->use_alt_buffer && + ((upd_data->update_region.width != upd_data->alt_buffer_data.alt_update_region.width) || + (upd_data->update_region.height != upd_data->alt_buffer_data.alt_update_region.height))) { + dev_err(fb_data->dev, + "Alternate update region dimensions must match screen update region dimensions.\n"); + return -EINVAL; + } + + spin_lock_irqsave(&fb_data->queue_lock, flags); + + /* + * If we are waiting to go into suspend, or the FB is blanked, + * we do not accept new updates + */ + if ((fb_data->waiting_for_idle) || (fb_data->blank != FB_BLANK_UNBLANK)) { + dev_dbg(fb_data->dev, "EPDC not active. Update request abort.\n"); + spin_unlock_irqrestore(&fb_data->queue_lock, flags); + return -EPERM; + } + + /* + * Get available intermediate (PxP output) buffer to hold + * processed update region + */ + if (list_empty(&fb_data->upd_buf_free_list->list)) { + dev_err(fb_data->dev, "No free intermediate buffers available.\n"); + spin_unlock_irqrestore(&fb_data->queue_lock, flags); + return -ENOMEM; + } + + /* Grab first available buffer and delete it from the free list */ + upd_data_list = + list_entry(fb_data->upd_buf_free_list->list.next, + struct update_data_list, list); + + list_del_init(&upd_data_list->list); + + /* + * We can release lock on queues now + * that we have grabbed the one we need + */ + spin_unlock_irqrestore(&fb_data->queue_lock, flags); + + /* copy update parameters to the current update data object */ + memcpy(&upd_data_list->upd_data, upd_data, + sizeof(struct mxcfb_update_data)); + memcpy(&upd_data_list->upd_data.update_region, &upd_data->update_region, + sizeof(struct mxcfb_rect)); + + /* + * Hold on to original screen update region, which we + * will ultimately use when telling EPDC where to update on panel + */ + screen_upd_region = &upd_data_list->upd_data.update_region; + + /* + * Gotta do a whole bunch of buffer ptr manipulation to + * work around HW restrictions for PxP & EPDC + */ + + /* + * Are we using FB or an alternate (overlay) + * buffer for source of update? + */ + if (upd_data->use_alt_buffer) { + src_width = upd_data->alt_buffer_data.width; + src_upd_region = &upd_data->alt_buffer_data.alt_update_region; + } else { + src_width = fb_data->info.var.xres; + src_upd_region = screen_upd_region; + } + + /* + * Compute buffer offset to account for + * PxP limitation (must read 8x8 pixel blocks) + */ + offset_from_8 = src_upd_region->left & 0x7; + bytes_per_pixel = fb_data->info.var.bits_per_pixel/8; + if ((offset_from_8 * fb_data->info.var.bits_per_pixel/8 % 4) != 0) { + /* Leave a gap between PxP input addr and update region pixels */ + pxp_input_offs = + (src_upd_region->top * src_width + src_upd_region->left) + * bytes_per_pixel & 0xFFFFFFFC; + /* Update region should change to reflect relative position to input ptr */ + pxp_upd_region.top = 0; + pxp_upd_region.left = (offset_from_8 & 0x3) % bytes_per_pixel; + } else { + pxp_input_offs = + (src_upd_region->top * src_width + src_upd_region->left) + * bytes_per_pixel; + /* Update region should change to reflect relative position to input ptr */ + pxp_upd_region.top = 0; + pxp_upd_region.left = 0; + } + + /* Update region to meet 8x8 pixel requirement */ + adj_left = pxp_upd_region.left & 0x7; + adj_top = pxp_upd_region.top & 0x7; + pxp_upd_region.width = ALIGN(src_upd_region->width + adj_left, 8); + pxp_upd_region.height = ALIGN(src_upd_region->height + adj_top, 8); + pxp_upd_region.top &= ~0x7; + pxp_upd_region.left &= ~0x7; + + switch (fb_data->info.var.rotate) { + case FB_ROTATE_UR: + default: + post_rotation_xcoord = pxp_upd_region.left; + post_rotation_ycoord = pxp_upd_region.top; + width_pxp_blocks = pxp_upd_region.width; + break; + case FB_ROTATE_CW: + width_pxp_blocks = pxp_upd_region.height; + post_rotation_xcoord = width_pxp_blocks - src_upd_region->height; + post_rotation_ycoord = pxp_upd_region.left; + break; + case FB_ROTATE_UD: + width_pxp_blocks = pxp_upd_region.width; + post_rotation_xcoord = width_pxp_blocks - src_upd_region->width - pxp_upd_region.left; + post_rotation_ycoord = pxp_upd_region.height - src_upd_region->height - pxp_upd_region.top; + break; + case FB_ROTATE_CCW: + width_pxp_blocks = pxp_upd_region.height; + post_rotation_xcoord = pxp_upd_region.top; + post_rotation_ycoord = pxp_upd_region.width - src_upd_region->width - pxp_upd_region.left; + break; + } + + pxp_output_offs = post_rotation_ycoord * width_pxp_blocks + + post_rotation_xcoord; + + pxp_output_shift = ALIGN(pxp_output_offs, 8) - pxp_output_offs; + + upd_data_list->epdc_offs = pxp_output_offs + pxp_output_shift; + + /* Source address either comes from alternate buffer + provided in update data, or from the framebuffer. */ + if (upd_data->use_alt_buffer) + sg_dma_address(&fb_data->sg[0]) = + upd_data->alt_buffer_data.phys_addr + pxp_input_offs; + else { + sg_dma_address(&fb_data->sg[0]) = + fb_data->info.fix.smem_start + fb_data->fb_offset + + pxp_input_offs; + sg_set_page(&fb_data->sg[0], + virt_to_page(fb_data->info.screen_base), + fb_data->info.fix.smem_len, + offset_in_page(fb_data->info.screen_base)); + } + + /* Update sg[1] to point to output of PxP proc task */ + sg_dma_address(&fb_data->sg[1]) = upd_data_list->phys_addr + pxp_output_offs; + sg_set_page(&fb_data->sg[1], virt_to_page(upd_data_list->virt_addr), + upd_data_list->size, + offset_in_page(upd_data_list->virt_addr)); + + mutex_lock(&fb_data->pxp_mutex); + + /* This is a blocking call, so upon return PxP tx should be done */ + ret = pxp_process_update(fb_data, &pxp_upd_region); + if (ret) { + dev_err(fb_data->dev, "Unable to submit PxP update task.\n"); + mutex_unlock(&fb_data->pxp_mutex); + return ret; + } + + mutex_unlock(&fb_data->pxp_mutex); + + /* If needed, enable EPDC HW while ePxP is processing */ + if ((fb_data->power_state == POWER_STATE_OFF) + || fb_data->powering_down) { + wait_for_power = true; + epdc_powerup(fb_data); + } + + mutex_lock(&fb_data->pxp_mutex); + + /* This is a blocking call, so upon return PxP tx should be done */ + ret = pxp_complete_update(fb_data, &hist_stat); + if (ret) { + dev_err(fb_data->dev, "Unable to complete PxP update task.\n"); + mutex_unlock(&fb_data->pxp_mutex); + return ret; + } + + mutex_unlock(&fb_data->pxp_mutex); + + /* Grab lock for queue manipulation and update submission */ + spin_lock_irqsave(&fb_data->queue_lock, flags); + + /* Update coordinates for rotation */ + adjust_coordinates(fb_data, &upd_data_list->upd_data.update_region); + + /* Update waveform mode from PxP histogram results */ + if (upd_data_list->upd_data.waveform_mode == WAVEFORM_MODE_AUTO) { + if (hist_stat & 0x1) + upd_data_list->upd_data.waveform_mode = + fb_data->wv_modes.mode_du; + else if (hist_stat & 0x2) + upd_data_list->upd_data.waveform_mode = + fb_data->wv_modes.mode_gc4; + else if (hist_stat & 0x4) + upd_data_list->upd_data.waveform_mode = + fb_data->wv_modes.mode_gc8; + else if (hist_stat & 0x8) + upd_data_list->upd_data.waveform_mode = + fb_data->wv_modes.mode_gc16; + else + upd_data_list->upd_data.waveform_mode = + fb_data->wv_modes.mode_gc32; + + /* Pass selected waveform mode back to user */ + upd_data->waveform_mode = upd_data_list->upd_data.waveform_mode; + + dev_dbg(fb_data->dev, "hist_stat = 0x%x, new waveform = 0x%x\n", + hist_stat, upd_data_list->upd_data.waveform_mode); + } + + /* If marker specified, associate it with a completion */ + if (upd_data->update_marker != 0) { + /* Find available update marker and set it up */ + for (i = 0; i < EPDC_MAX_NUM_UPDATES; i++) { + /* Marker value set to 0 signifies it is not currently in use */ + if (fb_data->update_marker_array[i].update_marker == 0) { + fb_data->update_marker_array[i].update_marker = upd_data->update_marker; + init_completion(&fb_data->update_marker_array[i].update_completion); + upd_data_list->upd_marker_data = &fb_data->update_marker_array[i]; + break; + } + } + } else { + if (upd_data_list->upd_marker_data) + upd_data_list->upd_marker_data->update_marker = 0; + } + + upd_data_list->is_collision = false; + + /* + * Is the working buffer idle? + * If either the working buffer is busy, or there are no LUTs available, + * then we return and let the ISR handle the update later + */ + if ((fb_data->cur_update != NULL) || !epdc_any_luts_available()) { + /* Add processed Y buffer to update list */ + list_add_tail(&upd_data_list->list, + &fb_data->upd_buf_queue->list); + + /* Return and allow the udpate to be submitted by the ISR. */ + spin_unlock_irqrestore(&fb_data->queue_lock, flags); + return 0; + } + + /* Save current update */ + fb_data->cur_update = upd_data_list; + + /* LUTs are available, so we get one here */ + upd_data_list->lut_num = epdc_get_next_lut(); + + /* Associate LUT with update marker */ + if (upd_data_list->upd_marker_data) + if (upd_data_list->upd_marker_data->update_marker != 0) + upd_data_list->upd_marker_data->lut_num = upd_data_list->lut_num; + + /* Mark LUT as containing new update */ + fb_data->lut_update_type[upd_data_list->lut_num] = LUT_UPDATE_NEW; + + /* Clear status and Enable LUT complete and WB complete IRQs */ + epdc_working_buf_intr(true); + epdc_lut_complete_intr(fb_data->cur_update->lut_num, true); + + /* Program EPDC update to process buffer */ + epdc_set_update_addr(upd_data_list->phys_addr + upd_data_list->epdc_offs); + epdc_set_update_coord(screen_upd_region->left, screen_upd_region->top); + epdc_set_update_dimensions(screen_upd_region->width, screen_upd_region->height); + if (upd_data_list->upd_data.temp != TEMP_USE_AMBIENT) { + temp_index = mxc_epdc_fb_get_temp_index(fb_data, upd_data_list->upd_data.temp); + epdc_set_temp(temp_index); + } + epdc_submit_update(upd_data_list->lut_num, + upd_data_list->upd_data.waveform_mode, + upd_data_list->upd_data.update_mode, false, 0); + + spin_unlock_irqrestore(&fb_data->queue_lock, flags); + + return 0; +} + +static int mxc_epdc_fb_wait_update_complete(u32 update_marker, + struct fb_info *info) +{ + struct mxc_epdc_fb_data *fb_data = (struct mxc_epdc_fb_data *)info; + int ret; + int i; + + /* 0 is an invalid update_marker value */ + if (update_marker == 0) + return -EINVAL; + + /* Wait for completion associated with update_marker requested */ + for (i = 0; i < EPDC_MAX_NUM_UPDATES; i++) { + if (fb_data->update_marker_array[i].update_marker == update_marker) { + dev_dbg(fb_data->dev, "Waiting for marker %d\n", update_marker); + ret = wait_for_completion_timeout(&fb_data->update_marker_array[i].update_completion, msecs_to_jiffies(5000)); + if (!ret) + dev_err(fb_data->dev, "Timed out waiting for update completion\n"); + + dev_dbg(fb_data->dev, "marker %d signalled!\n", update_marker); + + /* Reset marker so it can be reused */ + fb_data->update_marker_array[i].update_marker = 0; + + break; + } + } + + return 0; +} + +static int mxc_epdc_fb_ioctl(struct fb_info *info, unsigned int cmd, + unsigned long arg) +{ + void __user *argp = (void __user *)arg; + struct mxc_epdc_fb_data *fb_data = (struct mxc_epdc_fb_data *)info; + struct mxcfb_waveform_modes modes; + int temperature; + u32 auto_mode = 0; + struct mxcfb_update_data upd_data; + u32 update_marker = 0; + int ret = -EINVAL; + + switch (cmd) { + case MXCFB_SET_WAVEFORM_MODES: + if (!copy_from_user(&modes, argp, sizeof(modes))) { + memcpy(&fb_data->wv_modes, &modes, sizeof(modes)); + ret = 0; + } + break; + case MXCFB_SET_TEMPERATURE: + if (!get_user(temperature, (int32_t __user *) arg)) + ret = + mxc_epdc_fb_set_temperature(temperature, + info); + break; + case MXCFB_SET_AUTO_UPDATE_MODE: + if (!get_user(auto_mode, (__u32 __user *) arg)) + ret = + mxc_epdc_fb_set_auto_update(auto_mode, info); + break; + case MXCFB_SEND_UPDATE: + if (!copy_from_user(&upd_data, argp, sizeof(upd_data))) { + ret = mxc_epdc_fb_send_update(&upd_data, info); + if (ret == 0 && copy_to_user(argp, &upd_data, sizeof(upd_data))) + ret = -EFAULT; + } else { + ret = -EFAULT; + } + + break; + case MXCFB_WAIT_FOR_UPDATE_COMPLETE: + if (!get_user(update_marker, (__u32 __user *) arg)) + ret = + mxc_epdc_fb_wait_update_complete(update_marker, + info); + break; + default: + break; + } + return ret; +} + +static void mxc_epdc_fb_update_pages(struct mxc_epdc_fb_data *fb_data, + u16 y1, u16 y2) +{ + struct mxcfb_update_data update; + + /* Do partial screen update, Update full horizontal lines */ + update.update_region.left = 0; + update.update_region.width = fb_data->info.var.xres; + update.update_region.top = y1; + update.update_region.height = y2 - y1; + update.waveform_mode = WAVEFORM_MODE_AUTO; + update.update_mode = UPDATE_MODE_FULL; + update.update_marker = 0; + update.temp = TEMP_USE_AMBIENT; + update.use_alt_buffer = false; + + mxc_epdc_fb_send_update(&update, &fb_data->info); +} + +/* this is called back from the deferred io workqueue */ +static void mxc_epdc_fb_deferred_io(struct fb_info *info, + struct list_head *pagelist) +{ + struct mxc_epdc_fb_data *fb_data = (struct mxc_epdc_fb_data *)info; + struct page *page; + unsigned long beg, end; + int y1, y2, miny, maxy; + + if (fb_data->auto_mode != AUTO_UPDATE_MODE_AUTOMATIC_MODE) + return; + + miny = INT_MAX; + maxy = 0; + list_for_each_entry(page, pagelist, lru) { + beg = page->index << PAGE_SHIFT; + end = beg + PAGE_SIZE - 1; + y1 = beg / info->fix.line_length; + y2 = end / info->fix.line_length; + if (y2 >= info->var.yres) + y2 = info->var.yres - 1; + if (miny > y1) + miny = y1; + if (maxy < y2) + maxy = y2; + } + + mxc_epdc_fb_update_pages(fb_data, miny, maxy); +} + +static void mxc_epdc_fb_disable(struct mxc_epdc_fb_data *fb_data) +{ + unsigned long flags; + /* Grab queue lock to prevent any new updates from being submitted */ + + spin_lock_irqsave(&fb_data->queue_lock, flags); + + /* If any updates in flight, we must wait for them to complete */ + if (!(list_empty(&fb_data->upd_buf_collision_list->list) && + list_empty(&fb_data->upd_buf_queue->list) && + (fb_data->cur_update == NULL))) { + /* Initialize event signalling updates are done */ + init_completion(&fb_data->updates_done); + fb_data->waiting_for_idle = true; + + spin_unlock_irqrestore(&fb_data->queue_lock, flags); + /* Wait for any currently active updates to complete */ + wait_for_completion_timeout(&fb_data->updates_done, msecs_to_jiffies(2000)); + spin_lock_irqsave(&fb_data->queue_lock, flags); + fb_data->waiting_for_idle = false; + } + + spin_unlock_irqrestore(&fb_data->queue_lock, flags); +} + +static int mxc_epdc_fb_blank(int blank, struct fb_info *info) +{ + struct mxc_epdc_fb_data *fb_data = (struct mxc_epdc_fb_data *)info; + + dev_dbg(fb_data->dev, "blank = %d\n", blank); + + if (fb_data->blank == blank) + return 0; + + fb_data->blank = blank; + + switch (blank) { + case FB_BLANK_POWERDOWN: + case FB_BLANK_VSYNC_SUSPEND: + case FB_BLANK_HSYNC_SUSPEND: + case FB_BLANK_NORMAL: + mxc_epdc_fb_disable(fb_data); + break; + } + return 0; +} + +static int mxc_epdc_fb_pan_display(struct fb_var_screeninfo *var, + struct fb_info *info) +{ + struct mxc_epdc_fb_data *fb_data = (struct mxc_epdc_fb_data *)info; + struct mxcfb_update_data update; + int ret = 0; + u_int y_bottom; + + dev_dbg(info->device, "%s: var->xoffset %d, info->var.xoffset %d\n", + __func__, var->xoffset, info->var.xoffset); + /* check if var is valid; also, xpan is not supported */ + if (!var || (var->xoffset != info->var.xoffset) || + (var->yoffset + var->yres > var->yres_virtual)) { + dev_dbg(info->device, "x panning not supported\n"); + return -EINVAL; + } + + if ((info->var.xoffset == var->xoffset) && + (info->var.yoffset == var->yoffset)) + return 0; /* No change, do nothing */ + + y_bottom = var->yoffset; + + if (!(var->vmode & FB_VMODE_YWRAP)) + y_bottom += var->yres; + + if (y_bottom > info->var.yres_virtual) + return -EINVAL; + + fb_data->fb_offset = (var->yoffset * var->xres_virtual + var->xoffset) + * (var->bits_per_pixel) / 8; + + /* Update to new view of FB */ + update.update_region.left = 0; + update.update_region.width = fb_data->info.var.xres; + update.update_region.top = 0; + update.update_region.height = fb_data->info.var.yres; + update.waveform_mode = WAVEFORM_MODE_AUTO; + update.update_mode = UPDATE_MODE_FULL; + update.update_marker = PAN_UPDATE_MARKER; + update.temp = TEMP_USE_AMBIENT; + update.use_alt_buffer = false; + + mxc_epdc_fb_send_update(&update, &fb_data->info); + + /* Block on initial update */ + ret = mxc_epdc_fb_wait_update_complete(update.update_marker, info); + if (ret < 0) + dev_err(fb_data->dev, + "Wait for update complete failed. Error = 0x%x", ret); + + info->var.xoffset = var->xoffset; + info->var.yoffset = var->yoffset; + + if (var->vmode & FB_VMODE_YWRAP) + info->var.vmode |= FB_VMODE_YWRAP; + else + info->var.vmode &= ~FB_VMODE_YWRAP; + + return ret; +} + +static struct fb_ops mxc_epdc_fb_ops = { + .owner = THIS_MODULE, + .fb_check_var = mxc_epdc_fb_check_var, + .fb_set_par = mxc_epdc_fb_set_par, + .fb_setcolreg = mxc_epdc_fb_setcolreg, + .fb_pan_display = mxc_epdc_fb_pan_display, + .fb_ioctl = mxc_epdc_fb_ioctl, + .fb_mmap = mxc_epdc_fb_mmap, + .fb_blank = mxc_epdc_fb_blank, + .fb_fillrect = cfb_fillrect, + .fb_copyarea = cfb_copyarea, + .fb_imageblit = cfb_imageblit, +}; + +static struct fb_deferred_io mxc_epdc_fb_defio = { + .delay = HZ / 2, + .deferred_io = mxc_epdc_fb_deferred_io, +}; + +static void epdc_done_work_func(struct work_struct *work) +{ + struct mxc_epdc_fb_data *fb_data = + container_of(work, struct mxc_epdc_fb_data, epdc_done_work); + epdc_powerdown(fb_data); +} + +static bool is_free_list_full(struct mxc_epdc_fb_data *fb_data) +{ + int count = 0; + struct update_data_list *plist; + + /* Count buffers in free buffer list */ + list_for_each_entry(plist, &fb_data->upd_buf_free_list->list, list) + count++; + + /* Check to see if all buffers are in this list */ + if (count == EPDC_MAX_NUM_UPDATES) + return true; + else + return false; +} + +static irqreturn_t mxc_epdc_irq_handler(int irq, void *dev_id) +{ + struct mxc_epdc_fb_data *fb_data = dev_id; + struct update_data_list *collision_update; + struct mxcfb_rect *next_upd_region; + unsigned long flags; + int temp_index; + u32 luts_completed_mask; + u32 temp_mask; + u32 lut; + bool ignore_collision = false; + int i, j; + + /* + * If we just completed one-time panel init, bypass + * queue handling, clear interrupt and return + */ + if (fb_data->in_init) { + if (epdc_is_working_buffer_complete()) { + epdc_working_buf_intr(false); + epdc_clear_working_buf_irq(); + dev_dbg(fb_data->dev, "Cleared WB for init update\n"); + } + + if (epdc_is_lut_complete(0)) { + epdc_lut_complete_intr(0, false); + epdc_clear_lut_complete_irq(0); + fb_data->in_init = false; + dev_dbg(fb_data->dev, "Cleared LUT complete for init update\n"); + } + + return IRQ_HANDLED; + } + + if (!(__raw_readl(EPDC_IRQ_MASK) & __raw_readl(EPDC_IRQ))) + return IRQ_HANDLED; + + if (__raw_readl(EPDC_IRQ) & EPDC_IRQ_TCE_UNDERRUN_IRQ) { + dev_err(fb_data->dev, "TCE underrun! Panel may lock up.\n"); + return IRQ_HANDLED; + } + + /* Protect access to buffer queues and to update HW */ + spin_lock_irqsave(&fb_data->queue_lock, flags); + + /* Free any LUTs that have completed */ + luts_completed_mask = 0; + for (i = 0; i < EPDC_NUM_LUTS; i++) { + if (!epdc_is_lut_complete(i)) + continue; + + dev_dbg(fb_data->dev, "\nLUT %d completed\n", i); + + /* Disable IRQ for completed LUT */ + epdc_lut_complete_intr(i, false); + + /* + * Go through all updates in the collision list and + * unmask any updates that were colliding with + * the completed LUT. + */ + list_for_each_entry(collision_update, + &fb_data->upd_buf_collision_list-> + list, list) { + collision_update->collision_mask = + collision_update->collision_mask & ~(1 << i); + } + + epdc_clear_lut_complete_irq(i); + + luts_completed_mask |= 1 << i; + + fb_data->lut_update_type[i] = LUT_UPDATE_NONE; + + /* Signal completion if anyone waiting on this LUT */ + for (j = 0; j < EPDC_MAX_NUM_UPDATES; j++) { + if (fb_data->update_marker_array[j].lut_num != i) + continue; + + /* Signal completion of update */ + dev_dbg(fb_data->dev, + "Signaling marker %d\n", + fb_data->update_marker_array[j].update_marker); + complete(&fb_data->update_marker_array[j].update_completion); + /* Ensure this doesn't get signaled again inadvertently */ + fb_data->update_marker_array[j].lut_num = INVALID_LUT; + } + } + + /* Check to see if all updates have completed */ + if (is_free_list_full(fb_data) && + (fb_data->cur_update == NULL) && + !epdc_any_luts_active()) { + +#ifndef NO_POWERDOWN + /* + * Set variable to prevent overlapping + * enable/disable requests + */ + fb_data->powering_down = true; + + /* Schedule task to disable EPDC HW until next update */ + schedule_work(&fb_data->epdc_done_work); +#endif + + if (fb_data->waiting_for_idle) + complete(&fb_data->updates_done); + } + + /* Is Working Buffer busy? */ + if (epdc_is_working_buffer_busy()) { + /* Can't submit another update until WB is done */ + spin_unlock_irqrestore(&fb_data->queue_lock, flags); + return IRQ_HANDLED; + } + + /* + * Were we waiting on working buffer? + * If so, update queues and check for collisions + */ + if (fb_data->cur_update != NULL) { + dev_dbg(fb_data->dev, "\nWorking buffer completed\n"); + + /* Was there a collision? */ + if (epdc_is_collision()) { + /* Check list of colliding LUTs, and add to our collision mask */ + fb_data->cur_update->collision_mask = + epdc_get_colliding_luts(); + + dev_dbg(fb_data->dev, "\nCollision mask = 0x%x\n", + epdc_get_colliding_luts()); + + /* Clear collisions that just completed */ + fb_data->cur_update->collision_mask &= ~luts_completed_mask; + + /* + * If this is a re-collision, AND we re-collide + * with only new updates, then we don't want + * to re-submit it again. + */ + if (fb_data->cur_update->is_collision) { + /* + * Check whether collided LUTs are + * new updates or resubmitted collisions + */ + temp_mask = fb_data->cur_update->collision_mask; + lut = 0; + while (temp_mask != 0) { + if ((temp_mask & 0x1) && + (fb_data->lut_update_type[lut] == LUT_UPDATE_NEW)) { + dev_dbg(fb_data->dev, "Ignoring collision with new update.\n"); + ignore_collision = true; + break; + } + lut++; + temp_mask = temp_mask >> 1; + } + } + + if (ignore_collision) { + /* Add to free buffer list */ + list_add_tail(&fb_data->cur_update->list, + &fb_data->upd_buf_free_list->list); + } else { + /* + * If update has a marker, clear the LUT, since we + * don't want to signal that it is complete. + */ + if (fb_data->cur_update->upd_marker_data) + if (fb_data->cur_update->upd_marker_data->update_marker != 0) + fb_data->cur_update->upd_marker_data->lut_num = INVALID_LUT; + + fb_data->cur_update->is_collision = true; + + /* Move to collision list */ + list_add_tail(&fb_data->cur_update->list, + &fb_data->upd_buf_collision_list->list); + } + } else { + /* Add to free buffer list */ + list_add_tail(&fb_data->cur_update->list, + &fb_data->upd_buf_free_list->list); + } + /* Clear current update */ + fb_data->cur_update = NULL; + + /* Clear IRQ for working buffer */ + epdc_working_buf_intr(false); + epdc_clear_working_buf_irq(); + } + + /* Check to see if any LUTs are free */ + if (!epdc_any_luts_available()) { + dev_dbg(fb_data->dev, "No luts available.\n"); + spin_unlock_irqrestore(&fb_data->queue_lock, flags); + return IRQ_HANDLED; + } + + /* + * Are any of our collision updates able to go now? + * Go through all updates in the collision list and check to see + * if the collision mask has been fully cleared + */ + list_for_each_entry(collision_update, + &fb_data->upd_buf_collision_list->list, list) { + + if (collision_update->collision_mask != 0) + continue; + + dev_dbg(fb_data->dev, "A collision update is ready to go!\n"); + /* + * We have a collision cleared, so select it + * and we will retry the update + */ + fb_data->cur_update = collision_update; + list_del_init(&fb_data->cur_update->list); + break; + } + + /* + * If we didn't find a collision update ready to go, + * we try to grab one from the update queue + */ + if (fb_data->cur_update == NULL) { + /* Is update list empty? */ + if (list_empty(&fb_data->upd_buf_queue->list)) { + dev_dbg(fb_data->dev, "No pending updates.\n"); + + /* No updates pending, so we are done */ + spin_unlock_irqrestore(&fb_data->queue_lock, flags); + return IRQ_HANDLED; + } else { + dev_dbg(fb_data->dev, "Found a pending update!\n"); + + /* Process next item in update list */ + fb_data->cur_update = + list_entry(fb_data->upd_buf_queue->list.next, + struct update_data_list, list); + list_del_init(&fb_data->cur_update->list); + } + } + + /* LUTs are available, so we get one here */ + fb_data->cur_update->lut_num = epdc_get_next_lut(); + + /* Associate LUT with update marker */ + if ((fb_data->cur_update->upd_marker_data) + && (fb_data->cur_update->upd_marker_data->update_marker != 0)) + fb_data->cur_update->upd_marker_data->lut_num = + fb_data->cur_update->lut_num; + + /* Mark LUT as containing new update */ + if (fb_data->cur_update->is_collision) + fb_data->lut_update_type[fb_data->cur_update->lut_num] = LUT_UPDATE_COLLISION; + else + fb_data->lut_update_type[fb_data->cur_update->lut_num] = LUT_UPDATE_NEW; + + /* Enable Collision and WB complete IRQs */ + epdc_working_buf_intr(true); + epdc_lut_complete_intr(fb_data->cur_update->lut_num, true); + + /* Program EPDC update to process buffer */ + next_upd_region = &fb_data->cur_update->upd_data.update_region; + if (fb_data->cur_update->upd_data.temp != TEMP_USE_AMBIENT) { + temp_index = mxc_epdc_fb_get_temp_index(fb_data, fb_data->cur_update->upd_data.temp); + epdc_set_temp(temp_index); + } + epdc_set_update_addr(fb_data->cur_update->phys_addr + fb_data->cur_update->epdc_offs); + epdc_set_update_coord(next_upd_region->left, next_upd_region->top); + epdc_set_update_dimensions(next_upd_region->width, + next_upd_region->height); + epdc_submit_update(fb_data->cur_update->lut_num, + fb_data->cur_update->upd_data.waveform_mode, + fb_data->cur_update->upd_data.update_mode, false, 0); + + /* Release buffer queues */ + spin_unlock_irqrestore(&fb_data->queue_lock, flags); + + return IRQ_HANDLED; +} + +static void draw_mode0(struct mxc_epdc_fb_data *fb_data) +{ + u32 *upd_buf_ptr; + int i; + + upd_buf_ptr = (u32 *)fb_data->info.screen_base; + + epdc_working_buf_intr(true); + epdc_lut_complete_intr(0, true); + fb_data->in_init = true; + + /* Program EPDC update to process buffer */ + epdc_set_update_addr(fb_data->phys_start); + epdc_set_update_coord(0, 0); + epdc_set_update_dimensions(fb_data->info.var.xres, + fb_data->info.var.yres); + epdc_submit_update(0, fb_data->wv_modes.mode_init, UPDATE_MODE_FULL, true, 0xFF); + + dev_dbg(fb_data->dev, "Mode0 update - Waiting for LUT to complete...\n"); + + /* Will timeout after ~4-5 seconds */ + + for (i = 0; i < 40; i++) { + if (!epdc_is_lut_active(0)) { + dev_dbg(fb_data->dev, "Mode0 init complete\n"); + return; + } + msleep(100); + } + + dev_err(fb_data->dev, "Mode0 init failed!\n"); + + return; +} + +static int mxc_epdc_fb_init_hw(struct fb_info *info) +{ + struct mxc_epdc_fb_data *fb_data = (struct mxc_epdc_fb_data *)info; + const struct firmware *fw; + struct mxcfb_update_data update; + struct mxcfb_waveform_data_file *wv_file; + int wv_data_offs; + int ret; + int i; + + ret = request_firmware(&fw, "imx/epdc.fw", fb_data->dev); + if (ret) { + printk(KERN_ERR "Failed to load image imx/epdc.ihex err %d\n", + ret); + return ret; + } + + wv_file = (struct mxcfb_waveform_data_file *)fw->data; + + /* Get size and allocate temperature range table */ + fb_data->trt_entries = wv_file->wdh.trc + 1; + fb_data->temp_range_bounds = kzalloc(fb_data->trt_entries, GFP_KERNEL); + + for (i = 0; i < fb_data->trt_entries; i++) + dev_dbg(fb_data->dev, "trt entry #%d = 0x%x\n", i, *((u8 *)&wv_file->data + i)); + + /* Copy TRT data */ + memcpy(fb_data->temp_range_bounds, &wv_file->data, fb_data->trt_entries); + + /* Get offset and size for waveform data */ + wv_data_offs = sizeof(wv_file->wdh) + fb_data->trt_entries + 1; + fb_data->waveform_buffer_size = fw->size - wv_data_offs; + + /* Allocate memory for waveform data */ + fb_data->waveform_buffer_virt = dma_alloc_coherent(fb_data->dev, + fb_data->waveform_buffer_size, + &fb_data->waveform_buffer_phys, + GFP_DMA); + if (fb_data->waveform_buffer_virt == NULL) { + dev_err(fb_data->dev, "Can't allocate mem for waveform!\n"); + ret = -ENOMEM; + } + + memcpy(fb_data->waveform_buffer_virt, (u8 *)(fw->data) + wv_data_offs, + fb_data->waveform_buffer_size); + + release_firmware(fw); + + /* Enable clocks to access EPDC regs */ + clk_enable(fb_data->epdc_clk_axi); + + /* Enable pix clk for EPDC */ + clk_enable(fb_data->epdc_clk_pix); + clk_set_rate(fb_data->epdc_clk_pix, 20000000); + + epdc_init_sequence(fb_data); + + /* Enable clocks to access EPDC regs */ + clk_disable(fb_data->epdc_clk_axi); + clk_disable(fb_data->epdc_clk_pix); + + fb_data->hw_ready = true; + + update.update_region.left = 0; + update.update_region.width = info->var.xres; + update.update_region.top = 0; + update.update_region.height = info->var.yres; + update.update_mode = UPDATE_MODE_FULL; + update.waveform_mode = WAVEFORM_MODE_AUTO; + update.update_marker = INIT_UPDATE_MARKER; + update.temp = TEMP_USE_AMBIENT; + update.use_alt_buffer = false; + + mxc_epdc_fb_send_update(&update, info); + + /* Block on initial update */ + ret = mxc_epdc_fb_wait_update_complete(update.update_marker, info); + if (ret < 0) + dev_err(fb_data->dev, + "Wait for update complete failed. Error = 0x%x", ret); + + return 0; +} + +static ssize_t store_update(struct device *device, + struct device_attribute *attr, + const char *buf, size_t count) +{ + struct mxcfb_update_data update; + struct fb_info *info = dev_get_drvdata(device); + struct mxc_epdc_fb_data *fb_data = (struct mxc_epdc_fb_data *)info; + + if (strncmp(buf, "direct", 6) == 0) + update.waveform_mode = fb_data->wv_modes.mode_du; + else if (strncmp(buf, "gc16", 4) == 0) + update.waveform_mode = fb_data->wv_modes.mode_gc16; + else if (strncmp(buf, "gc4", 3) == 0) + update.waveform_mode = fb_data->wv_modes.mode_gc4; + + /* Now, request full screen update */ + update.update_region.left = 0; + update.update_region.width = info->var.xres; + update.update_region.top = 0; + update.update_region.height = info->var.yres; + update.update_mode = UPDATE_MODE_FULL; + update.temp = TEMP_USE_AMBIENT; + update.update_marker = 0; + update.use_alt_buffer = false; + + mxc_epdc_fb_send_update(&update, info); + + return count; +} + +static struct device_attribute fb_attrs[] = { + __ATTR(update, S_IRUGO|S_IWUSR, NULL, store_update), +}; + +int __devinit mxc_epdc_fb_probe(struct platform_device *pdev) +{ + int ret = 0; + struct mxc_epdc_fb_data *fb_data; + struct resource *res; + struct fb_info *info; + struct mxc_epdc_platform_fb_data *pdata; + struct mxc_epdc_platform_fb_entry *pentry; + struct pxp_config_data *pxp_conf; + struct pxp_proc_data *proc_data; + struct scatterlist *sg; + struct update_data_list *upd_list; + struct update_data_list *plist, *temp_list; + int i; + + fb_data = (struct mxc_epdc_fb_data *)framebuffer_alloc( + sizeof(struct mxc_epdc_fb_data), &pdev->dev); + if (fb_data == NULL) { + ret = -ENOMEM; + goto out; + } + + fb_data->dev = &pdev->dev; + /* We want to use hard-coded structure defined in this file */ + pentry = &ed060sc4_fb_entry; + fb_data->cur = pentry; + platform_set_drvdata(pdev, fb_data); + info = &fb_data->info; + + /* Allocate color map for the FB */ + ret = fb_alloc_cmap(&info->cmap, 256, 0); + if (ret) + goto out_fbdata; + + dev_dbg(&pdev->dev, "resolution %dx%d, bpp %d\n", pentry->x_res, + pentry->y_res, pentry->bpp); + + fb_data->mem_size = pentry->x_res * pentry->y_res * pentry->bpp/8; + + fb_data->map_size = PAGE_ALIGN(fb_data->mem_size) * NUM_SCREENS; + dev_dbg(&pdev->dev, "memory to allocate: %d\n", fb_data->map_size); + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (res == NULL) { + ret = -ENODEV; + goto out_cmap; + } + + epdc_base = ioremap(res->start, SZ_4K); + if (epdc_base == NULL) { + ret = -ENOMEM; + goto out_cmap; + } + + /* Allocate FB memory */ + info->screen_base = dma_alloc_writecombine(&pdev->dev, + fb_data->map_size, + &fb_data->phys_start, + GFP_KERNEL); + + if (info->screen_base == NULL) { + ret = -ENOMEM; + goto out_mapregs; + } + dev_dbg(&pdev->dev, "allocated at %p:0x%x\n", info->screen_base, + fb_data->phys_start); + + mxc_epdc_fb_default.bits_per_pixel = pentry->bpp; + mxc_epdc_fb_default.xres = pentry->x_res; + mxc_epdc_fb_default.yres = pentry->y_res; + mxc_epdc_fb_default.xres_virtual = pentry->x_res; + mxc_epdc_fb_default.yres_virtual = pentry->y_res * 2; /* FB doubled in virtual space */ + + mxc_epdc_fb_fix.smem_start = fb_data->phys_start; + mxc_epdc_fb_fix.smem_len = mxc_epdc_fb_default.yres_virtual + * pentry->x_res * 2 * pentry->bpp / 8; + mxc_epdc_fb_fix.ypanstep = 0; + + switch (pentry->bpp) { + case 32: + case 24: + mxc_epdc_fb_default.red.offset = 16; + mxc_epdc_fb_default.red.length = 8; + mxc_epdc_fb_default.green.offset = 8; + mxc_epdc_fb_default.green.length = 8; + mxc_epdc_fb_default.blue.offset = 0; + mxc_epdc_fb_default.blue.length = 8; + break; + + case 16: + mxc_epdc_fb_default.red.offset = 11; + mxc_epdc_fb_default.red.length = 5; + mxc_epdc_fb_default.green.offset = 5; + mxc_epdc_fb_default.green.length = 6; + mxc_epdc_fb_default.blue.offset = 0; + mxc_epdc_fb_default.blue.length = 5; + break; + + default: + dev_err(&pdev->dev, "unsupported bitwidth %d\n", pentry->bpp); + ret = -EINVAL; + goto out_dma_fb; + } + + fb_data->native_width = pentry->x_res; + fb_data->native_height = pentry->y_res; + + info->fbops = &mxc_epdc_fb_ops; + info->var = mxc_epdc_fb_default; + info->fix = mxc_epdc_fb_fix; + info->var.activate = FB_ACTIVATE_NOW; + info->pseudo_palette = fb_data->pseudo_palette; + info->screen_size = info->fix.smem_len; + fb_data->par = NULL; + info->flags = FBINFO_FLAG_DEFAULT; + + mxc_epdc_fb_set_fix(info); + + fb_data->auto_mode = AUTO_UPDATE_MODE_REGION_MODE; + + init_waitqueue_head(&fb_data->vsync_wait_q); + fb_data->vsync_count = 0; + + fb_data->fb_offset = 0; + + /* Allocate head objects for our lists */ + fb_data->upd_buf_queue = + kzalloc(sizeof(struct update_data_list), GFP_KERNEL); + fb_data->upd_buf_collision_list = + kzalloc(sizeof(struct update_data_list), GFP_KERNEL); + fb_data->upd_buf_free_list = + kzalloc(sizeof(struct update_data_list), GFP_KERNEL); + if ((fb_data->upd_buf_queue == NULL) || (fb_data->upd_buf_free_list == NULL) + || (fb_data->upd_buf_collision_list == NULL)) { + ret = -ENOMEM; + goto out_dma_fb; + } + + /* + * Initialize lists for update requests, update collisions, + * and available update (PxP output) buffers + */ + INIT_LIST_HEAD(&fb_data->upd_buf_queue->list); + INIT_LIST_HEAD(&fb_data->upd_buf_free_list->list); + INIT_LIST_HEAD(&fb_data->upd_buf_collision_list->list); + + /* Allocate update buffers and add them to the list */ + for (i = 0; i < EPDC_MAX_NUM_UPDATES; i++) { + upd_list = kzalloc(sizeof(*upd_list), GFP_KERNEL); + if (upd_list == NULL) { + ret = -ENOMEM; + goto out_upd_buffers; + } + + /* Clear update data structure */ + memset(&upd_list->upd_data, 0, + sizeof(struct mxcfb_update_data)); + + /* + * Each update buffer is 1 byte per pixel, and can + * be as big as the full-screen frame buffer + */ + upd_list->size = info->var.xres * info->var.yres; + + /* Allocate memory for PxP output buffer */ + upd_list->virt_addr = + dma_alloc_coherent(fb_data->info.device, upd_list->size, + &upd_list->phys_addr, GFP_DMA); + if (upd_list->virt_addr == NULL) { + kfree(upd_list); + ret = -ENOMEM; + goto out_upd_buffers; + } + + /* Add newly allocated buffer to free list */ + list_add(&upd_list->list, &fb_data->upd_buf_free_list->list); + + dev_dbg(fb_data->info.device, "allocated %d bytes @ 0x%08X\n", + upd_list->size, upd_list->phys_addr); + } + + fb_data->working_buffer_size = pentry->y_res * pentry->x_res * 2; + /* Allocate memory for EPDC working buffer */ + fb_data->working_buffer_virt = + dma_alloc_coherent(&pdev->dev, fb_data->working_buffer_size, + &fb_data->working_buffer_phys, GFP_DMA); + if (fb_data->working_buffer_virt == NULL) { + dev_err(&pdev->dev, "Can't allocate mem for working buf!\n"); + ret = -ENOMEM; + goto out_upd_buffers; + } + + fb_data->epdc_clk_axi = clk_get(fb_data->dev, "epdc_axi"); + fb_data->epdc_clk_pix = clk_get(fb_data->dev, "epdc_pix"); + + fb_data->in_init = false; + + fb_data->hw_ready = false; + + /* + * Set default waveform mode values. + * Should be overwritten via ioctl. + */ + fb_data->wv_modes.mode_init = 0; + fb_data->wv_modes.mode_du = 1; + fb_data->wv_modes.mode_gc4 = 3; + fb_data->wv_modes.mode_gc8 = 2; + fb_data->wv_modes.mode_gc16 = 2; + fb_data->wv_modes.mode_gc32 = 2; + + /* Initialize markers */ + for (i = 0; i < EPDC_MAX_NUM_UPDATES; i++) { + fb_data->update_marker_array[i].update_marker = 0; + fb_data->update_marker_array[i].lut_num = INVALID_LUT; + } + + /* Initialize all LUTs to inactive */ + for (i = 0; i < EPDC_NUM_LUTS; i++) + fb_data->lut_update_type[i] = LUT_UPDATE_NONE; + + /* Retrieve EPDC IRQ num */ + res = platform_get_resource(pdev, IORESOURCE_IRQ, 0); + if (res == NULL) { + dev_err(&pdev->dev, "cannot get IRQ resource\n"); + ret = -ENODEV; + goto out_dma_work_buf; + } + fb_data->epdc_irq = res->start; + + /* Register IRQ handler */ + ret = request_irq(fb_data->epdc_irq, mxc_epdc_irq_handler, 0, + "fb_dma", fb_data); + if (ret) { + dev_err(&pdev->dev, "request_irq (%d) failed with error %d\n", + fb_data->epdc_irq, ret); + ret = -ENODEV; + goto out_dma_work_buf; + } + + INIT_WORK(&fb_data->epdc_done_work, epdc_done_work_func); + + info->fbdefio = &mxc_epdc_fb_defio; +#ifdef CONFIG_FB_MXC_EINK_AUTO_UPDATE_MODE + fb_deferred_io_init(info); +#endif + + /* get pmic regulators */ + fb_data->display_regulator = regulator_get(NULL, "DISPLAY"); + if (IS_ERR(fb_data->display_regulator)) { + dev_err(&pdev->dev, "Unable to get display PMIC regulator." + "err = 0x%x\n", fb_data->display_regulator); + ret = -ENODEV; + goto out_dma_work_buf; + } + fb_data->vcom_regulator = regulator_get(NULL, "VCOM"); + if (IS_ERR(fb_data->vcom_regulator)) { + regulator_put(fb_data->display_regulator); + dev_err(&pdev->dev, "Unable to get VCOM regulator." + "err = 0x%x\n", fb_data->vcom_regulator); + ret = -ENODEV; + goto out_dma_work_buf; + } + + if (device_create_file(info->dev, &fb_attrs[0])) + dev_err(&pdev->dev, "Unable to create file from fb_attrs\n"); + + fb_data->cur_update = NULL; + + spin_lock_init(&fb_data->queue_lock); + + mutex_init(&fb_data->pxp_mutex); + + mutex_init(&fb_data->power_mutex); + + /* PxP DMA interface */ + dmaengine_get(); + + /* + * Fill out PxP config data structure based on FB info and + * processing tasks required + */ + pxp_conf = &fb_data->pxp_conf; + proc_data = &pxp_conf->proc_data; + + /* Initialize non-channel-specific PxP parameters */ + proc_data->drect.left = proc_data->srect.left = 0; + proc_data->drect.top = proc_data->srect.top = 0; + proc_data->drect.width = proc_data->srect.width = fb_data->info.var.xres; + proc_data->drect.height = proc_data->srect.height = fb_data->info.var.yres; + proc_data->scaling = 0; + proc_data->hflip = 0; + proc_data->vflip = 0; + proc_data->rotate = 0; + proc_data->bgcolor = 0; + proc_data->overlay_state = 0; + proc_data->lut_transform = PXP_LUT_NONE; + + /* + * We initially configure PxP for RGB->YUV conversion, + * and only write out Y component of the result. + */ + + /* + * Initialize S0 channel parameters + * Parameters should match FB format/width/height + */ + pxp_conf->s0_param.pixel_fmt = PXP_PIX_FMT_RGB565; + pxp_conf->s0_param.width = fb_data->info.var.xres; + pxp_conf->s0_param.height = fb_data->info.var.yres; + pxp_conf->s0_param.color_key = -1; + pxp_conf->s0_param.color_key_enable = false; + + /* + * Initialize OL0 channel parameters + * No overlay will be used for PxP operation + */ + for (i = 0; i < 8; i++) { + pxp_conf->ol_param[i].combine_enable = false; + pxp_conf->ol_param[i].width = 0; + pxp_conf->ol_param[i].height = 0; + pxp_conf->ol_param[i].pixel_fmt = PXP_PIX_FMT_RGB565; + pxp_conf->ol_param[i].color_key_enable = false; + pxp_conf->ol_param[i].color_key = -1; + pxp_conf->ol_param[i].global_alpha_enable = false; + pxp_conf->ol_param[i].global_alpha = 0; + pxp_conf->ol_param[i].local_alpha_enable = false; + } + + /* + * Initialize Output channel parameters + * Output is Y-only greyscale + * Output width/height will vary based on update region size + */ + pxp_conf->out_param.width = fb_data->info.var.xres; + pxp_conf->out_param.height = fb_data->info.var.yres; + pxp_conf->out_param.pixel_fmt = PXP_PIX_FMT_GREY; + + /* + * Ensure this is set to NULL here...we will initialize pxp_chan + * later in our thread. + */ + fb_data->pxp_chan = NULL; + + /* Initialize Scatter-gather list containing 2 buffer addresses. */ + sg = fb_data->sg; + sg_init_table(sg, 2); + + /* + * For use in PxP transfers: + * sg[0] holds the FB buffer pointer + * sg[1] holds the Output buffer pointer (configured before TX request) + */ + sg_dma_address(&sg[0]) = info->fix.smem_start; + sg_set_page(&sg[0], virt_to_page(info->screen_base), + info->fix.smem_len, offset_in_page(info->screen_base)); + + fb_data->waiting_for_idle = false; + fb_data->blank = FB_BLANK_UNBLANK; + fb_data->power_state = POWER_STATE_OFF; + fb_data->powering_down = false; + + /* Register FB */ + ret = register_framebuffer(info); + if (ret) { + dev_err(&pdev->dev, + "register_framebuffer failed with error %d\n", ret); + goto out_irq; + } + +#ifdef DEFAULT_PANEL_HW_INIT + ret = mxc_epdc_fb_init_hw((struct fb_info *)fb_data); + if (ret) { + dev_err(&pdev->dev, "Failed to read firmware!\n"); + goto out_dmaengine; + } +#endif + + goto out; + +out_dmaengine: + dmaengine_put(); + unregister_framebuffer(&fb_data->info); +out_irq: + free_irq(fb_data->epdc_irq, fb_data); +out_dma_work_buf: + dma_free_writecombine(&pdev->dev, fb_data->working_buffer_size, + fb_data->working_buffer_virt, fb_data->working_buffer_phys); +out_upd_buffers: + list_for_each_entry_safe(plist, temp_list, &fb_data->upd_buf_free_list->list, list) { + list_del(&plist->list); + dma_free_writecombine(&pdev->dev, plist->size, plist->virt_addr, + plist->phys_addr); + kfree(plist); + } +out_dma_fb: + dma_free_writecombine(&pdev->dev, fb_data->map_size, info->screen_base, + fb_data->phys_start); + +out_mapregs: + iounmap(epdc_base); +out_cmap: + fb_dealloc_cmap(&info->cmap); +out_fbdata: + kfree(fb_data); +out: + return ret; +} + +static int mxc_epdc_fb_remove(struct platform_device *pdev) +{ + struct update_data_list *plist, *temp_list; + struct mxc_epdc_fb_data *fb_data = platform_get_drvdata(pdev); + + mxc_epdc_fb_blank(FB_BLANK_POWERDOWN, &fb_data->info); + + regulator_put(fb_data->display_regulator); + regulator_put(fb_data->vcom_regulator); + + unregister_framebuffer(&fb_data->info); + free_irq(fb_data->epdc_irq, fb_data); + + dma_free_writecombine(&pdev->dev, fb_data->working_buffer_size, fb_data->working_buffer_virt, + fb_data->working_buffer_phys); + dma_free_writecombine(&pdev->dev, fb_data->waveform_buffer_size, fb_data->waveform_buffer_virt, + fb_data->waveform_buffer_phys); + list_for_each_entry_safe(plist, temp_list, &fb_data->upd_buf_free_list->list, list) { + list_del(&plist->list); + dma_free_writecombine(&pdev->dev, plist->size, plist->virt_addr, + plist->phys_addr); + kfree(plist); + } + dma_free_writecombine(&pdev->dev, fb_data->map_size, fb_data->info.screen_base, + fb_data->phys_start); + + /* Release PxP-related resources */ + if (fb_data->pxp_chan != NULL) + dma_release_channel(&fb_data->pxp_chan->dma_chan); + + dmaengine_put(); + + iounmap(epdc_base); + +#ifdef CONFIG_FB_MXC_EINK_AUTO_UPDATE_MODE + fb_deferred_io_cleanup(&fb_data->info); +#endif + fb_dealloc_cmap(&fb_data->info.cmap); + + framebuffer_release(&fb_data->info); + platform_set_drvdata(pdev, NULL); + + return 0; +} + +#ifdef CONFIG_PM +static int mxc_epdc_fb_suspend(struct platform_device *pdev, pm_message_t state) +{ + struct mxc_epdc_fb_data *data = platform_get_drvdata(pdev); + int ret; + + ret = mxc_epdc_fb_blank(FB_BLANK_POWERDOWN, &data->info); + if (ret) + goto out; + +out: + return ret; +} + +static int mxc_epdc_fb_resume(struct platform_device *pdev) +{ + struct mxc_epdc_fb_data *data = platform_get_drvdata(pdev); + + mxc_epdc_fb_blank(FB_BLANK_UNBLANK, &data->info); + return 0; +} +#else +#define mxc_epdc_fb_suspend NULL +#define mxc_epdc_fb_resume NULL +#endif + +static struct platform_driver mxc_epdc_fb_driver = { + .probe = mxc_epdc_fb_probe, + .remove = mxc_epdc_fb_remove, + .suspend = mxc_epdc_fb_suspend, + .resume = mxc_epdc_fb_resume, + .driver = { + .name = "mxc_epdc_fb", + .owner = THIS_MODULE, + }, +}; + +/* Callback function triggered after PxP receives an EOF interrupt */ +static void pxp_dma_done(void *arg) +{ + struct pxp_tx_desc *tx_desc = to_tx_desc(arg); + struct dma_chan *chan = tx_desc->txd.chan; + struct pxp_channel *pxp_chan = to_pxp_channel(chan); + struct mxc_epdc_fb_data *fb_data = pxp_chan->client; + + /* This call will signal wait_for_completion_timeout() in send_buffer_to_pxp */ + complete(&fb_data->pxp_tx_cmpl); +} + +/* Function to request PXP DMA channel */ +static int pxp_chan_init(struct mxc_epdc_fb_data *fb_data) +{ + dma_cap_mask_t mask; + struct dma_chan *chan; + + /* + * Request a free channel + */ + dma_cap_zero(mask); + dma_cap_set(DMA_SLAVE, mask); + dma_cap_set(DMA_PRIVATE, mask); + chan = dma_request_channel(mask, NULL, NULL); + if (!chan) { + dev_err(fb_data->dev, "Unsuccessfully received channel!!!!\n"); + return -EBUSY; + } + + dev_dbg(fb_data->dev, "Successfully received channel.\n"); + + fb_data->pxp_chan = to_pxp_channel(chan); + + dev_dbg(fb_data->dev, "dma_chan = 0x%x\n", fb_data->pxp_chan->dma_chan); + + fb_data->pxp_chan->client = fb_data; + + init_completion(&fb_data->pxp_tx_cmpl); + + return 0; +} + +/* + * Function to call PxP DMA driver and send our latest FB update region + * through the PxP and out to an intermediate buffer. + * Note: This is a blocking call, so upon return the PxP tx should be complete. + */ +static int pxp_process_update(struct mxc_epdc_fb_data *fb_data, + struct mxcfb_rect *update_region) +{ + dma_cookie_t cookie; + struct scatterlist *sg = fb_data->sg; + struct dma_chan *dma_chan; + struct pxp_tx_desc *desc; + struct dma_async_tx_descriptor *txd; + struct pxp_config_data *pxp_conf = &fb_data->pxp_conf; + struct pxp_proc_data *proc_data = &fb_data->pxp_conf.proc_data; + int i, ret; + + dev_dbg(fb_data->dev, "Starting PxP Send Buffer\n"); + + /* First, check to see that we have acquired a PxP Channel object */ + if (fb_data->pxp_chan == NULL) { + /* + * PxP Channel has not yet been created and initialized, + * so let's go ahead and try + */ + ret = pxp_chan_init(fb_data); + if (ret) { + /* + * PxP channel init failed, and we can't use the + * PxP until the PxP DMA driver has loaded, so we abort + */ + dev_err(fb_data->dev, "PxP chan init failed\n"); + return -ENODEV; + } + } + + /* + * Init completion, so that we + * can be properly informed of the completion + * of the PxP task when it is done. + */ + init_completion(&fb_data->pxp_tx_cmpl); + + dev_dbg(fb_data->dev, "sg[0] = 0x%x, sg[1] = 0x%x\n", + sg_dma_address(&sg[0]), sg_dma_address(&sg[1])); + + dma_chan = &fb_data->pxp_chan->dma_chan; + + txd = dma_chan->device->device_prep_slave_sg(dma_chan, sg, 2, + DMA_TO_DEVICE, + DMA_PREP_INTERRUPT); + if (!txd) { + dev_err(fb_data->info.device, + "Error preparing a DMA transaction descriptor.\n"); + return -EIO; + } + + txd->callback_param = txd; + txd->callback = pxp_dma_done; + + /* + * Configure PxP for processing of new update region + * The rest of our config params were set up in + * probe() and should not need to be changed. + */ + proc_data->srect.top = update_region->top; + proc_data->srect.left = update_region->left; + proc_data->srect.width = update_region->width; + proc_data->srect.height = update_region->height; + + /* + * Because only YUV/YCbCr image can be scaled, configure + * drect equivalent to srect, as such do not perform scaling. + */ + proc_data->drect.top = 0; + proc_data->drect.left = 0; + proc_data->drect.width = proc_data->srect.width; + proc_data->drect.height = proc_data->srect.height; + + /* PXP expects rotation in terms of degrees */ + proc_data->rotate = fb_data->info.var.rotate * 90; + if (proc_data->rotate > 270) + proc_data->rotate = 0; + + pxp_conf->out_param.width = update_region->width; + pxp_conf->out_param.height = update_region->height; + + desc = to_tx_desc(txd); + int length = desc->len; + for (i = 0; i < length; i++) { + if (i == 0) {/* S0 */ + memcpy(&desc->proc_data, proc_data, sizeof(struct pxp_proc_data)); + pxp_conf->s0_param.paddr = sg_dma_address(&sg[0]); + memcpy(&desc->layer_param.s0_param, &pxp_conf->s0_param, + sizeof(struct pxp_layer_param)); + } else if (i == 1) { + pxp_conf->out_param.paddr = sg_dma_address(&sg[1]); + memcpy(&desc->layer_param.out_param, &pxp_conf->out_param, + sizeof(struct pxp_layer_param)); + } + /* TODO: OverLay */ + + desc = desc->next; + } + + /* Submitting our TX starts the PxP processing task */ + cookie = txd->tx_submit(txd); + dev_dbg(fb_data->info.device, "%d: Submit %p #%d\n", __LINE__, txd, + cookie); + if (cookie < 0) { + dev_err(fb_data->info.device, "Error sending FB through PxP\n"); + return -EIO; + } + + fb_data->txd = txd; + + /* trigger ePxP */ + dma_async_issue_pending(dma_chan); + + return 0; +} + +static int pxp_complete_update(struct mxc_epdc_fb_data *fb_data, u32 *hist_stat) +{ + int ret; + /* + * Wait for completion event, which will be set + * through our TX callback function. + */ + ret = wait_for_completion_timeout(&fb_data->pxp_tx_cmpl, HZ / 10); + if (ret <= 0) { + dev_info(fb_data->info.device, + "PxP operation failed due to %s\n", + ret < 0 ? "user interrupt" : "timeout"); + dma_release_channel(&fb_data->pxp_chan->dma_chan); + fb_data->pxp_chan = NULL; + return ret ? : -ETIMEDOUT; + } + + *hist_stat = to_tx_desc(fb_data->txd)->hist_status; + dma_release_channel(&fb_data->pxp_chan->dma_chan); + fb_data->pxp_chan = NULL; + + dev_dbg(fb_data->dev, "TX completed\n"); + + return 0; +} + +static int __init mxc_epdc_fb_init(void) +{ + return platform_driver_register(&mxc_epdc_fb_driver); +} +late_initcall(mxc_epdc_fb_init); + + +static void __exit mxc_epdc_fb_exit(void) +{ + platform_driver_unregister(&mxc_epdc_fb_driver); +} +module_exit(mxc_epdc_fb_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MXC EPDC framebuffer driver"); +MODULE_LICENSE("GPL"); +MODULE_SUPPORTED_DEVICE("fb"); diff --git a/drivers/video/mxc/mxc_ipuv3_fb.c b/drivers/video/mxc/mxc_ipuv3_fb.c new file mode 100644 index 000000000000..23e3047cc749 --- /dev/null +++ b/drivers/video/mxc/mxc_ipuv3_fb.c @@ -0,0 +1,1867 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @defgroup Framebuffer Framebuffer Driver for SDC and ADC. + */ + +/*! + * @file mxcfb.c + * + * @brief MXC Frame buffer driver for SDC + * + * @ingroup Framebuffer + */ + +/*! + * Include files + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Driver name + */ +#define MXCFB_NAME "mxc_sdc_fb" +/*! + * Structure containing the MXC specific framebuffer information. + */ +struct mxcfb_info { + char *fb_mode_str; + int default_bpp; + int cur_blank; + int next_blank; + ipu_channel_t ipu_ch; + int ipu_di; + u32 ipu_di_pix_fmt; + bool ipu_ext_clk; + bool overlay; + bool alpha_chan_en; + dma_addr_t alpha_phy_addr0; + dma_addr_t alpha_phy_addr1; + void *alpha_virt_addr0; + void *alpha_virt_addr1; + uint32_t alpha_mem_len; + uint32_t ipu_ch_irq; + uint32_t cur_ipu_buf; + uint32_t cur_ipu_alpha_buf; + + u32 pseudo_palette[16]; + + bool wait4vsync; + uint32_t waitcnt; + struct semaphore flip_sem; + struct semaphore alpha_flip_sem; + struct completion vsync_complete; +}; + +struct mxcfb_alloc_list { + struct list_head list; + dma_addr_t phy_addr; + void *cpu_addr; + u32 size; +}; + +enum { + BOTH_ON, + SRC_ON, + TGT_ON, + BOTH_OFF +}; + +static bool g_dp_in_use; +LIST_HEAD(fb_alloc_list); +static struct fb_info *mxcfb_info[3]; + +static uint32_t bpp_to_pixfmt(struct fb_info *fbi) +{ + uint32_t pixfmt = 0; + + if (fbi->var.nonstd) + return fbi->var.nonstd; + + switch (fbi->var.bits_per_pixel) { + case 24: + pixfmt = IPU_PIX_FMT_BGR24; + break; + case 32: + pixfmt = IPU_PIX_FMT_BGR32; + break; + case 16: + pixfmt = IPU_PIX_FMT_RGB565; + break; + } + return pixfmt; +} + +static irqreturn_t mxcfb_irq_handler(int irq, void *dev_id); +static int mxcfb_blank(int blank, struct fb_info *info); +static int mxcfb_map_video_memory(struct fb_info *fbi); +static int mxcfb_unmap_video_memory(struct fb_info *fbi); +static int mxcfb_option_setup(struct fb_info *info, char *options); + +/* + * Set fixed framebuffer parameters based on variable settings. + * + * @param info framebuffer information pointer + */ +static int mxcfb_set_fix(struct fb_info *info) +{ + struct fb_fix_screeninfo *fix = &info->fix; + struct fb_var_screeninfo *var = &info->var; + + fix->line_length = var->xres_virtual * var->bits_per_pixel / 8; + + fix->type = FB_TYPE_PACKED_PIXELS; + fix->accel = FB_ACCEL_NONE; + fix->visual = FB_VISUAL_TRUECOLOR; + fix->xpanstep = 1; + fix->ypanstep = 1; + + return 0; +} + +static int _setup_disp_channel1(struct fb_info *fbi) +{ + ipu_channel_params_t params; + struct mxcfb_info *mxc_fbi = (struct mxcfb_info *)fbi->par; + + memset(¶ms, 0, sizeof(params)); + params.mem_dp_bg_sync.di = mxc_fbi->ipu_di; + + /* + * Assuming interlaced means yuv output, below setting also + * valid for mem_dc_sync. FG should have the same vmode as BG. + */ + if (mxc_fbi->ipu_ch == MEM_FG_SYNC) { + struct mxcfb_info *mxc_fbi_tmp; + int i; + + for (i = 0; i < num_registered_fb; i++) { + mxc_fbi_tmp = (struct mxcfb_info *) + (registered_fb[i]->par); + if (mxc_fbi_tmp->ipu_ch == MEM_BG_SYNC) { + fbi->var.vmode = + registered_fb[i]->var.vmode; + mxc_fbi->ipu_di_pix_fmt = + mxc_fbi_tmp->ipu_di_pix_fmt; + break; + } + } + } + if (mxc_fbi->ipu_ch == MEM_DC_SYNC) { + if (fbi->var.vmode & FB_VMODE_INTERLACED) { + params.mem_dc_sync.interlaced = true; + params.mem_dc_sync.out_pixel_fmt = + IPU_PIX_FMT_YUV444; + } else { + if (mxc_fbi->ipu_di_pix_fmt) + params.mem_dc_sync.out_pixel_fmt = mxc_fbi->ipu_di_pix_fmt; + else + params.mem_dc_sync.out_pixel_fmt = IPU_PIX_FMT_RGB666; + } + params.mem_dc_sync.in_pixel_fmt = bpp_to_pixfmt(fbi); + } else { + if (fbi->var.vmode & FB_VMODE_INTERLACED) { + params.mem_dp_bg_sync.interlaced = true; + params.mem_dp_bg_sync.out_pixel_fmt = + IPU_PIX_FMT_YUV444; + } else { + if (mxc_fbi->ipu_di_pix_fmt) + params.mem_dp_bg_sync.out_pixel_fmt = mxc_fbi->ipu_di_pix_fmt; + else + params.mem_dp_bg_sync.out_pixel_fmt = IPU_PIX_FMT_RGB666; + } + params.mem_dp_bg_sync.in_pixel_fmt = bpp_to_pixfmt(fbi); + if (mxc_fbi->alpha_chan_en) + params.mem_dp_bg_sync.alpha_chan_en = true; + } + ipu_init_channel(mxc_fbi->ipu_ch, ¶ms); + + return 0; +} + +static int _setup_disp_channel2(struct fb_info *fbi) +{ + int retval = 0; + struct mxcfb_info *mxc_fbi = (struct mxcfb_info *)fbi->par; + int fb_stride; + + switch (bpp_to_pixfmt(fbi)) { + case IPU_PIX_FMT_YUV420P2: + case IPU_PIX_FMT_YVU420P: + case IPU_PIX_FMT_NV12: + case IPU_PIX_FMT_YUV422P: + case IPU_PIX_FMT_YVU422P: + case IPU_PIX_FMT_YUV420P: + fb_stride = fbi->var.xres_virtual; + break; + default: + fb_stride = fbi->fix.line_length; + } + + mxc_fbi->cur_ipu_buf = 1; + sema_init(&mxc_fbi->flip_sem, 1); + if (mxc_fbi->alpha_chan_en) { + mxc_fbi->cur_ipu_alpha_buf = 1; + sema_init(&mxc_fbi->alpha_flip_sem, 1); + } + fbi->var.xoffset = fbi->var.yoffset = 0; + + retval = ipu_init_channel_buffer(mxc_fbi->ipu_ch, IPU_INPUT_BUFFER, + bpp_to_pixfmt(fbi), + fbi->var.xres, fbi->var.yres, + fb_stride, + IPU_ROTATE_NONE, + fbi->fix.smem_start + + (fbi->fix.line_length * fbi->var.yres), + fbi->fix.smem_start, + 0, 0); + if (retval) { + dev_err(fbi->device, + "ipu_init_channel_buffer error %d\n", retval); + } + + if (mxc_fbi->alpha_chan_en) { + retval = ipu_init_channel_buffer(mxc_fbi->ipu_ch, + IPU_ALPHA_IN_BUFFER, + IPU_PIX_FMT_GENERIC, + fbi->var.xres, fbi->var.yres, + fbi->var.xres, + IPU_ROTATE_NONE, + mxc_fbi->alpha_phy_addr1, + mxc_fbi->alpha_phy_addr0, + 0, 0); + if (retval) { + dev_err(fbi->device, + "ipu_init_channel_buffer error %d\n", retval); + return retval; + } + } + + return retval; +} + +/* + * Set framebuffer parameters and change the operating mode. + * + * @param info framebuffer information pointer + */ +static int mxcfb_set_par(struct fb_info *fbi) +{ + int retval = 0; + u32 mem_len, alpha_mem_len; + ipu_di_signal_cfg_t sig_cfg; + struct mxcfb_info *mxc_fbi = (struct mxcfb_info *)fbi->par; + + dev_dbg(fbi->device, "Reconfiguring framebuffer\n"); + + ipu_disable_irq(mxc_fbi->ipu_ch_irq); + ipu_disable_channel(mxc_fbi->ipu_ch, true); + ipu_uninit_channel(mxc_fbi->ipu_ch); + ipu_clear_irq(mxc_fbi->ipu_ch_irq); + mxcfb_set_fix(fbi); + + mem_len = fbi->var.yres_virtual * fbi->fix.line_length; + if (!fbi->fix.smem_start || (mem_len > fbi->fix.smem_len)) { + if (fbi->fix.smem_start) + mxcfb_unmap_video_memory(fbi); + + if (mxcfb_map_video_memory(fbi) < 0) + return -ENOMEM; + } + if (mxc_fbi->alpha_chan_en) { + alpha_mem_len = fbi->var.xres * fbi->var.yres; + if ((!mxc_fbi->alpha_phy_addr0 && !mxc_fbi->alpha_phy_addr1) || + (alpha_mem_len > mxc_fbi->alpha_mem_len)) { + if (mxc_fbi->alpha_phy_addr0) + dma_free_coherent(fbi->device, + mxc_fbi->alpha_mem_len, + mxc_fbi->alpha_virt_addr0, + mxc_fbi->alpha_phy_addr0); + if (mxc_fbi->alpha_phy_addr1) + dma_free_coherent(fbi->device, + mxc_fbi->alpha_mem_len, + mxc_fbi->alpha_virt_addr1, + mxc_fbi->alpha_phy_addr1); + + mxc_fbi->alpha_virt_addr0 = + dma_alloc_coherent(fbi->device, + alpha_mem_len, + &mxc_fbi->alpha_phy_addr0, + GFP_DMA | GFP_KERNEL); + + mxc_fbi->alpha_virt_addr1 = + dma_alloc_coherent(fbi->device, + alpha_mem_len, + &mxc_fbi->alpha_phy_addr1, + GFP_DMA | GFP_KERNEL); + if (mxc_fbi->alpha_virt_addr0 == NULL || + mxc_fbi->alpha_virt_addr1 == NULL) { + dev_err(fbi->device, "mxcfb: dma alloc for" + " alpha buffer failed.\n"); + if (mxc_fbi->alpha_virt_addr0) + dma_free_coherent(fbi->device, + mxc_fbi->alpha_mem_len, + mxc_fbi->alpha_virt_addr0, + mxc_fbi->alpha_phy_addr0); + if (mxc_fbi->alpha_virt_addr1) + dma_free_coherent(fbi->device, + mxc_fbi->alpha_mem_len, + mxc_fbi->alpha_virt_addr1, + mxc_fbi->alpha_phy_addr1); + return -ENOMEM; + } + mxc_fbi->alpha_mem_len = alpha_mem_len; + } + } + + if (mxc_fbi->next_blank != FB_BLANK_UNBLANK) + return retval; + + _setup_disp_channel1(fbi); + + if (!mxc_fbi->overlay) { + uint32_t out_pixel_fmt; + + memset(&sig_cfg, 0, sizeof(sig_cfg)); + if (fbi->var.vmode & FB_VMODE_INTERLACED) { + sig_cfg.interlaced = true; + out_pixel_fmt = IPU_PIX_FMT_YUV444; + } else { + if (mxc_fbi->ipu_di_pix_fmt) + out_pixel_fmt = mxc_fbi->ipu_di_pix_fmt; + else + out_pixel_fmt = IPU_PIX_FMT_RGB666; + } + if (fbi->var.vmode & FB_VMODE_ODD_FLD_FIRST) /* PAL */ + sig_cfg.odd_field_first = true; + if ((fbi->var.sync & FB_SYNC_EXT) || mxc_fbi->ipu_ext_clk) + sig_cfg.ext_clk = true; + if (fbi->var.sync & FB_SYNC_HOR_HIGH_ACT) + sig_cfg.Hsync_pol = true; + if (fbi->var.sync & FB_SYNC_VERT_HIGH_ACT) + sig_cfg.Vsync_pol = true; + if (!(fbi->var.sync & FB_SYNC_CLK_LAT_FALL)) + sig_cfg.clk_pol = true; + if (fbi->var.sync & FB_SYNC_DATA_INVERT) + sig_cfg.data_pol = true; + if (!(fbi->var.sync & FB_SYNC_OE_LOW_ACT)) + sig_cfg.enable_pol = true; + if (fbi->var.sync & FB_SYNC_CLK_IDLE_EN) + sig_cfg.clkidle_en = true; + + dev_dbg(fbi->device, "pixclock = %ul Hz\n", + (u32) (PICOS2KHZ(fbi->var.pixclock) * 1000UL)); + + if (ipu_init_sync_panel(mxc_fbi->ipu_di, + (PICOS2KHZ(fbi->var.pixclock)) * 1000UL, + fbi->var.xres, fbi->var.yres, + out_pixel_fmt, + fbi->var.left_margin, + fbi->var.hsync_len, + fbi->var.right_margin, + fbi->var.upper_margin, + fbi->var.vsync_len, + fbi->var.lower_margin, + 0, sig_cfg) != 0) { + dev_err(fbi->device, + "mxcfb: Error initializing panel.\n"); + return -EINVAL; + } + + fbi->mode = + (struct fb_videomode *)fb_match_mode(&fbi->var, + &fbi->modelist); + ipu_disp_set_window_pos(mxc_fbi->ipu_ch, 0, 0); + } + + retval = _setup_disp_channel2(fbi); + if (retval) + return retval; + + ipu_enable_channel(mxc_fbi->ipu_ch); + + return retval; +} + +static int _swap_channels(struct fb_info *fbi, + struct fb_info *fbi_to, bool both_on) +{ + int retval, tmp; + ipu_channel_t old_ch; + struct mxcfb_info *mxc_fbi_from = (struct mxcfb_info *)fbi->par; + struct mxcfb_info *mxc_fbi_to = (struct mxcfb_info *)fbi_to->par; + + if (both_on) { + ipu_disable_channel(mxc_fbi_to->ipu_ch, true); + ipu_uninit_channel(mxc_fbi_to->ipu_ch); + } + + /* switch the mxc fbi parameters */ + old_ch = mxc_fbi_from->ipu_ch; + mxc_fbi_from->ipu_ch = mxc_fbi_to->ipu_ch; + mxc_fbi_to->ipu_ch = old_ch; + tmp = mxc_fbi_from->ipu_ch_irq; + mxc_fbi_from->ipu_ch_irq = mxc_fbi_to->ipu_ch_irq; + mxc_fbi_to->ipu_ch_irq = tmp; + + _setup_disp_channel1(fbi); + retval = _setup_disp_channel2(fbi); + if (retval) + return retval; + + /* switch between dp and dc, disable old idmac, enable new idmac */ + retval = ipu_swap_channel(old_ch, mxc_fbi_from->ipu_ch); + ipu_uninit_channel(old_ch); + + if (both_on) { + _setup_disp_channel1(fbi_to); + retval = _setup_disp_channel2(fbi_to); + if (retval) + return retval; + ipu_enable_channel(mxc_fbi_to->ipu_ch); + } + + return retval; +} + +static int swap_channels(struct fb_info *fbi) +{ + int i; + int swap_mode; + ipu_channel_t ch_to; + struct mxcfb_info *mxc_fbi_from = (struct mxcfb_info *)fbi->par; + struct fb_info *fbi_to = NULL; + struct mxcfb_info *mxc_fbi_to; + + /* what's the target channel? */ + if (mxc_fbi_from->ipu_ch == MEM_BG_SYNC) + ch_to = MEM_DC_SYNC; + else + ch_to = MEM_BG_SYNC; + + for (i = 0; i < num_registered_fb; i++) { + mxc_fbi_to = + (struct mxcfb_info *)mxcfb_info[i]->par; + if (mxc_fbi_to->ipu_ch == ch_to) { + fbi_to = mxcfb_info[i]; + break; + } + } + if (fbi_to == NULL) + return -1; + + ipu_clear_irq(mxc_fbi_from->ipu_ch_irq); + ipu_clear_irq(mxc_fbi_to->ipu_ch_irq); + ipu_free_irq(mxc_fbi_from->ipu_ch_irq, fbi); + ipu_free_irq(mxc_fbi_to->ipu_ch_irq, fbi_to); + + if (mxc_fbi_from->cur_blank == FB_BLANK_UNBLANK) { + if (mxc_fbi_to->cur_blank == FB_BLANK_UNBLANK) + swap_mode = BOTH_ON; + else + swap_mode = SRC_ON; + } else { + if (mxc_fbi_to->cur_blank == FB_BLANK_UNBLANK) + swap_mode = TGT_ON; + else + swap_mode = BOTH_OFF; + } + + /* tvout di-1: for DC use UYVY, for DP use RGB */ + if (mxc_fbi_from->ipu_di == 1 && ch_to == MEM_DC_SYNC) { + fbi->var.bits_per_pixel = 16; + fbi->var.nonstd = IPU_PIX_FMT_UYVY; + } else if (mxc_fbi_from->ipu_di == 1 && ch_to == MEM_BG_SYNC) { + fbi->var.nonstd = 0; + } else if (mxc_fbi_from->ipu_di == 0 && ch_to == MEM_DC_SYNC) { + fbi_to->var.nonstd = 0; + } else if (mxc_fbi_from->ipu_di == 0 && ch_to == MEM_BG_SYNC) { + fbi->var.bits_per_pixel = 16; + fbi->var.nonstd = IPU_PIX_FMT_UYVY; + } + + switch (swap_mode) { + case BOTH_ON: + /* disable target->switch src->enable target */ + _swap_channels(fbi, fbi_to, true); + break; + case SRC_ON: + /* just switch src */ + _swap_channels(fbi, fbi_to, false); + break; + case TGT_ON: + /* just switch target */ + _swap_channels(fbi_to, fbi, false); + break; + case BOTH_OFF: + /* switch directly, no more need to do */ + mxc_fbi_to->ipu_ch = mxc_fbi_from->ipu_ch; + mxc_fbi_from->ipu_ch = ch_to; + i = mxc_fbi_from->ipu_ch_irq; + mxc_fbi_from->ipu_ch_irq = mxc_fbi_to->ipu_ch_irq; + mxc_fbi_to->ipu_ch_irq = i; + break; + default: + break; + } + + if (ipu_request_irq(mxc_fbi_from->ipu_ch_irq, mxcfb_irq_handler, 0, + MXCFB_NAME, fbi) != 0) { + dev_err(fbi->device, "Error registering irq %d\n", + mxc_fbi_from->ipu_ch_irq); + return -EBUSY; + } + ipu_disable_irq(mxc_fbi_from->ipu_ch_irq); + if (ipu_request_irq(mxc_fbi_to->ipu_ch_irq, mxcfb_irq_handler, 0, + MXCFB_NAME, fbi_to) != 0) { + dev_err(fbi_to->device, "Error registering irq %d\n", + mxc_fbi_to->ipu_ch_irq); + return -EBUSY; + } + ipu_disable_irq(mxc_fbi_to->ipu_ch_irq); + + return 0; +} + +/* + * Check framebuffer variable parameters and adjust to valid values. + * + * @param var framebuffer variable parameters + * + * @param info framebuffer information pointer + */ +static int mxcfb_check_var(struct fb_var_screeninfo *var, struct fb_info *info) +{ + u32 vtotal; + u32 htotal; + struct mxcfb_info *mxc_fbi = (struct mxcfb_info *)info->par; + + /* fg should not bigger than bg */ + if (mxc_fbi->ipu_ch == MEM_FG_SYNC) { + struct fb_info *fbi_tmp; + struct mxcfb_info *mxc_fbi_tmp; + int i, bg_xres, bg_yres; + int16_t pos_x, pos_y; + + bg_xres = var->xres; + bg_yres = var->yres; + + for (i = 0; i < num_registered_fb; i++) { + fbi_tmp = registered_fb[i]; + mxc_fbi_tmp = (struct mxcfb_info *) + (fbi_tmp->par); + if (mxc_fbi_tmp->ipu_ch == MEM_BG_SYNC) { + bg_xres = fbi_tmp->var.xres; + bg_yres = fbi_tmp->var.yres; + break; + } + } + + ipu_disp_get_window_pos(mxc_fbi->ipu_ch, &pos_x, &pos_y); + + if ((var->xres + pos_x) > bg_xres) + var->xres = bg_xres - pos_x; + if ((var->yres + pos_y) > bg_yres) + var->yres = bg_yres - pos_y; + } + + if (var->xres_virtual < var->xres) + var->xres_virtual = var->xres; + if (var->yres_virtual < var->yres) + var->yres_virtual = var->yres; + + if ((var->bits_per_pixel != 32) && (var->bits_per_pixel != 24) && + (var->bits_per_pixel != 16) && (var->bits_per_pixel != 12) && + (var->bits_per_pixel != 8)) + var->bits_per_pixel = 16; + + switch (var->bits_per_pixel) { + case 8: + var->red.length = 3; + var->red.offset = 5; + var->red.msb_right = 0; + + var->green.length = 3; + var->green.offset = 2; + var->green.msb_right = 0; + + var->blue.length = 2; + var->blue.offset = 0; + var->blue.msb_right = 0; + + var->transp.length = 0; + var->transp.offset = 0; + var->transp.msb_right = 0; + break; + case 16: + var->red.length = 5; + var->red.offset = 11; + var->red.msb_right = 0; + + var->green.length = 6; + var->green.offset = 5; + var->green.msb_right = 0; + + var->blue.length = 5; + var->blue.offset = 0; + var->blue.msb_right = 0; + + var->transp.length = 0; + var->transp.offset = 0; + var->transp.msb_right = 0; + break; + case 24: + var->red.length = 8; + var->red.offset = 16; + var->red.msb_right = 0; + + var->green.length = 8; + var->green.offset = 8; + var->green.msb_right = 0; + + var->blue.length = 8; + var->blue.offset = 0; + var->blue.msb_right = 0; + + var->transp.length = 0; + var->transp.offset = 0; + var->transp.msb_right = 0; + break; + case 32: + var->red.length = 8; + var->red.offset = 16; + var->red.msb_right = 0; + + var->green.length = 8; + var->green.offset = 8; + var->green.msb_right = 0; + + var->blue.length = 8; + var->blue.offset = 0; + var->blue.msb_right = 0; + + var->transp.length = 8; + var->transp.offset = 24; + var->transp.msb_right = 0; + break; + } + + if (var->pixclock < 1000) { + htotal = var->xres + var->right_margin + var->hsync_len + + var->left_margin; + vtotal = var->yres + var->lower_margin + var->vsync_len + + var->upper_margin; + var->pixclock = (vtotal * htotal * 6UL) / 100UL; + var->pixclock = KHZ2PICOS(var->pixclock); + dev_dbg(info->device, + "pixclock set for 60Hz refresh = %u ps\n", + var->pixclock); + } + + var->height = -1; + var->width = -1; + var->grayscale = 0; + + return 0; +} + +static inline u_int _chan_to_field(u_int chan, struct fb_bitfield *bf) +{ + chan &= 0xffff; + chan >>= 16 - bf->length; + return chan << bf->offset; +} + +static int mxcfb_setcolreg(u_int regno, u_int red, u_int green, u_int blue, + u_int trans, struct fb_info *fbi) +{ + unsigned int val; + int ret = 1; + + /* + * If greyscale is true, then we convert the RGB value + * to greyscale no matter what visual we are using. + */ + if (fbi->var.grayscale) + red = green = blue = (19595 * red + 38470 * green + + 7471 * blue) >> 16; + switch (fbi->fix.visual) { + case FB_VISUAL_TRUECOLOR: + /* + * 16-bit True Colour. We encode the RGB value + * according to the RGB bitfield information. + */ + if (regno < 16) { + u32 *pal = fbi->pseudo_palette; + + val = _chan_to_field(red, &fbi->var.red); + val |= _chan_to_field(green, &fbi->var.green); + val |= _chan_to_field(blue, &fbi->var.blue); + + pal[regno] = val; + ret = 0; + } + break; + + case FB_VISUAL_STATIC_PSEUDOCOLOR: + case FB_VISUAL_PSEUDOCOLOR: + break; + } + + return ret; +} + +/* + * Function to handle custom ioctls for MXC framebuffer. + * + * @param inode inode struct + * + * @param file file struct + * + * @param cmd Ioctl command to handle + * + * @param arg User pointer to command arguments + * + * @param fbi framebuffer information pointer + */ +static int mxcfb_ioctl(struct fb_info *fbi, unsigned int cmd, unsigned long arg) +{ + int retval = 0; + int __user *argp = (void __user *)arg; + struct mxcfb_info *mxc_fbi = (struct mxcfb_info *)fbi->par; + + switch (cmd) { + case MXCFB_SET_GBL_ALPHA: + { + struct mxcfb_gbl_alpha ga; + + if (copy_from_user(&ga, (void *)arg, sizeof(ga))) { + retval = -EFAULT; + break; + } + + if (ipu_disp_set_global_alpha(mxc_fbi->ipu_ch, + (bool)ga.enable, + ga.alpha)) { + retval = -EINVAL; + break; + } + + if (ga.enable) + mxc_fbi->alpha_chan_en = false; + + if (ga.enable) + dev_dbg(fbi->device, + "Set global alpha of %s to %d\n", + fbi->fix.id, ga.alpha); + break; + } + case MXCFB_SET_LOC_ALPHA: + { + struct mxcfb_loc_alpha la; + int i; + char *video_plane_idstr = ""; + + if (copy_from_user(&la, (void *)arg, sizeof(la))) { + retval = -EFAULT; + break; + } + + if (ipu_disp_set_global_alpha(mxc_fbi->ipu_ch, + !(bool)la.enable, 0)) { + retval = -EINVAL; + break; + } + + if (la.enable && !la.alpha_in_pixel) { + mxc_fbi->alpha_chan_en = true; + + if (mxc_fbi->ipu_ch == MEM_FG_SYNC) + video_plane_idstr = "DISP3 BG"; + else if (mxc_fbi->ipu_ch == MEM_BG_SYNC) + video_plane_idstr = "DISP3 FG"; + + for (i = 0; i < num_registered_fb; i++) { + char *idstr = registered_fb[i]->fix.id; + if (strcmp(idstr, video_plane_idstr) == 0) { + ((struct mxcfb_info *)(registered_fb[i]->par))->alpha_chan_en = false; + break; + } + } + } else + mxc_fbi->alpha_chan_en = false; + + mxcfb_set_par(fbi); + + la.alpha_phy_addr0 = mxc_fbi->alpha_phy_addr0; + la.alpha_phy_addr1 = mxc_fbi->alpha_phy_addr1; + if (copy_to_user((void *)arg, &la, sizeof(la))) { + retval = -EFAULT; + break; + } + + if (la.enable) + dev_dbg(fbi->device, + "Enable DP local alpha for %s\n", + fbi->fix.id); + break; + } + case MXCFB_SET_LOC_ALP_BUF: + { + unsigned long base; + uint32_t ipu_alp_ch_irq; + + if (!(((mxc_fbi->ipu_ch == MEM_FG_SYNC) || + (mxc_fbi->ipu_ch == MEM_BG_SYNC)) && + (mxc_fbi->alpha_chan_en))) { + dev_err(fbi->device, + "Should use background or overlay " + "framebuffer to set the alpha buffer " + "number\n"); + return -EINVAL; + } + + if (get_user(base, argp)) + return -EFAULT; + + if (base != mxc_fbi->alpha_phy_addr0 && + base != mxc_fbi->alpha_phy_addr1) { + dev_err(fbi->device, + "Wrong alpha buffer physical address " + "%lu\n", base); + return -EINVAL; + } + + if (mxc_fbi->ipu_ch == MEM_FG_SYNC) + ipu_alp_ch_irq = IPU_IRQ_FG_ALPHA_SYNC_EOF; + else + ipu_alp_ch_irq = IPU_IRQ_BG_ALPHA_SYNC_EOF; + + down(&mxc_fbi->alpha_flip_sem); + + mxc_fbi->cur_ipu_alpha_buf = + !mxc_fbi->cur_ipu_alpha_buf; + if (ipu_update_channel_buffer(mxc_fbi->ipu_ch, + IPU_ALPHA_IN_BUFFER, + mxc_fbi-> + cur_ipu_alpha_buf, + base) == 0) { + ipu_select_buffer(mxc_fbi->ipu_ch, + IPU_ALPHA_IN_BUFFER, + mxc_fbi->cur_ipu_alpha_buf); + ipu_clear_irq(ipu_alp_ch_irq); + ipu_enable_irq(ipu_alp_ch_irq); + } else { + dev_err(fbi->device, + "Error updating %s SDC alpha buf %d " + "to address=0x%08lX\n", + fbi->fix.id, + mxc_fbi->cur_ipu_alpha_buf, base); + } + break; + } + case MXCFB_SET_CLR_KEY: + { + struct mxcfb_color_key key; + if (copy_from_user(&key, (void *)arg, sizeof(key))) { + retval = -EFAULT; + break; + } + retval = ipu_disp_set_color_key(mxc_fbi->ipu_ch, + key.enable, + key.color_key); + dev_dbg(fbi->device, "Set color key to 0x%08X\n", + key.color_key); + break; + } + case MXCFB_SET_GAMMA: + { + struct mxcfb_gamma gamma; + if (copy_from_user(&gamma, (void *)arg, sizeof(gamma))) { + retval = -EFAULT; + break; + } + retval = ipu_disp_set_gamma_correction(mxc_fbi->ipu_ch, + gamma.enable, + gamma.constk, + gamma.slopek); + break; + } + case MXCFB_WAIT_FOR_VSYNC: + { + if (mxc_fbi->ipu_ch == MEM_FG_SYNC) { + struct mxcfb_info *bg_mxcfbi = NULL; + int i; + for (i = 0; i < num_registered_fb; i++) { + bg_mxcfbi = + ((struct mxcfb_info *)(registered_fb[i]->par)); + + if (bg_mxcfbi->ipu_ch == MEM_BG_SYNC) + break; + } + if (bg_mxcfbi->cur_blank != FB_BLANK_UNBLANK) { + retval = -EINVAL; + break; + } + } + if (mxc_fbi->cur_blank != FB_BLANK_UNBLANK) { + retval = -EINVAL; + break; + } + + init_completion(&mxc_fbi->vsync_complete); + + ipu_clear_irq(mxc_fbi->ipu_ch_irq); + mxc_fbi->wait4vsync = 1; + ipu_enable_irq(mxc_fbi->ipu_ch_irq); + retval = wait_for_completion_interruptible_timeout( + &mxc_fbi->vsync_complete, 1 * HZ); + if (retval == 0) { + dev_err(fbi->device, + "MXCFB_WAIT_FOR_VSYNC: timeout %d\n", + retval); + mxc_fbi->wait4vsync = 0; + retval = -ETIME; + } else if (retval > 0) { + retval = 0; + } + break; + } + case FBIO_ALLOC: + { + int size; + struct mxcfb_alloc_list *mem; + + mem = kzalloc(sizeof(*mem), GFP_KERNEL); + if (mem == NULL) + return -ENOMEM; + + if (get_user(size, argp)) + return -EFAULT; + + mem->size = PAGE_ALIGN(size); + + mem->cpu_addr = dma_alloc_coherent(fbi->device, size, + &mem->phy_addr, + GFP_DMA); + if (mem->cpu_addr == NULL) { + kfree(mem); + return -ENOMEM; + } + + list_add(&mem->list, &fb_alloc_list); + + dev_dbg(fbi->device, "allocated %d bytes @ 0x%08X\n", + mem->size, mem->phy_addr); + + if (put_user(mem->phy_addr, argp)) + return -EFAULT; + + break; + } + case FBIO_FREE: + { + unsigned long offset; + struct mxcfb_alloc_list *mem; + + if (get_user(offset, argp)) + return -EFAULT; + + retval = -EINVAL; + list_for_each_entry(mem, &fb_alloc_list, list) { + if (mem->phy_addr == offset) { + list_del(&mem->list); + dma_free_coherent(fbi->device, + mem->size, + mem->cpu_addr, + mem->phy_addr); + kfree(mem); + retval = 0; + break; + } + } + + break; + } + case MXCFB_SET_OVERLAY_POS: + { + struct mxcfb_pos pos; + struct fb_info *bg_fbi = NULL; + struct mxcfb_info *bg_mxcfbi = NULL; + int i; + + if (mxc_fbi->ipu_ch != MEM_FG_SYNC) { + dev_err(fbi->device, "Should use the overlay " + "framebuffer to set the position of " + "the overlay window\n"); + retval = -EINVAL; + break; + } + + if (copy_from_user(&pos, (void *)arg, sizeof(pos))) { + retval = -EFAULT; + break; + } + + for (i = 0; i < num_registered_fb; i++) { + bg_mxcfbi = + ((struct mxcfb_info *)(registered_fb[i]->par)); + + if (bg_mxcfbi->ipu_ch == MEM_BG_SYNC) { + bg_fbi = registered_fb[i]; + break; + } + } + + if (bg_fbi == NULL) { + dev_err(fbi->device, "Cannot find the " + "background framebuffer\n"); + retval = -ENOENT; + break; + } + + if (fbi->var.xres + pos.x > bg_fbi->var.xres) { + if (bg_fbi->var.xres < fbi->var.xres) + pos.x = 0; + else + pos.x = bg_fbi->var.xres - fbi->var.xres; + } + if (fbi->var.yres + pos.y > bg_fbi->var.yres) { + if (bg_fbi->var.yres < fbi->var.yres) + pos.y = 0; + else + pos.y = bg_fbi->var.yres - fbi->var.yres; + } + + retval = ipu_disp_set_window_pos(mxc_fbi->ipu_ch, + pos.x, pos.y); + + if (copy_to_user((void *)arg, &pos, sizeof(pos))) { + retval = -EFAULT; + break; + } + break; + } + case MXCFB_GET_FB_IPU_CHAN: + { + struct mxcfb_info *mxc_fbi = + (struct mxcfb_info *)fbi->par; + + if (put_user(mxc_fbi->ipu_ch, argp)) + return -EFAULT; + break; + } + case MXCFB_GET_DIFMT: + { + struct mxcfb_info *mxc_fbi = + (struct mxcfb_info *)fbi->par; + + if (put_user(mxc_fbi->ipu_di_pix_fmt, argp)) + return -EFAULT; + break; + } + case MXCFB_GET_FB_IPU_DI: + { + struct mxcfb_info *mxc_fbi = + (struct mxcfb_info *)fbi->par; + + if (put_user(mxc_fbi->ipu_di, argp)) + return -EFAULT; + break; + } + default: + retval = -EINVAL; + } + return retval; +} + +/* + * mxcfb_blank(): + * Blank the display. + */ +static int mxcfb_blank(int blank, struct fb_info *info) +{ + struct mxcfb_info *mxc_fbi = (struct mxcfb_info *)info->par; + + dev_dbg(info->device, "blank = %d\n", blank); + + if (mxc_fbi->cur_blank == blank) + return 0; + + mxc_fbi->next_blank = blank; + + switch (blank) { + case FB_BLANK_POWERDOWN: + case FB_BLANK_VSYNC_SUSPEND: + case FB_BLANK_HSYNC_SUSPEND: + case FB_BLANK_NORMAL: + ipu_disable_channel(mxc_fbi->ipu_ch, true); + ipu_uninit_channel(mxc_fbi->ipu_ch); + break; + case FB_BLANK_UNBLANK: + mxcfb_set_par(info); + break; + } + mxc_fbi->cur_blank = blank; + return 0; +} + +/* + * Pan or Wrap the Display + * + * This call looks only at xoffset, yoffset and the FB_VMODE_YWRAP flag + * + * @param var Variable screen buffer information + * @param info Framebuffer information pointer + */ +static int +mxcfb_pan_display(struct fb_var_screeninfo *var, struct fb_info *info) +{ + struct mxcfb_info *mxc_fbi = (struct mxcfb_info *)info->par, + *mxc_graphic_fbi = NULL; + u_int y_bottom; + unsigned long base, active_alpha_phy_addr = 0; + bool loc_alpha_en = false; + int i = 0; + + if (var->xoffset > 0) { + dev_dbg(info->device, "x panning not supported\n"); + return -EINVAL; + } + + if ((info->var.xoffset == var->xoffset) && + (info->var.yoffset == var->yoffset)) + return 0; /* No change, do nothing */ + + /* no pan display during fb blank */ + if (mxc_fbi->ipu_ch == MEM_FG_SYNC) { + struct mxcfb_info *bg_mxcfbi = NULL; + int j; + for (j = 0; j < num_registered_fb; j++) { + bg_mxcfbi = + ((struct mxcfb_info *)(registered_fb[j]->par)); + + if (bg_mxcfbi->ipu_ch == MEM_BG_SYNC) + break; + } + if (bg_mxcfbi->cur_blank != FB_BLANK_UNBLANK) + return -EINVAL; + } + if (mxc_fbi->cur_blank != FB_BLANK_UNBLANK) + return -EINVAL; + + y_bottom = var->yoffset; + + if (!(var->vmode & FB_VMODE_YWRAP)) + y_bottom += var->yres; + + if (y_bottom > info->var.yres_virtual) + return -EINVAL; + + base = (var->yoffset * var->xres_virtual + var->xoffset); + base = (var->bits_per_pixel) * base / 8; + base += info->fix.smem_start; + + /* Check if DP local alpha is enabled and find the graphic fb */ + if (mxc_fbi->ipu_ch == MEM_BG_SYNC || mxc_fbi->ipu_ch == MEM_FG_SYNC) { + for (i = 0; i < num_registered_fb; i++) { + char *idstr = registered_fb[i]->fix.id; + if ((strcmp(idstr, "DISP3 BG") == 0 || + strcmp(idstr, "DISP3 FG") == 0) && + ((struct mxcfb_info *) + (registered_fb[i]->par))->alpha_chan_en) { + loc_alpha_en = true; + mxc_graphic_fbi = (struct mxcfb_info *) + (registered_fb[i]->par); + active_alpha_phy_addr = mxc_fbi->cur_ipu_buf ? + mxc_graphic_fbi->alpha_phy_addr1 : + mxc_graphic_fbi->alpha_phy_addr0; + dev_dbg(info->device, "Updating SDC graphic " + "buf %d address=0x%08lX\n", + mxc_fbi->cur_ipu_buf, + active_alpha_phy_addr); + break; + } + } + } + + down(&mxc_fbi->flip_sem); + + mxc_fbi->cur_ipu_buf = !mxc_fbi->cur_ipu_buf; + + dev_dbg(info->device, "Updating SDC %s buf %d address=0x%08lX\n", + info->fix.id, mxc_fbi->cur_ipu_buf, base); + + if (ipu_update_channel_buffer(mxc_fbi->ipu_ch, IPU_INPUT_BUFFER, + mxc_fbi->cur_ipu_buf, base) == 0) { + /* Update the DP local alpha buffer only for graphic plane */ + if (loc_alpha_en && mxc_graphic_fbi == mxc_fbi && + ipu_update_channel_buffer(mxc_graphic_fbi->ipu_ch, + IPU_ALPHA_IN_BUFFER, + mxc_fbi->cur_ipu_buf, + active_alpha_phy_addr) == 0) { + ipu_select_buffer(mxc_graphic_fbi->ipu_ch, + IPU_ALPHA_IN_BUFFER, + mxc_fbi->cur_ipu_buf); + } + + ipu_select_buffer(mxc_fbi->ipu_ch, IPU_INPUT_BUFFER, + mxc_fbi->cur_ipu_buf); + ipu_clear_irq(mxc_fbi->ipu_ch_irq); + ipu_enable_irq(mxc_fbi->ipu_ch_irq); + } else { + dev_err(info->device, + "Error updating SDC buf %d to address=0x%08lX\n", + mxc_fbi->cur_ipu_buf, base); + mxc_fbi->cur_ipu_buf = !mxc_fbi->cur_ipu_buf; + ipu_clear_irq(mxc_fbi->ipu_ch_irq); + ipu_enable_irq(mxc_fbi->ipu_ch_irq); + return -EBUSY; + } + + dev_dbg(info->device, "Update complete\n"); + + info->var.xoffset = var->xoffset; + info->var.yoffset = var->yoffset; + + if (var->vmode & FB_VMODE_YWRAP) + info->var.vmode |= FB_VMODE_YWRAP; + else + info->var.vmode &= ~FB_VMODE_YWRAP; + + return 0; +} + +/* + * Function to handle custom mmap for MXC framebuffer. + * + * @param fbi framebuffer information pointer + * + * @param vma Pointer to vm_area_struct + */ +static int mxcfb_mmap(struct fb_info *fbi, struct vm_area_struct *vma) +{ + bool found = false; + u32 len; + unsigned long offset = vma->vm_pgoff << PAGE_SHIFT; + struct mxcfb_alloc_list *mem; + struct mxcfb_info *mxc_fbi = (struct mxcfb_info *)fbi->par; + + if (offset < fbi->fix.smem_len) { + /* mapping framebuffer memory */ + len = fbi->fix.smem_len - offset; + vma->vm_pgoff = (fbi->fix.smem_start + offset) >> PAGE_SHIFT; + } else if ((vma->vm_pgoff == + (mxc_fbi->alpha_phy_addr0 >> PAGE_SHIFT)) || + (vma->vm_pgoff == + (mxc_fbi->alpha_phy_addr1 >> PAGE_SHIFT))) { + len = mxc_fbi->alpha_mem_len; + } else { + list_for_each_entry(mem, &fb_alloc_list, list) { + if (offset == mem->phy_addr) { + found = true; + len = mem->size; + break; + } + } + if (!found) + return -EINVAL; + } + + len = PAGE_ALIGN(len); + if (vma->vm_end - vma->vm_start > len) + return -EINVAL; + + /* make buffers bufferable */ + vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot); + + vma->vm_flags |= VM_IO | VM_RESERVED; + + if (remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff, + vma->vm_end - vma->vm_start, vma->vm_page_prot)) { + dev_dbg(fbi->device, "mmap remap_pfn_range failed\n"); + return -ENOBUFS; + } + + return 0; +} + +/*! + * This structure contains the pointers to the control functions that are + * invoked by the core framebuffer driver to perform operations like + * blitting, rectangle filling, copy regions and cursor definition. + */ +static struct fb_ops mxcfb_ops = { + .owner = THIS_MODULE, + .fb_set_par = mxcfb_set_par, + .fb_check_var = mxcfb_check_var, + .fb_setcolreg = mxcfb_setcolreg, + .fb_pan_display = mxcfb_pan_display, + .fb_ioctl = mxcfb_ioctl, + .fb_mmap = mxcfb_mmap, + .fb_fillrect = cfb_fillrect, + .fb_copyarea = cfb_copyarea, + .fb_imageblit = cfb_imageblit, + .fb_blank = mxcfb_blank, +}; + +static irqreturn_t mxcfb_irq_handler(int irq, void *dev_id) +{ + struct fb_info *fbi = dev_id; + struct mxcfb_info *mxc_fbi = fbi->par; + + if (mxc_fbi->wait4vsync) { + complete(&mxc_fbi->vsync_complete); + ipu_disable_irq(irq); + mxc_fbi->wait4vsync = 0; + } else { + if (!ipu_check_buffer_busy(mxc_fbi->ipu_ch, + IPU_INPUT_BUFFER, mxc_fbi->cur_ipu_buf) + || (mxc_fbi->waitcnt > 2)) { + /* + * This interrupt come after pan display select + * cur_ipu_buf buffer, this buffer should become + * idle after show. If it keep busy, clear it manually. + */ + if (mxc_fbi->waitcnt > 2) + ipu_clear_buffer_ready(mxc_fbi->ipu_ch, + IPU_INPUT_BUFFER, + mxc_fbi->cur_ipu_buf); + up(&mxc_fbi->flip_sem); + ipu_disable_irq(irq); + mxc_fbi->waitcnt = 0; + } else + mxc_fbi->waitcnt++; + } + return IRQ_HANDLED; +} + +static irqreturn_t mxcfb_alpha_irq_handler(int irq, void *dev_id) +{ + struct fb_info *fbi = dev_id; + struct mxcfb_info *mxc_fbi = fbi->par; + + up(&mxc_fbi->alpha_flip_sem); + ipu_disable_irq(irq); + return IRQ_HANDLED; +} + +/* + * Suspends the framebuffer and blanks the screen. Power management support + */ +static int mxcfb_suspend(struct platform_device *pdev, pm_message_t state) +{ + struct fb_info *fbi = platform_get_drvdata(pdev); + struct mxcfb_info *mxc_fbi = (struct mxcfb_info *)fbi->par; + int saved_blank; +#ifdef CONFIG_FB_MXC_LOW_PWR_DISPLAY + void *fbmem; +#endif + + acquire_console_sem(); + fb_set_suspend(fbi, 1); + saved_blank = mxc_fbi->cur_blank; + mxcfb_blank(FB_BLANK_POWERDOWN, fbi); + mxc_fbi->next_blank = saved_blank; + release_console_sem(); + + return 0; +} + +/* + * Resumes the framebuffer and unblanks the screen. Power management support + */ +static int mxcfb_resume(struct platform_device *pdev) +{ + struct fb_info *fbi = platform_get_drvdata(pdev); + struct mxcfb_info *mxc_fbi = (struct mxcfb_info *)fbi->par; + + acquire_console_sem(); + mxcfb_blank(mxc_fbi->next_blank, fbi); + fb_set_suspend(fbi, 0); + release_console_sem(); + + return 0; +} + +/* + * Main framebuffer functions + */ + +/*! + * Allocates the DRAM memory for the frame buffer. This buffer is remapped + * into a non-cached, non-buffered, memory region to allow palette and pixel + * writes to occur without flushing the cache. Once this area is remapped, + * all virtual memory access to the video memory should occur at the new region. + * + * @param fbi framebuffer information pointer + * + * @return Error code indicating success or failure + */ +static int mxcfb_map_video_memory(struct fb_info *fbi) +{ + if (fbi->fix.smem_len < fbi->var.yres_virtual * fbi->fix.line_length) + fbi->fix.smem_len = fbi->var.yres_virtual * + fbi->fix.line_length; + + fbi->screen_base = dma_alloc_writecombine(fbi->device, + fbi->fix.smem_len, + (dma_addr_t *)&fbi->fix.smem_start, + GFP_DMA); + if (fbi->screen_base == 0) { + dev_err(fbi->device, "Unable to allocate framebuffer memory\n"); + fbi->fix.smem_len = 0; + fbi->fix.smem_start = 0; + return -EBUSY; + } + + dev_dbg(fbi->device, "allocated fb @ paddr=0x%08X, size=%d.\n", + (uint32_t) fbi->fix.smem_start, fbi->fix.smem_len); + + fbi->screen_size = fbi->fix.smem_len; + + /* Clear the screen */ + memset((char *)fbi->screen_base, 0, fbi->fix.smem_len); + + return 0; +} + +/*! + * De-allocates the DRAM memory for the frame buffer. + * + * @param fbi framebuffer information pointer + * + * @return Error code indicating success or failure + */ +static int mxcfb_unmap_video_memory(struct fb_info *fbi) +{ + dma_free_writecombine(fbi->device, fbi->fix.smem_len, + fbi->screen_base, fbi->fix.smem_start); + fbi->screen_base = 0; + fbi->fix.smem_start = 0; + fbi->fix.smem_len = 0; + return 0; +} + +/*! + * Initializes the framebuffer information pointer. After allocating + * sufficient memory for the framebuffer structure, the fields are + * filled with custom information passed in from the configurable + * structures. This includes information such as bits per pixel, + * color maps, screen width/height and RGBA offsets. + * + * @return Framebuffer structure initialized with our information + */ +static struct fb_info *mxcfb_init_fbinfo(struct device *dev, struct fb_ops *ops) +{ + struct fb_info *fbi; + struct mxcfb_info *mxcfbi; + + /* + * Allocate sufficient memory for the fb structure + */ + fbi = framebuffer_alloc(sizeof(struct mxcfb_info), dev); + if (!fbi) + return NULL; + + mxcfbi = (struct mxcfb_info *)fbi->par; + + fbi->var.activate = FB_ACTIVATE_NOW; + + fbi->fbops = ops; + fbi->flags = FBINFO_FLAG_DEFAULT; + fbi->pseudo_palette = mxcfbi->pseudo_palette; + + /* + * Allocate colormap + */ + fb_alloc_cmap(&fbi->cmap, 16, 0); + + return fbi; +} + +static ssize_t show_disp_chan(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct fb_info *info = dev_get_drvdata(dev); + struct mxcfb_info *mxcfbi = (struct mxcfb_info *)info->par; + + if (mxcfbi->ipu_ch == MEM_BG_SYNC) + return sprintf(buf, "2-layer-fb-bg\n"); + else if (mxcfbi->ipu_ch == MEM_FG_SYNC) + return sprintf(buf, "2-layer-fb-fg\n"); + else if (mxcfbi->ipu_ch == MEM_DC_SYNC) + return sprintf(buf, "1-layer-fb\n"); + else + return sprintf(buf, "err: no display chan\n"); +} + +static ssize_t swap_disp_chan(struct device *dev, + struct device_attribute *attr, + const char *buf, size_t count) +{ + struct fb_info *info = dev_get_drvdata(dev); + struct mxcfb_info *mxcfbi = (struct mxcfb_info *)info->par; + struct mxcfb_info *fg_mxcfbi = NULL; + + acquire_console_sem(); + /* swap only happen between DP-BG and DC, while DP-FG disable */ + if (((mxcfbi->ipu_ch == MEM_BG_SYNC) && + (strstr(buf, "1-layer-fb") != NULL)) || + ((mxcfbi->ipu_ch == MEM_DC_SYNC) && + (strstr(buf, "2-layer-fb-bg") != NULL))) { + int i; + + for (i = 0; i < num_registered_fb; i++) { + fg_mxcfbi = + (struct mxcfb_info *)mxcfb_info[i]->par; + if (fg_mxcfbi->ipu_ch == MEM_FG_SYNC) + break; + else + fg_mxcfbi = NULL; + } + if (!fg_mxcfbi || + fg_mxcfbi->cur_blank == FB_BLANK_UNBLANK) { + dev_err(dev, + "Can not switch while fb2(fb-fg) is on.\n"); + release_console_sem(); + return count; + } + + if (swap_channels(info) < 0) + dev_err(dev, "Swap display channel failed.\n"); + } + + release_console_sem(); + return count; +} +DEVICE_ATTR(fsl_disp_property, 644, show_disp_chan, swap_disp_chan); + +/*! + * Probe routine for the framebuffer driver. It is called during the + * driver binding process. The following functions are performed in + * this routine: Framebuffer initialization, Memory allocation and + * mapping, Framebuffer registration, IPU initialization. + * + * @return Appropriate error code to the kernel common code + */ +static int mxcfb_probe(struct platform_device *pdev) +{ + struct fb_info *fbi; + struct mxcfb_info *mxcfbi; + struct mxc_fb_platform_data *plat_data = pdev->dev.platform_data; + struct resource *res; + char *options; + char name[] = "mxcdi0fb"; + int ret = 0; + + /* + * Initialize FB structures + */ + fbi = mxcfb_init_fbinfo(&pdev->dev, &mxcfb_ops); + if (!fbi) { + ret = -ENOMEM; + goto err0; + } + mxcfbi = (struct mxcfb_info *)fbi->par; + + name[5] += pdev->id; + if (fb_get_options(name, &options)) + return -ENODEV; + + if (options) + mxcfb_option_setup(fbi, options); + + if (!g_dp_in_use) { + mxcfbi->ipu_ch_irq = IPU_IRQ_BG_SYNC_EOF; + mxcfbi->ipu_ch = MEM_BG_SYNC; + mxcfbi->cur_blank = mxcfbi->next_blank = FB_BLANK_UNBLANK; + } else { + mxcfbi->ipu_ch_irq = IPU_IRQ_DC_SYNC_EOF; + mxcfbi->ipu_ch = MEM_DC_SYNC; + mxcfbi->cur_blank = mxcfbi->next_blank = FB_BLANK_POWERDOWN; + } + + mxcfbi->ipu_di = pdev->id; + + if (pdev->id == 0) { + ipu_disp_set_global_alpha(mxcfbi->ipu_ch, true, 0x80); + ipu_disp_set_color_key(mxcfbi->ipu_ch, false, 0); + strcpy(fbi->fix.id, "DISP3 BG"); + + if (!g_dp_in_use) + if (ipu_request_irq(IPU_IRQ_BG_ALPHA_SYNC_EOF, + mxcfb_alpha_irq_handler, 0, + MXCFB_NAME, fbi) != 0) { + dev_err(&pdev->dev, "Error registering BG " + "alpha irq handler.\n"); + ret = -EBUSY; + goto err1; + } + g_dp_in_use = true; + } else if (pdev->id == 1) { + strcpy(fbi->fix.id, "DISP3 BG - DI1"); + + if (!g_dp_in_use) + if (ipu_request_irq(IPU_IRQ_BG_ALPHA_SYNC_EOF, + mxcfb_alpha_irq_handler, 0, + MXCFB_NAME, fbi) != 0) { + dev_err(&pdev->dev, "Error registering BG " + "alpha irq handler.\n"); + ret = -EBUSY; + goto err1; + } + g_dp_in_use = true; + } else if (pdev->id == 2) { /* Overlay */ + mxcfbi->ipu_ch_irq = IPU_IRQ_FG_SYNC_EOF; + mxcfbi->ipu_ch = MEM_FG_SYNC; + mxcfbi->ipu_di = -1; + mxcfbi->overlay = true; + mxcfbi->cur_blank = mxcfbi->next_blank = FB_BLANK_POWERDOWN; + + strcpy(fbi->fix.id, "DISP3 FG"); + + if (ipu_request_irq(IPU_IRQ_FG_ALPHA_SYNC_EOF, + mxcfb_alpha_irq_handler, 0, + MXCFB_NAME, fbi) != 0) { + dev_err(&pdev->dev, "Error registering FG alpha irq " + "handler.\n"); + ret = -EBUSY; + goto err1; + } + } + + mxcfb_info[pdev->id] = fbi; + + if (ipu_request_irq(mxcfbi->ipu_ch_irq, mxcfb_irq_handler, 0, + MXCFB_NAME, fbi) != 0) { + dev_err(&pdev->dev, "Error registering BG irq handler.\n"); + ret = -EBUSY; + goto err1; + } + ipu_disable_irq(mxcfbi->ipu_ch_irq); + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (res && res->end) { + fbi->fix.smem_len = res->end - res->start + 1; + fbi->fix.smem_start = res->start; + fbi->screen_base = ioremap(fbi->fix.smem_start, fbi->fix.smem_len); + } + + /* Need dummy values until real panel is configured */ + fbi->var.xres = 240; + fbi->var.yres = 320; + + if (!mxcfbi->default_bpp) + mxcfbi->default_bpp = 16; + + if (plat_data && !mxcfbi->ipu_di_pix_fmt) + mxcfbi->ipu_di_pix_fmt = plat_data->interface_pix_fmt; + + if (plat_data && plat_data->mode && plat_data->num_modes) + fb_videomode_to_modelist(plat_data->mode, plat_data->num_modes, + &fbi->modelist); + + if (!mxcfbi->fb_mode_str && plat_data && plat_data->mode_str) + mxcfbi->fb_mode_str = plat_data->mode_str; + + if (mxcfbi->fb_mode_str) { + ret = fb_find_mode(&fbi->var, fbi, mxcfbi->fb_mode_str, NULL, 0, NULL, + mxcfbi->default_bpp); + if ((!ret || (ret > 2)) && plat_data && plat_data->mode && plat_data->num_modes) + fb_find_mode(&fbi->var, fbi, mxcfbi->fb_mode_str, plat_data->mode, + plat_data->num_modes, NULL, mxcfbi->default_bpp); + } + + mxcfb_check_var(&fbi->var, fbi); + + /* Default Y virtual size is 2x panel size */ + fbi->var.yres_virtual = fbi->var.yres * 3; + + mxcfb_set_fix(fbi); + + /* alocate fb first */ + if (!res || !res->end) + if (mxcfb_map_video_memory(fbi) < 0) + return -ENOMEM; + + ret = register_framebuffer(fbi); + if (ret < 0) + goto err2; + + platform_set_drvdata(pdev, fbi); + + ret = device_create_file(fbi->dev, &dev_attr_fsl_disp_property); + if (ret) + dev_err(&pdev->dev, "Error %d on creating file\n", ret); + + return 0; + +err2: + ipu_free_irq(mxcfbi->ipu_ch_irq, fbi); +err1: + fb_dealloc_cmap(&fbi->cmap); + framebuffer_release(fbi); +err0: + return ret; +} + +static int mxcfb_remove(struct platform_device *pdev) +{ + struct fb_info *fbi = platform_get_drvdata(pdev); + struct mxcfb_info *mxc_fbi = fbi->par; + + if (!fbi) + return 0; + + mxcfb_blank(FB_BLANK_POWERDOWN, fbi); + ipu_free_irq(mxc_fbi->ipu_ch_irq, fbi); + mxcfb_unmap_video_memory(fbi); + + if (&fbi->cmap) + fb_dealloc_cmap(&fbi->cmap); + + unregister_framebuffer(fbi); + framebuffer_release(fbi); + return 0; +} + +/*! + * This structure contains pointers to the power management callback functions. + */ +static struct platform_driver mxcfb_driver = { + .driver = { + .name = MXCFB_NAME, + }, + .probe = mxcfb_probe, + .remove = mxcfb_remove, + .suspend = mxcfb_suspend, + .resume = mxcfb_resume, +}; + +/* + * Parse user specified options (`video=trident:') + * example: + * video=mxcdi0fb:RGB24, 1024x768M-16@60,bpp=16,noaccel + */ +static int mxcfb_option_setup(struct fb_info *info, char *options) +{ + struct mxcfb_info *mxcfbi = info->par; + char *opt; + + if (!options || !*options) + return 0; + + while ((opt = strsep(&options, ",")) != NULL) { + if (!*opt) + continue; + + if (!strncmp(opt, "RGB24", 5)) { + mxcfbi->ipu_di_pix_fmt = IPU_PIX_FMT_RGB24; + continue; + } + if (!strncmp(opt, "BGR24", 5)) { + mxcfbi->ipu_di_pix_fmt = IPU_PIX_FMT_BGR24; + continue; + } + if (!strncmp(opt, "RGB565", 6)) { + mxcfbi->ipu_di_pix_fmt = IPU_PIX_FMT_RGB565; + continue; + } + if (!strncmp(opt, "RGB666", 6)) { + mxcfbi->ipu_di_pix_fmt = IPU_PIX_FMT_RGB666; + continue; + } + if (!strncmp(opt, "YUV444", 6)) { + mxcfbi->ipu_di_pix_fmt = IPU_PIX_FMT_YUV444; + continue; + } + if (!strncmp(opt, "LVDS666", 7)) { + mxcfbi->ipu_di_pix_fmt = IPU_PIX_FMT_LVDS666; + continue; + } + if (!strncmp(opt, "YUYV16", 6)) { + mxcfbi->ipu_di_pix_fmt = IPU_PIX_FMT_YUYV; + continue; + } + if (!strncmp(opt, "UYVY16", 6)) { + mxcfbi->ipu_di_pix_fmt = IPU_PIX_FMT_UYVY; + continue; + } + if (!strncmp(opt, "YVYU16", 6)) { + mxcfbi->ipu_di_pix_fmt = IPU_PIX_FMT_YVYU; + continue; + } + if (!strncmp(opt, "VYUY16", 6)) { + mxcfbi->ipu_di_pix_fmt = IPU_PIX_FMT_VYUY; + continue; + } + if (!strncmp(opt, "ext_clk", 7)) { + mxcfbi->ipu_ext_clk = true; + continue; + } + if (!strncmp(opt, "bpp=", 4)) + mxcfbi->default_bpp = + simple_strtoul(opt + 4, NULL, 0); + else + mxcfbi->fb_mode_str = opt; + } + + return 0; +} + +/*! + * Main entry function for the framebuffer. The function registers the power + * management callback functions with the kernel and also registers the MXCFB + * callback functions with the core Linux framebuffer driver \b fbmem.c + * + * @return Error code indicating success or failure + */ +int __init mxcfb_init(void) +{ + return platform_driver_register(&mxcfb_driver); +} + +void mxcfb_exit(void) +{ + platform_driver_unregister(&mxcfb_driver); +} + +module_init(mxcfb_init); +module_exit(mxcfb_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MXC framebuffer driver"); +MODULE_LICENSE("GPL"); +MODULE_SUPPORTED_DEVICE("fb"); diff --git a/drivers/video/mxc/mxcfb.c b/drivers/video/mxc/mxcfb.c new file mode 100644 index 000000000000..93ce7f664976 --- /dev/null +++ b/drivers/video/mxc/mxcfb.c @@ -0,0 +1,1372 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @defgroup Framebuffer Framebuffer Driver for SDC and ADC. + */ + +/*! + * @file mxcfb.c + * + * @brief MXC Frame buffer driver for SDC + * + * @ingroup Framebuffer + */ + +/*! + * Include files + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Driver name + */ +#define MXCFB_NAME "mxc_sdc_fb" +/*! + * Structure containing the MXC specific framebuffer information. + */ +struct mxcfb_info { + int blank; + ipu_channel_t ipu_ch; + uint32_t ipu_ch_irq; + uint32_t cur_ipu_buf; + + u32 pseudo_palette[16]; + + struct semaphore flip_sem; + spinlock_t fb_lock; +}; + +struct mxcfb_data { + struct fb_info *fbi; + struct fb_info *fbi_ovl; + volatile int32_t vsync_flag; + wait_queue_head_t vsync_wq; + wait_queue_head_t suspend_wq; + bool suspended; + int backlight_level; +}; + +struct mxcfb_alloc_list { + struct list_head list; + dma_addr_t phy_addr; + void *cpu_addr; + u32 size; +}; + +static struct mxcfb_data mxcfb_drv_data; + +static char *fb_mode; +static unsigned long default_bpp = 16; +#ifdef CONFIG_FB_MXC_INTERNAL_MEM +static struct clk *iram_clk; +#endif +LIST_HEAD(fb_alloc_list); + +static uint32_t bpp_to_pixfmt(int bpp) +{ + uint32_t pixfmt = 0; + switch (bpp) { + case 24: + pixfmt = IPU_PIX_FMT_BGR24; + break; + case 32: + pixfmt = IPU_PIX_FMT_BGR32; + break; + case 16: + pixfmt = IPU_PIX_FMT_RGB565; + break; + } + return pixfmt; +} + +extern void gpio_lcd_active(void); +extern void gpio_lcd_inactive(void); +static irqreturn_t mxcfb_irq_handler(int irq, void *dev_id); +static int mxcfb_blank(int blank, struct fb_info *info); +static int mxcfb_map_video_memory(struct fb_info *fbi, bool use_internal_ram); +static int mxcfb_unmap_video_memory(struct fb_info *fbi); + +/* + * Set fixed framebuffer parameters based on variable settings. + * + * @param info framebuffer information pointer + */ +static int mxcfb_set_fix(struct fb_info *info) +{ + struct fb_fix_screeninfo *fix = &info->fix; + struct fb_var_screeninfo *var = &info->var; + struct mxcfb_info *mxc_fbi = (struct mxcfb_info *)info->par; + + if (mxc_fbi->ipu_ch == MEM_SDC_FG) + strncpy(fix->id, "DISP3 FG", 8); + else + strncpy(fix->id, "DISP3 BG", 8); + + fix->line_length = var->xres_virtual * var->bits_per_pixel / 8; + + fix->type = FB_TYPE_PACKED_PIXELS; + fix->accel = FB_ACCEL_NONE; + fix->visual = FB_VISUAL_TRUECOLOR; + fix->xpanstep = 1; + fix->ypanstep = 1; + + return 0; +} + +/* + * Set framebuffer parameters and change the operating mode. + * + * @param info framebuffer information pointer + */ +static int mxcfb_set_par(struct fb_info *fbi) +{ + int retval; + bool use_iram = false; + u32 mem_len; + ipu_di_signal_cfg_t sig_cfg; + ipu_panel_t mode = IPU_PANEL_TFT; + struct mxcfb_info *mxc_fbi = (struct mxcfb_info *)fbi->par; + + retval = wait_event_interruptible(mxcfb_drv_data.suspend_wq, (mxcfb_drv_data.suspended == false)); + if (retval < 0) + return retval; + + ipu_disable_irq(mxc_fbi->ipu_ch_irq); + ipu_disable_channel(mxc_fbi->ipu_ch, true); + ipu_uninit_channel(mxc_fbi->ipu_ch); + ipu_clear_irq(mxc_fbi->ipu_ch_irq); + mxcfb_set_fix(fbi); + + mem_len = fbi->var.yres_virtual * fbi->fix.line_length; + if (mem_len > fbi->fix.smem_len) { + if (fbi->fix.smem_start) + mxcfb_unmap_video_memory(fbi); + +#ifdef CONFIG_FB_MXC_INTERNAL_MEM + if (mxc_fbi->ipu_ch == MEM_SDC_BG) { + use_iram = true; + } +#endif + if (mxcfb_map_video_memory(fbi, use_iram) < 0) + return -ENOMEM; + } + + ipu_init_channel(mxc_fbi->ipu_ch, NULL); + + /* Clear the screen */ + memset((char *)fbi->screen_base, 0, fbi->fix.smem_len); + + if (mxc_fbi->ipu_ch == MEM_SDC_BG) { + memset(&sig_cfg, 0, sizeof(sig_cfg)); + if (fbi->var.sync & FB_SYNC_HOR_HIGH_ACT) + sig_cfg.Hsync_pol = true; + if (fbi->var.sync & FB_SYNC_VERT_HIGH_ACT) + sig_cfg.Vsync_pol = true; + if (!(fbi->var.sync & FB_SYNC_CLK_LAT_FALL)) + sig_cfg.clk_pol = true; + if (fbi->var.sync & FB_SYNC_DATA_INVERT) + sig_cfg.data_pol = true; + if (!(fbi->var.sync & FB_SYNC_OE_LOW_ACT)) + sig_cfg.enable_pol = true; + if (fbi->var.sync & FB_SYNC_CLK_IDLE_EN) + sig_cfg.clkidle_en = true; + if (fbi->var.sync & FB_SYNC_SHARP_MODE) + mode = IPU_PANEL_SHARP_TFT; + + dev_dbg(fbi->device, "pixclock = %ul Hz\n", + (u32) (PICOS2KHZ(fbi->var.pixclock) * 1000UL)); + + if (ipu_sdc_init_panel(mode, + (PICOS2KHZ(fbi->var.pixclock)) * 1000UL, + fbi->var.xres, fbi->var.yres, + (fbi->var.sync & FB_SYNC_SWAP_RGB) ? + IPU_PIX_FMT_BGR666 : IPU_PIX_FMT_RGB666, + fbi->var.left_margin, + fbi->var.hsync_len, + fbi->var.right_margin, + fbi->var.upper_margin, + fbi->var.vsync_len, + fbi->var.lower_margin, sig_cfg) != 0) { + dev_err(fbi->device, + "mxcfb: Error initializing panel.\n"); + return -EINVAL; + } + + fbi->mode = + (struct fb_videomode *)fb_match_mode(&fbi->var, + &fbi->modelist); + } + + ipu_disp_set_window_pos(mxc_fbi->ipu_ch, 0, 0); + + mxc_fbi->cur_ipu_buf = 1; + sema_init(&mxc_fbi->flip_sem, 1); + fbi->var.xoffset = fbi->var.yoffset = 0; + + retval = ipu_init_channel_buffer(mxc_fbi->ipu_ch, IPU_INPUT_BUFFER, + bpp_to_pixfmt(fbi->var.bits_per_pixel), + fbi->var.xres, fbi->var.yres, + fbi->var.xres_virtual, + IPU_ROTATE_NONE, + fbi->fix.smem_start + + (fbi->fix.line_length * fbi->var.yres), + fbi->fix.smem_start, + 0, 0); + if (retval) { + dev_err(fbi->device, + "ipu_init_channel_buffer error %d\n", retval); + return retval; + } + + if (mxc_fbi->blank == FB_BLANK_UNBLANK) { + ipu_enable_channel(mxc_fbi->ipu_ch); + } + + return 0; +} + +/* + * Check framebuffer variable parameters and adjust to valid values. + * + * @param var framebuffer variable parameters + * + * @param info framebuffer information pointer + */ +static int mxcfb_check_var(struct fb_var_screeninfo *var, struct fb_info *info) +{ + u32 vtotal; + u32 htotal; + + if (var->xres_virtual < var->xres) + var->xres_virtual = var->xres; + if (var->yres_virtual < var->yres) + var->yres_virtual = var->yres; + +#ifdef CONFIG_FB_MXC_INTERNAL_MEM + if ((info->fix.smem_start == FB_RAM_BASE_ADDR) && + ((var->yres_virtual * var->xres_virtual * var->bits_per_pixel / 8) > + FB_RAM_SIZE)) { + return -EINVAL; + } +#endif + + if ((var->bits_per_pixel != 32) && (var->bits_per_pixel != 24) && + (var->bits_per_pixel != 16)) { + var->bits_per_pixel = default_bpp; + } + + switch (var->bits_per_pixel) { + case 16: + var->red.length = 5; + var->red.offset = 11; + var->red.msb_right = 0; + + var->green.length = 6; + var->green.offset = 5; + var->green.msb_right = 0; + + var->blue.length = 5; + var->blue.offset = 0; + var->blue.msb_right = 0; + + var->transp.length = 0; + var->transp.offset = 0; + var->transp.msb_right = 0; + break; + case 24: + var->red.length = 8; + var->red.offset = 16; + var->red.msb_right = 0; + + var->green.length = 8; + var->green.offset = 8; + var->green.msb_right = 0; + + var->blue.length = 8; + var->blue.offset = 0; + var->blue.msb_right = 0; + + var->transp.length = 0; + var->transp.offset = 0; + var->transp.msb_right = 0; + break; + case 32: + var->red.length = 8; + var->red.offset = 16; + var->red.msb_right = 0; + + var->green.length = 8; + var->green.offset = 8; + var->green.msb_right = 0; + + var->blue.length = 8; + var->blue.offset = 0; + var->blue.msb_right = 0; + + var->transp.length = 8; + var->transp.offset = 24; + var->transp.msb_right = 0; + break; + } + + if (var->pixclock < 1000) { + htotal = var->xres + var->right_margin + var->hsync_len + + var->left_margin; + vtotal = var->yres + var->lower_margin + var->vsync_len + + var->upper_margin; + var->pixclock = (vtotal * htotal * 6UL) / 100UL; + var->pixclock = KHZ2PICOS(var->pixclock); + dev_dbg(info->device, + "pixclock set for 60Hz refresh = %u ps\n", + var->pixclock); + } + + var->height = -1; + var->width = -1; + var->grayscale = 0; + + /* nonstd used for YUV formats, but only RGB supported */ + var->nonstd = 0; + + return 0; +} + +static inline u_int _chan_to_field(u_int chan, struct fb_bitfield *bf) +{ + chan &= 0xffff; + chan >>= 16 - bf->length; + return chan << bf->offset; +} +static int +mxcfb_setcolreg(u_int regno, u_int red, u_int green, u_int blue, + u_int trans, struct fb_info *fbi) +{ + unsigned int val; + int ret = 1; + + /* + * If greyscale is true, then we convert the RGB value + * to greyscale no matter what visual we are using. + */ + if (fbi->var.grayscale) + red = green = blue = (19595 * red + 38470 * green + + 7471 * blue) >> 16; + switch (fbi->fix.visual) { + case FB_VISUAL_TRUECOLOR: + /* + * 16-bit True Colour. We encode the RGB value + * according to the RGB bitfield information. + */ + if (regno < 16) { + u32 *pal = fbi->pseudo_palette; + + val = _chan_to_field(red, &fbi->var.red); + val |= _chan_to_field(green, &fbi->var.green); + val |= _chan_to_field(blue, &fbi->var.blue); + + pal[regno] = val; + ret = 0; + } + break; + + case FB_VISUAL_STATIC_PSEUDOCOLOR: + case FB_VISUAL_PSEUDOCOLOR: + break; + } + + return ret; +} + +/* + * Function to handle custom ioctls for MXC framebuffer. + * + * @param inode inode struct + * + * @param file file struct + * + * @param cmd Ioctl command to handle + * + * @param arg User pointer to command arguments + * + * @param fbi framebuffer information pointer + */ +static int mxcfb_ioctl(struct fb_info *fbi, unsigned int cmd, unsigned long arg) +{ + int retval = 0; + int __user *argp = (void __user *)arg; + + retval = wait_event_interruptible(mxcfb_drv_data.suspend_wq, + (mxcfb_drv_data.suspended == + false)); + if (retval < 0) + return retval; + + switch (cmd) { + case MXCFB_SET_GBL_ALPHA: + { + struct mxcfb_gbl_alpha ga; + if (copy_from_user(&ga, (void *)arg, sizeof(ga))) { + retval = -EFAULT; + break; + } + retval = + ipu_sdc_set_global_alpha((bool) ga.enable, + ga.alpha); + dev_dbg(fbi->device, "Set global alpha to %d\n", + ga.alpha); + break; + } + case MXCFB_SET_CLR_KEY: + { + struct mxcfb_color_key key; + if (copy_from_user(&key, (void *)arg, sizeof(key))) { + retval = -EFAULT; + break; + } + retval = ipu_sdc_set_color_key(MEM_SDC_BG, key.enable, + key.color_key); + dev_dbg(fbi->device, "Set color key to 0x%08X\n", + key.color_key); + break; + } + case MXCFB_WAIT_FOR_VSYNC: + { +#ifndef CONFIG_ARCH_MX3 + mxcfb_drv_data.vsync_flag = 0; + ipu_enable_irq(IPU_IRQ_SDC_DISP3_VSYNC); + if (!wait_event_interruptible_timeout + (mxcfb_drv_data.vsync_wq, + mxcfb_drv_data.vsync_flag != 0, 1 * HZ)) { + dev_err(fbi->device, + "MXCFB_WAIT_FOR_VSYNC: timeout\n"); + retval = -ETIME; + break; + } else if (signal_pending(current)) { + dev_err(fbi->device, + "MXCFB_WAIT_FOR_VSYNC: interrupt received\n"); + retval = -ERESTARTSYS; + break; + } +#endif + break; + } + case MXCFB_GET_FB_IPU_CHAN: + { + struct mxcfb_info *mxc_fbi = + (struct mxcfb_info *)fbi->par; + + if (put_user(mxc_fbi->ipu_ch, argp)) + return -EFAULT; + + break; + } + default: + retval = -EINVAL; + } + return retval; +} + +/* + * Function to handle custom ioctls for MXC framebuffer. + * + * @param inode inode struct + * + * @param file file struct + * + * @param cmd Ioctl command to handle + * + * @param arg User pointer to command arguments + * + * @param fbi framebuffer information pointer + */ +static int mxcfb_ioctl_ovl(struct fb_info *fbi, unsigned int cmd, + unsigned long arg) +{ + int retval = 0; + int __user *argp = (void __user *)arg; + struct mxcfb_info *mxc_fbi = (struct mxcfb_info *)fbi->par; + + retval = wait_event_interruptible(mxcfb_drv_data.suspend_wq, + (mxcfb_drv_data.suspended == false)); + if (retval < 0) + return retval; + + switch (cmd) { + case FBIO_ALLOC: + { + int size; + struct mxcfb_alloc_list *mem; + + mem = kzalloc(sizeof(*mem), GFP_KERNEL); + if (mem == NULL) + return -ENOMEM; + + if (get_user(size, argp)) + return -EFAULT; + + mem->size = PAGE_ALIGN(size); + + mem->cpu_addr = dma_alloc_coherent(fbi->device, size, + &mem->phy_addr, + GFP_DMA); + if (mem->cpu_addr == NULL) { + kfree(mem); + return -ENOMEM; + } + + list_add(&mem->list, &fb_alloc_list); + + dev_dbg(fbi->device, "allocated %d bytes @ 0x%08X\n", + mem->size, mem->phy_addr); + + if (put_user(mem->phy_addr, argp)) + return -EFAULT; + + break; + } + case FBIO_FREE: + { + unsigned long offset; + struct mxcfb_alloc_list *mem; + + if (get_user(offset, argp)) + return -EFAULT; + + retval = -EINVAL; + list_for_each_entry(mem, &fb_alloc_list, list) { + if (mem->phy_addr == offset) { + list_del(&mem->list); + dma_free_coherent(fbi->device, + mem->size, + mem->cpu_addr, + mem->phy_addr); + kfree(mem); + retval = 0; + break; + } + } + + break; + } + case MXCFB_SET_OVERLAY_POS: + { + struct mxcfb_pos pos; + if (copy_from_user(&pos, (void *)arg, sizeof(pos))) { + retval = -EFAULT; + break; + } + retval = ipu_disp_set_window_pos(mxc_fbi->ipu_ch, + pos.x, pos.y); + break; + } + case MXCFB_GET_FB_IPU_CHAN: + { + struct mxcfb_info *mxc_fbi = + (struct mxcfb_info *)fbi->par; + + if (put_user(mxc_fbi->ipu_ch, argp)) + return -EFAULT; + + break; + } + default: + retval = -EINVAL; + } + return retval; +} + +/* + * mxcfb_blank(): + * Blank the display. + */ +static int mxcfb_blank(int blank, struct fb_info *info) +{ + int retval; + struct mxcfb_info *mxc_fbi = (struct mxcfb_info *)info->par; + + dev_dbg(info->device, "blank = %d\n", blank); + + if (mxc_fbi->blank == blank) + return 0; + + retval = wait_event_interruptible(mxcfb_drv_data.suspend_wq, + (mxcfb_drv_data.suspended == false)); + if (retval < 0) + return retval; + + mxc_fbi->blank = blank; + + switch (blank) { + case FB_BLANK_POWERDOWN: + case FB_BLANK_VSYNC_SUSPEND: + case FB_BLANK_HSYNC_SUSPEND: + case FB_BLANK_NORMAL: + ipu_disable_channel(MEM_SDC_BG, true); + gpio_lcd_inactive(); + break; + case FB_BLANK_UNBLANK: + gpio_lcd_active(); + ipu_enable_channel(MEM_SDC_BG); + break; + } + return 0; +} + +/* + * mxcfb_blank_ovl(): + * Blank the display. + */ +static int mxcfb_blank_ovl(int blank, struct fb_info *info) +{ + int retval; + struct mxcfb_info *mxc_fbi = (struct mxcfb_info *)info->par; + + dev_dbg(info->device, "ovl blank = %d\n", blank); + + if (mxc_fbi->blank == blank) + return 0; + + retval = wait_event_interruptible(mxcfb_drv_data.suspend_wq, + (mxcfb_drv_data.suspended == false)); + if (retval < 0) + return retval; + + mxc_fbi->blank = blank; + + switch (blank) { + case FB_BLANK_POWERDOWN: + case FB_BLANK_VSYNC_SUSPEND: + case FB_BLANK_HSYNC_SUSPEND: + case FB_BLANK_NORMAL: + ipu_disable_channel(MEM_SDC_FG, true); + break; + case FB_BLANK_UNBLANK: + ipu_enable_channel(MEM_SDC_FG); + break; + } + return 0; +} + +/* + * Pan or Wrap the Display + * + * This call looks only at xoffset, yoffset and the FB_VMODE_YWRAP flag + * + * @param var Variable screen buffer information + * @param info Framebuffer information pointer + */ +static int +mxcfb_pan_display(struct fb_var_screeninfo *var, struct fb_info *info) +{ + struct mxcfb_info *mxc_fbi = (struct mxcfb_info *)info->par; + unsigned long lock_flags = 0; + int retval; + u_int y_bottom; + unsigned long base; + + retval = wait_event_interruptible(mxcfb_drv_data.suspend_wq, + (mxcfb_drv_data.suspended == false)); + if (retval < 0) + return retval; + + if (var->xoffset > 0) { + dev_dbg(info->device, "x panning not supported\n"); + return -EINVAL; + } + + if ((info->var.xoffset == var->xoffset) && + (info->var.yoffset == var->yoffset)) { + /* No change, do nothing */ + return 0; + } + + y_bottom = var->yoffset; + + if (!(var->vmode & FB_VMODE_YWRAP)) { + y_bottom += var->yres; + } + + if (y_bottom > info->var.yres_virtual) { + return -EINVAL; + } + + base = (var->yoffset * var->xres_virtual + var->xoffset); + base *= (var->bits_per_pixel) / 8; + base += info->fix.smem_start; + + down(&mxc_fbi->flip_sem); + + spin_lock_irqsave(&mxc_fbi->fb_lock, lock_flags); + + dev_dbg(info->device, "Updating SDC BG buf %d address=0x%08lX\n", + mxc_fbi->cur_ipu_buf, base); + + mxc_fbi->cur_ipu_buf = !mxc_fbi->cur_ipu_buf; + if (ipu_update_channel_buffer(mxc_fbi->ipu_ch, IPU_INPUT_BUFFER, + mxc_fbi->cur_ipu_buf, base) == 0) { + ipu_select_buffer(mxc_fbi->ipu_ch, IPU_INPUT_BUFFER, + mxc_fbi->cur_ipu_buf); + ipu_clear_irq(mxc_fbi->ipu_ch_irq); + ipu_enable_irq(mxc_fbi->ipu_ch_irq); + } else { + dev_err(info->device, + "Error updating SDC buf %d to address=0x%08lX\n", + mxc_fbi->cur_ipu_buf, base); + } + + spin_unlock_irqrestore(&mxc_fbi->fb_lock, lock_flags); + + dev_dbg(info->device, "Update complete\n"); + + info->var.xoffset = var->xoffset; + info->var.yoffset = var->yoffset; + + if (var->vmode & FB_VMODE_YWRAP) { + info->var.vmode |= FB_VMODE_YWRAP; + } else { + info->var.vmode &= ~FB_VMODE_YWRAP; + } + + return 0; +} + +/* + * Function to handle custom mmap for MXC framebuffer. + * + * @param fbi framebuffer information pointer + * + * @param vma Pointer to vm_area_struct + */ +static int mxcfb_mmap(struct fb_info *fbi, struct vm_area_struct *vma) +{ + bool found = false; + u32 len; + unsigned long offset = vma->vm_pgoff << PAGE_SHIFT; + struct mxcfb_alloc_list *mem; + + if (offset < fbi->fix.smem_len) { + /* mapping framebuffer memory */ + len = fbi->fix.smem_len - offset; + vma->vm_pgoff = (fbi->fix.smem_start + offset) >> PAGE_SHIFT; + } else { + list_for_each_entry(mem, &fb_alloc_list, list) { + if (offset == mem->phy_addr) { + found = true; + len = mem->size; + break; + } + } + if (!found) { + return -EINVAL; + } + } + + len = PAGE_ALIGN(len); + if (vma->vm_end - vma->vm_start > len) { + return -EINVAL; + } + + /* make buffers write-thru cacheable */ + vma->vm_page_prot = __pgprot(pgprot_val(vma->vm_page_prot) & + ~L_PTE_BUFFERABLE); + + vma->vm_flags |= VM_IO | VM_RESERVED; + + if (remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff, + vma->vm_end - vma->vm_start, vma->vm_page_prot)) { + dev_dbg(fbi->device, "mmap remap_pfn_range failed\n"); + return -ENOBUFS; + + } + + return 0; +} + +/*! + * This structure contains the pointers to the control functions that are + * invoked by the core framebuffer driver to perform operations like + * blitting, rectangle filling, copy regions and cursor definition. + */ +static struct fb_ops mxcfb_ops = { + .owner = THIS_MODULE, + .fb_set_par = mxcfb_set_par, + .fb_check_var = mxcfb_check_var, + .fb_setcolreg = mxcfb_setcolreg, + .fb_pan_display = mxcfb_pan_display, + .fb_ioctl = mxcfb_ioctl, + .fb_fillrect = cfb_fillrect, + .fb_copyarea = cfb_copyarea, + .fb_imageblit = cfb_imageblit, + .fb_blank = mxcfb_blank, +}; + +static struct fb_ops mxcfb_ovl_ops = { + .owner = THIS_MODULE, + .fb_set_par = mxcfb_set_par, + .fb_check_var = mxcfb_check_var, + .fb_setcolreg = mxcfb_setcolreg, + .fb_pan_display = mxcfb_pan_display, + .fb_ioctl = mxcfb_ioctl_ovl, + .fb_mmap = mxcfb_mmap, + .fb_fillrect = cfb_fillrect, + .fb_copyarea = cfb_copyarea, + .fb_imageblit = cfb_imageblit, + .fb_blank = mxcfb_blank_ovl, +}; + +static irqreturn_t mxcfb_vsync_irq_handler(int irq, void *dev_id) +{ + struct mxcfb_data *fb_data = dev_id; + + ipu_disable_irq(irq); + + fb_data->vsync_flag = 1; + wake_up_interruptible(&fb_data->vsync_wq); + return IRQ_HANDLED; +} + +static irqreturn_t mxcfb_irq_handler(int irq, void *dev_id) +{ + struct fb_info *fbi = dev_id; + struct mxcfb_info *mxc_fbi = fbi->par; + + up(&mxc_fbi->flip_sem); + ipu_disable_irq(irq); + return IRQ_HANDLED; +} + +#ifdef CONFIG_PM +/* + * Power management hooks. Note that we won't be called from IRQ context, + * unlike the blank functions above, so we may sleep. + */ + +/* + * Suspends the framebuffer and blanks the screen. Power management support + */ +static int mxcfb_suspend(struct platform_device *pdev, pm_message_t state) +{ + struct mxcfb_data *drv_data = platform_get_drvdata(pdev); + struct mxcfb_info *mxc_fbi = (struct mxcfb_info *)drv_data->fbi->par; + struct mxcfb_info *mxc_fbi_ovl = + (struct mxcfb_info *)drv_data->fbi_ovl->par; +#ifdef CONFIG_FB_MXC_LOW_PWR_DISPLAY + void *fbmem; +#endif + + drv_data->suspended = true; + + acquire_console_sem(); + fb_set_suspend(drv_data->fbi, 1); + fb_set_suspend(drv_data->fbi_ovl, 1); + release_console_sem(); + + if (mxc_fbi_ovl->blank == FB_BLANK_UNBLANK) { + ipu_disable_channel(MEM_SDC_FG, true); + } + + if (mxc_fbi->blank == FB_BLANK_UNBLANK) { +#ifdef CONFIG_FB_MXC_LOW_PWR_DISPLAY + if (drv_data->fbi->fix.smem_start != FB_RAM_BASE_ADDR) { + fbmem = ioremap(FB_RAM_BASE_ADDR, FB_RAM_SIZE); + memcpy(fbmem, drv_data->fbi->screen_base, FB_RAM_SIZE); + iounmap(fbmem); + mxc_fbi->cur_ipu_buf = !mxc_fbi->cur_ipu_buf; + ipu_update_channel_buffer(MEM_SDC_BG, IPU_INPUT_BUFFER, + mxc_fbi->cur_ipu_buf, + FB_RAM_BASE_ADDR); + ipu_select_buffer(MEM_SDC_BG, IPU_INPUT_BUFFER, + mxc_fbi->cur_ipu_buf); + } + ipu_lowpwr_display_enable(); +#else + ipu_disable_channel(MEM_SDC_BG, true); + gpio_lcd_inactive(); +#endif + } + return 0; +} + +/* + * Resumes the framebuffer and unblanks the screen. Power management support + */ +static int mxcfb_resume(struct platform_device *pdev) +{ + struct mxcfb_data *drv_data = platform_get_drvdata(pdev); + struct mxcfb_info *mxc_fbi = (struct mxcfb_info *)drv_data->fbi->par; + struct mxcfb_info *mxc_fbi_ovl = + (struct mxcfb_info *)drv_data->fbi_ovl->par; + + drv_data->suspended = false; + + if (mxc_fbi->blank == FB_BLANK_UNBLANK) { +#ifdef CONFIG_FB_MXC_LOW_PWR_DISPLAY + ipu_lowpwr_display_disable(); + if (drv_data->fbi->fix.smem_start != FB_RAM_BASE_ADDR) { + mxc_fbi->cur_ipu_buf = !mxc_fbi->cur_ipu_buf; + ipu_update_channel_buffer(MEM_SDC_BG, IPU_INPUT_BUFFER, + mxc_fbi->cur_ipu_buf, + drv_data->fbi->fix. + smem_start); + ipu_select_buffer(MEM_SDC_BG, IPU_INPUT_BUFFER, + mxc_fbi->cur_ipu_buf); + } +#else + gpio_lcd_active(); + ipu_enable_channel(MEM_SDC_BG); +#endif + } + + if (mxc_fbi_ovl->blank == FB_BLANK_UNBLANK) { + ipu_enable_channel(MEM_SDC_FG); + } + + acquire_console_sem(); + fb_set_suspend(drv_data->fbi, 0); + fb_set_suspend(drv_data->fbi_ovl, 0); + release_console_sem(); + + wake_up_interruptible(&drv_data->suspend_wq); + return 0; +} +#else +#define mxcfb_suspend NULL +#define mxcfb_resume NULL +#endif + +/* + * Main framebuffer functions + */ + +/*! + * Allocates the DRAM memory for the frame buffer. This buffer is remapped + * into a non-cached, non-buffered, memory region to allow palette and pixel + * writes to occur without flushing the cache. Once this area is remapped, + * all virtual memory access to the video memory should occur at the new region. + * + * @param fbi framebuffer information pointer + * + * @param use_internal_ram flag on whether to use internal RAM for memory + * + * @return Error code indicating success or failure + */ +static int mxcfb_map_video_memory(struct fb_info *fbi, bool use_internal_ram) +{ + int retval = 0; + +#ifdef CONFIG_FB_MXC_INTERNAL_MEM + if (use_internal_ram) { + fbi->fix.smem_len = FB_RAM_SIZE; + fbi->fix.smem_start = FB_RAM_BASE_ADDR; + if (fbi->fix.smem_len < + (fbi->var.yres_virtual * fbi->fix.line_length)) { + dev_err(fbi->device, + "Not enough internal RAM for framebuffer configuration\n"); + retval = -EINVAL; + goto err0; + } + + if (request_mem_region(fbi->fix.smem_start, fbi->fix.smem_len, + fbi->device->driver->name) == NULL) { + dev_err(fbi->device, + "Unable to request internal RAM\n"); + retval = -ENOMEM; + goto err0; + } + + fbi->screen_base = ioremap(fbi->fix.smem_start, + fbi->fix.smem_len); + if (!fbi->screen_base) { + dev_err(fbi->device, + "Unable to map fb memory to virtual address\n"); + release_mem_region(fbi->fix.smem_start, + fbi->fix.smem_len); + retval = -EIO; + goto err0; + } + + iram_clk = clk_get(NULL, "iram_clk"); + clk_enable(iram_clk); + } else +#endif + { + fbi->fix.smem_len = fbi->var.yres_virtual * + fbi->fix.line_length; + fbi->screen_base = + dma_alloc_writecombine(fbi->device, + fbi->fix.smem_len, + (dma_addr_t *) &fbi->fix.smem_start, + GFP_DMA); + + if (fbi->screen_base == 0) { + dev_err(fbi->device, + "Unable to allocate framebuffer memory\n"); + retval = -EBUSY; + goto err0; + } + } + + dev_dbg(fbi->device, "allocated fb @ paddr=0x%08X, size=%d.\n", + (uint32_t) fbi->fix.smem_start, fbi->fix.smem_len); + + fbi->screen_size = fbi->fix.smem_len; + + /* Clear the screen */ + memset((char *)fbi->screen_base, 0, fbi->fix.smem_len); + + return 0; + + err0: + fbi->fix.smem_len = 0; + fbi->fix.smem_start = 0; + fbi->screen_base = NULL; + return retval; +} + +/*! + * De-allocates the DRAM memory for the frame buffer. + * + * @param fbi framebuffer information pointer + * + * @return Error code indicating success or failure + */ +static int mxcfb_unmap_video_memory(struct fb_info *fbi) +{ +#ifdef CONFIG_FB_MXC_INTERNAL_MEM + if (fbi->fix.smem_start == FB_RAM_BASE_ADDR) { + iounmap(fbi->screen_base); + release_mem_region(fbi->fix.smem_start, fbi->fix.smem_len); + fbi->fix.smem_start = 0; + fbi->fix.smem_len = 0; + clk_disable(iram_clk); + } else +#endif + { + dma_free_writecombine(fbi->device, fbi->fix.smem_len, + fbi->screen_base, fbi->fix.smem_start); + } + fbi->screen_base = 0; + fbi->fix.smem_start = 0; + fbi->fix.smem_len = 0; + return 0; +} + +/*! + * Initializes the framebuffer information pointer. After allocating + * sufficient memory for the framebuffer structure, the fields are + * filled with custom information passed in from the configurable + * structures. This includes information such as bits per pixel, + * color maps, screen width/height and RGBA offsets. + * + * @return Framebuffer structure initialized with our information + */ +static struct fb_info *mxcfb_init_fbinfo(struct device *dev, struct fb_ops *ops) +{ + struct fb_info *fbi; + struct mxcfb_info *mxcfbi; + + /* + * Allocate sufficient memory for the fb structure + */ + fbi = framebuffer_alloc(sizeof(struct mxcfb_info), dev); + if (!fbi) + return NULL; + + mxcfbi = (struct mxcfb_info *)fbi->par; + + fbi->var.activate = FB_ACTIVATE_NOW; + + fbi->fbops = ops; + fbi->flags = FBINFO_FLAG_DEFAULT; + fbi->pseudo_palette = mxcfbi->pseudo_palette; + + spin_lock_init(&mxcfbi->fb_lock); + + /* + * Allocate colormap + */ + fb_alloc_cmap(&fbi->cmap, 16, 0); + + return fbi; +} + +/*! + * Probe routine for the framebuffer driver. It is called during the + * driver binding process. The following functions are performed in + * this routine: Framebuffer initialization, Memory allocation and + * mapping, Framebuffer registration, IPU initialization. + * + * @return Appropriate error code to the kernel common code + */ +static int mxcfb_probe(struct platform_device *pdev) +{ + char *mode = pdev->dev.platform_data; + struct fb_info *fbi; + struct mxcfb_info *mxcfbi; + struct fb_info *fbi_ovl; + int ret = 0; + + /* + * Initialize FB structures + */ + fbi = mxcfb_init_fbinfo(&pdev->dev, &mxcfb_ops); + if (!fbi) { + ret = -ENOMEM; + goto err0; + } + mxcfbi = (struct mxcfb_info *)fbi->par; + + mxcfbi->ipu_ch_irq = IPU_IRQ_SDC_BG_EOF; + mxcfbi->cur_ipu_buf = 0; + mxcfbi->ipu_ch = MEM_SDC_BG; + + ipu_sdc_set_global_alpha(true, 0xFF); + ipu_sdc_set_color_key(MEM_SDC_BG, false, 0); + + if (ipu_request_irq(IPU_IRQ_SDC_BG_EOF, mxcfb_irq_handler, 0, + MXCFB_NAME, fbi) != 0) { + dev_err(&pdev->dev, "Error registering BG irq handler.\n"); + ret = -EBUSY; + goto err1; + } + ipu_disable_irq(IPU_IRQ_SDC_BG_EOF); + + if (fb_mode == NULL) { + fb_mode = mode; + } + + if (!fb_find_mode(&fbi->var, fbi, fb_mode, mxcfb_modedb, + mxcfb_modedb_sz, NULL, default_bpp)) { + ret = -EBUSY; + goto err2; + } + fb_videomode_to_modelist(mxcfb_modedb, mxcfb_modedb_sz, &fbi->modelist); + + /* Default Y virtual size is 2x panel size */ +#ifndef CONFIG_FB_MXC_INTERNAL_MEM + fbi->var.yres_virtual = fbi->var.yres * 2; +#endif + + mxcfb_drv_data.fbi = fbi; + mxcfb_drv_data.backlight_level = 255; + mxcfb_drv_data.suspended = false; + init_waitqueue_head(&mxcfb_drv_data.suspend_wq); + + mxcfbi->blank = FB_BLANK_NORMAL; + ret = mxcfb_set_par(fbi); + if (ret < 0) { + goto err2; + } + mxcfb_blank(FB_BLANK_UNBLANK, fbi); + + /* + * Register framebuffer + */ + ret = register_framebuffer(fbi); + if (ret < 0) { + goto err2; + } + + /* + * Initialize Overlay FB structures + */ + fbi_ovl = mxcfb_init_fbinfo(&pdev->dev, &mxcfb_ovl_ops); + if (!fbi_ovl) { + ret = -ENOMEM; + goto err3; + } + mxcfb_drv_data.fbi_ovl = fbi_ovl; + mxcfbi = (struct mxcfb_info *)fbi_ovl->par; + + mxcfbi->ipu_ch_irq = IPU_IRQ_SDC_FG_EOF; + mxcfbi->cur_ipu_buf = 0; + mxcfbi->ipu_ch = MEM_SDC_FG; + + if (ipu_request_irq(IPU_IRQ_SDC_FG_EOF, mxcfb_irq_handler, 0, + MXCFB_NAME, fbi_ovl) != 0) { + dev_err(fbi->device, "Error registering FG irq handler.\n"); + ret = -EBUSY; + goto err4; + } + ipu_disable_irq(mxcfbi->ipu_ch_irq); + + /* Default Y virtual size is 2x panel size */ + fbi_ovl->var = fbi->var; + fbi_ovl->var.yres_virtual = fbi->var.yres * 2; + + /* Overlay is blanked by default */ + mxcfbi->blank = FB_BLANK_NORMAL; + + ret = mxcfb_set_par(fbi_ovl); + if (ret < 0) { + goto err5; + } + + /* + * Register overlay framebuffer + */ + ret = register_framebuffer(fbi_ovl); + if (ret < 0) { + goto err5; + } + + platform_set_drvdata(pdev, &mxcfb_drv_data); + + init_waitqueue_head(&mxcfb_drv_data.vsync_wq); + if (!cpu_is_mx31() && !cpu_is_mx32()) { + ret = ipu_request_irq(IPU_IRQ_SDC_DISP3_VSYNC, + mxcfb_vsync_irq_handler, + 0, MXCFB_NAME, + &mxcfb_drv_data); + if (ret < 0) + goto err6; + ipu_disable_irq(IPU_IRQ_SDC_DISP3_VSYNC); + } + + printk(KERN_INFO "mxcfb: fb registered, using mode %s\n", fb_mode); + return 0; + + err6: + unregister_framebuffer(fbi_ovl); + err5: + ipu_free_irq(IPU_IRQ_SDC_FG_EOF, fbi_ovl); + err4: + fb_dealloc_cmap(&fbi_ovl->cmap); + framebuffer_release(fbi_ovl); + err3: + unregister_framebuffer(fbi); + err2: + ipu_free_irq(IPU_IRQ_SDC_BG_EOF, fbi); + err1: + fb_dealloc_cmap(&fbi->cmap); + framebuffer_release(fbi); + err0: + printk(KERN_ERR "mxcfb: failed to register fb\n"); + return ret; +} + +/*! + * This structure contains pointers to the power management callback functions. + */ +static struct platform_driver mxcfb_driver = { + .driver = { + .name = MXCFB_NAME, + }, + .probe = mxcfb_probe, + .suspend = mxcfb_suspend, + .resume = mxcfb_resume, +}; + +/* + * Parse user specified options (`video=trident:') + * example: + * video=trident:800x600,bpp=16,noaccel + */ +int mxcfb_setup(char *options) +{ + char *opt; + if (!options || !*options) + return 0; + while ((opt = strsep(&options, ",")) != NULL) { + if (!*opt) + continue; + if (!strncmp(opt, "bpp=", 4)) + default_bpp = simple_strtoul(opt + 4, NULL, 0); + else + fb_mode = opt; + } + return 0; +} + +/*! + * Main entry function for the framebuffer. The function registers the power + * management callback functions with the kernel and also registers the MXCFB + * callback functions with the core Linux framebuffer driver \b fbmem.c + * + * @return Error code indicating success or failure + */ +int __init mxcfb_init(void) +{ + int ret = 0; +#ifndef MODULE + char *option = NULL; +#endif + +#ifndef MODULE + if (fb_get_options("mxcfb", &option)) + return -ENODEV; + mxcfb_setup(option); +#endif + + ret = platform_driver_register(&mxcfb_driver); + return ret; +} + +void mxcfb_exit(void) +{ + struct fb_info *fbi = mxcfb_drv_data.fbi; + + if (fbi) { + mxcfb_unmap_video_memory(fbi); + + if (&fbi->cmap) + fb_dealloc_cmap(&fbi->cmap); + + unregister_framebuffer(fbi); + framebuffer_release(fbi); + } + + fbi = mxcfb_drv_data.fbi_ovl; + if (fbi) { + mxcfb_unmap_video_memory(fbi); + + if (&fbi->cmap) + fb_dealloc_cmap(&fbi->cmap); + + unregister_framebuffer(fbi); + framebuffer_release(fbi); + } +#ifndef CONFIG_ARCH_MX3 + ipu_free_irq(IPU_IRQ_SDC_DISP3_VSYNC, &mxcfb_drv_data); +#endif + + platform_driver_unregister(&mxcfb_driver); +} + +module_init(mxcfb_init); +module_exit(mxcfb_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MXC framebuffer driver"); +MODULE_LICENSE("GPL"); +MODULE_SUPPORTED_DEVICE("fb"); diff --git a/drivers/video/mxc/mxcfb_ch7026.c b/drivers/video/mxc/mxcfb_ch7026.c new file mode 100644 index 000000000000..a3f508450852 --- /dev/null +++ b/drivers/video/mxc/mxcfb_ch7026.c @@ -0,0 +1,370 @@ +/* + * Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @defgroup Framebuffer Framebuffer Driver for SDC and ADC. + */ + +/*! + * @file mxcfb_epson_vga.c + * + * @brief MXC Frame buffer driver for SDC + * + * @ingroup Framebuffer + */ + +/*! + * Include files + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static struct i2c_client *ch7026_client; + +static int lcd_init(void); +static void lcd_poweron(struct fb_info *info); +static void lcd_poweroff(void); + +static void (*lcd_reset) (void); +static struct regulator *io_reg; +static struct regulator *core_reg; +static struct regulator *analog_reg; + + /* 8 800x600-60 VESA */ +static struct fb_videomode mode = { + NULL, 60, 800, 600, 25000, 88, 40, 23, 1, 128, 4, + FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, + FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA +}; + +static void lcd_init_fb(struct fb_info *info) +{ + struct fb_var_screeninfo var; + + memset(&var, 0, sizeof(var)); + + fb_videomode_to_var(&var, &mode); + + var.activate = FB_ACTIVATE_ALL; + + acquire_console_sem(); + info->flags |= FBINFO_MISC_USEREVENT; + fb_set_var(info, &var); + fb_blank(info, FB_BLANK_UNBLANK); + info->flags &= ~FBINFO_MISC_USEREVENT; + release_console_sem(); +} + +static int lcd_fb_event(struct notifier_block *nb, unsigned long val, void *v) +{ + struct fb_event *event = v; + + if (strcmp(event->info->fix.id, "DISP3 BG - DI1")) + return 0; + + switch (val) { + case FB_EVENT_FB_REGISTERED: + lcd_init_fb(event->info); + lcd_poweron(event->info); + break; + case FB_EVENT_BLANK: + if (*((int *)event->data) == FB_BLANK_UNBLANK) + lcd_poweron(event->info); + else + lcd_poweroff(); + break; + } + return 0; +} + +static struct notifier_block nb = { + .notifier_call = lcd_fb_event, +}; + +/*! + * This function is called whenever the SPI slave device is detected. + * + * @param spi the SPI slave device + * + * @return Returns 0 on SUCCESS and error on FAILURE. + */ +static int __devinit lcd_probe(struct device *dev) +{ + int ret = 0; + int i; + struct mxc_lcd_platform_data *plat = dev->platform_data; + + if (plat) { + + io_reg = regulator_get(dev, plat->io_reg); + if (!IS_ERR(io_reg)) { + regulator_set_voltage(io_reg, 1800000, 1800000); + regulator_enable(io_reg); + } else { + io_reg = NULL; + } + + core_reg = regulator_get(dev, plat->core_reg); + if (!IS_ERR(core_reg)) { + regulator_set_voltage(core_reg, 2500000, 2500000); + regulator_enable(core_reg); + } else { + core_reg = NULL; + } + analog_reg = regulator_get(dev, plat->analog_reg); + if (!IS_ERR(analog_reg)) { + regulator_set_voltage(analog_reg, 2775000, 2775000); + regulator_enable(analog_reg); + } else { + analog_reg = NULL; + } + msleep(100); + + lcd_reset = plat->reset; + if (lcd_reset) + lcd_reset(); + } + + for (i = 0; i < num_registered_fb; i++) { + if (strcmp(registered_fb[i]->fix.id, "DISP3 BG - DI1") == 0) { + ret = lcd_init(); + if (ret < 0) + goto err; + + lcd_init_fb(registered_fb[i]); + fb_show_logo(registered_fb[i], 0); + lcd_poweron(registered_fb[i]); + } + } + + fb_register_client(&nb); + return 0; +err: + if (io_reg) + regulator_disable(io_reg); + if (core_reg) + regulator_disable(core_reg); + if (analog_reg) + regulator_disable(analog_reg); + + return ret; +} + +static int __devinit ch7026_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + ch7026_client = client; + + return lcd_probe(&client->dev); +} + +static int __devexit ch7026_remove(struct i2c_client *client) +{ + fb_unregister_client(&nb); + lcd_poweroff(); + regulator_put(io_reg); + regulator_put(core_reg); + regulator_put(analog_reg); + + return 0; +} + +static int ch7026_suspend(struct i2c_client *client, pm_message_t message) +{ + return 0; +} + +static int ch7026_resume(struct i2c_client *client) +{ + return 0; +} + +u8 reg_init[][2] = { + { 0x02, 0x01 }, + { 0x02, 0x03 }, + { 0x03, 0x00 }, + { 0x06, 0x6B }, + { 0x08, 0x08 }, + { 0x09, 0x80 }, + { 0x0C, 0x0A }, + { 0x0D, 0x89 }, + { 0x0F, 0x23 }, + { 0x10, 0x20 }, + { 0x11, 0x20 }, + { 0x12, 0x40 }, + { 0x13, 0x28 }, + { 0x14, 0x80 }, + { 0x15, 0x52 }, + { 0x16, 0x58 }, + { 0x17, 0x74 }, + { 0x19, 0x01 }, + { 0x1A, 0x04 }, + { 0x1B, 0x23 }, + { 0x1C, 0x20 }, + { 0x1D, 0x20 }, + { 0x1F, 0x28 }, + { 0x20, 0x80 }, + { 0x21, 0x12 }, + { 0x22, 0x58 }, + { 0x23, 0x74 }, + { 0x25, 0x01 }, + { 0x26, 0x04 }, + { 0x37, 0x20 }, + { 0x39, 0x20 }, + { 0x3B, 0x20 }, + { 0x41, 0xA2 }, + { 0x4D, 0x03 }, + { 0x4E, 0x13 }, + { 0x4F, 0xB1 }, + { 0x50, 0x3B }, + { 0x51, 0x54 }, + { 0x52, 0x12 }, + { 0x53, 0x13 }, + { 0x55, 0xE5 }, + { 0x5E, 0x80 }, + { 0x69, 0x64 }, + { 0x7D, 0x62 }, + { 0x04, 0x00 }, + { 0x06, 0x69 }, + + /* + NOTE: The following five repeated sentences are used here to wait memory initial complete, please don't remove...(you could refer to Appendix A of programming guide document (CH7025(26)B Programming Guide Rev2.03.pdf) for detailed information about memory initialization! + */ + { 0x03, 0x00 }, + { 0x03, 0x00 }, + { 0x03, 0x00 }, + { 0x03, 0x00 }, + { 0x03, 0x00 }, + + { 0x06, 0x68 }, + { 0x02, 0x02 }, + { 0x02, 0x03 }, +}; + +#define REGMAP_LENGTH (sizeof(reg_init) / (2*sizeof(u8))) + +/* + * Send init commands to L4F00242T03 + * + */ +static int lcd_init(void) +{ + int i; + int dat; + + dev_dbg(&ch7026_client->dev, "initializing CH7026\n"); + + /* read device ID */ + msleep(100); + dat = i2c_smbus_read_byte_data(ch7026_client, 0x00); + dev_dbg(&ch7026_client->dev, "read id = 0x%02X\n", dat); + if (dat != 0x54) + return -ENODEV; + + for (i = 0; i < REGMAP_LENGTH; ++i) { + if (i2c_smbus_write_byte_data + (ch7026_client, reg_init[i][0], reg_init[i][1]) < 0) + return -EIO; + } + + return 0; +} + +static int lcd_on; +/* + * Send Power On commands to L4F00242T03 + * + */ +static void lcd_poweron(struct fb_info *info) +{ + u16 data[4]; + u32 refresh; + + if (lcd_on) + return; + + dev_dbg(&ch7026_client->dev, "turning on LCD\n"); + + data[0] = PICOS2KHZ(info->var.pixclock) / 10; + data[2] = info->var.hsync_len + info->var.left_margin + + info->var.xres + info->var.right_margin; + data[3] = info->var.vsync_len + info->var.upper_margin + + info->var.yres + info->var.lower_margin; + + refresh = data[2] * data[3]; + refresh = (PICOS2KHZ(info->var.pixclock) * 1000) / refresh; + data[1] = refresh * 100; + + lcd_on = 1; +} + +/* + * Send Power Off commands to L4F00242T03 + * + */ +static void lcd_poweroff(void) +{ + if (!lcd_on) + return; + + dev_dbg(&ch7026_client->dev, "turning off LCD\n"); + + lcd_on = 0; +} + +static const struct i2c_device_id ch7026_id[] = { + {"ch7026", 0}, + {}, +}; + +MODULE_DEVICE_TABLE(i2c, ch7026_id); + +static struct i2c_driver ch7026_driver = { + .driver = { + .name = "ch7026", + }, + .probe = ch7026_probe, + .remove = ch7026_remove, + .suspend = ch7026_suspend, + .resume = ch7026_resume, + .id_table = ch7026_id, +}; + +static int __init ch7026_init(void) +{ + return i2c_add_driver(&ch7026_driver); +} + +static void __exit ch7026_exit(void) +{ + i2c_del_driver(&ch7026_driver); +} + +module_init(ch7026_init); +module_exit(ch7026_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("CH7026 VGA driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/video/mxc/mxcfb_claa_wvga.c b/drivers/video/mxc/mxcfb_claa_wvga.c new file mode 100644 index 000000000000..8f696c19e7d9 --- /dev/null +++ b/drivers/video/mxc/mxcfb_claa_wvga.c @@ -0,0 +1,239 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @defgroup Framebuffer Framebuffer Driver for SDC and ADC. + */ + +/*! + * @file mxcfb_claa_wvga.c + * + * @brief MXC Frame buffer driver for SDC + * + * @ingroup Framebuffer + */ + +/*! + * Include files + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static void lcd_poweron(void); +static void lcd_poweroff(void); + +static struct platform_device *plcd_dev; +static struct regulator *io_reg; +static struct regulator *core_reg; +static int lcd_on; + +static struct fb_videomode video_modes[] = { + { + /* 800x480 @ 57 Hz , pixel clk @ 27MHz */ + "CLAA-WVGA", 57, 800, 480, 37037, 40, 60, 10, 10, 20, 10, + FB_SYNC_CLK_LAT_FALL, + FB_VMODE_NONINTERLACED, + 0,}, +}; + +static void lcd_init_fb(struct fb_info *info) +{ + struct fb_var_screeninfo var; + + memset(&var, 0, sizeof(var)); + + fb_videomode_to_var(&var, &video_modes[0]); + + var.activate = FB_ACTIVATE_ALL; + var.yres_virtual = var.yres * 3; + + acquire_console_sem(); + info->flags |= FBINFO_MISC_USEREVENT; + fb_set_var(info, &var); + info->flags &= ~FBINFO_MISC_USEREVENT; + release_console_sem(); +} + +static int lcd_fb_event(struct notifier_block *nb, unsigned long val, void *v) +{ + struct fb_event *event = v; + + if (strcmp(event->info->fix.id, "DISP3 BG") && + strcmp(event->info->fix.id, "mxc_elcdif_fb")) + return 0; + + switch (val) { + case FB_EVENT_FB_REGISTERED: + lcd_init_fb(event->info); + fb_show_logo(event->info, 0); + lcd_poweron(); + break; + case FB_EVENT_BLANK: + if ((event->info->var.xres != 800) || + (event->info->var.yres != 480)) { + break; + } + if (*((int *)event->data) == FB_BLANK_UNBLANK) { + lcd_poweron(); + } else { + lcd_poweroff(); + } + break; + } + return 0; +} + +static struct notifier_block nb = { + .notifier_call = lcd_fb_event, +}; + +/*! + * This function is called whenever the SPI slave device is detected. + * + * @param spi the SPI slave device + * + * @return Returns 0 on SUCCESS and error on FAILURE. + */ +static int __devinit lcd_probe(struct platform_device *pdev) +{ + int i; + struct mxc_lcd_platform_data *plat = pdev->dev.platform_data; + + if (plat) { + if (plat->reset) + plat->reset(); + + io_reg = regulator_get(&pdev->dev, plat->io_reg); + if (IS_ERR(io_reg)) + io_reg = NULL; + core_reg = regulator_get(&pdev->dev, plat->core_reg); + if (!IS_ERR(core_reg)) { + regulator_set_voltage(io_reg, 1800000, 1800000); + } else { + core_reg = NULL; + } + } + + for (i = 0; i < num_registered_fb; i++) { + if (strcmp(registered_fb[i]->fix.id, "DISP3 BG") == 0 || + strcmp(registered_fb[i]->fix.id, "mxc_elcdif_fb") == 0) { + lcd_init_fb(registered_fb[i]); + fb_show_logo(registered_fb[i], 0); + lcd_poweron(); + } else if (strcmp(registered_fb[i]->fix.id, "DISP3 FG") == 0) { + lcd_init_fb(registered_fb[i]); + } + } + + fb_register_client(&nb); + + plcd_dev = pdev; + + return 0; +} + +static int __devexit lcd_remove(struct platform_device *pdev) +{ + fb_unregister_client(&nb); + lcd_poweroff(); + if (io_reg) + regulator_put(io_reg); + if (core_reg) + regulator_put(core_reg); + + return 0; +} + +#ifdef CONFIG_PM +static int lcd_suspend(struct platform_device *pdev, pm_message_t state) +{ + return 0; +} + +static int lcd_resume(struct platform_device *pdev) +{ + return 0; +} +#else +#define lcd_suspend NULL +#define lcd_resume NULL +#endif + +/*! + * platform driver structure for CLAA WVGA + */ +static struct platform_driver lcd_driver = { + .driver = { + .name = "lcd_claa"}, + .probe = lcd_probe, + .remove = __devexit_p(lcd_remove), + .suspend = lcd_suspend, + .resume = lcd_resume, +}; + +/* + * Send Power On commands to L4F00242T03 + * + */ +static void lcd_poweron(void) +{ + if (lcd_on) + return; + + dev_dbg(&plcd_dev->dev, "turning on LCD\n"); + if (core_reg) + regulator_enable(core_reg); + if (io_reg) + regulator_enable(io_reg); + lcd_on = 1; +} + +/* + * Send Power Off commands to L4F00242T03 + * + */ +static void lcd_poweroff(void) +{ + lcd_on = 0; + dev_dbg(&plcd_dev->dev, "turning off LCD\n"); + if (io_reg) + regulator_disable(io_reg); + if (core_reg) + regulator_disable(core_reg); +} + +static int __init claa_lcd_init(void) +{ + return platform_driver_register(&lcd_driver); +} + +static void __exit claa_lcd_exit(void) +{ + platform_driver_unregister(&lcd_driver); +} + +module_init(claa_lcd_init); +module_exit(claa_lcd_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("CLAA WVGA LCD init driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/video/mxc/mxcfb_epson.c b/drivers/video/mxc/mxcfb_epson.c new file mode 100644 index 000000000000..2b9bbec8a7e4 --- /dev/null +++ b/drivers/video/mxc/mxcfb_epson.c @@ -0,0 +1,1153 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file mxcfb_epson.c + * + * @brief MXC Frame buffer driver for ADC + * + * @ingroup Framebuffer + */ + +/*! + * Include files + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define PARTIAL_REFRESH +#define MXCFB_REFRESH_DEFAULT MXCFB_REFRESH_PARTIAL +/* + * Driver name + */ +#define MXCFB_NAME "MXCFB_EPSON" + +#define MXCFB_SCREEN_TOP_OFFSET 0 +#define MXCFB_SCREEN_LEFT_OFFSET 2 +#define MXCFB_SCREEN_WIDTH 176 +#define MXCFB_SCREEN_HEIGHT 220 + +/*! + * Enum defining Epson panel commands. + */ +enum { + DISON = 0xAF, + DISOFF = 0xAE, + DISCTL = 0xCA, + SD_CSET = 0x15, + SD_PSET = 0x75, + DATCTL = 0xBC, + SLPIN = 0x95, + SLPOUT = 0x94, + DISNOR = 0xA6, + RAMWR = 0x5C, + VOLCTR = 0xC6, + GCP16 = 0xCC, + GCP64 = 0xCB, +}; + +struct mxcfb_info { + int open_count; + int blank; + uint32_t disp_num; + + u32 pseudo_palette[16]; + + int32_t cur_update_mode; + dma_addr_t alloc_start_paddr; + void *alloc_start_vaddr; + u32 alloc_size; + uint32_t snoop_window_size; +}; + +struct mxcfb_data { + struct fb_info *fbi; + volatile int32_t vsync_flag; + wait_queue_head_t vsync_wq; + wait_queue_head_t suspend_wq; + bool suspended; +}; + +static struct mxcfb_data mxcfb_drv_data; +static unsigned long default_bpp = 16; + +void slcd_gpio_config(void); +extern void gpio_lcd_active(void); +static int mxcfb_blank(int blank, struct fb_info *fbi); + +static uint32_t bpp_to_pixfmt(int bpp) +{ + uint32_t pixfmt = 0; + switch (bpp) { + case 24: + pixfmt = IPU_PIX_FMT_BGR24; + break; + case 32: + pixfmt = IPU_PIX_FMT_BGR32; + break; + case 16: + pixfmt = IPU_PIX_FMT_RGB565; + break; + } + return pixfmt; +} + +/*! + * This function sets display region in the Epson panel + * + * @param disp display panel to config + * @param x1 x-coordinate of one vertex. + * @param x2 x-coordinate of second vertex. + * @param y1 y-coordinate of one vertex. + * @param y2 y-coordinate of second vertex. + */ +void set_panel_region(int disp, uint32_t x1, uint32_t x2, + uint32_t y1, uint32_t y2) +{ + uint32_t param[8]; + + memset(param, 0, sizeof(uint32_t) * 8); + param[0] = x1; + param[2] = x2; + param[4] = y1; + param[6] = y2; + + /* SD_CSET */ + ipu_adc_write_cmd(disp, CMD, SD_CSET, param, 4); + + /* SD_PSET */ + ipu_adc_write_cmd(disp, CMD, SD_PSET, &(param[4]), 4); +} + +/*! + * Function to create and initiate template command buffer for ADC. This + * template will be written to Panel memory. + */ +static void init_channel_template(int disp) +{ + /* template command buffer for ADC is 32 */ + uint32_t tempCmd[TEMPLATE_BUF_SIZE]; + uint32_t i = 0; + + memset(tempCmd, 0, sizeof(uint32_t) * TEMPLATE_BUF_SIZE); + /* setup update display region */ + /* whole the screen during init */ + /*WRITE Y COORDINATE CMND */ + tempCmd[i++] = ipu_adc_template_gen(WR_CMND, 0, SINGLE_STEP, SD_PSET); + /*WRITE Y START ADDRESS CMND LSB[22:8] */ + tempCmd[i++] = ipu_adc_template_gen(WR_YADDR, 1, SINGLE_STEP, 0x01); + /*WRITE Y START ADDRESS CMND MSB[22:16] */ + tempCmd[i++] = ipu_adc_template_gen(WR_YADDR, 1, SINGLE_STEP, 0x09); + /*WRITE Y STOP ADDRESS CMND LSB */ + tempCmd[i++] = ipu_adc_template_gen(WR_CMND, 1, SINGLE_STEP, + MXCFB_SCREEN_HEIGHT - 1); + /*WRITE Y STOP ADDRESS CMND MSB */ + tempCmd[i++] = ipu_adc_template_gen(WR_CMND, 1, SINGLE_STEP, 0); + /*WRITE X COORDINATE CMND */ + tempCmd[i++] = ipu_adc_template_gen(WR_CMND, 0, SINGLE_STEP, SD_CSET); + /*WRITE X ADDRESS CMND LSB[7:0] */ + tempCmd[i++] = ipu_adc_template_gen(WR_XADDR, 1, SINGLE_STEP, 0x01); + /*WRITE X ADDRESS CMND MSB[22:8] */ + tempCmd[i++] = ipu_adc_template_gen(WR_CMND, 1, SINGLE_STEP, 0); + /*WRITE X STOP ADDRESS CMND LSB */ + tempCmd[i++] = ipu_adc_template_gen(WR_CMND, 1, SINGLE_STEP, + MXCFB_SCREEN_WIDTH + 1); + /*WRITE X STOP ADDRESS CMND MSB */ + tempCmd[i++] = ipu_adc_template_gen(WR_CMND, 1, SINGLE_STEP, 0); + /*WRITE MEMORY CMND MSB */ + tempCmd[i++] = ipu_adc_template_gen(WR_CMND, 0, SINGLE_STEP, RAMWR); + /*WRITE DATA CMND and STP */ + tempCmd[i++] = ipu_adc_template_gen(WR_DATA, 1, STOP, 0); + + ipu_adc_write_template(disp, tempCmd, true); +} + +/*! + * Function to initialize the panel. First it resets the panel and then + * initilizes panel. + */ +static void _init_panel(int disp) +{ + uint32_t cmd_param; + uint32_t i; + + gpio_lcd_active(); + slcd_gpio_config(); + + /* DATCTL */ +#ifdef CONFIG_FB_MXC_ASYNC_PANEL_IFC_16_BIT + /* 16-bit 565 mode */ + cmd_param = 0x28; +#else + /* 8-bit 666 mode */ + cmd_param = 0x08; +#endif + ipu_adc_write_cmd(disp, CMD, DATCTL, &cmd_param, 1); + + /* Sleep OUT */ + ipu_adc_write_cmd(disp, CMD, SLPOUT, 0, 0); + + /* Set display to white + Setup page and column addresses */ + set_panel_region(disp, MXCFB_SCREEN_LEFT_OFFSET, + MXCFB_SCREEN_WIDTH + MXCFB_SCREEN_LEFT_OFFSET - 1, + 0, MXCFB_SCREEN_HEIGHT - 1); + /* Do RAM write cmd */ + ipu_adc_write_cmd(disp, CMD, RAMWR, 0, 0); +#ifdef CONFIG_FB_MXC_ASYNC_PANEL_IFC_16_BIT + for (i = 0; i < (MXCFB_SCREEN_WIDTH * MXCFB_SCREEN_HEIGHT); i++) +#else + for (i = 0; i < (MXCFB_SCREEN_WIDTH * MXCFB_SCREEN_HEIGHT * 3); i++) +#endif + ipu_adc_write_cmd(disp, DAT, 0xFFFF, 0, 0); + + /* Pause 80 ms */ + mdelay(80); + + /* Display ON */ + ipu_adc_write_cmd(disp, CMD, DISON, 0, 0); + /* Pause 200 ms */ + mdelay(200); + + pr_debug("initialized panel\n"); +} + +#ifdef PARTIAL_REFRESH +static irqreturn_t mxcfb_sys2_eof_irq_handler(int irq, void *dev_id) +{ + ipu_channel_params_t params; + struct fb_info *fbi = dev_id; + struct mxcfb_info *mxc_fbi = fbi->par; + uint32_t stat[2], seg_size; + uint32_t lsb, msb; + uint32_t update_height, start_line, start_addr, end_line, end_addr; + uint32_t stride_pixels = (fbi->fix.line_length * 8) / + fbi->var.bits_per_pixel; + + ipu_adc_get_snooping_status(&stat[0], &stat[1]); + + if (!stat[0] && !stat[1]) { + dev_err(fbi->device, "error no bus snooping bits set\n"); + return IRQ_HANDLED; + } + ipu_disable_irq(IPU_IRQ_ADC_SYS2_EOF); + + lsb = ffs(stat[0]); + if (lsb) { + lsb--; + } else { + lsb = ffs(stat[1]); + lsb += 32 - 1; + } + msb = fls(stat[1]); + if (msb) { + msb += 32; + } else { + msb = fls(stat[0]); + } + + seg_size = mxc_fbi->snoop_window_size / 64; + + start_addr = lsb * seg_size; /* starting address offset */ + start_line = start_addr / fbi->fix.line_length; + start_addr = start_line * fbi->fix.line_length; /* Addr aligned to line */ + start_addr += fbi->fix.smem_start; + + end_addr = msb * seg_size; /* ending address offset */ + end_line = end_addr / fbi->fix.line_length; + end_line++; + + if (end_line > fbi->var.yres) { + end_line = fbi->var.yres; + } + + update_height = end_line - start_line; + dev_dbg(fbi->device, "updating rows %d to %d, start addr = 0x%08X\n", + start_line, end_line, start_addr); + + ipu_uninit_channel(ADC_SYS1); + params.adc_sys1.disp = mxc_fbi->disp_num; + params.adc_sys1.ch_mode = WriteTemplateNonSeq; + params.adc_sys1.out_left = MXCFB_SCREEN_LEFT_OFFSET; + params.adc_sys1.out_top = start_line; + ipu_init_channel(ADC_SYS1, ¶ms); + + ipu_init_channel_buffer(ADC_SYS1, IPU_INPUT_BUFFER, + bpp_to_pixfmt(fbi->var.bits_per_pixel), + MXCFB_SCREEN_WIDTH, + update_height, + stride_pixels, + IPU_ROTATE_NONE, (dma_addr_t) start_addr, 0, + 0, 0); + ipu_enable_channel(ADC_SYS1); + ipu_select_buffer(ADC_SYS1, IPU_INPUT_BUFFER, 0); + ipu_enable_irq(IPU_IRQ_ADC_SYS1_EOF); + + return IRQ_HANDLED; +} + +static irqreturn_t mxcfb_sys1_eof_irq_handler(int irq, void *dev_id) +{ + ipu_disable_irq(IPU_IRQ_ADC_SYS1_EOF); + ipu_disable_channel(ADC_SYS1, false); + + ipu_enable_channel(ADC_SYS2); + ipu_enable_irq(IPU_IRQ_ADC_SYS2_EOF); + + return IRQ_HANDLED; +} +#endif + +/*! + * Function to initialize Asynchronous Display Controller. It also initilizes + * the ADC System 1 channel. Configure ADC display 0 parallel interface for + * the panel. + * + * @param fbi framebuffer information pointer + */ +static void mxcfb_init_panel(struct fb_info *fbi) +{ + int msb; + int panel_stride; + ipu_channel_params_t params; + struct mxcfb_info *mxc_fbi = (struct mxcfb_info *)fbi->par; + +#ifdef CONFIG_FB_MXC_ASYNC_PANEL_IFC_16_BIT + uint32_t pix_fmt = IPU_PIX_FMT_RGB565; + ipu_adc_sig_cfg_t sig = { 0, 0, 0, 0, 0, 0, 0, 0, + IPU_ADC_BURST_WCS, + IPU_ADC_IFC_MODE_SYS80_TYPE2, + 16, 0, 0, IPU_ADC_SER_NO_RW + }; + mxc_fbi->disp_num = DISP0; +#elif defined(CONFIG_FB_MXC_ASYNC_PANEL_IFC_8_BIT) + uint32_t pix_fmt = IPU_PIX_FMT_RGB666; + ipu_adc_sig_cfg_t sig = { 0, 0, 0, 0, 0, 0, 0, 0, + IPU_ADC_BURST_WCS, + IPU_ADC_IFC_MODE_SYS80_TYPE2, + 8, 0, 0, IPU_ADC_SER_NO_RW + }; + mxc_fbi->disp_num = DISP0; +#else + uint32_t pix_fmt = IPU_PIX_FMT_RGB565; + ipu_adc_sig_cfg_t sig = { 0, 1, 0, 0, 0, 0, 0, 0, + IPU_ADC_BURST_SERIAL, + IPU_ADC_IFC_MODE_5WIRE_SERIAL_CLK, + 16, 0, 0, IPU_ADC_SER_NO_RW + }; + fbi->disp_num = DISP1; +#endif + +#ifdef PARTIAL_REFRESH + if (ipu_request_irq(IPU_IRQ_ADC_SYS2_EOF, mxcfb_sys2_eof_irq_handler, 0, + MXCFB_NAME, fbi) != 0) { + dev_err(fbi->device, "Error registering SYS2 irq handler.\n"); + return; + } + + if (ipu_request_irq(IPU_IRQ_ADC_SYS1_EOF, mxcfb_sys1_eof_irq_handler, 0, + MXCFB_NAME, fbi) != 0) { + dev_err(fbi->device, "Error registering SYS1 irq handler.\n"); + return; + } + ipu_disable_irq(IPU_IRQ_ADC_SYS1_EOF); + ipu_disable_irq(IPU_IRQ_ADC_SYS2_EOF); +#endif + /* Init DI interface */ + msb = fls(MXCFB_SCREEN_WIDTH); + if (!(MXCFB_SCREEN_WIDTH & ((1UL << msb) - 1))) + msb--; /* Already aligned to power 2 */ + panel_stride = 1UL << msb; + ipu_adc_init_panel(mxc_fbi->disp_num, + MXCFB_SCREEN_WIDTH + MXCFB_SCREEN_LEFT_OFFSET, + MXCFB_SCREEN_HEIGHT, + pix_fmt, panel_stride, sig, XY, 0, VsyncInternal); + + ipu_adc_init_ifc_timing(mxc_fbi->disp_num, true, + 190, 17, 104, 190, 5000000); + ipu_adc_init_ifc_timing(mxc_fbi->disp_num, false, 123, 17, 68, 0, 0); + + /* Needed to turn on ADC clock for panel init */ + memset(¶ms, 0, sizeof(params)); + params.adc_sys1.disp = mxc_fbi->disp_num; + params.adc_sys1.ch_mode = WriteTemplateNonSeq; + params.adc_sys1.out_left = MXCFB_SCREEN_LEFT_OFFSET; + params.adc_sys1.out_top = MXCFB_SCREEN_TOP_OFFSET; + ipu_init_channel(ADC_SYS1, ¶ms); + + _init_panel(mxc_fbi->disp_num); + init_channel_template(mxc_fbi->disp_num); +} + +int mxcfb_set_refresh_mode(struct fb_info *fbi, int mode, + struct mxcfb_rect *update_region) +{ + unsigned long start_addr; + int ret_mode; + uint32_t dummy; + ipu_channel_params_t params; + struct mxcfb_rect rect; + struct mxcfb_info *mxc_fbi = (struct mxcfb_info *)fbi->par; + uint32_t stride_pixels = (fbi->fix.line_length * 8) / + fbi->var.bits_per_pixel; + uint32_t memsize = fbi->fix.smem_len; + + if (mxc_fbi->cur_update_mode == mode) + return mode; + + ret_mode = mxc_fbi->cur_update_mode; + + ipu_disable_irq(IPU_IRQ_ADC_SYS1_EOF); + ipu_adc_set_update_mode(ADC_SYS1, IPU_ADC_REFRESH_NONE, 0, 0, 0); +#ifdef PARTIAL_REFRESH + ipu_disable_irq(IPU_IRQ_ADC_SYS2_EOF); + ipu_adc_set_update_mode(ADC_SYS2, IPU_ADC_REFRESH_NONE, 0, 0, 0); +#endif + + ipu_disable_channel(ADC_SYS1, true); + ipu_clear_irq(IPU_IRQ_ADC_SYS1_EOF); +#ifdef PARTIAL_REFRESH + ipu_disable_channel(ADC_SYS2, true); + ipu_clear_irq(IPU_IRQ_ADC_SYS2_EOF); +#endif + ipu_adc_get_snooping_status(&dummy, &dummy); + + mxc_fbi->cur_update_mode = mode; + + switch (mode) { + case MXCFB_REFRESH_OFF: + if (ipu_adc_set_update_mode(ADC_SYS1, IPU_ADC_REFRESH_NONE, + 0, 0, 0) < 0) + dev_err(fbi->device, "Error enabling auto refesh.\n"); + if (ipu_adc_set_update_mode(ADC_SYS2, IPU_ADC_REFRESH_NONE, + 0, 0, 0) < 0) + dev_err(fbi->device, "Error enabling auto refesh.\n"); +#if 0 + ipu_init_channel_buffer(ADC_SYS2, IPU_INPUT_BUFFER, + bpp_to_pixfmt(fbi->var.bits_per_pixel), + 1, 1, 4, + IPU_ROTATE_NONE, + fbi->fix.smem_start, + fbi->fix.smem_start, 0, 0); + ipu_enable_channel(ADC_SYS2); + ipu_select_buffer(ADC_SYS2, IPU_INPUT_BUFFER, 0); + ipu_select_buffer(ADC_SYS2, IPU_INPUT_BUFFER, 1); + msleep(10); +#endif + ipu_uninit_channel(ADC_SYS1); +#ifdef PARTIAL_REFRESH + ipu_uninit_channel(ADC_SYS2); +#endif + break; + case MXCFB_REFRESH_PARTIAL: +#ifdef PARTIAL_REFRESH + ipu_adc_get_snooping_status(&dummy, &dummy); + + params.adc_sys2.disp = DISP0; + params.adc_sys2.ch_mode = WriteTemplateNonSeq; + params.adc_sys2.out_left = 0; + params.adc_sys2.out_top = 0; + ipu_init_channel(ADC_SYS2, ¶ms); + + if (ipu_adc_set_update_mode(ADC_SYS1, IPU_ADC_REFRESH_NONE, + 0, 0, 0) < 0) { + dev_err(fbi->device, "Error enabling auto refesh.\n"); + } + if (ipu_adc_set_update_mode + (ADC_SYS2, IPU_ADC_AUTO_REFRESH_SNOOP, 30, + fbi->fix.smem_start, &memsize) < 0) { + dev_err(fbi->device, "Error enabling auto refesh.\n"); + } + mxc_fbi->snoop_window_size = memsize; + + ipu_init_channel_buffer(ADC_SYS2, IPU_INPUT_BUFFER, + bpp_to_pixfmt(fbi->var.bits_per_pixel), + 1, 1, 4, + IPU_ROTATE_NONE, + fbi->fix.smem_start, 0, 0, 0); + + params.adc_sys1.disp = mxc_fbi->disp_num; + params.adc_sys1.ch_mode = WriteTemplateNonSeq; + params.adc_sys1.out_left = MXCFB_SCREEN_LEFT_OFFSET; + params.adc_sys1.out_top = MXCFB_SCREEN_TOP_OFFSET; + ipu_init_channel(ADC_SYS1, ¶ms); + + ipu_init_channel_buffer(ADC_SYS1, IPU_INPUT_BUFFER, + bpp_to_pixfmt(fbi->var.bits_per_pixel), + MXCFB_SCREEN_WIDTH, MXCFB_SCREEN_HEIGHT, + stride_pixels, IPU_ROTATE_NONE, + fbi->fix.smem_start, 0, 0, 0); + ipu_enable_channel(ADC_SYS1); + ipu_select_buffer(ADC_SYS1, IPU_INPUT_BUFFER, 0); + ipu_enable_irq(IPU_IRQ_ADC_SYS1_EOF); + break; +#endif + case MXCFB_REFRESH_AUTO: + if (update_region == NULL) { + update_region = ▭ + rect.top = 0; + rect.left = 0; + rect.height = MXCFB_SCREEN_HEIGHT; + rect.width = MXCFB_SCREEN_WIDTH; + } + params.adc_sys1.disp = mxc_fbi->disp_num; + params.adc_sys1.ch_mode = WriteTemplateNonSeq; + params.adc_sys1.out_left = MXCFB_SCREEN_LEFT_OFFSET + + update_region->left; + params.adc_sys1.out_top = MXCFB_SCREEN_TOP_OFFSET + + update_region->top; + ipu_init_channel(ADC_SYS1, ¶ms); + + /* Address aligned to line */ + start_addr = update_region->top * fbi->fix.line_length; + start_addr += fbi->fix.smem_start; + start_addr += update_region->left * fbi->var.bits_per_pixel / 8; + + ipu_init_channel_buffer(ADC_SYS1, IPU_INPUT_BUFFER, + bpp_to_pixfmt(fbi->var.bits_per_pixel), + update_region->width, + update_region->height, stride_pixels, + IPU_ROTATE_NONE, start_addr, 0, 0, 0); + ipu_enable_channel(ADC_SYS1); + ipu_select_buffer(ADC_SYS1, IPU_INPUT_BUFFER, 0); + + if (ipu_adc_set_update_mode + (ADC_SYS1, IPU_ADC_AUTO_REFRESH_SNOOP, 30, + fbi->fix.smem_start, &memsize) < 0) + dev_err(fbi->device, "Error enabling auto refesh.\n"); + + mxc_fbi->snoop_window_size = memsize; + + break; + } + return ret_mode; +} + +/* + * Open the main framebuffer. + * + * @param fbi framebuffer information pointer + * + * @param user Set if opened by user or clear if opened by kernel + */ +static int mxcfb_open(struct fb_info *fbi, int user) +{ + int retval = 0; + struct mxcfb_info *mxc_fbi = fbi->par; + + retval = wait_event_interruptible(mxcfb_drv_data.suspend_wq, + (mxcfb_drv_data.suspended == false)); + if (retval < 0) + return retval; + + mxc_fbi->open_count++; + + retval = mxcfb_blank(FB_BLANK_UNBLANK, fbi); + return retval; +} + +/* + * Close the main framebuffer. + * + * @param fbi framebuffer information pointer + * + * @param user Set if opened by user or clear if opened by kernel + */ +static int mxcfb_release(struct fb_info *fbi, int user) +{ + int retval = 0; + struct mxcfb_info *mxc_fbi = fbi->par; + + retval = wait_event_interruptible(mxcfb_drv_data.suspend_wq, + (mxcfb_drv_data.suspended == false)); + if (retval < 0) + return retval; + + --mxc_fbi->open_count; + if (mxc_fbi->open_count == 0) { + retval = mxcfb_blank(FB_BLANK_POWERDOWN, fbi); + } + return retval; +} + +/* + * Set fixed framebuffer parameters based on variable settings. + * + * @param info framebuffer information pointer + */ +static int mxcfb_set_fix(struct fb_info *info) +{ + struct fb_fix_screeninfo *fix = &info->fix; + struct fb_var_screeninfo *var = &info->var; + struct mxcfb_info *mxc_fbi = (struct mxcfb_info *)info->par; + + /* Set framebuffer id to IPU display number. */ + strcpy(fix->id, "DISP0 FB"); + fix->id[4] = '0' + mxc_fbi->disp_num; + + /* Init settings based on the panel size */ + fix->line_length = MXCFB_SCREEN_WIDTH * var->bits_per_pixel / 8; + + fix->type = FB_TYPE_PACKED_PIXELS; + fix->accel = FB_ACCEL_NONE; + fix->visual = FB_VISUAL_TRUECOLOR; + fix->xpanstep = 0; + fix->ypanstep = 0; + + return 0; +} + +/* + * Set framebuffer parameters and change the operating mode. + * + * @param info framebuffer information pointer + */ +static int mxcfb_set_par(struct fb_info *fbi) +{ + int retval = 0; + int mode; + + retval = wait_event_interruptible(mxcfb_drv_data.suspend_wq, + (mxcfb_drv_data.suspended == false)); + if (retval < 0) + return retval; + + mode = mxcfb_set_refresh_mode(fbi, MXCFB_REFRESH_OFF, NULL); + + mxcfb_set_fix(fbi); + + if (mode != MXCFB_REFRESH_OFF) { +#ifdef PARTIAL_REFRESH + mxcfb_set_refresh_mode(fbi, MXCFB_REFRESH_PARTIAL, NULL); +#else + mxcfb_set_refresh_mode(fbi, MXCFB_REFRESH_AUTO, NULL); +#endif + } + return 0; +} + +/* + * Check framebuffer variable parameters and adjust to valid values. + * + * @param var framebuffer variable parameters + * + * @param info framebuffer information pointer + */ +static int mxcfb_check_var(struct fb_var_screeninfo *var, struct fb_info *fbi) +{ + if (var->xres > MXCFB_SCREEN_WIDTH) + var->xres = MXCFB_SCREEN_WIDTH; + if (var->yres > MXCFB_SCREEN_HEIGHT) + var->yres = MXCFB_SCREEN_HEIGHT; + if (var->xres_virtual < var->xres) + var->xres_virtual = var->xres; + if (var->yres_virtual < var->yres) + var->yres_virtual = var->yres; + + if ((var->bits_per_pixel != 32) && (var->bits_per_pixel != 24) && + (var->bits_per_pixel != 16)) { + var->bits_per_pixel = default_bpp; + } + + switch (var->bits_per_pixel) { + case 16: + var->red.length = 5; + var->red.offset = 11; + var->red.msb_right = 0; + + var->green.length = 6; + var->green.offset = 5; + var->green.msb_right = 0; + + var->blue.length = 5; + var->blue.offset = 0; + var->blue.msb_right = 0; + + var->transp.length = 0; + var->transp.offset = 0; + var->transp.msb_right = 0; + break; + case 24: + var->red.length = 8; + var->red.offset = 16; + var->red.msb_right = 0; + + var->green.length = 8; + var->green.offset = 8; + var->green.msb_right = 0; + + var->blue.length = 8; + var->blue.offset = 0; + var->blue.msb_right = 0; + + var->transp.length = 0; + var->transp.offset = 0; + var->transp.msb_right = 0; + break; + case 32: + var->red.length = 8; + var->red.offset = 16; + var->red.msb_right = 0; + + var->green.length = 8; + var->green.offset = 8; + var->green.msb_right = 0; + + var->blue.length = 8; + var->blue.offset = 0; + var->blue.msb_right = 0; + + var->transp.length = 8; + var->transp.offset = 24; + var->transp.msb_right = 0; + break; + } + + var->height = -1; + var->width = -1; + var->grayscale = 0; + var->nonstd = 0; + + var->pixclock = -1; + var->left_margin = -1; + var->right_margin = -1; + var->upper_margin = -1; + var->lower_margin = -1; + var->hsync_len = -1; + var->vsync_len = -1; + + var->vmode = FB_VMODE_NONINTERLACED; + var->sync = 0; + + return 0; +} + +static inline u_int _chan_to_field(u_int chan, struct fb_bitfield *bf) +{ + chan &= 0xffff; + chan >>= 16 - bf->length; + return chan << bf->offset; +} + +static int +mxcfb_setcolreg(u_int regno, u_int red, u_int green, u_int blue, + u_int trans, struct fb_info *fbi) +{ + unsigned int val; + int ret = 1; + + /* + * If greyscale is true, then we convert the RGB value + * to greyscale no matter what visual we are using. + */ + if (fbi->var.grayscale) + red = green = blue = (19595 * red + 38470 * green + + 7471 * blue) >> 16; + switch (fbi->fix.visual) { + case FB_VISUAL_TRUECOLOR: + /* + * 16-bit True Colour. We encode the RGB value + * according to the RGB bitfield information. + */ + if (regno < 16) { + u32 *pal = fbi->pseudo_palette; + + val = _chan_to_field(red, &fbi->var.red); + val |= _chan_to_field(green, &fbi->var.green); + val |= _chan_to_field(blue, &fbi->var.blue); + + pal[regno] = val; + ret = 0; + } + break; + + case FB_VISUAL_STATIC_PSEUDOCOLOR: + case FB_VISUAL_PSEUDOCOLOR: + break; + } + + return ret; +} + +/* + * mxcfb_blank(): + * Blank the display. + */ +static int mxcfb_blank(int blank, struct fb_info *fbi) +{ + int retval = 0; + struct mxcfb_info *mxc_fbi = fbi->par; + + dev_dbg(fbi->device, "blank = %d\n", blank); + + retval = wait_event_interruptible(mxcfb_drv_data.suspend_wq, + (mxcfb_drv_data.suspended == false)); + if (retval < 0) + return retval; + + mxc_fbi->blank = blank; + + switch (blank) { + case FB_BLANK_POWERDOWN: + case FB_BLANK_VSYNC_SUSPEND: + case FB_BLANK_HSYNC_SUSPEND: + case FB_BLANK_NORMAL: + mxcfb_set_refresh_mode(fbi, MXCFB_REFRESH_OFF, NULL); + break; + case FB_BLANK_UNBLANK: + mxcfb_set_refresh_mode(fbi, MXCFB_REFRESH_DEFAULT, NULL); + break; + } + return 0; +} + +/*! + * This structure contains the pointers to the control functions that are + * invoked by the core framebuffer driver to perform operations like + * blitting, rectangle filling, copy regions and cursor definition. + */ +static struct fb_ops mxcfb_ops = { + .owner = THIS_MODULE, + .fb_open = mxcfb_open, + .fb_release = mxcfb_release, + .fb_set_par = mxcfb_set_par, + .fb_check_var = mxcfb_check_var, + .fb_setcolreg = mxcfb_setcolreg, + .fb_fillrect = cfb_fillrect, + .fb_copyarea = cfb_copyarea, + .fb_imageblit = cfb_imageblit, + .fb_blank = mxcfb_blank, +}; + +/*! + * Allocates the DRAM memory for the frame buffer. This buffer is remapped + * into a non-cached, non-buffered, memory region to allow palette and pixel + * writes to occur without flushing the cache. Once this area is remapped, + * all virtual memory access to the video memory should occur at the new region. + * + * @param fbi framebuffer information pointer + * + * @return Error code indicating success or failure + */ +static int mxcfb_map_video_memory(struct fb_info *fbi) +{ + u32 msb; + u32 offset; + struct mxcfb_info *mxcfbi = fbi->par; + + fbi->fix.smem_len = fbi->var.xres_virtual * fbi->var.yres_virtual * 4; + + /* Set size to power of 2. */ + msb = fls(fbi->fix.smem_len); + if (!(fbi->fix.smem_len & ((1UL << msb) - 1))) + msb--; /* Already aligned to power 2 */ + if (msb < 11) + msb = 11; + mxcfbi->alloc_size = (1UL << msb) * 2; + + mxcfbi->alloc_start_vaddr = dma_alloc_coherent(fbi->device, + mxcfbi->alloc_size, + &mxcfbi-> + alloc_start_paddr, + GFP_KERNEL | GFP_DMA); + + if (mxcfbi->alloc_start_vaddr == 0) { + dev_err(fbi->device, "Unable to allocate framebuffer memory\n"); + return -ENOMEM; + } + dev_dbg(fbi->device, "allocated fb memory @ paddr=0x%08X, size=%d.\n", + (uint32_t) mxcfbi->alloc_start_paddr, mxcfbi->alloc_size); + + offset = + ((mxcfbi->alloc_size / 2) - 1) & ~((mxcfbi->alloc_size / 2) - 1); + fbi->fix.smem_start = mxcfbi->alloc_start_paddr + offset; + dev_dbg(fbi->device, "aligned fb start @ paddr=0x%08lX, size=%u.\n", + fbi->fix.smem_start, fbi->fix.smem_len); + + fbi->screen_base = mxcfbi->alloc_start_vaddr + offset; + + /* Clear the screen */ + memset(fbi->screen_base, 0, fbi->fix.smem_len); + return 0; +} + +/*! + * De-allocates the DRAM memory for the frame buffer. + * + * @param fbi framebuffer information pointer + * + * @return Error code indicating success or failure + */ +static int mxcfb_unmap_video_memory(struct fb_info *fbi) +{ + struct mxcfb_info *mxc_fbi = (struct mxcfb_info *)fbi->par; + + dma_free_coherent(fbi->device, mxc_fbi->alloc_size, + mxc_fbi->alloc_start_vaddr, + mxc_fbi->alloc_start_paddr); + return 0; +} + +/*! + * Initializes the framebuffer information pointer. After allocating + * sufficient memory for the framebuffer structure, the fields are + * filled with custom information passed in from the configurable + * structures. This includes information such as bits per pixel, + * color maps, screen width/height and RGBA offsets. + * + * @return Framebuffer structure initialized with our information + */ +static struct fb_info *mxcfb_init_fbinfo(struct device *dev, struct fb_ops *ops) +{ + struct fb_info *fbi; + struct mxcfb_info *mxcfbi; + + /* + * Allocate sufficient memory for the fb structure + */ + fbi = framebuffer_alloc(sizeof(struct mxcfb_info), dev); + if (!fbi) + return NULL; + + mxcfbi = (struct mxcfb_info *)fbi->par; + + /* + * Fill in fb_info structure information + */ + fbi->var.xres = fbi->var.xres_virtual = MXCFB_SCREEN_WIDTH; + fbi->var.yres = fbi->var.yres_virtual = MXCFB_SCREEN_HEIGHT; + fbi->var.activate = FB_ACTIVATE_NOW; + mxcfb_check_var(&fbi->var, fbi); + + mxcfb_set_fix(fbi); + + fbi->fbops = ops; + fbi->flags = FBINFO_FLAG_DEFAULT; + fbi->pseudo_palette = mxcfbi->pseudo_palette; + + /* + * Allocate colormap + */ + fb_alloc_cmap(&fbi->cmap, 16, 0); + + return fbi; +} + +/*! + * Probe routine for the framebuffer driver. It is called during the + * driver binding process. The following functions are performed in + * this routine: Framebuffer initialization, Memory allocation and + * mapping, Framebuffer registration, IPU initialization. + * + * @return Appropriate error code to the kernel common code + */ +static int mxcfb_probe(struct platform_device *pdev) +{ + struct fb_info *fbi; + struct mxcfb_info *mxc_fbi; + int ret; + + platform_set_drvdata(pdev, &mxcfb_drv_data); + + /* + * Initialize FB structures + */ + fbi = mxcfb_init_fbinfo(&pdev->dev, &mxcfb_ops); + if (!fbi) { + ret = -ENOMEM; + goto err0; + } + mxcfb_drv_data.fbi = fbi; + mxc_fbi = fbi->par; + + mxcfb_drv_data.suspended = false; + init_waitqueue_head(&mxcfb_drv_data.suspend_wq); + + /* + * Allocate memory + */ + ret = mxcfb_map_video_memory(fbi); + if (ret < 0) { + goto err1; + } + + mxcfb_init_panel(fbi); + + /* + * Register framebuffer + */ + ret = register_framebuffer(fbi); + if (ret < 0) { + goto err2; + } + + dev_info(&pdev->dev, "%s registered\n", MXCFB_NAME); + + return 0; + + err2: + mxcfb_unmap_video_memory(fbi); + err1: + if (&fbi->cmap) + fb_dealloc_cmap(&fbi->cmap); + framebuffer_release(fbi); + err0: + return ret; +} + +#ifdef CONFIG_PM +/*! + * Power management hooks. Note that we won't be called from IRQ context, + * unlike the blank functions above, so we may sleep. + */ + +/*! + * Suspends the framebuffer and blanks the screen. Power management support + * + * @param pdev pointer to device structure. + * @param state state of the device. + * + * @return success + */ +static int mxcfb_suspend(struct platform_device *pdev, pm_message_t state) +{ + struct mxcfb_data *drv_data = platform_get_drvdata(pdev); + struct fb_info *fbi = drv_data->fbi; + struct mxcfb_info *mxc_fbi = fbi->par; + + drv_data->suspended = true; + + if (mxc_fbi->blank == FB_BLANK_UNBLANK) + mxcfb_set_refresh_mode(fbi, MXCFB_REFRESH_OFF, NULL); + /* Display OFF */ + ipu_adc_write_cmd(mxc_fbi->disp_num, CMD, DISOFF, 0, 0); + + return 0; +} + +/*! + * Resumes the framebuffer and unblanks the screen. Power management support + * + * @param pdev pointer to device structure. + * + * @return success + */ +static int mxcfb_resume(struct platform_device *pdev) +{ + struct mxcfb_data *drv_data = platform_get_drvdata(pdev); + struct fb_info *fbi = drv_data->fbi; + struct mxcfb_info *mxc_fbi = fbi->par; + + /* Display ON */ + ipu_adc_write_cmd(mxc_fbi->disp_num, CMD, DISON, 0, 0); + drv_data->suspended = false; + + if (mxc_fbi->blank == FB_BLANK_UNBLANK) + mxcfb_set_refresh_mode(fbi, MXCFB_REFRESH_DEFAULT, NULL); + wake_up_interruptible(&drv_data->suspend_wq); + + return 0; +} +#else +#define mxcfb_suspend NULL +#define mxcfb_resume NULL +#endif + +/*! + * This structure contains pointers to the power management callback functions. + */ +static struct platform_driver mxcfb_driver = { + .driver = { + .name = MXCFB_NAME, + }, + .probe = mxcfb_probe, + .suspend = mxcfb_suspend, + .resume = mxcfb_resume, +}; + +/*! + * Device definition for the Framebuffer + */ +static struct platform_device mxcfb_device = { + .name = MXCFB_NAME, + .id = 0, + .dev = { + .coherent_dma_mask = 0xFFFFFFFF, + } +}; + +/*! + * Main entry function for the framebuffer. The function registers the power + * management callback functions with the kernel and also registers the MXCFB + * callback functions with the core Linux framebuffer driver \b fbmem.c + * + * @return Error code indicating success or failure + */ +static int mxcfb_init(void) +{ + int ret = 0; + + ret = platform_driver_register(&mxcfb_driver); + if (ret == 0) { + ret = platform_device_register(&mxcfb_device); + if (ret != 0) { + platform_driver_unregister(&mxcfb_driver); + } + } + return ret; +} + +static void mxcfb_exit(void) +{ + struct fb_info *fbi = dev_get_drvdata(&mxcfb_device.dev); + + if (fbi) { + mxcfb_unmap_video_memory(fbi); + + if (&fbi->cmap) + fb_dealloc_cmap(&fbi->cmap); + + unregister_framebuffer(fbi); + framebuffer_release(fbi); + } + + platform_device_unregister(&mxcfb_device); + platform_driver_unregister(&mxcfb_driver); +} + +module_init(mxcfb_init); +module_exit(mxcfb_exit); + +EXPORT_SYMBOL(mxcfb_set_refresh_mode); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MXC Epson framebuffer driver"); +MODULE_SUPPORTED_DEVICE("fb"); diff --git a/drivers/video/mxc/mxcfb_epson_vga.c b/drivers/video/mxc/mxcfb_epson_vga.c new file mode 100644 index 000000000000..8b5ea1a945d4 --- /dev/null +++ b/drivers/video/mxc/mxcfb_epson_vga.c @@ -0,0 +1,362 @@ +/* + * Copyright 2007-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @defgroup Framebuffer Framebuffer Driver for SDC and ADC. + */ + +/*! + * @file mxcfb_epson_vga.c + * + * @brief MXC Frame buffer driver for SDC + * + * @ingroup Framebuffer + */ + +/*! + * Include files + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static struct spi_device *lcd_spi; +static struct device *lcd_dev; + +static void lcd_init(void); +static void lcd_poweron(void); +static void lcd_poweroff(void); + +static void (*lcd_reset) (void); +static struct regulator *io_reg; +static struct regulator *core_reg; + +static struct fb_videomode video_modes[] = { + { + /* 480x640 @ 60 Hz */ + "Epson-VGA", 60, 480, 640, 41701, 60, 41, 10, 5, 20, 10, + 0, + FB_VMODE_NONINTERLACED, + 0,}, +}; + +static void lcd_init_fb(struct fb_info *info) +{ + struct fb_var_screeninfo var; + + memset(&var, 0, sizeof(var)); + + fb_videomode_to_var(&var, &video_modes[0]); + + if (machine_is_mx31_3ds()) { + var.upper_margin = 0; + var.left_margin = 0; + } + + var.activate = FB_ACTIVATE_ALL; + var.yres_virtual = var.yres * 3; + + acquire_console_sem(); + info->flags |= FBINFO_MISC_USEREVENT; + fb_set_var(info, &var); + info->flags &= ~FBINFO_MISC_USEREVENT; + release_console_sem(); +} + +static int lcd_fb_event(struct notifier_block *nb, unsigned long val, void *v) +{ + struct fb_event *event = v; + + if (strcmp(event->info->fix.id, "DISP3 BG")) { + return 0; + } + + switch (val) { + case FB_EVENT_FB_REGISTERED: + lcd_init_fb(event->info); + lcd_poweron(); + break; + case FB_EVENT_BLANK: + if ((event->info->var.xres != 480) || + (event->info->var.yres != 640)) { + break; + } + if (*((int *)event->data) == FB_BLANK_UNBLANK) { + lcd_poweron(); + } else { + lcd_poweroff(); + } + break; + } + return 0; +} + +static struct notifier_block nb = { + .notifier_call = lcd_fb_event, +}; + +/*! + * This function is called whenever the SPI slave device is detected. + * + * @param spi the SPI slave device + * + * @return Returns 0 on SUCCESS and error on FAILURE. + */ +static int __devinit lcd_probe(struct device *dev) +{ + int i; + struct mxc_lcd_platform_data *plat = dev->platform_data; + + lcd_dev = dev; + + if (plat) { + io_reg = regulator_get(dev, plat->io_reg); + if (!IS_ERR(io_reg)) { + regulator_set_voltage(io_reg, 1800000, 1800000); + regulator_enable(io_reg); + } + core_reg = regulator_get(dev, plat->core_reg); + if (!IS_ERR(core_reg)) { + regulator_set_voltage(core_reg, 2800000, 2800000); + regulator_enable(core_reg); + } + + lcd_reset = plat->reset; + if (lcd_reset) + lcd_reset(); + } + + lcd_init(); + + for (i = 0; i < num_registered_fb; i++) { + if (strcmp(registered_fb[i]->fix.id, "DISP3 BG") == 0) { + lcd_init_fb(registered_fb[i]); + fb_show_logo(registered_fb[i], 0); + lcd_poweron(); + } + } + + fb_register_client(&nb); + + return 0; +} + +static int __devinit lcd_plat_probe(struct platform_device *pdev) +{ + ipu_adc_sig_cfg_t sig; + ipu_channel_params_t param; + + memset(&sig, 0, sizeof(sig)); + sig.ifc_width = 9; + sig.clk_pol = 1; + ipu_init_async_panel(0, IPU_PANEL_SERIAL, 90, IPU_PIX_FMT_GENERIC, sig); + + memset(¶m, 0, sizeof(param)); + ipu_init_channel(DIRECT_ASYNC1, ¶m); + + return lcd_probe(&pdev->dev); +} + +static int __devinit lcd_spi_probe(struct spi_device *spi) +{ + lcd_spi = spi; + + spi->bits_per_word = 9; + spi_setup(spi); + + return lcd_probe(&spi->dev); +} + +static int __devexit lcd_remove(struct device *dev) +{ + fb_unregister_client(&nb); + lcd_poweroff(); + regulator_put(io_reg); + regulator_put(core_reg); + + return 0; +} + +static int __devexit lcd_spi_remove(struct spi_device *spi) +{ + int ret = lcd_remove(&spi->dev); + lcd_spi = NULL; + return ret; +} + +static int __devexit lcd_plat_remove(struct platform_device *pdev) +{ + return lcd_remove(&pdev->dev); +} + +static int lcd_suspend(struct spi_device *spi, pm_message_t message) +{ + lcd_poweroff(); + return 0; +} + +static int lcd_resume(struct spi_device *spi) +{ + if (lcd_reset) + lcd_reset(); + + lcd_init(); + lcd_poweron(); + return 0; +} + +/*! + * spi driver structure for LTV350QV + */ +static struct spi_driver lcd_spi_dev_driver = { + + .driver = { + .name = "lcd_spi", + .owner = THIS_MODULE, + }, + .probe = lcd_spi_probe, + .remove = __devexit_p(lcd_spi_remove), + .suspend = lcd_suspend, + .resume = lcd_resume, +}; + +static struct platform_driver lcd_plat_driver = { + .driver = { + .name = "lcd_spi", + .owner = THIS_MODULE, + }, + .probe = lcd_plat_probe, + .remove = __devexit_p(lcd_plat_remove), +}; + +#define param(x) ((x) | 0x100) + +/* + * Send init commands to L4F00242T03 + * + */ +static void lcd_init(void) +{ + const u16 cmd[] = { 0x36, param(0), 0x3A, param(0x60) }; + + dev_dbg(lcd_dev, "initializing LCD\n"); + if (lcd_spi) { + spi_write(lcd_spi, (const u8 *)cmd, ARRAY_SIZE(cmd)); + } else { + ipu_disp_direct_write(DIRECT_ASYNC1, 0x36, 0); + ipu_disp_direct_write(DIRECT_ASYNC1, 0x100, 0); + ipu_disp_direct_write(DIRECT_ASYNC1, 0x3A, 0); + ipu_disp_direct_write(DIRECT_ASYNC1, 0x160, 0); + msleep(1); + ipu_uninit_channel(DIRECT_ASYNC1); + } +} + +static int lcd_on; +/* + * Send Power On commands to L4F00242T03 + * + */ +static void lcd_poweron(void) +{ + const u16 slpout = 0x11; + const u16 dison = 0x29; + ipu_channel_params_t param; + if (lcd_on) + return; + + dev_dbg(lcd_dev, "turning on LCD\n"); + + if (lcd_spi) { + msleep(60); + spi_write(lcd_spi, (const u8 *)&slpout, 1); + msleep(60); + spi_write(lcd_spi, (const u8 *)&dison, 1); + } else { + memset(¶m, 0, sizeof(param)); + ipu_init_channel(DIRECT_ASYNC1, ¶m); + ipu_disp_direct_write(DIRECT_ASYNC1, slpout, 0); + msleep(60); + ipu_disp_direct_write(DIRECT_ASYNC1, dison, 0); + msleep(1); + ipu_uninit_channel(DIRECT_ASYNC1); + } + lcd_on = 1; +} + +/* + * Send Power Off commands to L4F00242T03 + * + */ +static void lcd_poweroff(void) +{ + const u16 slpin = 0x10; + const u16 disoff = 0x28; + ipu_channel_params_t param; + if (!lcd_on) + return; + + dev_dbg(lcd_dev, "turning off LCD\n"); + + if (lcd_spi) { + msleep(60); + spi_write(lcd_spi, (const u8 *)&disoff, 1); + msleep(60); + spi_write(lcd_spi, (const u8 *)&slpin, 1); + } else { + memset(¶m, 0, sizeof(param)); + ipu_init_channel(DIRECT_ASYNC1, ¶m); + ipu_disp_direct_write(DIRECT_ASYNC1, disoff, 0); + msleep(60); + ipu_disp_direct_write(DIRECT_ASYNC1, slpin, 0); + msleep(1); + ipu_uninit_channel(DIRECT_ASYNC1); + } + lcd_on = 0; +} + +static int __init epson_lcd_init(void) +{ + int ret; + + ret = platform_driver_register(&lcd_plat_driver); + if (ret) + return ret; + + return spi_register_driver(&lcd_spi_dev_driver); + +} + +static void __exit epson_lcd_exit(void) +{ + spi_unregister_driver(&lcd_spi_dev_driver); +} + +module_init(epson_lcd_init); +module_exit(epson_lcd_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("Epson VGA LCD init driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/video/mxc/mxcfb_modedb.c b/drivers/video/mxc/mxcfb_modedb.c new file mode 100644 index 000000000000..2e73560c44b9 --- /dev/null +++ b/drivers/video/mxc/mxcfb_modedb.c @@ -0,0 +1,69 @@ +/* + * Copyright 2007-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include + +struct fb_videomode mxcfb_modedb[] = { + { + /* 240x320 @ 60 Hz */ + "Sharp-QVGA", 60, 240, 320, 185925, 9, 16, 7, 9, 1, 1, + FB_SYNC_HOR_HIGH_ACT | FB_SYNC_SHARP_MODE | + FB_SYNC_DATA_INVERT | FB_SYNC_CLK_IDLE_EN, + FB_VMODE_NONINTERLACED, + 0,}, + { + /* 240x33 @ 60 Hz */ + "Sharp-CLI", 60, 240, 33, 185925, 9, 16, 7, 9 + 287, 1, 1, + FB_SYNC_HOR_HIGH_ACT | FB_SYNC_SHARP_MODE | + FB_SYNC_DATA_INVERT | FB_SYNC_CLK_IDLE_EN, + FB_VMODE_NONINTERLACED, + 0,}, + { + /* 640x480 @ 60 Hz */ + "NEC-VGA", 60, 640, 480, 38255, 144, 0, 34, 40, 1, 1, + FB_SYNC_VERT_HIGH_ACT, + FB_VMODE_NONINTERLACED, + 0,}, + { + /* 640x480 @ 60 Hz */ + "CPT-VGA", 60, 640, 480, 39683, 45, 114, 33, 11, 1, 1, + FB_SYNC_CLK_LAT_FALL, + FB_VMODE_NONINTERLACED, + 0,}, + { + /* NTSC TV output */ + "TV-NTSC", 60, 640, 480, 37538, + 38, 858 - 640 - 38 - 3, + 36, 518 - 480 - 36 - 1, + 3, 1, + 0, + FB_VMODE_NONINTERLACED, + 0,}, + { + /* PAL TV output */ + "TV-PAL", 50, 640, 480, 37538, + 38, 960 - 640 - 38 - 32, + 32, 555 - 480 - 32 - 3, + 32, 3, + 0, + FB_VMODE_NONINTERLACED, + 0,}, + { + /* TV output VGA mode, 640x480 @ 65 Hz */ + "TV-VGA", 60, 640, 480, 40574, 35, 45, 9, 1, 46, 5, + 0, FB_VMODE_NONINTERLACED, 0, + }, +}; + +int mxcfb_modedb_sz = ARRAY_SIZE(mxcfb_modedb); diff --git a/drivers/video/mxc/tve.c b/drivers/video/mxc/tve.c new file mode 100644 index 000000000000..2596167045f7 --- /dev/null +++ b/drivers/video/mxc/tve.c @@ -0,0 +1,922 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file tve.c + * @brief Driver for i.MX TV encoder + * + * @ingroup Framebuffer + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define TVE_ENABLE (1UL) +#define TVE_DAC_FULL_RATE (0UL<<1) +#define TVE_DAC_DIV2_RATE (1UL<<1) +#define TVE_DAC_DIV4_RATE (2UL<<1) +#define TVE_IPU_CLK_ENABLE (1UL<<3) + +#define CD_LM_INT 0x00000001 +#define CD_SM_INT 0x00000002 +#define CD_MON_END_INT 0x00000004 +#define CD_CH_0_LM_ST 0x00000001 +#define CD_CH_0_SM_ST 0x00000010 +#define CD_CH_1_LM_ST 0x00000002 +#define CD_CH_1_SM_ST 0x00000020 +#define CD_CH_2_LM_ST 0x00000004 +#define CD_CH_2_SM_ST 0x00000040 +#define CD_MAN_TRIG 0x00000100 + +#define TVE_STAND_MASK (0x0F<<8) +#define TVE_NTSC_STAND (0UL<<8) +#define TVE_PAL_STAND (3UL<<8) +#define TVE_HD720P60_STAND (4UL<<8) + +#define TVOUT_FMT_OFF 0 +#define TVOUT_FMT_NTSC 1 +#define TVOUT_FMT_PAL 2 +#define TVOUT_FMT_720P60 3 + +static int enabled; /* enable power on or not */ +DEFINE_SPINLOCK(tve_lock); + +static struct fb_info *tve_fbi; +static struct fb_modelist tve_modelist; +static bool g_enable_tve; + +struct tve_data { + struct platform_device *pdev; + int revision; + int cur_mode; + int output_mode; + int detect; + void *base; + int irq; + int blank; + struct clk *clk; + struct regulator *dac_reg; + struct regulator *dig_reg; + struct delayed_work cd_work; +} tve; + +struct tve_reg_mapping { + u32 tve_com_conf_reg; + u32 tve_cd_cont_reg; + u32 tve_int_cont_reg; + u32 tve_stat_reg; + u32 tve_mv_cont_reg; +}; + +struct tve_reg_fields_mapping { + u32 cd_en; + u32 cd_trig_mode; + u32 cd_lm_int; + u32 cd_sm_int; + u32 cd_mon_end_int; + u32 cd_man_trig; + u32 sync_ch_mask; + u32 tvout_mode_mask; + u32 sync_ch_offset; + u32 tvout_mode_offset; + u32 cd_ch_stat_offset; +}; + +static struct tve_reg_mapping tve_regs_v1 = { + 0, 0x14, 0x28, 0x2C, 0x48 +}; + +static struct tve_reg_fields_mapping tve_reg_fields_v1 = { + 1, 2, 1, 2, 4, 0x00010000, 0x7000, 0x70, 12, 4, 8 +}; + +static struct tve_reg_mapping tve_regs_v2 = { + 0, 0x34, 0x64, 0x68, 0xDC +}; + +static struct tve_reg_fields_mapping tve_reg_fields_v2 = { + 1, 2, 1, 2, 4, 0x01000000, 0x700000, 0x7000, 20, 12, 16 +}; + + +struct tve_reg_mapping *tve_regs; +struct tve_reg_fields_mapping *tve_reg_fields; + +/* For MX37 need modify some fields in tve_probe */ +static struct fb_videomode video_modes[] = { + { + /* NTSC TV output */ + "TV-NTSC", 60, 720, 480, 74074, + 122, 15, + 18, 26, + 1, 1, + FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT | FB_SYNC_EXT, + FB_VMODE_INTERLACED, + 0,}, + { + /* PAL TV output */ + "TV-PAL", 50, 720, 576, 74074, + 132, 11, + 22, 26, + 1, 1, + FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT | FB_SYNC_EXT, + FB_VMODE_INTERLACED | FB_VMODE_ODD_FLD_FIRST, + 0,}, + { + /* 720p60 TV output */ + "720P60", 60, 1280, 720, 13468, + 260, 109, + 25, 4, + 1, 1, + FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT | + FB_SYNC_EXT, + FB_VMODE_NONINTERLACED, + 0,}, +}; + +enum tvout_mode { + TV_OFF, + CVBS0, + CVBS2, + CVBS02, + SVIDEO, + SVIDEO_CVBS, + YPBPR, + RGB +}; + +static unsigned short tvout_mode_to_channel_map[8] = { + 0, /* TV_OFF */ + 1, /* CVBS0 */ + 4, /* CVBS2 */ + 5, /* CVBS02 */ + 1, /* SVIDEO */ + 5, /* SVIDEO_CVBS */ + 1, /* YPBPR */ + 7 /* RGB */ +}; + + +static void tve_set_tvout_mode(int mode) +{ + u32 conf_reg; + + conf_reg = __raw_readl(tve.base + tve_regs->tve_com_conf_reg); + conf_reg &= ~(tve_reg_fields->sync_ch_mask | + tve_reg_fields->tvout_mode_mask); + /* clear sync_ch and tvout_mode fields */ + conf_reg |= + mode << tve_reg_fields-> + tvout_mode_offset | tvout_mode_to_channel_map[mode] << + tve_reg_fields->sync_ch_offset; + __raw_writel(conf_reg, tve.base + tve_regs->tve_com_conf_reg); +} + +static int _is_tvout_mode_hd_compatible(void) +{ + u32 conf_reg, mode; + + conf_reg = __raw_readl(tve.base + tve_regs->tve_com_conf_reg); + mode = (conf_reg >> tve_reg_fields->tvout_mode_offset) & 7; + if (mode == YPBPR || mode == RGB) { + return 1; + } else { + return 0; + } +} + + +/** + * tve_setup + * initial the CH7024 chipset by setting register + * @param: + * vos: output video format + * @return: + * 0 successful + * otherwise failed + */ +static int tve_setup(int mode) +{ + u32 reg; + struct clk *tve_parent_clk; + unsigned long parent_clock_rate = 216000000, di1_clock_rate = 27000000; + unsigned long tve_clock_rate = 216000000; + struct clk *ipu_di1_clk; + unsigned long lock_flags; + + spin_lock_irqsave(&tve_lock, lock_flags); + + switch (mode) { + case TVOUT_FMT_PAL: + case TVOUT_FMT_NTSC: + parent_clock_rate = 216000000; + di1_clock_rate = 27000000; + break; + case TVOUT_FMT_720P60: + parent_clock_rate = 297000000; + if (cpu_is_mx53()) + tve_clock_rate = 297000000; + di1_clock_rate = 74250000; + break; + } + if (enabled) + clk_disable(tve.clk); + + tve_parent_clk = clk_get_parent(tve.clk); + ipu_di1_clk = clk_get(NULL, "ipu_di1_clk"); + + clk_disable(tve_parent_clk); + clk_set_rate(tve_parent_clk, parent_clock_rate); + + if (cpu_is_mx53()) + clk_set_rate(tve.clk, tve_clock_rate); + + clk_enable(tve.clk); + clk_set_rate(ipu_di1_clk, di1_clock_rate); + + if (tve.cur_mode == mode) { + if (!enabled) + clk_disable(tve.clk); + spin_unlock_irqrestore(&tve_lock, lock_flags); + return 0; + } + + tve.cur_mode = mode; + + /* select output video format */ + if (mode == TVOUT_FMT_PAL) { + reg = __raw_readl(tve.base + tve_regs->tve_com_conf_reg); + reg = (reg & ~TVE_STAND_MASK) | TVE_PAL_STAND; + __raw_writel(reg, tve.base + tve_regs->tve_com_conf_reg); + pr_debug("TVE: change to PAL video\n"); + } else if (mode == TVOUT_FMT_NTSC) { + reg = __raw_readl(tve.base + tve_regs->tve_com_conf_reg); + reg = (reg & ~TVE_STAND_MASK) | TVE_NTSC_STAND; + __raw_writel(reg, tve.base + tve_regs->tve_com_conf_reg); + pr_debug("TVE: change to NTSC video\n"); + } else if (mode == TVOUT_FMT_720P60) { + if (!_is_tvout_mode_hd_compatible()) { + tve_set_tvout_mode(YPBPR); + pr_debug("The TV out mode is HD incompatible. Setting to YPBPR."); + } + reg = __raw_readl(tve.base + tve_regs->tve_com_conf_reg); + reg = (reg & ~TVE_STAND_MASK) | TVE_HD720P60_STAND; + __raw_writel(reg, tve.base + tve_regs->tve_com_conf_reg); + pr_debug("TVE: change to 720P60 video\n"); + } else if (mode == TVOUT_FMT_OFF) { + __raw_writel(0x0, tve.base + tve_regs->tve_com_conf_reg); + pr_debug("TVE: change to OFF video\n"); + } else { + pr_debug("TVE: no such video format.\n"); + if (!enabled) + clk_disable(tve.clk); + spin_unlock_irqrestore(&tve_lock, lock_flags); + return -EINVAL; + } + + if (!enabled) + clk_disable(tve.clk); + + spin_unlock_irqrestore(&tve_lock, lock_flags); + return 0; +} + +/** + * tve_enable + * Enable the tve Power to begin TV encoder + */ +static void tve_enable(void) +{ + u32 reg; + unsigned long lock_flags; + + spin_lock_irqsave(&tve_lock, lock_flags); + if (!enabled) { + enabled = 1; + clk_enable(tve.clk); + reg = __raw_readl(tve.base + tve_regs->tve_com_conf_reg); + __raw_writel(reg | TVE_IPU_CLK_ENABLE | TVE_ENABLE, + tve.base + tve_regs->tve_com_conf_reg); + pr_debug("TVE power on.\n"); + } + + /* enable interrupt */ + __raw_writel(CD_SM_INT | CD_LM_INT | CD_MON_END_INT, + tve.base + tve_regs->tve_stat_reg); + __raw_writel(CD_SM_INT | CD_LM_INT | CD_MON_END_INT, + tve.base + tve_regs->tve_int_cont_reg); + spin_unlock_irqrestore(&tve_lock, lock_flags); +} + +/** + * tve_disable + * Disable the tve Power to stop TV encoder + */ +static void tve_disable(void) +{ + u32 reg; + unsigned long lock_flags; + + spin_lock_irqsave(&tve_lock, lock_flags); + if (enabled) { + enabled = 0; + reg = __raw_readl(tve.base + tve_regs->tve_com_conf_reg); + __raw_writel(reg & ~TVE_ENABLE & ~TVE_IPU_CLK_ENABLE, + tve.base + tve_regs->tve_com_conf_reg); + clk_disable(tve.clk); + pr_debug("TVE power off.\n"); + } + spin_unlock_irqrestore(&tve_lock, lock_flags); +} + +static int tve_update_detect_status(void) +{ + int old_detect = tve.detect; + u32 stat_lm, stat_sm, stat; + u32 int_ctl; + u32 cd_cont_reg; + u32 timeout = 40; + unsigned long lock_flags; + + spin_lock_irqsave(&tve_lock, lock_flags); + + if (!enabled) { + pr_warning("Warning: update tve status while it disabled!\n"); + tve.detect = 0; + goto done; + } + + int_ctl = __raw_readl(tve.base + tve_regs->tve_int_cont_reg); + cd_cont_reg = __raw_readl(tve.base + tve_regs->tve_cd_cont_reg); + + if ((cd_cont_reg & 0x1) == 0) { + pr_warning("Warning: pls enable TVE CD first!\n"); + goto done; + } + + stat = __raw_readl(tve.base + tve_regs->tve_stat_reg); + while (((stat & CD_MON_END_INT) == 0) && (timeout > 0)) { + spin_unlock_irqrestore(&tve_lock, lock_flags); + msleep(2); + spin_lock_irqsave(&tve_lock, lock_flags); + timeout -= 2; + if (!enabled) { + pr_warning("Warning: update tve status while it disabled!\n"); + tve.detect = 0; + goto done; + } else + stat = __raw_readl(tve.base + tve_regs->tve_stat_reg); + } + if (((stat & CD_MON_END_INT) == 0) && (timeout <= 0)) { + pr_warning("Warning: get detect resultwithout CD_MON_END_INT!\n"); + goto done; + } + + stat = stat >> tve_reg_fields->cd_ch_stat_offset; + stat_lm = stat & (CD_CH_0_LM_ST | CD_CH_1_LM_ST | CD_CH_2_LM_ST); + if ((stat_lm == (CD_CH_0_LM_ST | CD_CH_1_LM_ST | CD_CH_2_LM_ST)) && + ((stat & (CD_CH_0_SM_ST | CD_CH_1_SM_ST | CD_CH_2_SM_ST)) == 0) + ) { + tve.detect = 3; + tve.output_mode = YPBPR; + } else if ((stat_lm == (CD_CH_0_LM_ST | CD_CH_1_LM_ST)) && + ((stat & (CD_CH_0_SM_ST | CD_CH_1_SM_ST)) == 0)) { + tve.detect = 4; + tve.output_mode = SVIDEO; + } else if (stat_lm == CD_CH_0_LM_ST) { + stat_sm = stat & CD_CH_0_SM_ST; + if (stat_sm != 0) { + /* headset */ + tve.detect = 2; + tve.output_mode = TV_OFF; + } else { + tve.detect = 1; + tve.output_mode = CVBS0; + } + } else if (stat_lm == CD_CH_2_LM_ST) { + stat_sm = stat & CD_CH_2_SM_ST; + if (stat_sm != 0) { + /* headset */ + tve.detect = 2; + tve.output_mode = TV_OFF; + } else { + tve.detect = 1; + tve.output_mode = CVBS2; + } + } else { + /* none */ + tve.detect = 0; + tve.output_mode = TV_OFF; + } + + tve_set_tvout_mode(tve.output_mode); + + /* clear interrupt */ + __raw_writel(CD_MON_END_INT | CD_LM_INT | CD_SM_INT, + tve.base + tve_regs->tve_stat_reg); + + __raw_writel(int_ctl | CD_SM_INT | CD_LM_INT, + tve.base + tve_regs->tve_int_cont_reg); + + if (old_detect != tve.detect) + sysfs_notify(&tve.pdev->dev.kobj, NULL, "headphone"); + + dev_dbg(&tve.pdev->dev, "detect = %d mode = %d\n", + tve.detect, tve.output_mode); +done: + spin_unlock_irqrestore(&tve_lock, lock_flags); + return tve.detect; +} + +static void cd_work_func(struct work_struct *work) +{ + tve_update_detect_status(); +} +#if 0 +static int tve_man_detect(void) +{ + u32 cd_cont; + u32 int_cont; + + if (!enabled) + return -1; + + int_cont = __raw_readl(tve.base + tve_regs->tve_int_cont_reg); + __raw_writel(int_cont & + ~(tve_reg_fields->cd_sm_int | tve_reg_fields->cd_lm_int), + tve.base + tve_regs->tve_int_cont_reg); + + cd_cont = __raw_readl(tve.base + tve_regs->tve_cd_cont_reg); + __raw_writel(cd_cont | tve_reg_fields->cd_trig_mode, + tve.base + tve_regs->tve_cd_cont_reg); + + __raw_writel(tve_reg_fields->cd_sm_int | tve_reg_fields-> + cd_lm_int | tve_reg_fields-> + cd_mon_end_int | tve_reg_fields->cd_man_trig, + tve.base + tve_regs->tve_stat_reg); + + while ((__raw_readl(tve.base + tve_regs->tve_stat_reg) + & tve_reg_fields->cd_mon_end_int) == 0) + msleep(5); + + tve_update_detect_status(); + + __raw_writel(cd_cont, tve.base + tve_regs->tve_cd_cont_reg); + __raw_writel(int_cont, tve.base + tve_regs->tve_int_cont_reg); + + return tve.detect; +} +#endif + +static irqreturn_t tve_detect_handler(int irq, void *data) +{ + u32 int_ctl = __raw_readl(tve.base + tve_regs->tve_int_cont_reg); + + /* disable INT first */ + int_ctl &= ~(CD_SM_INT | CD_LM_INT | CD_MON_END_INT); + __raw_writel(int_ctl, tve.base + tve_regs->tve_int_cont_reg); + + __raw_writel(CD_MON_END_INT | CD_LM_INT | CD_SM_INT, + tve.base + tve_regs->tve_stat_reg); + + schedule_delayed_work(&tve.cd_work, msecs_to_jiffies(1000)); + + return IRQ_HANDLED; +} + +/* Re-construct clk for tve display */ +static inline void tve_recfg_fb(struct fb_info *fbi) +{ + struct fb_var_screeninfo var; + + memset(&var, 0, sizeof(var)); + fb_videomode_to_var(&var, fbi->mode); + fbi->flags &= ~FBINFO_MISC_USEREVENT; + fb_set_var(fbi, &var); +} + +int tve_fb_event(struct notifier_block *nb, unsigned long val, void *v) +{ + struct fb_event *event = v; + struct fb_info *fbi = event->info; + + switch (val) { + case FB_EVENT_FB_REGISTERED: + pr_debug("fb registered event\n"); + if ((tve_fbi != NULL) || strcmp(fbi->fix.id, "DISP3 BG - DI1")) + break; + + tve_fbi = fbi; + fb_add_videomode(&video_modes[0], &tve_modelist.list); + fb_add_videomode(&video_modes[1], &tve_modelist.list); + fb_add_videomode(&video_modes[2], &tve_modelist.list); + break; + case FB_EVENT_MODE_CHANGE: + { + struct fb_videomode cur_mode; + struct fb_videomode *mode; + struct list_head *pos; + struct fb_modelist *modelist; + + if (tve_fbi != fbi) + break; + + fb_var_to_videomode(&cur_mode, &fbi->var); + + list_for_each(pos, &tve_modelist.list) { + modelist = list_entry(pos, struct fb_modelist, list); + mode = &modelist->mode; + if (fb_mode_is_equal(&cur_mode, mode)) { + fbi->mode = mode; + break; + } + } + + if (!fbi->mode) { + tve_disable(); + tve.cur_mode = TVOUT_FMT_OFF; + return 0; + } + + pr_debug("fb mode change event: xres=%d, yres=%d\n", + fbi->mode->xres, fbi->mode->yres); + + tve_disable(); + + if (fb_mode_is_equal(fbi->mode, &video_modes[0])) { + tve_setup(TVOUT_FMT_NTSC); + tve_enable(); + } else if (fb_mode_is_equal(fbi->mode, &video_modes[1])) { + tve_setup(TVOUT_FMT_PAL); + tve_enable(); + } else if (fb_mode_is_equal(fbi->mode, &video_modes[2])) { + tve_setup(TVOUT_FMT_720P60); + tve_enable(); + } else { + tve_setup(TVOUT_FMT_OFF); + } + break; + } + case FB_EVENT_BLANK: + if ((tve_fbi != fbi) || (fbi->mode == NULL)) + return 0; + + if (*((int *)event->data) == FB_BLANK_UNBLANK) { + if (tve.blank != FB_BLANK_UNBLANK) { + if (fb_mode_is_equal(fbi->mode, &video_modes[0])) { + tve_disable(); + tve_setup(TVOUT_FMT_NTSC); + tve_enable(); + tve_recfg_fb(fbi); + } else if (fb_mode_is_equal(fbi->mode, + &video_modes[1])) { + tve_disable(); + tve_setup(TVOUT_FMT_PAL); + tve_enable(); + tve_recfg_fb(fbi); + } else if (fb_mode_is_equal(fbi->mode, + &video_modes[2])) { + tve_disable(); + tve_setup(TVOUT_FMT_720P60); + tve_enable(); + tve_recfg_fb(fbi); + } else { + tve_setup(TVOUT_FMT_OFF); + } + tve.blank = FB_BLANK_UNBLANK; + } + } else { + tve_disable(); + tve.blank = FB_BLANK_POWERDOWN; + } + break; + } + return 0; +} + +static struct notifier_block nb = { + .notifier_call = tve_fb_event, +}; + +static ssize_t show_headphone(struct device *dev, + struct device_attribute *attr, char *buf) +{ + int detect; + + if (!enabled) { + strcpy(buf, "tve power off\n"); + return strlen(buf); + } + + detect = tve_update_detect_status(); + + if (detect == 0) + strcpy(buf, "none\n"); + else if (detect == 1) + strcpy(buf, "cvbs\n"); + else if (detect == 2) + strcpy(buf, "headset\n"); + else if (detect == 3) + strcpy(buf, "component\n"); + else + strcpy(buf, "svideo\n"); + + return strlen(buf); +} + +static DEVICE_ATTR(headphone, S_IRUGO | S_IWUSR, show_headphone, NULL); + +static int _tve_get_revision(void) +{ + u32 conf_reg; + u32 rev = 0; + + /* find out TVE rev based on the base addr default value + * can be used at the init/probe ONLY */ + conf_reg = __raw_readl(tve.base); + switch (conf_reg) { + case 0x00842000: + rev = 1; + break; + case 0x00100000: + rev = 2; + break; + } + return rev; +} + +static int tve_probe(struct platform_device *pdev) +{ + int ret, i, primary = 0; + struct resource *res; + struct tve_platform_data *plat_data = pdev->dev.platform_data; + u32 conf_reg; + + if (g_enable_tve == false) + return -ENODEV; + + INIT_LIST_HEAD(&tve_modelist.list); + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (res == NULL) + return -ENOMEM; + + tve.pdev = pdev; + tve.base = ioremap(res->start, res->end - res->start); + + tve.irq = platform_get_irq(pdev, 0); + if (tve.irq < 0) { + ret = tve.irq; + goto err0; + } + + ret = request_irq(tve.irq, tve_detect_handler, 0, pdev->name, pdev); + if (ret < 0) + goto err0; + + ret = device_create_file(&pdev->dev, &dev_attr_headphone); + if (ret < 0) + goto err1; + + for (i = 0; i < num_registered_fb; i++) { + if (strcmp(registered_fb[i]->fix.id, "DISP3 BG - DI1") == 0) { + tve_fbi = registered_fb[i]; + if (i == 0) { + primary = 1; + acquire_console_sem(); + fb_blank(tve_fbi, FB_BLANK_POWERDOWN); + release_console_sem(); + } + break; + } + } + + /* adjust video mode for mx37 */ + if (cpu_is_mx37()) { + video_modes[0].left_margin = 121; + video_modes[0].right_margin = 16; + video_modes[0].upper_margin = 17; + video_modes[0].lower_margin = 5; + video_modes[1].left_margin = 131; + video_modes[1].right_margin = 12; + video_modes[1].upper_margin = 21; + video_modes[1].lower_margin = 3; + } + + if (tve_fbi != NULL) { + fb_add_videomode(&video_modes[0], &tve_modelist.list); + fb_add_videomode(&video_modes[1], &tve_modelist.list); + fb_add_videomode(&video_modes[2], &tve_modelist.list); + } + + tve.dac_reg = regulator_get(&pdev->dev, plat_data->dac_reg); + if (!IS_ERR(tve.dac_reg)) { + regulator_set_voltage(tve.dac_reg, 2500000, 2500000); + regulator_enable(tve.dac_reg); + } + + tve.dig_reg = regulator_get(&pdev->dev, plat_data->dig_reg); + if (!IS_ERR(tve.dig_reg)) { + regulator_set_voltage(tve.dig_reg, 1250000, 1250000); + regulator_enable(tve.dig_reg); + } + + tve.clk = clk_get(&pdev->dev, "tve_clk"); + if (IS_ERR(tve.clk)) { + ret = PTR_ERR(tve.clk); + goto err2; + } + clk_set_rate(tve.clk, 216000000); + clk_enable(tve.clk); + + tve.revision = _tve_get_revision(); + if (tve.revision == 1) { + tve_regs = &tve_regs_v1; + tve_reg_fields = &tve_reg_fields_v1; + } else { + tve_regs = &tve_regs_v2; + tve_reg_fields = &tve_reg_fields_v2; + } + + /* Setup cable detect, for YPrPb mode, default use channel#0 for Y */ + INIT_DELAYED_WORK(&tve.cd_work, cd_work_func); + if (tve.revision == 1) + __raw_writel(0x01067701, tve.base + tve_regs->tve_cd_cont_reg); + else + __raw_writel(0x00770601, tve.base + tve_regs->tve_cd_cont_reg); + + conf_reg = 0; + __raw_writel(conf_reg, tve.base + tve_regs->tve_com_conf_reg); + + __raw_writel(0x00000000, tve.base + tve_regs->tve_mv_cont_reg - 4 * 5); + __raw_writel(0x00000000, tve.base + tve_regs->tve_mv_cont_reg - 4 * 4); + __raw_writel(0x00000000, tve.base + tve_regs->tve_mv_cont_reg - 4 * 3); + __raw_writel(0x00000000, tve.base + tve_regs->tve_mv_cont_reg - 4 * 2); + __raw_writel(0x00000000, tve.base + tve_regs->tve_mv_cont_reg - 4); + __raw_writel(0x00000000, tve.base + tve_regs->tve_mv_cont_reg); + + clk_disable(tve.clk); + + ret = fb_register_client(&nb); + if (ret < 0) + goto err2; + + tve.blank = -1; + + /* is primary display? */ + if (primary) { + struct fb_var_screeninfo var; + const struct fb_videomode *mode; + + memset(&var, 0, sizeof(var)); + mode = fb_match_mode(&tve_fbi->var, &tve_modelist.list); + if (mode) { + pr_debug("TVE: fb mode found\n"); + fb_videomode_to_var(&var, mode); + } else { + pr_warning("TVE: can not find video mode\n"); + goto done; + } + acquire_console_sem(); + tve_fbi->flags |= FBINFO_MISC_USEREVENT; + fb_set_var(tve_fbi, &var); + tve_fbi->flags &= ~FBINFO_MISC_USEREVENT; + release_console_sem(); + + acquire_console_sem(); + fb_blank(tve_fbi, FB_BLANK_UNBLANK); + release_console_sem(); + + fb_show_logo(tve_fbi, 0); + } + +done: + return 0; +err2: + device_remove_file(&pdev->dev, &dev_attr_headphone); +err1: + free_irq(tve.irq, pdev); +err0: + iounmap(tve.base); + return ret; +} + +static int tve_remove(struct platform_device *pdev) +{ + if (enabled) { + clk_disable(tve.clk); + enabled = 0; + } + free_irq(tve.irq, pdev); + device_remove_file(&pdev->dev, &dev_attr_headphone); + fb_unregister_client(&nb); + return 0; +} + +/*! + * PM suspend/resume routing + */ +static int tve_suspend(struct platform_device *pdev, pm_message_t state) +{ + if (enabled) { + __raw_writel(0, tve.base + tve_regs->tve_int_cont_reg); + __raw_writel(0, tve.base + tve_regs->tve_cd_cont_reg); + __raw_writel(0, tve.base + tve_regs->tve_com_conf_reg); + clk_disable(tve.clk); + } + return 0; +} + +static int tve_resume(struct platform_device *pdev) +{ + if (enabled) { + clk_enable(tve.clk); + + /* Setup cable detect */ + if (tve.revision == 1) + __raw_writel(0x01067701, + tve.base + tve_regs->tve_cd_cont_reg); + else + __raw_writel(0x00770601, + tve.base + tve_regs->tve_cd_cont_reg); + + if (tve.cur_mode == TVOUT_FMT_NTSC) { + tve_disable(); + tve.cur_mode = TVOUT_FMT_OFF; + tve_setup(TVOUT_FMT_NTSC); + } else if (tve.cur_mode == TVOUT_FMT_PAL) { + tve_disable(); + tve.cur_mode = TVOUT_FMT_OFF; + tve_setup(TVOUT_FMT_PAL); + } else if (tve.cur_mode == TVOUT_FMT_720P60) { + tve_disable(); + tve.cur_mode = TVOUT_FMT_OFF; + tve_setup(TVOUT_FMT_720P60); + } + tve_enable(); + } + + return 0; +} + +static struct platform_driver tve_driver = { + .driver = { + .name = "tve", + }, + .probe = tve_probe, + .remove = tve_remove, + .suspend = tve_suspend, + .resume = tve_resume, +}; + +static int __init enable_tve_setup(char *options) +{ + g_enable_tve = true; + + return 1; +} +__setup("tve", enable_tve_setup); + +static int __init tve_init(void) +{ + return platform_driver_register(&tve_driver); +} + +static void __exit tve_exit(void) +{ + platform_driver_unregister(&tve_driver); +} + +module_init(tve_init); +module_exit(tve_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("i.MX TV encoder driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/video/mxs/Kconfig b/drivers/video/mxs/Kconfig new file mode 100644 index 000000000000..35b896e95d4f --- /dev/null +++ b/drivers/video/mxs/Kconfig @@ -0,0 +1,28 @@ +config FB_MXS + tristate "MXS Framebuffer driver" + depends on FB && ARCH_MXS + select FB_CFB_FILLRECT + select FB_CFB_COPYAREA + select FB_CFB_IMAGEBLIT + default y + ---help--- + Say Y here to enable support for the framebuffer driver for the + Freescale MXS Board. + +config FB_MXS_LCD_43WVF1G + depends on FB_MXS + tristate "SEIKO 4.3' LCD WVGA(800x480) PANEL" + default y if ARCH_MX28 + +config FB_MXS_LCD_LMS430 + depends on FB_MXS + bool "LMS430" + default y if ARCH_MX23 + ---help--- + Use LMS430 dotclock LCD panel for MXS + +config FB_MXS_TVENC + depends on ARCH_MXS + bool "TVENC" + ---help--- + Use TVOUT encoder for MXS diff --git a/drivers/video/mxs/Makefile b/drivers/video/mxs/Makefile new file mode 100644 index 000000000000..fbab953718c7 --- /dev/null +++ b/drivers/video/mxs/Makefile @@ -0,0 +1,6 @@ +obj-$(CONFIG_ARCH_MXS) += lcdif.o +obj-$(CONFIG_FB_MXS) += mxsfb.o +obj-$(CONFIG_FB_MXS_LCD_43WVF1G) += lcd_43wvf1g.o +obj-$(CONFIG_FB_MXS_LCD_LMS430) += lcd_lms430.o +# TVOUT support +obj-$(CONFIG_FB_MXS_TVENC) += tvenc.o diff --git a/drivers/video/mxs/lcd_43wvf1g.c b/drivers/video/mxs/lcd_43wvf1g.c new file mode 100644 index 000000000000..1a8157f277a0 --- /dev/null +++ b/drivers/video/mxs/lcd_43wvf1g.c @@ -0,0 +1,289 @@ +/* + * Freescale MX28 Seiko 43WVF1G LCD panel driver + * + * Copyright (C) 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#define DOTCLK_H_ACTIVE 800 +#define DOTCLK_H_PULSE_WIDTH 10 +#define DOTCLK_HF_PORCH 164 +#define DOTCLK_HB_PORCH 89 +#define DOTCLK_H_WAIT_CNT (DOTCLK_H_PULSE_WIDTH + DOTCLK_HB_PORCH) +#define DOTCLK_H_PERIOD (DOTCLK_H_WAIT_CNT + DOTCLK_HF_PORCH + DOTCLK_H_ACTIVE) + +#define DOTCLK_V_ACTIVE 480 +#define DOTCLK_V_PULSE_WIDTH 10 +#define DOTCLK_VF_PORCH 10 +#define DOTCLK_VB_PORCH 23 +#define DOTCLK_V_WAIT_CNT (DOTCLK_V_PULSE_WIDTH + DOTCLK_VB_PORCH) +#define DOTCLK_V_PERIOD (DOTCLK_VF_PORCH + DOTCLK_V_ACTIVE + DOTCLK_V_WAIT_CNT) + +static struct mxs_platform_bl_data bl_data; +static struct clk *lcd_clk; + +static int init_panel(struct device *dev, dma_addr_t phys, int memsize, + struct mxs_platform_fb_entry *pentry) +{ + int ret = 0; + lcd_clk = clk_get(dev, "dis_lcdif"); + if (IS_ERR(lcd_clk)) { + ret = PTR_ERR(lcd_clk); + goto out; + } + ret = clk_enable(lcd_clk); + if (ret) { + clk_put(lcd_clk); + goto out; + } + + ret = clk_set_rate(lcd_clk, 1000000 / pentry->cycle_time_ns); /* kHz */ + if (ret) { + clk_disable(lcd_clk); + clk_put(lcd_clk); + goto out; + } + + /* + * Make sure we do a high-to-low transition to reset the panel. + * First make it low for 100 msec, hi for 10 msec, low for 10 msec, + * then hi. + */ + __raw_writel(BM_LCDIF_CTRL1_RESET, REGS_LCDIF_BASE + HW_LCDIF_CTRL1_CLR); /* low */ + mdelay(100); + __raw_writel(BM_LCDIF_CTRL1_RESET, REGS_LCDIF_BASE + HW_LCDIF_CTRL1_SET); /* high */ + mdelay(10); + __raw_writel(BM_LCDIF_CTRL1_RESET, REGS_LCDIF_BASE + HW_LCDIF_CTRL1_CLR); /* low */ + + /* For the Samsung, Reset must be held low at least 30 uSec + * Therefore, we'll hold it low for about 10 mSec just to be sure. + * Then we'll wait 1 mSec afterwards. + */ + mdelay(10); + __raw_writel(BM_LCDIF_CTRL1_RESET, REGS_LCDIF_BASE + HW_LCDIF_CTRL1_SET); /* high */ + mdelay(1); + + setup_dotclk_panel(DOTCLK_V_PULSE_WIDTH, DOTCLK_V_PERIOD, + DOTCLK_V_WAIT_CNT, DOTCLK_V_ACTIVE, + DOTCLK_H_PULSE_WIDTH, DOTCLK_H_PERIOD, + DOTCLK_H_WAIT_CNT, DOTCLK_H_ACTIVE, 0); + + ret = mxs_lcdif_dma_init(dev, phys, memsize); + if (ret) + goto out; + + mxs_lcd_set_bl_pdata(pentry->bl_data); + mxs_lcdif_notify_clients(MXS_LCDIF_PANEL_INIT, pentry); + return 0; + +out: + return ret; +} + +static void release_panel(struct device *dev, + struct mxs_platform_fb_entry *pentry) +{ + mxs_lcdif_notify_clients(MXS_LCDIF_PANEL_RELEASE, pentry); + release_dotclk_panel(); + mxs_lcdif_dma_release(); + clk_disable(lcd_clk); + clk_put(lcd_clk); +} + +static int blank_panel(int blank) +{ + int ret = 0, count; + + switch (blank) { + case FB_BLANK_NORMAL: + case FB_BLANK_VSYNC_SUSPEND: + case FB_BLANK_HSYNC_SUSPEND: + case FB_BLANK_POWERDOWN: + __raw_writel(BM_LCDIF_CTRL_BYPASS_COUNT, + REGS_LCDIF_BASE + HW_LCDIF_CTRL_CLR); + for (count = 10000; count; count--) { + if (__raw_readl(REGS_LCDIF_BASE + HW_LCDIF_STAT) & + BM_LCDIF_STAT_TXFIFO_EMPTY) + break; + udelay(1); + } + break; + + case FB_BLANK_UNBLANK: + __raw_writel(BM_LCDIF_CTRL_BYPASS_COUNT, + REGS_LCDIF_BASE + HW_LCDIF_CTRL_SET); + break; + + default: + ret = -EINVAL; + } + return ret; +} + +static struct mxs_platform_fb_entry fb_entry = { + .name = "43wvf1g", + .x_res = 480, + .y_res = 800, + .bpp = 32, + .cycle_time_ns = 30, + .lcd_type = MXS_LCD_PANEL_DOTCLK, + .init_panel = init_panel, + .release_panel = release_panel, + .blank_panel = blank_panel, + .run_panel = mxs_lcdif_run, + .stop_panel = mxs_lcdif_stop, + .pan_display = mxs_lcdif_pan_display, + .bl_data = &bl_data, +}; + +static struct clk *pwm_clk; + +static int init_bl(struct mxs_platform_bl_data *data) +{ + int ret = 0; + + pwm_clk = clk_get(NULL, "pwm"); + if (IS_ERR(pwm_clk)) { + ret = PTR_ERR(pwm_clk); + return ret; + } + clk_enable(pwm_clk); + mxs_reset_block(REGS_PWM_BASE, 1); + + __raw_writel(BF_PWM_ACTIVEn_INACTIVE(0) | + BF_PWM_ACTIVEn_ACTIVE(0), + REGS_PWM_BASE + HW_PWM_ACTIVEn(2)); + __raw_writel(BF_PWM_PERIODn_CDIV(6) | /* divide by 64 */ + BF_PWM_PERIODn_INACTIVE_STATE(2) | /* low */ + BF_PWM_PERIODn_ACTIVE_STATE(3) | /* high */ + BF_PWM_PERIODn_PERIOD(599), + REGS_PWM_BASE + HW_PWM_PERIODn(2)); + __raw_writel(BM_PWM_CTRL_PWM2_ENABLE, REGS_PWM_BASE + HW_PWM_CTRL_SET); + + return 0; +} + +static void free_bl(struct mxs_platform_bl_data *data) +{ + __raw_writel(BF_PWM_ACTIVEn_INACTIVE(0) | + BF_PWM_ACTIVEn_ACTIVE(0), + REGS_PWM_BASE + HW_PWM_ACTIVEn(2)); + __raw_writel(BF_PWM_PERIODn_CDIV(6) | /* divide by 64 */ + BF_PWM_PERIODn_INACTIVE_STATE(2) | /* low */ + BF_PWM_PERIODn_ACTIVE_STATE(3) | /* high */ + BF_PWM_PERIODn_PERIOD(599), + REGS_PWM_BASE + HW_PWM_PERIODn(2)); + __raw_writel(BM_PWM_CTRL_PWM2_ENABLE, REGS_PWM_BASE + HW_PWM_CTRL_CLR); + + clk_disable(pwm_clk); + clk_put(pwm_clk); +} + +static int values[] = { 0, 4, 9, 14, 20, 27, 35, 45, 57, 75, 100 }; + +static int power[] = { + 0, 1500, 3600, 6100, 10300, + 15500, 74200, 114200, 155200, + 190100, 191000 +}; + +static int bl_to_power(int br) +{ + int base; + int rem; + + if (br > 100) + br = 100; + base = power[br / 10]; + rem = br % 10; + if (!rem) + return base; + else + return base + (rem * (power[br / 10 + 1]) - base) / 10; +} + +static int set_bl_intensity(struct mxs_platform_bl_data *data, + struct backlight_device *bd, int suspended) +{ + int intensity = bd->props.brightness; + int scaled_int; + + if (bd->props.power != FB_BLANK_UNBLANK) + intensity = 0; + if (bd->props.fb_blank != FB_BLANK_UNBLANK) + intensity = 0; + if (suspended) + intensity = 0; + + /* + * This is not too cool but what can we do? + * Luminance changes non-linearly... + */ + if (regulator_set_current_limit + (data->regulator, bl_to_power(intensity), bl_to_power(intensity))) + return -EBUSY; + + scaled_int = values[intensity / 10]; + if (scaled_int < 100) { + int rem = intensity - 10 * (intensity / 10); /* r = i % 10; */ + scaled_int += rem * (values[intensity / 10 + 1] - + values[intensity / 10]) / 10; + } + __raw_writel(BF_PWM_ACTIVEn_INACTIVE(scaled_int) | + BF_PWM_ACTIVEn_ACTIVE(0), + REGS_PWM_BASE + HW_PWM_ACTIVEn(2)); + __raw_writel(BF_PWM_PERIODn_CDIV(6) | /* divide by 64 */ + BF_PWM_PERIODn_INACTIVE_STATE(2) | /* low */ + BF_PWM_PERIODn_ACTIVE_STATE(3) | /* high */ + BF_PWM_PERIODn_PERIOD(399), + REGS_PWM_BASE + HW_PWM_PERIODn(2)); + return 0; +} + +static struct mxs_platform_bl_data bl_data = { + .bl_max_intensity = 100, + .bl_default_intensity = 50, + .bl_cons_intensity = 50, + .init_bl = init_bl, + .free_bl = free_bl, + .set_bl_intensity = set_bl_intensity, +}; + +static int __init register_devices(void) +{ + struct platform_device *pdev; + pdev = mxs_get_device("mxs-fb", 0); + if (pdev == NULL || IS_ERR(pdev)) + return -ENODEV; + + mxs_lcd_register_entry(&fb_entry, pdev->dev.platform_data); + + return 0; +} + +subsys_initcall(register_devices); diff --git a/drivers/video/mxs/lcd_lms430.c b/drivers/video/mxs/lcd_lms430.c new file mode 100644 index 000000000000..c167774d5785 --- /dev/null +++ b/drivers/video/mxs/lcd_lms430.c @@ -0,0 +1,300 @@ +/* + * Freescale MXS Samsung LMS430 LCD panel initialization + * + * Embedded Alley Solutions, Inc + * + * Copyright (C) 2009-2010 Freescale Semiconductor, Inc. + * Copyright 2009 Embedded Alley Solutions, Inc All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#define REGS_PWM_BASE IO_ADDRESS(PWM_PHYS_ADDR) + +#define DOTCLK_H_ACTIVE 480 +#define DOTCLK_H_PULSE_WIDTH 1 +#define DOTCLK_HF_PORCH 8 +#define DOTCLK_HB_PORCH 15 +#define DOTCLK_H_WAIT_CNT (DOTCLK_H_PULSE_WIDTH + (3 * DOTCLK_HB_PORCH)) +#define DOTCLK_H_PERIOD (DOTCLK_H_WAIT_CNT + DOTCLK_HF_PORCH + DOTCLK_H_ACTIVE) + +#define DOTCLK_V_ACTIVE 272 +#define DOTCLK_V_PULSE_WIDTH 1 +#define DOTCLK_VF_PORCH 4 +#define DOTCLK_VB_PORCH 12 +#define DOTCLK_V_WAIT_CNT (DOTCLK_V_PULSE_WIDTH + DOTCLK_VB_PORCH) +#define DOTCLK_V_PERIOD (DOTCLK_VF_PORCH + DOTCLK_V_ACTIVE + DOTCLK_V_WAIT_CNT) + +static struct mxs_platform_bl_data bl_data; +static struct clk *lcd_clk; + +static int init_panel(struct device *dev, dma_addr_t phys, int memsize, + struct mxs_platform_fb_entry *pentry) +{ + int ret = 0; + lcd_clk = clk_get(NULL, "lcdif"); + if (IS_ERR(lcd_clk)) { + ret = PTR_ERR(lcd_clk); + goto out; + } + ret = clk_enable(lcd_clk); + if (ret) { + clk_put(lcd_clk); + goto out; + } + + ret = clk_set_rate(lcd_clk, 1000000000 / pentry->cycle_time_ns); /* Hz */ + if (ret) { + clk_disable(lcd_clk); + clk_put(lcd_clk); + goto out; + } + + /* + * Make sure we do a high-to-low transition to reset the panel. + * First make it low for 100 msec, hi for 10 msec, low for 10 msec, + * then hi. + */ + __raw_writel(BM_LCDIF_CTRL1_RESET, REGS_LCDIF_BASE + HW_LCDIF_CTRL1_CLR); /* low */ + mdelay(100); + __raw_writel(BM_LCDIF_CTRL1_RESET, REGS_LCDIF_BASE + HW_LCDIF_CTRL1_SET); /* high */ + mdelay(10); + __raw_writel(BM_LCDIF_CTRL1_RESET, REGS_LCDIF_BASE + HW_LCDIF_CTRL1_CLR); /* low */ + + /* For the Samsung, Reset must be held low at least 30 uSec + * Therefore, we'll hold it low for about 10 mSec just to be sure. + * Then we'll wait 1 mSec afterwards. + */ + mdelay(10); + __raw_writel(BM_LCDIF_CTRL1_RESET, REGS_LCDIF_BASE + HW_LCDIF_CTRL1_SET); /* high */ + mdelay(1); + + setup_dotclk_panel(DOTCLK_V_PULSE_WIDTH, DOTCLK_V_PERIOD, + DOTCLK_V_WAIT_CNT, DOTCLK_V_ACTIVE, + DOTCLK_H_PULSE_WIDTH, DOTCLK_H_PERIOD, + DOTCLK_H_WAIT_CNT, DOTCLK_H_ACTIVE, 0); + + ret = mxs_lcdif_dma_init(dev, phys, memsize); + if (ret) + goto out; + + mxs_lcd_set_bl_pdata(pentry->bl_data); + mxs_lcdif_notify_clients(MXS_LCDIF_PANEL_INIT, pentry); + return 0; + +out: + return ret; +} + +static void release_panel(struct device *dev, + struct mxs_platform_fb_entry *pentry) +{ + /* Reset LCD panel signel. */ + __raw_writel(BM_LCDIF_CTRL1_RESET, + REGS_LCDIF_BASE + HW_LCDIF_CTRL1_CLR); + mdelay(100); + mxs_lcdif_notify_clients(MXS_LCDIF_PANEL_RELEASE, pentry); + release_dotclk_panel(); + mxs_lcdif_dma_release(); + clk_disable(lcd_clk); + clk_put(lcd_clk); + __raw_writel(BM_LCDIF_CTRL_CLKGATE, + REGS_LCDIF_BASE + HW_LCDIF_CTRL_SET); +} + +static int blank_panel(int blank) +{ + int ret = 0, count; + + switch (blank) { + case FB_BLANK_NORMAL: + case FB_BLANK_VSYNC_SUSPEND: + case FB_BLANK_HSYNC_SUSPEND: + case FB_BLANK_POWERDOWN: + __raw_writel(BM_LCDIF_CTRL_BYPASS_COUNT, + REGS_LCDIF_BASE + HW_LCDIF_CTRL_CLR); + for (count = 10000; count; count--) { + if (__raw_readl(REGS_LCDIF_BASE + HW_LCDIF_STAT) & + BM_LCDIF_STAT_TXFIFO_EMPTY) + break; + udelay(1); + } + break; + + case FB_BLANK_UNBLANK: + __raw_writel(BM_LCDIF_CTRL_BYPASS_COUNT, + REGS_LCDIF_BASE + HW_LCDIF_CTRL_SET); + break; + + default: + ret = -EINVAL; + } + return ret; +} + +static struct mxs_platform_fb_entry fb_entry = { + .name = "lms430", + .x_res = 272, + .y_res = 480, + .bpp = 32, + .cycle_time_ns = 150, + .lcd_type = MXS_LCD_PANEL_DOTCLK, + .init_panel = init_panel, + .release_panel = release_panel, + .blank_panel = blank_panel, + .run_panel = mxs_lcdif_run, + .stop_panel = mxs_lcdif_stop, + .pan_display = mxs_lcdif_pan_display, + .bl_data = &bl_data, +}; + +static struct clk *pwm_clk; + +static int init_bl(struct mxs_platform_bl_data *data) +{ + int ret = 0; + + pwm_clk = clk_get(NULL, "pwm"); + if (IS_ERR(pwm_clk)) { + ret = PTR_ERR(pwm_clk); + return ret; + } + clk_enable(pwm_clk); + mxs_reset_block(REGS_PWM_BASE, 1); + + __raw_writel(BF_PWM_ACTIVEn_INACTIVE(0) | + BF_PWM_ACTIVEn_ACTIVE(0), + REGS_PWM_BASE + HW_PWM_ACTIVEn(2)); + __raw_writel(BF_PWM_PERIODn_CDIV(6) | /* divide by 64 */ + BF_PWM_PERIODn_INACTIVE_STATE(2) | /* low */ + BF_PWM_PERIODn_ACTIVE_STATE(3) | /* high */ + BF_PWM_PERIODn_PERIOD(599), + REGS_PWM_BASE + HW_PWM_PERIODn(2)); + __raw_writel(BM_PWM_CTRL_PWM2_ENABLE, REGS_PWM_BASE + HW_PWM_CTRL_SET); + + return 0; +} + +static void free_bl(struct mxs_platform_bl_data *data) +{ + __raw_writel(BF_PWM_ACTIVEn_INACTIVE(0) | + BF_PWM_ACTIVEn_ACTIVE(0), + REGS_PWM_BASE + HW_PWM_ACTIVEn(2)); + __raw_writel(BF_PWM_PERIODn_CDIV(6) | /* divide by 64 */ + BF_PWM_PERIODn_INACTIVE_STATE(2) | /* low */ + BF_PWM_PERIODn_ACTIVE_STATE(3) | /* high */ + BF_PWM_PERIODn_PERIOD(599), + REGS_PWM_BASE + HW_PWM_PERIODn(2)); + __raw_writel(BM_PWM_CTRL_PWM2_ENABLE, REGS_PWM_BASE + HW_PWM_CTRL_CLR); + + clk_disable(pwm_clk); + clk_put(pwm_clk); +} + +static int values[] = { 0, 4, 9, 14, 20, 27, 35, 45, 57, 75, 100 }; + +static int power[] = { + 0, 1500, 3600, 6100, 10300, + 15500, 74200, 114200, 155200, + 190100, 191000 +}; + +static int bl_to_power(int br) +{ + int base; + int rem; + + if (br > 100) + br = 100; + base = power[br / 10]; + rem = br % 10; + if (!rem) + return base; + else + return base + (rem * (power[br / 10 + 1]) - base) / 10; +} + +static int set_bl_intensity(struct mxs_platform_bl_data *data, + struct backlight_device *bd, int suspended) +{ + int intensity = bd->props.brightness; + int scaled_int; + + if (bd->props.power != FB_BLANK_UNBLANK) + intensity = 0; + if (bd->props.fb_blank != FB_BLANK_UNBLANK) + intensity = 0; + if (suspended) + intensity = 0; + + /* + * This is not too cool but what can we do? + * Luminance changes non-linearly... + */ + if (regulator_set_current_limit + (data->regulator, bl_to_power(intensity), bl_to_power(intensity))) + return -EBUSY; + + scaled_int = values[intensity / 10]; + if (scaled_int < 100) { + int rem = intensity - 10 * (intensity / 10); /* r = i % 10; */ + scaled_int += rem * (values[intensity / 10 + 1] - + values[intensity / 10]) / 10; + } + __raw_writel(BF_PWM_ACTIVEn_INACTIVE(scaled_int) | + BF_PWM_ACTIVEn_ACTIVE(0), + REGS_PWM_BASE + HW_PWM_ACTIVEn(2)); + __raw_writel(BF_PWM_PERIODn_CDIV(6) | /* divide by 64 */ + BF_PWM_PERIODn_INACTIVE_STATE(2) | /* low */ + BF_PWM_PERIODn_ACTIVE_STATE(3) | /* high */ + BF_PWM_PERIODn_PERIOD(399), + REGS_PWM_BASE + HW_PWM_PERIODn(2)); + return 0; +} + +static struct mxs_platform_bl_data bl_data = { + .bl_max_intensity = 100, + .bl_default_intensity = 50, + .bl_cons_intensity = 50, + .init_bl = init_bl, + .free_bl = free_bl, + .set_bl_intensity = set_bl_intensity, +}; + +static int __init register_devices(void) +{ + struct platform_device *pdev; + pdev = mxs_get_device("mxs-fb", 0); + if (pdev == NULL || IS_ERR(pdev)) + return -ENODEV; + + mxs_lcd_register_entry(&fb_entry, pdev->dev.platform_data); + + return 0; +} + +subsys_initcall(register_devices); diff --git a/drivers/video/mxs/lcdif.c b/drivers/video/mxs/lcdif.c new file mode 100644 index 000000000000..f7d48a6fb3e9 --- /dev/null +++ b/drivers/video/mxs/lcdif.c @@ -0,0 +1,136 @@ +/* + * Freescale MXS LCDIF low-level routines + * + * Author: Vitaly Wool + * + * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. + * Copyright (C) 2009-2010 Freescale Semiconductor, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include +#include + +#include +#include +#include +#include + +#define REGS_LCDIF_BASE IO_ADDRESS(LCDIF_PHYS_ADDR) + +void mxs_init_lcdif(void) +{ + __raw_writel(BM_LCDIF_CTRL_CLKGATE, + REGS_LCDIF_BASE + HW_LCDIF_CTRL_CLR); + /* Reset controller */ + __raw_writel(BM_LCDIF_CTRL_SFTRST, REGS_LCDIF_BASE + HW_LCDIF_CTRL_SET); + udelay(10); + + /* Take controller out of reset */ + __raw_writel(BM_LCDIF_CTRL_SFTRST | BM_LCDIF_CTRL_CLKGATE, + REGS_LCDIF_BASE + HW_LCDIF_CTRL_CLR); + + /* Setup the bus protocol */ + __raw_writel(BM_LCDIF_CTRL1_MODE86, + REGS_LCDIF_BASE + HW_LCDIF_CTRL1_CLR); + __raw_writel(BM_LCDIF_CTRL1_BUSY_ENABLE, + REGS_LCDIF_BASE + HW_LCDIF_CTRL1_CLR); + + /* Take display out of reset */ + __raw_writel(BM_LCDIF_CTRL1_RESET, + REGS_LCDIF_BASE + HW_LCDIF_CTRL1_SET); + + /* VSYNC is an input by default */ + __raw_writel(BM_LCDIF_VDCTRL0_VSYNC_OEB, + REGS_LCDIF_BASE + HW_LCDIF_VDCTRL0_SET); + + /* Reset display */ + __raw_writel(BM_LCDIF_CTRL1_RESET, + REGS_LCDIF_BASE + HW_LCDIF_CTRL1_CLR); + udelay(10); + __raw_writel(BM_LCDIF_CTRL1_RESET, + REGS_LCDIF_BASE + HW_LCDIF_CTRL1_SET); + udelay(10); +} +EXPORT_SYMBOL(mxs_init_lcdif); + +int mxs_lcdif_dma_init(struct device *dev, dma_addr_t phys, int memsize) +{ + __raw_writel(BM_LCDIF_CTRL_LCDIF_MASTER, + REGS_LCDIF_BASE + HW_LCDIF_CTRL_SET); + + __raw_writel(phys, REGS_LCDIF_BASE + HW_LCDIF_CUR_BUF); + __raw_writel(phys, REGS_LCDIF_BASE + HW_LCDIF_NEXT_BUF); + + return 0; +} +EXPORT_SYMBOL(mxs_lcdif_dma_init); + +void mxs_lcdif_dma_release(void) +{ + __raw_writel(BM_LCDIF_CTRL_LCDIF_MASTER, + REGS_LCDIF_BASE + HW_LCDIF_CTRL_CLR); + return; +} +EXPORT_SYMBOL(mxs_lcdif_dma_release); + +void mxs_lcdif_run(void) +{ + __raw_writel(BM_LCDIF_CTRL_LCDIF_MASTER, + REGS_LCDIF_BASE + HW_LCDIF_CTRL_SET); + __raw_writel(BM_LCDIF_CTRL_RUN, REGS_LCDIF_BASE + HW_LCDIF_CTRL_SET); +} +EXPORT_SYMBOL(mxs_lcdif_run); + +void mxs_lcdif_stop(void) +{ + __raw_writel(BM_LCDIF_CTRL_RUN, REGS_LCDIF_BASE + HW_LCDIF_CTRL_CLR); + __raw_writel(BM_LCDIF_CTRL_LCDIF_MASTER, + REGS_LCDIF_BASE + HW_LCDIF_CTRL_CLR); + udelay(100); +} +EXPORT_SYMBOL(mxs_lcdif_stop); + +int mxs_lcdif_pan_display(dma_addr_t addr) +{ + __raw_writel(addr, REGS_LCDIF_BASE + HW_LCDIF_NEXT_BUF); + + return 0; +} + +EXPORT_SYMBOL(mxs_lcdif_pan_display); + +static BLOCKING_NOTIFIER_HEAD(lcdif_client_list); + +int mxs_lcdif_register_client(struct notifier_block *nb) +{ + return blocking_notifier_chain_register(&lcdif_client_list, nb); +} + +EXPORT_SYMBOL(mxs_lcdif_register_client); + +void mxs_lcdif_unregister_client(struct notifier_block *nb) +{ + blocking_notifier_chain_unregister(&lcdif_client_list, nb); +} +EXPORT_SYMBOL(mxs_lcdif_unregister_client); + +void mxs_lcdif_notify_clients(unsigned long event, + struct mxs_platform_fb_entry *pentry) +{ + blocking_notifier_call_chain(&lcdif_client_list, event, pentry); +} +EXPORT_SYMBOL(mxs_lcdif_notify_clients); diff --git a/drivers/video/mxs/mxsfb.c b/drivers/video/mxs/mxsfb.c new file mode 100644 index 000000000000..0e58ced83066 --- /dev/null +++ b/drivers/video/mxs/mxsfb.c @@ -0,0 +1,950 @@ +/* + * Freescale MXS framebuffer driver + * + * Author: Vitaly Wool + * + * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. + * Copyright (C) 2009-2010 Freescale Semiconductor, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#define NUM_SCREENS 1 + +enum { + F_DISABLE = 0, + F_ENABLE, + F_REENABLE, +}; + +struct mxs_fb_data { + struct fb_info info; + struct mxs_platform_fb_data *pdata; + struct work_struct work; + struct mutex blank_mutex; + u32 state; + u32 task_state; + ssize_t mem_size; + ssize_t map_size; + dma_addr_t phys_start; + dma_addr_t cur_phys; + int irq; + unsigned long regbase; + void *virt_start; + struct device *dev; + wait_queue_head_t vsync_wait_q; + u32 vsync_count; + void *par; +}; + +/* forward declaration */ +static int mxsfb_blank(int blank, struct fb_info *info); +static unsigned char *default_panel_name; +static struct mxs_fb_data *cdata; +static void init_timings(struct mxs_fb_data *data); + +static void mxsfb_enable_controller(struct mxs_fb_data *data) +{ + struct mxs_platform_fb_entry *pentry = data->pdata->cur; + + if (!data || !data->pdata || !data->pdata->cur) + return; + + mxs_init_lcdif(); + init_timings(data); + pentry->init_panel(data->dev, data->phys_start, + data->info.fix.smem_len, data->pdata->cur); + pentry->run_panel(); + + if (pentry->blank_panel) + pentry->blank_panel(FB_BLANK_UNBLANK); +} + +static void mxsfb_disable_controller(struct mxs_fb_data *data) +{ + struct mxs_platform_fb_entry *pentry = data->pdata->cur; + + if (!data || !data->pdata || !data->pdata->cur) + return; + + if (pentry->blank_panel) + pentry->blank_panel(FB_BLANK_POWERDOWN); + + if (pentry->stop_panel) + pentry->stop_panel(); + pentry->release_panel(data->dev, pentry); +} + +static void set_controller_state(struct mxs_fb_data *data, u32 state) +{ + struct mxs_platform_fb_entry *pentry = data->pdata->cur; + struct fb_info *info = &data->info; + u32 old_state; + + mutex_lock(&data->blank_mutex); + old_state = data->state; + pr_debug("%s, old_state %d, state %d\n", __func__, old_state, state); + + switch (state) { + case F_DISABLE: + /* + * Disable controller + */ + if (old_state != F_DISABLE) { + data->state = F_DISABLE; + mxsfb_disable_controller(data); + } + break; + + case F_REENABLE: + /* + * Re-enable the controller when panel changed. + */ + if (old_state == F_ENABLE) { + mxsfb_disable_controller(data); + + pentry = data->pdata->cur = data->pdata->next; + info->fix.smem_len = pentry->y_res * pentry->x_res * + pentry->bpp / 8; + info->screen_size = info->fix.smem_len; + memset((void *)info->screen_base, 0, info->screen_size); + + mxsfb_enable_controller(data); + + data->state = F_ENABLE; + } else if (old_state == F_DISABLE) { + pentry = data->pdata->cur = data->pdata->next; + info->fix.smem_len = pentry->y_res * pentry->x_res * + pentry->bpp / 8; + info->screen_size = info->fix.smem_len; + memset((void *)info->screen_base, 0, info->screen_size); + + data->state = F_DISABLE; + } + break; + + case F_ENABLE: + if (old_state != F_ENABLE) { + data->state = F_ENABLE; + mxsfb_enable_controller(data); + } + break; + } + mutex_unlock(&data->blank_mutex); + +} + +static void mxsfb_task(struct work_struct *work) +{ + struct mxs_fb_data *data = container_of(work, struct mxs_fb_data, work); + + u32 state = xchg(&data->task_state, -1); + pr_debug("%s: state = %d, data->task_state = %d\n", + __func__, state, data->task_state); + + set_controller_state(data, state); +} + +static void mxs_schedule_work(struct mxs_fb_data *data, u32 state) +{ + unsigned long flags; + + local_irq_save(flags); + + data->task_state = state; + schedule_work(&data->work); + + local_irq_restore(flags); +} + +static irqreturn_t lcd_irq_handler(int irq, void *dev_id) +{ + struct mxs_fb_data *data = dev_id; + u32 status_lcd = __raw_readl(data->regbase + HW_LCDIF_CTRL1); + pr_debug("%s: irq %d\n", __func__, irq); + + if (status_lcd & BM_LCDIF_CTRL1_VSYNC_EDGE_IRQ) { + pr_debug("%s: VSYNC irq\n", __func__); + data->vsync_count++; + __raw_writel(BM_LCDIF_CTRL1_VSYNC_EDGE_IRQ, + data->regbase + HW_LCDIF_CTRL1_CLR); + wake_up_interruptible(&data->vsync_wait_q); + } + if (status_lcd & BM_LCDIF_CTRL1_CUR_FRAME_DONE_IRQ) { + pr_debug("%s: frame done irq\n", __func__); + __raw_writel(BM_LCDIF_CTRL1_CUR_FRAME_DONE_IRQ, + data->regbase + HW_LCDIF_CTRL1_CLR); + data->vsync_count++; + } + if (status_lcd & BM_LCDIF_CTRL1_UNDERFLOW_IRQ) { + pr_debug("%s: underflow irq\n", __func__); + __raw_writel(BM_LCDIF_CTRL1_UNDERFLOW_IRQ, + data->regbase + HW_LCDIF_CTRL1_CLR); + } + if (status_lcd & BM_LCDIF_CTRL1_OVERFLOW_IRQ) { + pr_debug("%s: overflow irq\n", __func__); + __raw_writel(BM_LCDIF_CTRL1_OVERFLOW_IRQ, + data->regbase + HW_LCDIF_CTRL1_CLR); + } + return IRQ_HANDLED; +} + +static struct fb_var_screeninfo mxsfb_default __devinitdata = { + .activate = FB_ACTIVATE_TEST, + .height = -1, + .width = -1, + .pixclock = 20000, + .left_margin = 64, + .right_margin = 64, + .upper_margin = 32, + .lower_margin = 32, + .hsync_len = 64, + .vsync_len = 2, + .vmode = FB_VMODE_NONINTERLACED, +}; + +static struct fb_fix_screeninfo mxsfb_fix __devinitdata = { + .id = "mxsfb", + .type = FB_TYPE_PACKED_PIXELS, + .visual = FB_VISUAL_TRUECOLOR, + .xpanstep = 0, + .ypanstep = 0, + .ywrapstep = 0, + .accel = FB_ACCEL_NONE, +}; + +int mxsfb_get_info(struct fb_var_screeninfo *var, struct fb_fix_screeninfo *fix) +{ + if (!cdata) + return -ENODEV; + + *var = cdata->info.var; + *fix = cdata->info.fix; + return 0; +} + +void mxsfb_cfg_pxp(int enable, dma_addr_t pxp_phys) +{ + if (enable) + cdata->pdata->cur->pan_display(pxp_phys); + else + cdata->pdata->cur->pan_display(cdata->cur_phys); +} + +static int mxsfb_mmap(struct fb_info *info, struct vm_area_struct *vma) +{ + struct mxs_fb_data *data = (struct mxs_fb_data *)info; + + unsigned long off = vma->vm_pgoff << PAGE_SHIFT; + + if (off < info->fix.smem_len) + return dma_mmap_writecombine(data->dev, vma, + data->virt_start, + data->phys_start, + info->fix.smem_len); + else + return -EINVAL; +} + +static int mxsfb_setcolreg(u_int regno, u_int red, u_int green, u_int blue, + u_int transp, struct fb_info *info) +{ + if (regno >= 256) /* no. of hw registers */ + return 1; + /* + * Program hardware... do anything you want with transp + */ + + /* grayscale works only partially under directcolor */ + if (info->var.grayscale) { + /* grayscale = 0.30*R + 0.59*G + 0.11*B */ + red = green = blue = (red * 77 + green * 151 + blue * 28) >> 8; + } + + /* Directcolor: + * var->{color}.offset contains start of bitfield + * var->{color}.length contains length of bitfield + * {hardwarespecific} contains width of RAMDAC + * cmap[X] is programmed to + * (X << red.offset) | (X << green.offset) | (X << blue.offset) + * RAMDAC[X] is programmed to (red, green, blue) + * + * Pseudocolor: + * uses offset = 0 && length = RAMDAC register width. + * var->{color}.offset is 0 + * var->{color}.length contains widht of DAC + * cmap is not used + * RAMDAC[X] is programmed to (red, green, blue) + * Truecolor: + * does not use DAC. Usually 3 are present. + * var->{color}.offset contains start of bitfield + * var->{color}.length contains length of bitfield + * cmap is programmed to + * (red << red.offset) | (green << green.offset) | + * (blue << blue.offset) | (transp << transp.offset) + * RAMDAC does not exist + */ +#define CNVT_TOHW(val, width) ((((val)<<(width))+0x7FFF-(val))>>16) + switch (info->fix.visual) { + case FB_VISUAL_TRUECOLOR: + case FB_VISUAL_PSEUDOCOLOR: + red = CNVT_TOHW(red, info->var.red.length); + green = CNVT_TOHW(green, info->var.green.length); + blue = CNVT_TOHW(blue, info->var.blue.length); + transp = CNVT_TOHW(transp, info->var.transp.length); + break; + case FB_VISUAL_DIRECTCOLOR: + red = CNVT_TOHW(red, 8); /* expect 8 bit DAC */ + green = CNVT_TOHW(green, 8); + blue = CNVT_TOHW(blue, 8); + /* hey, there is bug in transp handling... */ + transp = CNVT_TOHW(transp, 8); + break; + } +#undef CNVT_TOHW + /* Truecolor has hardware independent palette */ + if (info->fix.visual == FB_VISUAL_TRUECOLOR) { + + if (regno >= 16) + return 1; + + ((u32 *) (info->pseudo_palette))[regno] = + (red << info->var.red.offset) | + (green << info->var.green.offset) | + (blue << info->var.blue.offset) | + (transp << info->var.transp.offset); + } + return 0; +} + +static inline u_long get_line_length(int xres_virtual, int bpp) +{ + u_long length; + + length = xres_virtual * bpp; + length = (length + 31) & ~31; + length >>= 3; + return length; +} + +static int get_matching_pentry(struct mxs_platform_fb_entry *pentry, + void *data, int ret_prev) +{ + struct fb_var_screeninfo *info = data; + pr_debug("%s: %d:%d:%d vs %d:%d:%d\n", __func__, + pentry->x_res, pentry->y_res, pentry->bpp, + info->yres, info->xres, info->bits_per_pixel); + if (pentry->x_res == info->yres && pentry->y_res == info->xres && + pentry->bpp == info->bits_per_pixel) + ret_prev = (int)pentry; + return ret_prev; +} + +static int get_matching_pentry_by_name(struct mxs_platform_fb_entry *pentry, + void *data, int ret_prev) +{ + unsigned char *name = data; + if (!strcmp(pentry->name, name)) + ret_prev = (int)pentry; + return ret_prev; +} + +/* + * This routine actually sets the video mode. It's in here where we + * the hardware state info->par and fix which can be affected by the + * change in par. For this driver it doesn't do much. + * + * XXX: REVISIT + */ +static int mxsfb_set_par(struct fb_info *info) +{ + struct mxs_fb_data *data = (struct mxs_fb_data *)info; + struct mxs_platform_fb_data *pdata = data->pdata; + struct mxs_platform_fb_entry *pentry; + pentry = (void *)mxs_lcd_iterate_pdata(pdata, + get_matching_pentry, &info->var); + + dev_dbg(data->dev, "%s: xres %d, yres %d, bpp %d\n", + __func__, + info->var.xres, info->var.yres, info->var.bits_per_pixel); + if (!pentry) + return -EINVAL; + + info->fix.line_length = get_line_length(info->var.xres_virtual, + info->var.bits_per_pixel); + + if (pentry == pdata->cur || !pdata->cur) + return 0; + + /* init next panel */ + pdata->next = pentry; + + set_controller_state(data, F_REENABLE); + + return 0; +} + +static int mxsfb_check_var(struct fb_var_screeninfo *var, struct fb_info *info) +{ + u32 line_length; + struct mxs_fb_data *data = (struct mxs_fb_data *)info; + struct mxs_platform_fb_data *pdata = data->pdata; + + /* + * FB_VMODE_CONUPDATE and FB_VMODE_SMOOTH_XPAN are equal! + * as FB_VMODE_SMOOTH_XPAN is only used internally + */ + + if (var->vmode & FB_VMODE_CONUPDATE) { + var->vmode |= FB_VMODE_YWRAP; + var->xoffset = info->var.xoffset; + var->yoffset = info->var.yoffset; + } + + pr_debug("%s: xres %d, yres %d, bpp %d\n", __func__, + var->xres, var->yres, var->bits_per_pixel); + /* + * Some very basic checks + */ + if (!var->xres) + var->xres = 1; + if (!var->yres) + var->yres = 1; + if (var->xres > var->xres_virtual) + var->xres_virtual = var->xres; + if (var->yres > var->yres_virtual) + var->yres_virtual = var->yres; + + if (var->xres_virtual < var->xoffset + var->xres) + var->xres_virtual = var->xoffset + var->xres; + if (var->yres_virtual < var->yoffset + var->yres) + var->yres_virtual = var->yoffset + var->yres; + + line_length = get_line_length(var->xres_virtual, var->bits_per_pixel); + dev_dbg(data->dev, + "line_length %d, var->yres_virtual %d, data->mem_size %d\n", + line_length, var->yres_virtual, data->mem_size); + if (line_length * var->yres_virtual > data->map_size) + return -ENOMEM; + + if (!mxs_lcd_iterate_pdata(pdata, get_matching_pentry, var)) + return -EINVAL; + + if (var->bits_per_pixel == 16) { + /* RGBA 5551 */ + if (var->transp.length) { + var->red.offset = 0; + var->red.length = 5; + var->green.offset = 5; + var->green.length = 5; + var->blue.offset = 10; + var->blue.length = 5; + var->transp.offset = 15; + var->transp.length = 1; + } else { /* RGB 565 */ + var->red.offset = 0; + var->red.length = 5; + var->green.offset = 5; + var->green.length = 6; + var->blue.offset = 11; + var->blue.length = 5; + var->transp.offset = 0; + var->transp.length = 0; + } + } else { + var->red.offset = 16; + var->red.length = 8; + var->green.offset = 8; + var->green.length = 8; + var->blue.offset = 0; + var->blue.length = 8; + } + + var->red.msb_right = 0; + var->green.msb_right = 0; + var->blue.msb_right = 0; + var->transp.msb_right = 0; + + return 0; +} + +static int mxsfb_wait_for_vsync(u32 channel, struct fb_info *info) +{ + struct mxs_fb_data *data = (struct mxs_fb_data *)info; + u32 count = data->vsync_count; + int ret = 0; + + __raw_writel(BM_LCDIF_CTRL1_VSYNC_EDGE_IRQ_EN, + data->regbase + HW_LCDIF_CTRL1_SET); + ret = wait_event_interruptible_timeout(data->vsync_wait_q, + count != data->vsync_count, + HZ / 10); + __raw_writel(BM_LCDIF_CTRL1_VSYNC_EDGE_IRQ_EN, + data->regbase + HW_LCDIF_CTRL1_CLR); + if (!ret) { + dev_err(data->dev, "wait for vsync timed out\n"); + ret = -ETIMEDOUT; + } + return ret; +} + +static int mxsfb_ioctl(struct fb_info *info, unsigned int cmd, + unsigned long arg) +{ + u32 channel = 0; + int ret = -EINVAL; + + switch (cmd) { + case FBIO_WAITFORVSYNC: + if (!get_user(channel, (__u32 __user *) arg)) + ret = mxsfb_wait_for_vsync(channel, info); + break; + default: + break; + } + return ret; +} + +static int mxsfb_blank(int blank, struct fb_info *info) +{ + struct mxs_fb_data *data = (struct mxs_fb_data *)info; + int ret = 0; + + switch (blank) { + case FB_BLANK_NORMAL: + case FB_BLANK_VSYNC_SUSPEND: + case FB_BLANK_HSYNC_SUSPEND: + case FB_BLANK_POWERDOWN: + pr_debug("%s: FB_BLANK_POWERDOWN\n", __func__); + mxs_schedule_work(data, F_DISABLE); + break; + + case FB_BLANK_UNBLANK: + pr_debug("%s: FB_BLANK_UNBLANK\n", __func__); + mxs_schedule_work(data, F_ENABLE); + break; + + default: + ret = -EINVAL; + } + return ret; +} + +static int mxsfb_pan_display(struct fb_var_screeninfo *var, + struct fb_info *info) +{ + struct mxs_fb_data *data = (struct mxs_fb_data *)info; + int ret = 0; + + pr_debug("%s: var->xoffset %d, info->var.xoffset %d\n", + __func__, var->xoffset, info->var.xoffset); + /* check if var is valid; also, xpan is not supported */ + if (!var || (var->xoffset != info->var.xoffset) || + (var->yoffset + var->yres > var->yres_virtual)) { + ret = -EINVAL; + goto out; + } + + if (!data->pdata->cur->pan_display) { + ret = -EINVAL; + goto out; + } + + /* update framebuffer visual */ + data->cur_phys = data->phys_start + + info->fix.line_length * var->yoffset; + data->pdata->cur->pan_display(data->cur_phys); +out: + return ret; +} + +static struct fb_ops mxsfb_ops = { + .owner = THIS_MODULE, + .fb_check_var = mxsfb_check_var, + .fb_set_par = mxsfb_set_par, + .fb_mmap = mxsfb_mmap, + .fb_setcolreg = mxsfb_setcolreg, + .fb_ioctl = mxsfb_ioctl, + .fb_blank = mxsfb_blank, + .fb_pan_display = mxsfb_pan_display, + .fb_fillrect = cfb_fillrect, + .fb_copyarea = cfb_copyarea, + .fb_imageblit = cfb_imageblit, +}; + +static void init_timings(struct mxs_fb_data *data) +{ + unsigned phase_time; + unsigned timings; + + /* Just use a phase_time of 1. As optimal as it gets, now. */ + phase_time = 1; + + /* Program all 4 timings the same */ + timings = phase_time; + timings |= timings << 8; + timings |= timings << 16; + __raw_writel(timings, data->regbase + HW_LCDIF_TIMING); +} + +#ifdef CONFIG_CPU_FREQ + +struct mxsfb_notifier_block { + struct mxs_fb_data *fb_data; + struct notifier_block nb; +}; + +static int mxsfb_notifier(struct notifier_block *self, + unsigned long phase, void *p) +{ + struct mxsfb_notifier_block *block = + container_of(self, struct mxsfb_notifier_block, nb); + struct mxs_fb_data *data = block->fb_data; + struct mxs_platform_fb_entry *pentry = data->pdata->cur; + u32 old_state = data->state; + + if (!data || !data->pdata || !data->pdata->cur) + return NOTIFY_BAD; + + /* REVISIT */ + switch (phase) { + case CPUFREQ_PRECHANGE: + if (old_state == F_ENABLE) + if (pentry->blank_panel) + pentry->blank_panel(FB_BLANK_POWERDOWN); + break; + + case CPUFREQ_POSTCHANGE: + if (old_state == F_ENABLE) + if (pentry->blank_panel) + pentry->blank_panel(FB_BLANK_UNBLANK); + break; + + default: + dev_dbg(data->dev, "didn't handle notify %ld\n", phase); + } + + return NOTIFY_DONE; +} + +static struct mxsfb_notifier_block mxsfb_nb = { + .nb = { + .notifier_call = mxsfb_notifier, + }, +}; +#endif /* CONFIG_CPU_FREQ */ + +static int get_max_memsize(struct mxs_platform_fb_entry *pentry, + void *data, int ret_prev) +{ + struct mxs_fb_data *fbdata = data; + int sz = pentry->x_res * pentry->y_res * pentry->bpp / 8; + fbdata->mem_size = sz < ret_prev ? ret_prev : sz; + pr_debug("%s: mem_size now %d\n", __func__, fbdata->mem_size); + return fbdata->mem_size; +} + +static int __devinit mxsfb_probe(struct platform_device *pdev) +{ + int ret = 0; + struct mxs_fb_data *data; + struct resource *res; + struct fb_info *info; + struct mxs_platform_fb_data *pdata = pdev->dev.platform_data; + struct mxs_platform_fb_entry *pentry = NULL; + + if (pdata == NULL) { + ret = -ENODEV; + goto out; + } + + if (default_panel_name) { + pentry = (void *)mxs_lcd_iterate_pdata(pdata, + get_matching_pentry_by_name, + default_panel_name); + if (pentry) { + mxs_lcd_move_pentry_up(pentry, pdata); + pdata->cur = pentry; + } + } + if (!default_panel_name || !pentry) + pentry = pdata->cur; + if (!pentry || !pentry->init_panel || !pentry->run_panel || + !pentry->release_panel) { + ret = -EINVAL; + goto out; + } + + data = + (struct mxs_fb_data *)framebuffer_alloc(sizeof(struct mxs_fb_data) + + sizeof(u32) * 256 - + sizeof(struct fb_info), + &pdev->dev); + if (data == NULL) { + ret = -ENOMEM; + goto out; + } + + cdata = data; + data->dev = &pdev->dev; + data->pdata = pdata; + platform_set_drvdata(pdev, data); + info = &data->info; + + dev_dbg(&pdev->dev, "resolution %dx%d, bpp %d\n", pentry->x_res, + pentry->y_res, pentry->bpp); + + mxs_lcd_iterate_pdata(pdata, get_max_memsize, data); + + data->map_size = PAGE_ALIGN(data->mem_size) * NUM_SCREENS; + dev_dbg(&pdev->dev, "memory to allocate: %d\n", data->map_size); + + data->virt_start = dma_alloc_writecombine(&pdev->dev, + data->map_size, + &data->phys_start, + GFP_KERNEL); + + if (data->virt_start == NULL) { + ret = -ENOMEM; + goto out_dma; + } + dev_dbg(&pdev->dev, "allocated at %p:0x%x\n", data->virt_start, + data->phys_start); + mutex_init(&data->blank_mutex); + INIT_WORK(&data->work, mxsfb_task); + data->state = F_ENABLE; + + mxsfb_default.bits_per_pixel = pentry->bpp; + /* NB: rotated */ + mxsfb_default.xres = pentry->y_res; + mxsfb_default.yres = pentry->x_res; + mxsfb_default.xres_virtual = pentry->y_res; + mxsfb_default.yres_virtual = data->map_size / + (pentry->y_res * pentry->bpp / 8); + if (mxsfb_default.yres_virtual >= mxsfb_default.yres * 2) + mxsfb_default.yres_virtual = mxsfb_default.yres * 2; + else + mxsfb_default.yres_virtual = mxsfb_default.yres; + + mxsfb_fix.smem_start = data->phys_start; + mxsfb_fix.smem_len = pentry->y_res * pentry->x_res * pentry->bpp / 8; + mxsfb_fix.ypanstep = 1; + + switch (pentry->bpp) { + case 32: + case 24: + mxsfb_default.red.offset = 16; + mxsfb_default.red.length = 8; + mxsfb_default.green.offset = 8; + mxsfb_default.green.length = 8; + mxsfb_default.blue.offset = 0; + mxsfb_default.blue.length = 8; + break; + + case 16: + mxsfb_default.red.offset = 11; + mxsfb_default.red.length = 5; + mxsfb_default.green.offset = 5; + mxsfb_default.green.length = 6; + mxsfb_default.blue.offset = 0; + mxsfb_default.blue.length = 5; + break; + + default: + dev_err(&pdev->dev, "unsupported bitwidth %d\n", pentry->bpp); + ret = -EINVAL; + goto out_dma; + } + + info->screen_base = data->virt_start; + info->fbops = &mxsfb_ops; + info->var = mxsfb_default; + info->fix = mxsfb_fix; + info->pseudo_palette = &data->par; + data->par = NULL; + info->flags = FBINFO_FLAG_DEFAULT; + + init_waitqueue_head(&data->vsync_wait_q); + data->vsync_count = 0; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (res == NULL) { + dev_err(&pdev->dev, "cannot get IRQ resource\n"); + ret = -ENODEV; + goto out_dma; + } + data->regbase = (unsigned long)IO_ADDRESS(res->start); + + res = platform_get_resource(pdev, IORESOURCE_IRQ, 0); + if (res == NULL) { + dev_err(&pdev->dev, "cannot get IRQ resource\n"); + ret = -ENODEV; + goto out_dma; + } + data->irq = res->start; + + mxsfb_check_var(&info->var, info); + + ret = fb_alloc_cmap(&info->cmap, 256, 0); + if (ret) + goto out_cmap; + + mxsfb_set_par(info); + + mxs_init_lcdif(); + ret = pentry->init_panel(data->dev, data->phys_start, + mxsfb_fix.smem_len, pentry); + if (ret) { + dev_err(&pdev->dev, "cannot initialize LCD panel\n"); + goto out_panel; + } + dev_dbg(&pdev->dev, "LCD panel initialized\n"); + init_timings(data); + + ret = request_irq(data->irq, lcd_irq_handler, 0, "fb_irq", data); + if (ret) { + dev_err(&pdev->dev, "request_irq (%d) failed with error %d\n", + data->irq, ret); + goto out_panel; + } + ret = register_framebuffer(info); + if (ret) + goto out_irq; + + pentry->run_panel(); + /* REVISIT: temporary workaround for MX23EVK */ + mxsfb_disable_controller(data); + mxsfb_enable_controller(data); + data->cur_phys = data->phys_start; + dev_dbg(&pdev->dev, "LCD running now\n"); + +#ifdef CONFIG_CPU_FREQ + mxsfb_nb.fb_data = data; + cpufreq_register_notifier(&mxsfb_nb.nb, CPUFREQ_TRANSITION_NOTIFIER); +#endif /* CONFIG_CPU_FREQ */ + + goto out; + +out_irq: + free_irq(data->irq, data); +out_panel: + fb_dealloc_cmap(&info->cmap); +out_cmap: + dma_free_writecombine(&pdev->dev, data->map_size, data->virt_start, + data->phys_start); +out_dma: + kfree(data); +out: + return ret; +} + +static int mxsfb_remove(struct platform_device *pdev) +{ + struct mxs_fb_data *data = platform_get_drvdata(pdev); + + set_controller_state(data, F_DISABLE); + + unregister_framebuffer(&data->info); + framebuffer_release(&data->info); + fb_dealloc_cmap(&data->info.cmap); + free_irq(data->irq, data); + dma_free_writecombine(&pdev->dev, data->map_size, data->virt_start, + data->phys_start); + kfree(data); + platform_set_drvdata(pdev, NULL); + return 0; +} + +#ifdef CONFIG_PM +static int mxsfb_suspend(struct platform_device *pdev, pm_message_t state) +{ + struct mxs_fb_data *data = platform_get_drvdata(pdev); + + set_controller_state(data, F_DISABLE); + + return 0; +} + +static int mxsfb_resume(struct platform_device *pdev) +{ + struct mxs_fb_data *data = platform_get_drvdata(pdev); + + set_controller_state(data, F_ENABLE); + return 0; +} +#else +#define mxsfb_suspend NULL +#define mxsfb_resume NULL +#endif + +static struct platform_driver mxsfb_driver = { + .probe = mxsfb_probe, + .remove = mxsfb_remove, + .suspend = mxsfb_suspend, + .resume = mxsfb_resume, + .driver = { + .name = "mxs-fb", + .owner = THIS_MODULE, + }, +}; + +static int __init mxsfb_init(void) +{ + return platform_driver_register(&mxsfb_driver); +} + +static void __exit mxsfb_exit(void) +{ + platform_driver_unregister(&mxsfb_driver); +} + +module_init(mxsfb_init); +module_exit(mxsfb_exit); + +/* + * LCD panel select + */ +static int __init default_panel_select(char *str) +{ + default_panel_name = str; + return 0; +} + +__setup("lcd_panel=", default_panel_select); + +MODULE_AUTHOR("Vitaly Wool "); +MODULE_DESCRIPTION("MXS Framebuffer Driver"); +MODULE_LICENSE("GPL"); diff --git a/drivers/video/mxs/regs-tvenc.h b/drivers/video/mxs/regs-tvenc.h new file mode 100644 index 000000000000..bd2493e2dee5 --- /dev/null +++ b/drivers/video/mxs/regs-tvenc.h @@ -0,0 +1,583 @@ +/* + * Freescale TVENC Register Definitions + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. + * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * This file is created by xml file. Don't Edit it. + * + * Xml Revision: 1.00 + * Template revision: 26195 + */ + +#ifndef __ARCH_ARM___TVENC_H +#define __ARCH_ARM___TVENC_H + + +#define HW_TVENC_CTRL (0x00000000) +#define HW_TVENC_CTRL_SET (0x00000004) +#define HW_TVENC_CTRL_CLR (0x00000008) +#define HW_TVENC_CTRL_TOG (0x0000000c) + +#define BM_TVENC_CTRL_SFTRST 0x80000000 +#define BM_TVENC_CTRL_CLKGATE 0x40000000 +#define BM_TVENC_CTRL_TVENC_MACROVISION_PRESENT 0x20000000 +#define BM_TVENC_CTRL_TVENC_COMPOSITE_PRESENT 0x10000000 +#define BM_TVENC_CTRL_TVENC_SVIDEO_PRESENT 0x08000000 +#define BM_TVENC_CTRL_TVENC_COMPONENT_PRESENT 0x04000000 +#define BP_TVENC_CTRL_RSRVD1 6 +#define BM_TVENC_CTRL_RSRVD1 0x03FFFFC0 +#define BF_TVENC_CTRL_RSRVD1(v) \ + (((v) << 6) & BM_TVENC_CTRL_RSRVD1) +#define BM_TVENC_CTRL_DAC_FIFO_NO_WRITE 0x00000020 +#define BM_TVENC_CTRL_DAC_FIFO_NO_READ 0x00000010 +#define BM_TVENC_CTRL_DAC_DATA_FIFO_RST 0x00000008 +#define BP_TVENC_CTRL_RSRVD2 1 +#define BM_TVENC_CTRL_RSRVD2 0x00000006 +#define BF_TVENC_CTRL_RSRVD2(v) \ + (((v) << 1) & BM_TVENC_CTRL_RSRVD2) +#define BM_TVENC_CTRL_DAC_MUX_MODE 0x00000001 + +#define HW_TVENC_CONFIG (0x00000010) +#define HW_TVENC_CONFIG_SET (0x00000014) +#define HW_TVENC_CONFIG_CLR (0x00000018) +#define HW_TVENC_CONFIG_TOG (0x0000001c) + +#define BP_TVENC_CONFIG_RSRVD5 28 +#define BM_TVENC_CONFIG_RSRVD5 0xF0000000 +#define BF_TVENC_CONFIG_RSRVD5(v) \ + (((v) << 28) & BM_TVENC_CONFIG_RSRVD5) +#define BM_TVENC_CONFIG_DEFAULT_PICFORM 0x08000000 +#define BP_TVENC_CONFIG_YDEL_ADJ 24 +#define BM_TVENC_CONFIG_YDEL_ADJ 0x07000000 +#define BF_TVENC_CONFIG_YDEL_ADJ(v) \ + (((v) << 24) & BM_TVENC_CONFIG_YDEL_ADJ) +#define BM_TVENC_CONFIG_RSRVD4 0x00800000 +#define BM_TVENC_CONFIG_RSRVD3 0x00400000 +#define BM_TVENC_CONFIG_ADD_YPBPR_PED 0x00200000 +#define BM_TVENC_CONFIG_PAL_SHAPE 0x00100000 +#define BM_TVENC_CONFIG_NO_PED 0x00080000 +#define BM_TVENC_CONFIG_COLOR_BAR_EN 0x00040000 +#define BP_TVENC_CONFIG_YGAIN_SEL 16 +#define BM_TVENC_CONFIG_YGAIN_SEL 0x00030000 +#define BF_TVENC_CONFIG_YGAIN_SEL(v) \ + (((v) << 16) & BM_TVENC_CONFIG_YGAIN_SEL) +#define BP_TVENC_CONFIG_CGAIN 14 +#define BM_TVENC_CONFIG_CGAIN 0x0000C000 +#define BF_TVENC_CONFIG_CGAIN(v) \ + (((v) << 14) & BM_TVENC_CONFIG_CGAIN) +#define BP_TVENC_CONFIG_CLK_PHS 12 +#define BM_TVENC_CONFIG_CLK_PHS 0x00003000 +#define BF_TVENC_CONFIG_CLK_PHS(v) \ + (((v) << 12) & BM_TVENC_CONFIG_CLK_PHS) +#define BM_TVENC_CONFIG_RSRVD2 0x00000800 +#define BM_TVENC_CONFIG_FSYNC_ENBL 0x00000400 +#define BM_TVENC_CONFIG_FSYNC_PHS 0x00000200 +#define BM_TVENC_CONFIG_HSYNC_PHS 0x00000100 +#define BM_TVENC_CONFIG_VSYNC_PHS 0x00000080 +#define BP_TVENC_CONFIG_SYNC_MODE 4 +#define BM_TVENC_CONFIG_SYNC_MODE 0x00000070 +#define BF_TVENC_CONFIG_SYNC_MODE(v) \ + (((v) << 4) & BM_TVENC_CONFIG_SYNC_MODE) +#define BM_TVENC_CONFIG_RSRVD1 0x00000008 +#define BP_TVENC_CONFIG_ENCD_MODE 0 +#define BM_TVENC_CONFIG_ENCD_MODE 0x00000007 +#define BF_TVENC_CONFIG_ENCD_MODE(v) \ + (((v) << 0) & BM_TVENC_CONFIG_ENCD_MODE) + +#define HW_TVENC_FILTCTRL (0x00000020) +#define HW_TVENC_FILTCTRL_SET (0x00000024) +#define HW_TVENC_FILTCTRL_CLR (0x00000028) +#define HW_TVENC_FILTCTRL_TOG (0x0000002c) + +#define BP_TVENC_FILTCTRL_RSRVD1 20 +#define BM_TVENC_FILTCTRL_RSRVD1 0xFFF00000 +#define BF_TVENC_FILTCTRL_RSRVD1(v) \ + (((v) << 20) & BM_TVENC_FILTCTRL_RSRVD1) +#define BM_TVENC_FILTCTRL_YSHARP_BW 0x00080000 +#define BM_TVENC_FILTCTRL_YD_OFFSETSEL 0x00040000 +#define BM_TVENC_FILTCTRL_SEL_YLPF 0x00020000 +#define BM_TVENC_FILTCTRL_SEL_CLPF 0x00010000 +#define BM_TVENC_FILTCTRL_SEL_YSHARP 0x00008000 +#define BM_TVENC_FILTCTRL_YLPF_COEFSEL 0x00004000 +#define BM_TVENC_FILTCTRL_COEFSEL_CLPF 0x00002000 +#define BM_TVENC_FILTCTRL_YS_GAINSGN 0x00001000 +#define BP_TVENC_FILTCTRL_YS_GAINSEL 10 +#define BM_TVENC_FILTCTRL_YS_GAINSEL 0x00000C00 +#define BF_TVENC_FILTCTRL_YS_GAINSEL(v) \ + (((v) << 10) & BM_TVENC_FILTCTRL_YS_GAINSEL) +#define BM_TVENC_FILTCTRL_RSRVD2 0x00000200 +#define BM_TVENC_FILTCTRL_RSRVD3 0x00000100 +#define BP_TVENC_FILTCTRL_RSRVD4 0 +#define BM_TVENC_FILTCTRL_RSRVD4 0x000000FF +#define BF_TVENC_FILTCTRL_RSRVD4(v) \ + (((v) << 0) & BM_TVENC_FILTCTRL_RSRVD4) + +#define HW_TVENC_SYNCOFFSET (0x00000030) +#define HW_TVENC_SYNCOFFSET_SET (0x00000034) +#define HW_TVENC_SYNCOFFSET_CLR (0x00000038) +#define HW_TVENC_SYNCOFFSET_TOG (0x0000003c) + +#define BM_TVENC_SYNCOFFSET_RSRVD1 0x80000000 +#define BP_TVENC_SYNCOFFSET_HSO 20 +#define BM_TVENC_SYNCOFFSET_HSO 0x7FF00000 +#define BF_TVENC_SYNCOFFSET_HSO(v) \ + (((v) << 20) & BM_TVENC_SYNCOFFSET_HSO) +#define BP_TVENC_SYNCOFFSET_VSO 10 +#define BM_TVENC_SYNCOFFSET_VSO 0x000FFC00 +#define BF_TVENC_SYNCOFFSET_VSO(v) \ + (((v) << 10) & BM_TVENC_SYNCOFFSET_VSO) +#define BP_TVENC_SYNCOFFSET_HLC 0 +#define BM_TVENC_SYNCOFFSET_HLC 0x000003FF +#define BF_TVENC_SYNCOFFSET_HLC(v) \ + (((v) << 0) & BM_TVENC_SYNCOFFSET_HLC) + +#define HW_TVENC_HTIMINGSYNC0 (0x00000040) +#define HW_TVENC_HTIMINGSYNC0_SET (0x00000044) +#define HW_TVENC_HTIMINGSYNC0_CLR (0x00000048) +#define HW_TVENC_HTIMINGSYNC0_TOG (0x0000004c) + +#define BP_TVENC_HTIMINGSYNC0_RSRVD2 26 +#define BM_TVENC_HTIMINGSYNC0_RSRVD2 0xFC000000 +#define BF_TVENC_HTIMINGSYNC0_RSRVD2(v) \ + (((v) << 26) & BM_TVENC_HTIMINGSYNC0_RSRVD2) +#define BP_TVENC_HTIMINGSYNC0_SYNC_END 16 +#define BM_TVENC_HTIMINGSYNC0_SYNC_END 0x03FF0000 +#define BF_TVENC_HTIMINGSYNC0_SYNC_END(v) \ + (((v) << 16) & BM_TVENC_HTIMINGSYNC0_SYNC_END) +#define BP_TVENC_HTIMINGSYNC0_RSRVD1 10 +#define BM_TVENC_HTIMINGSYNC0_RSRVD1 0x0000FC00 +#define BF_TVENC_HTIMINGSYNC0_RSRVD1(v) \ + (((v) << 10) & BM_TVENC_HTIMINGSYNC0_RSRVD1) +#define BP_TVENC_HTIMINGSYNC0_SYNC_STRT 0 +#define BM_TVENC_HTIMINGSYNC0_SYNC_STRT 0x000003FF +#define BF_TVENC_HTIMINGSYNC0_SYNC_STRT(v) \ + (((v) << 0) & BM_TVENC_HTIMINGSYNC0_SYNC_STRT) + +#define HW_TVENC_HTIMINGSYNC1 (0x00000050) +#define HW_TVENC_HTIMINGSYNC1_SET (0x00000054) +#define HW_TVENC_HTIMINGSYNC1_CLR (0x00000058) +#define HW_TVENC_HTIMINGSYNC1_TOG (0x0000005c) + +#define BP_TVENC_HTIMINGSYNC1_RSRVD2 26 +#define BM_TVENC_HTIMINGSYNC1_RSRVD2 0xFC000000 +#define BF_TVENC_HTIMINGSYNC1_RSRVD2(v) \ + (((v) << 26) & BM_TVENC_HTIMINGSYNC1_RSRVD2) +#define BP_TVENC_HTIMINGSYNC1_SYNC_EQEND 16 +#define BM_TVENC_HTIMINGSYNC1_SYNC_EQEND 0x03FF0000 +#define BF_TVENC_HTIMINGSYNC1_SYNC_EQEND(v) \ + (((v) << 16) & BM_TVENC_HTIMINGSYNC1_SYNC_EQEND) +#define BP_TVENC_HTIMINGSYNC1_RSRVD1 10 +#define BM_TVENC_HTIMINGSYNC1_RSRVD1 0x0000FC00 +#define BF_TVENC_HTIMINGSYNC1_RSRVD1(v) \ + (((v) << 10) & BM_TVENC_HTIMINGSYNC1_RSRVD1) +#define BP_TVENC_HTIMINGSYNC1_SYNC_SREND 0 +#define BM_TVENC_HTIMINGSYNC1_SYNC_SREND 0x000003FF +#define BF_TVENC_HTIMINGSYNC1_SYNC_SREND(v) \ + (((v) << 0) & BM_TVENC_HTIMINGSYNC1_SYNC_SREND) + +#define HW_TVENC_HTIMINGACTIVE (0x00000060) +#define HW_TVENC_HTIMINGACTIVE_SET (0x00000064) +#define HW_TVENC_HTIMINGACTIVE_CLR (0x00000068) +#define HW_TVENC_HTIMINGACTIVE_TOG (0x0000006c) + +#define BP_TVENC_HTIMINGACTIVE_RSRVD2 26 +#define BM_TVENC_HTIMINGACTIVE_RSRVD2 0xFC000000 +#define BF_TVENC_HTIMINGACTIVE_RSRVD2(v) \ + (((v) << 26) & BM_TVENC_HTIMINGACTIVE_RSRVD2) +#define BP_TVENC_HTIMINGACTIVE_ACTV_END 16 +#define BM_TVENC_HTIMINGACTIVE_ACTV_END 0x03FF0000 +#define BF_TVENC_HTIMINGACTIVE_ACTV_END(v) \ + (((v) << 16) & BM_TVENC_HTIMINGACTIVE_ACTV_END) +#define BP_TVENC_HTIMINGACTIVE_RSRVD1 10 +#define BM_TVENC_HTIMINGACTIVE_RSRVD1 0x0000FC00 +#define BF_TVENC_HTIMINGACTIVE_RSRVD1(v) \ + (((v) << 10) & BM_TVENC_HTIMINGACTIVE_RSRVD1) +#define BP_TVENC_HTIMINGACTIVE_ACTV_STRT 0 +#define BM_TVENC_HTIMINGACTIVE_ACTV_STRT 0x000003FF +#define BF_TVENC_HTIMINGACTIVE_ACTV_STRT(v) \ + (((v) << 0) & BM_TVENC_HTIMINGACTIVE_ACTV_STRT) + +#define HW_TVENC_HTIMINGBURST0 (0x00000070) +#define HW_TVENC_HTIMINGBURST0_SET (0x00000074) +#define HW_TVENC_HTIMINGBURST0_CLR (0x00000078) +#define HW_TVENC_HTIMINGBURST0_TOG (0x0000007c) + +#define BP_TVENC_HTIMINGBURST0_RSRVD2 26 +#define BM_TVENC_HTIMINGBURST0_RSRVD2 0xFC000000 +#define BF_TVENC_HTIMINGBURST0_RSRVD2(v) \ + (((v) << 26) & BM_TVENC_HTIMINGBURST0_RSRVD2) +#define BP_TVENC_HTIMINGBURST0_WBRST_STRT 16 +#define BM_TVENC_HTIMINGBURST0_WBRST_STRT 0x03FF0000 +#define BF_TVENC_HTIMINGBURST0_WBRST_STRT(v) \ + (((v) << 16) & BM_TVENC_HTIMINGBURST0_WBRST_STRT) +#define BP_TVENC_HTIMINGBURST0_RSRVD1 10 +#define BM_TVENC_HTIMINGBURST0_RSRVD1 0x0000FC00 +#define BF_TVENC_HTIMINGBURST0_RSRVD1(v) \ + (((v) << 10) & BM_TVENC_HTIMINGBURST0_RSRVD1) +#define BP_TVENC_HTIMINGBURST0_NBRST_STRT 0 +#define BM_TVENC_HTIMINGBURST0_NBRST_STRT 0x000003FF +#define BF_TVENC_HTIMINGBURST0_NBRST_STRT(v) \ + (((v) << 0) & BM_TVENC_HTIMINGBURST0_NBRST_STRT) + +#define HW_TVENC_HTIMINGBURST1 (0x00000080) +#define HW_TVENC_HTIMINGBURST1_SET (0x00000084) +#define HW_TVENC_HTIMINGBURST1_CLR (0x00000088) +#define HW_TVENC_HTIMINGBURST1_TOG (0x0000008c) + +#define BP_TVENC_HTIMINGBURST1_RSRVD1 10 +#define BM_TVENC_HTIMINGBURST1_RSRVD1 0xFFFFFC00 +#define BF_TVENC_HTIMINGBURST1_RSRVD1(v) \ + (((v) << 10) & BM_TVENC_HTIMINGBURST1_RSRVD1) +#define BP_TVENC_HTIMINGBURST1_BRST_END 0 +#define BM_TVENC_HTIMINGBURST1_BRST_END 0x000003FF +#define BF_TVENC_HTIMINGBURST1_BRST_END(v) \ + (((v) << 0) & BM_TVENC_HTIMINGBURST1_BRST_END) + +#define HW_TVENC_VTIMING0 (0x00000090) +#define HW_TVENC_VTIMING0_SET (0x00000094) +#define HW_TVENC_VTIMING0_CLR (0x00000098) +#define HW_TVENC_VTIMING0_TOG (0x0000009c) + +#define BP_TVENC_VTIMING0_RSRVD3 26 +#define BM_TVENC_VTIMING0_RSRVD3 0xFC000000 +#define BF_TVENC_VTIMING0_RSRVD3(v) \ + (((v) << 26) & BM_TVENC_VTIMING0_RSRVD3) +#define BP_TVENC_VTIMING0_VSTRT_PREEQ 16 +#define BM_TVENC_VTIMING0_VSTRT_PREEQ 0x03FF0000 +#define BF_TVENC_VTIMING0_VSTRT_PREEQ(v) \ + (((v) << 16) & BM_TVENC_VTIMING0_VSTRT_PREEQ) +#define BP_TVENC_VTIMING0_RSRVD2 14 +#define BM_TVENC_VTIMING0_RSRVD2 0x0000C000 +#define BF_TVENC_VTIMING0_RSRVD2(v) \ + (((v) << 14) & BM_TVENC_VTIMING0_RSRVD2) +#define BP_TVENC_VTIMING0_VSTRT_ACTV 8 +#define BM_TVENC_VTIMING0_VSTRT_ACTV 0x00003F00 +#define BF_TVENC_VTIMING0_VSTRT_ACTV(v) \ + (((v) << 8) & BM_TVENC_VTIMING0_VSTRT_ACTV) +#define BP_TVENC_VTIMING0_RSRVD1 6 +#define BM_TVENC_VTIMING0_RSRVD1 0x000000C0 +#define BF_TVENC_VTIMING0_RSRVD1(v) \ + (((v) << 6) & BM_TVENC_VTIMING0_RSRVD1) +#define BP_TVENC_VTIMING0_VSTRT_SUBPH 0 +#define BM_TVENC_VTIMING0_VSTRT_SUBPH 0x0000003F +#define BF_TVENC_VTIMING0_VSTRT_SUBPH(v) \ + (((v) << 0) & BM_TVENC_VTIMING0_VSTRT_SUBPH) + +#define HW_TVENC_VTIMING1 (0x000000a0) +#define HW_TVENC_VTIMING1_SET (0x000000a4) +#define HW_TVENC_VTIMING1_CLR (0x000000a8) +#define HW_TVENC_VTIMING1_TOG (0x000000ac) + +#define BP_TVENC_VTIMING1_RSRVD3 30 +#define BM_TVENC_VTIMING1_RSRVD3 0xC0000000 +#define BF_TVENC_VTIMING1_RSRVD3(v) \ + (((v) << 30) & BM_TVENC_VTIMING1_RSRVD3) +#define BP_TVENC_VTIMING1_VSTRT_POSTEQ 24 +#define BM_TVENC_VTIMING1_VSTRT_POSTEQ 0x3F000000 +#define BF_TVENC_VTIMING1_VSTRT_POSTEQ(v) \ + (((v) << 24) & BM_TVENC_VTIMING1_VSTRT_POSTEQ) +#define BP_TVENC_VTIMING1_RSRVD2 22 +#define BM_TVENC_VTIMING1_RSRVD2 0x00C00000 +#define BF_TVENC_VTIMING1_RSRVD2(v) \ + (((v) << 22) & BM_TVENC_VTIMING1_RSRVD2) +#define BP_TVENC_VTIMING1_VSTRT_SERRA 16 +#define BM_TVENC_VTIMING1_VSTRT_SERRA 0x003F0000 +#define BF_TVENC_VTIMING1_VSTRT_SERRA(v) \ + (((v) << 16) & BM_TVENC_VTIMING1_VSTRT_SERRA) +#define BP_TVENC_VTIMING1_RSRVD1 10 +#define BM_TVENC_VTIMING1_RSRVD1 0x0000FC00 +#define BF_TVENC_VTIMING1_RSRVD1(v) \ + (((v) << 10) & BM_TVENC_VTIMING1_RSRVD1) +#define BP_TVENC_VTIMING1_LAST_FLD_LN 0 +#define BM_TVENC_VTIMING1_LAST_FLD_LN 0x000003FF +#define BF_TVENC_VTIMING1_LAST_FLD_LN(v) \ + (((v) << 0) & BM_TVENC_VTIMING1_LAST_FLD_LN) + +#define HW_TVENC_MISC (0x000000b0) +#define HW_TVENC_MISC_SET (0x000000b4) +#define HW_TVENC_MISC_CLR (0x000000b8) +#define HW_TVENC_MISC_TOG (0x000000bc) + +#define BP_TVENC_MISC_RSRVD3 25 +#define BM_TVENC_MISC_RSRVD3 0xFE000000 +#define BF_TVENC_MISC_RSRVD3(v) \ + (((v) << 25) & BM_TVENC_MISC_RSRVD3) +#define BP_TVENC_MISC_LPF_RST_OFF 16 +#define BM_TVENC_MISC_LPF_RST_OFF 0x01FF0000 +#define BF_TVENC_MISC_LPF_RST_OFF(v) \ + (((v) << 16) & BM_TVENC_MISC_LPF_RST_OFF) +#define BP_TVENC_MISC_RSRVD2 12 +#define BM_TVENC_MISC_RSRVD2 0x0000F000 +#define BF_TVENC_MISC_RSRVD2(v) \ + (((v) << 12) & BM_TVENC_MISC_RSRVD2) +#define BM_TVENC_MISC_NTSC_LN_CNT 0x00000800 +#define BM_TVENC_MISC_PAL_FSC_PHASE_ALT 0x00000400 +#define BP_TVENC_MISC_FSC_PHASE_RST 8 +#define BM_TVENC_MISC_FSC_PHASE_RST 0x00000300 +#define BF_TVENC_MISC_FSC_PHASE_RST(v) \ + (((v) << 8) & BM_TVENC_MISC_FSC_PHASE_RST) +#define BP_TVENC_MISC_BRUCHB 6 +#define BM_TVENC_MISC_BRUCHB 0x000000C0 +#define BF_TVENC_MISC_BRUCHB(v) \ + (((v) << 6) & BM_TVENC_MISC_BRUCHB) +#define BP_TVENC_MISC_AGC_LVL_CTRL 4 +#define BM_TVENC_MISC_AGC_LVL_CTRL 0x00000030 +#define BF_TVENC_MISC_AGC_LVL_CTRL(v) \ + (((v) << 4) & BM_TVENC_MISC_AGC_LVL_CTRL) +#define BM_TVENC_MISC_RSRVD1 0x00000008 +#define BM_TVENC_MISC_CS_INVERT_CTRL 0x00000004 +#define BP_TVENC_MISC_Y_BLANK_CTRL 0 +#define BM_TVENC_MISC_Y_BLANK_CTRL 0x00000003 +#define BF_TVENC_MISC_Y_BLANK_CTRL(v) \ + (((v) << 0) & BM_TVENC_MISC_Y_BLANK_CTRL) + +#define HW_TVENC_COLORSUB0 (0x000000c0) +#define HW_TVENC_COLORSUB0_SET (0x000000c4) +#define HW_TVENC_COLORSUB0_CLR (0x000000c8) +#define HW_TVENC_COLORSUB0_TOG (0x000000cc) + +#define BP_TVENC_COLORSUB0_PHASE_INC 0 +#define BM_TVENC_COLORSUB0_PHASE_INC 0xFFFFFFFF +#define BF_TVENC_COLORSUB0_PHASE_INC(v) (v) + +#define HW_TVENC_COLORSUB1 (0x000000d0) +#define HW_TVENC_COLORSUB1_SET (0x000000d4) +#define HW_TVENC_COLORSUB1_CLR (0x000000d8) +#define HW_TVENC_COLORSUB1_TOG (0x000000dc) + +#define BP_TVENC_COLORSUB1_PHASE_OFFSET 0 +#define BM_TVENC_COLORSUB1_PHASE_OFFSET 0xFFFFFFFF +#define BF_TVENC_COLORSUB1_PHASE_OFFSET(v) (v) + +#define HW_TVENC_COPYPROTECT (0x000000e0) +#define HW_TVENC_COPYPROTECT_SET (0x000000e4) +#define HW_TVENC_COPYPROTECT_CLR (0x000000e8) +#define HW_TVENC_COPYPROTECT_TOG (0x000000ec) + +#define BP_TVENC_COPYPROTECT_RSRVD1 16 +#define BM_TVENC_COPYPROTECT_RSRVD1 0xFFFF0000 +#define BF_TVENC_COPYPROTECT_RSRVD1(v) \ + (((v) << 16) & BM_TVENC_COPYPROTECT_RSRVD1) +#define BM_TVENC_COPYPROTECT_WSS_ENBL 0x00008000 +#define BM_TVENC_COPYPROTECT_CGMS_ENBL 0x00004000 +#define BP_TVENC_COPYPROTECT_WSS_CGMS_DATA 0 +#define BM_TVENC_COPYPROTECT_WSS_CGMS_DATA 0x00003FFF +#define BF_TVENC_COPYPROTECT_WSS_CGMS_DATA(v) \ + (((v) << 0) & BM_TVENC_COPYPROTECT_WSS_CGMS_DATA) + +#define HW_TVENC_CLOSEDCAPTION (0x000000f0) +#define HW_TVENC_CLOSEDCAPTION_SET (0x000000f4) +#define HW_TVENC_CLOSEDCAPTION_CLR (0x000000f8) +#define HW_TVENC_CLOSEDCAPTION_TOG (0x000000fc) + +#define BP_TVENC_CLOSEDCAPTION_RSRVD1 20 +#define BM_TVENC_CLOSEDCAPTION_RSRVD1 0xFFF00000 +#define BF_TVENC_CLOSEDCAPTION_RSRVD1(v) \ + (((v) << 20) & BM_TVENC_CLOSEDCAPTION_RSRVD1) +#define BP_TVENC_CLOSEDCAPTION_CC_ENBL 18 +#define BM_TVENC_CLOSEDCAPTION_CC_ENBL 0x000C0000 +#define BF_TVENC_CLOSEDCAPTION_CC_ENBL(v) \ + (((v) << 18) & BM_TVENC_CLOSEDCAPTION_CC_ENBL) +#define BP_TVENC_CLOSEDCAPTION_CC_FILL 16 +#define BM_TVENC_CLOSEDCAPTION_CC_FILL 0x00030000 +#define BF_TVENC_CLOSEDCAPTION_CC_FILL(v) \ + (((v) << 16) & BM_TVENC_CLOSEDCAPTION_CC_FILL) +#define BP_TVENC_CLOSEDCAPTION_CC_DATA 0 +#define BM_TVENC_CLOSEDCAPTION_CC_DATA 0x0000FFFF +#define BF_TVENC_CLOSEDCAPTION_CC_DATA(v) \ + (((v) << 0) & BM_TVENC_CLOSEDCAPTION_CC_DATA) + +#define HW_TVENC_COLORBURST (0x00000140) +#define HW_TVENC_COLORBURST_SET (0x00000144) +#define HW_TVENC_COLORBURST_CLR (0x00000148) +#define HW_TVENC_COLORBURST_TOG (0x0000014c) + +#define BP_TVENC_COLORBURST_NBA 24 +#define BM_TVENC_COLORBURST_NBA 0xFF000000 +#define BF_TVENC_COLORBURST_NBA(v) \ + (((v) << 24) & BM_TVENC_COLORBURST_NBA) +#define BP_TVENC_COLORBURST_PBA 16 +#define BM_TVENC_COLORBURST_PBA 0x00FF0000 +#define BF_TVENC_COLORBURST_PBA(v) \ + (((v) << 16) & BM_TVENC_COLORBURST_PBA) +#define BP_TVENC_COLORBURST_RSRVD1 12 +#define BM_TVENC_COLORBURST_RSRVD1 0x0000F000 +#define BF_TVENC_COLORBURST_RSRVD1(v) \ + (((v) << 12) & BM_TVENC_COLORBURST_RSRVD1) +#define BP_TVENC_COLORBURST_RSRVD2 0 +#define BM_TVENC_COLORBURST_RSRVD2 0x00000FFF +#define BF_TVENC_COLORBURST_RSRVD2(v) \ + (((v) << 0) & BM_TVENC_COLORBURST_RSRVD2) + +#define HW_TVENC_MACROVISION0 (0x00000150) +#define HW_TVENC_MACROVISION0_SET (0x00000154) +#define HW_TVENC_MACROVISION0_CLR (0x00000158) +#define HW_TVENC_MACROVISION0_TOG (0x0000015c) + +#define BP_TVENC_MACROVISION0_DATA 0 +#define BM_TVENC_MACROVISION0_DATA 0xFFFFFFFF +#define BF_TVENC_MACROVISION0_DATA(v) (v) + +#define HW_TVENC_MACROVISION1 (0x00000160) +#define HW_TVENC_MACROVISION1_SET (0x00000164) +#define HW_TVENC_MACROVISION1_CLR (0x00000168) +#define HW_TVENC_MACROVISION1_TOG (0x0000016c) + +#define BP_TVENC_MACROVISION1_DATA 0 +#define BM_TVENC_MACROVISION1_DATA 0xFFFFFFFF +#define BF_TVENC_MACROVISION1_DATA(v) (v) + +#define HW_TVENC_MACROVISION2 (0x00000170) +#define HW_TVENC_MACROVISION2_SET (0x00000174) +#define HW_TVENC_MACROVISION2_CLR (0x00000178) +#define HW_TVENC_MACROVISION2_TOG (0x0000017c) + +#define BP_TVENC_MACROVISION2_DATA 0 +#define BM_TVENC_MACROVISION2_DATA 0xFFFFFFFF +#define BF_TVENC_MACROVISION2_DATA(v) (v) + +#define HW_TVENC_MACROVISION3 (0x00000180) +#define HW_TVENC_MACROVISION3_SET (0x00000184) +#define HW_TVENC_MACROVISION3_CLR (0x00000188) +#define HW_TVENC_MACROVISION3_TOG (0x0000018c) + +#define BP_TVENC_MACROVISION3_DATA 0 +#define BM_TVENC_MACROVISION3_DATA 0xFFFFFFFF +#define BF_TVENC_MACROVISION3_DATA(v) (v) + +#define HW_TVENC_MACROVISION4 (0x00000190) +#define HW_TVENC_MACROVISION4_SET (0x00000194) +#define HW_TVENC_MACROVISION4_CLR (0x00000198) +#define HW_TVENC_MACROVISION4_TOG (0x0000019c) + +#define BP_TVENC_MACROVISION4_RSRVD2 24 +#define BM_TVENC_MACROVISION4_RSRVD2 0xFF000000 +#define BF_TVENC_MACROVISION4_RSRVD2(v) \ + (((v) << 24) & BM_TVENC_MACROVISION4_RSRVD2) +#define BP_TVENC_MACROVISION4_MACV_TST 16 +#define BM_TVENC_MACROVISION4_MACV_TST 0x00FF0000 +#define BF_TVENC_MACROVISION4_MACV_TST(v) \ + (((v) << 16) & BM_TVENC_MACROVISION4_MACV_TST) +#define BP_TVENC_MACROVISION4_RSRVD1 11 +#define BM_TVENC_MACROVISION4_RSRVD1 0x0000F800 +#define BF_TVENC_MACROVISION4_RSRVD1(v) \ + (((v) << 11) & BM_TVENC_MACROVISION4_RSRVD1) +#define BP_TVENC_MACROVISION4_DATA 0 +#define BM_TVENC_MACROVISION4_DATA 0x000007FF +#define BF_TVENC_MACROVISION4_DATA(v) \ + (((v) << 0) & BM_TVENC_MACROVISION4_DATA) + +#define HW_TVENC_DACCTRL (0x000001a0) +#define HW_TVENC_DACCTRL_SET (0x000001a4) +#define HW_TVENC_DACCTRL_CLR (0x000001a8) +#define HW_TVENC_DACCTRL_TOG (0x000001ac) + +#define BM_TVENC_DACCTRL_TEST3 0x80000000 +#define BM_TVENC_DACCTRL_RSRVD1 0x40000000 +#define BM_TVENC_DACCTRL_RSRVD2 0x20000000 +#define BM_TVENC_DACCTRL_JACK1_DIS_DET_EN 0x10000000 +#define BM_TVENC_DACCTRL_TEST2 0x08000000 +#define BM_TVENC_DACCTRL_RSRVD3 0x04000000 +#define BM_TVENC_DACCTRL_RSRVD4 0x02000000 +#define BM_TVENC_DACCTRL_JACK1_DET_EN 0x01000000 +#define BM_TVENC_DACCTRL_TEST1 0x00800000 +#define BM_TVENC_DACCTRL_DISABLE_GND_DETECT 0x00400000 +#define BP_TVENC_DACCTRL_JACK_DIS_ADJ 20 +#define BM_TVENC_DACCTRL_JACK_DIS_ADJ 0x00300000 +#define BF_TVENC_DACCTRL_JACK_DIS_ADJ(v) \ + (((v) << 20) & BM_TVENC_DACCTRL_JACK_DIS_ADJ) +#define BM_TVENC_DACCTRL_GAINDN 0x00080000 +#define BM_TVENC_DACCTRL_GAINUP 0x00040000 +#define BM_TVENC_DACCTRL_INVERT_CLK 0x00020000 +#define BM_TVENC_DACCTRL_SELECT_CLK 0x00010000 +#define BM_TVENC_DACCTRL_BYPASS_ACT_CASCODE 0x00008000 +#define BM_TVENC_DACCTRL_RSRVD5 0x00004000 +#define BM_TVENC_DACCTRL_RSRVD6 0x00002000 +#define BM_TVENC_DACCTRL_PWRUP1 0x00001000 +#define BM_TVENC_DACCTRL_WELL_TOVDD 0x00000800 +#define BM_TVENC_DACCTRL_RSRVD7 0x00000400 +#define BM_TVENC_DACCTRL_RSRVD8 0x00000200 +#define BM_TVENC_DACCTRL_DUMP_TOVDD1 0x00000100 +#define BM_TVENC_DACCTRL_LOWER_SIGNAL 0x00000080 +#define BP_TVENC_DACCTRL_RVAL 4 +#define BM_TVENC_DACCTRL_RVAL 0x00000070 +#define BF_TVENC_DACCTRL_RVAL(v) \ + (((v) << 4) & BM_TVENC_DACCTRL_RVAL) +#define BM_TVENC_DACCTRL_NO_INTERNAL_TERM 0x00000008 +#define BM_TVENC_DACCTRL_HALF_CURRENT 0x00000004 +#define BP_TVENC_DACCTRL_CASC_ADJ 0 +#define BM_TVENC_DACCTRL_CASC_ADJ 0x00000003 +#define BF_TVENC_DACCTRL_CASC_ADJ(v) \ + (((v) << 0) & BM_TVENC_DACCTRL_CASC_ADJ) + +#define HW_TVENC_DACSTATUS (0x000001b0) +#define HW_TVENC_DACSTATUS_SET (0x000001b4) +#define HW_TVENC_DACSTATUS_CLR (0x000001b8) +#define HW_TVENC_DACSTATUS_TOG (0x000001bc) + +#define BP_TVENC_DACSTATUS_RSRVD1 13 +#define BM_TVENC_DACSTATUS_RSRVD1 0xFFFFE000 +#define BF_TVENC_DACSTATUS_RSRVD1(v) \ + (((v) << 13) & BM_TVENC_DACSTATUS_RSRVD1) +#define BM_TVENC_DACSTATUS_RSRVD2 0x00001000 +#define BM_TVENC_DACSTATUS_RSRVD3 0x00000800 +#define BM_TVENC_DACSTATUS_JACK1_DET_STATUS 0x00000400 +#define BM_TVENC_DACSTATUS_RSRVD4 0x00000200 +#define BM_TVENC_DACSTATUS_RSRVD5 0x00000100 +#define BM_TVENC_DACSTATUS_JACK1_GROUNDED 0x00000080 +#define BM_TVENC_DACSTATUS_RSRVD6 0x00000040 +#define BM_TVENC_DACSTATUS_RSRVD7 0x00000020 +#define BM_TVENC_DACSTATUS_JACK1_DIS_DET_IRQ 0x00000010 +#define BM_TVENC_DACSTATUS_RSRVD8 0x00000008 +#define BM_TVENC_DACSTATUS_RSRVD9 0x00000004 +#define BM_TVENC_DACSTATUS_JACK1_DET_IRQ 0x00000002 +#define BM_TVENC_DACSTATUS_ENIRQ_JACK 0x00000001 + +#define HW_TVENC_VDACTEST (0x000001c0) +#define HW_TVENC_VDACTEST_SET (0x000001c4) +#define HW_TVENC_VDACTEST_CLR (0x000001c8) +#define HW_TVENC_VDACTEST_TOG (0x000001cc) + +#define BP_TVENC_VDACTEST_RSRVD1 14 +#define BM_TVENC_VDACTEST_RSRVD1 0xFFFFC000 +#define BF_TVENC_VDACTEST_RSRVD1(v) \ + (((v) << 14) & BM_TVENC_VDACTEST_RSRVD1) +#define BM_TVENC_VDACTEST_ENABLE_PIX_INT_GAIN 0x00002000 +#define BM_TVENC_VDACTEST_BYPASS_PIX_INT 0x00001000 +#define BM_TVENC_VDACTEST_BYPASS_PIX_INT_DROOP 0x00000800 +#define BM_TVENC_VDACTEST_TEST_FIFO_FULL 0x00000400 +#define BP_TVENC_VDACTEST_DATA 0 +#define BM_TVENC_VDACTEST_DATA 0x000003FF +#define BF_TVENC_VDACTEST_DATA(v) \ + (((v) << 0) & BM_TVENC_VDACTEST_DATA) + +#define HW_TVENC_VERSION (0x000001d0) + +#define BP_TVENC_VERSION_MAJOR 24 +#define BM_TVENC_VERSION_MAJOR 0xFF000000 +#define BF_TVENC_VERSION_MAJOR(v) \ + (((v) << 24) & BM_TVENC_VERSION_MAJOR) +#define BP_TVENC_VERSION_MINOR 16 +#define BM_TVENC_VERSION_MINOR 0x00FF0000 +#define BF_TVENC_VERSION_MINOR(v) \ + (((v) << 16) & BM_TVENC_VERSION_MINOR) +#define BP_TVENC_VERSION_STEP 0 +#define BM_TVENC_VERSION_STEP 0x0000FFFF +#define BF_TVENC_VERSION_STEP(v) \ + (((v) << 0) & BM_TVENC_VERSION_STEP) +#endif /* __ARCH_ARM___TVENC_H */ diff --git a/drivers/video/mxs/tvenc.c b/drivers/video/mxs/tvenc.c new file mode 100644 index 000000000000..7aaa1fd013b0 --- /dev/null +++ b/drivers/video/mxs/tvenc.c @@ -0,0 +1,279 @@ +/* + * Freescale STMP378X dvi panel initialization + * + * Embedded Alley Solutions, Inc + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. + * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +/* #define DEBUG */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "regs-tvenc.h" + +enum { + TVENC_MODE_OFF = 0, + TVENC_MODE_NTSC, + TVENC_MODE_PAL, +}; + +#define REGS_TVENC_BASE (IO_ADDRESS(TVENC_PHYS_ADDR)) + +/* NTSC 720x480 mode */ +#define NTSC_X_RES 720 +#define NTSC_Y_RES 480 +#define NTSC_H_BLANKING 262 +#define NTSC_V_LINES 525 + +/* PAL 720x576 mode */ +#define PAL_X_RES 720 +#define PAL_Y_RES 576 +#define PAL_H_BLANKING 274 +#define PAL_V_LINES 625 + +/* frame size */ +#define DVI_H_BLANKING(m) (m == TVENC_MODE_NTSC ? \ + NTSC_H_BLANKING : PAL_H_BLANKING) +#define DVI_V_LINES(m) (m == TVENC_MODE_NTSC ? \ + NTSC_V_LINES : PAL_V_LINES) +#define DVI_H_ACTIVE(m) (m == TVENC_MODE_NTSC ? NTSC_X_RES : PAL_X_RES) +#define DVI_V_ACTIVE(m) (m == TVENC_MODE_NTSC ? NTSC_Y_RES : PAL_Y_RES) +/* fileds range */ +#define DVI_F1_START(m) 1 +#define DVI_F1_END(m) (DVI_V_LINES(m) / 2) +#define DVI_F2_START(m) (DVI_F1_END(m) + 1) +#define DVI_F2_END(m) DVI_V_LINES(m) +/* blanking range */ +#define DVI_V1_BLANK_START(m) DVI_F1_END(m) +#define DVI_V1_BLANK_END(m) (DVI_V1_BLANK_START(m) + \ + (DVI_V_LINES(m) - DVI_V_ACTIVE(m)) / 2) +#define DVI_V2_BLANK_START(m) DVI_F2_END(m) +#define DVI_V2_BLANK_END(m) ((DVI_V2_BLANK_START(m) + \ + (DVI_V_LINES(m) - DVI_V_ACTIVE(m)) / 2 - 1) % \ + DVI_V_LINES(m)) + +static struct clk *lcd_clk; +static struct clk *clk_tv108M_ng; +static struct clk *clk_tv27M; + +static int tvenc_mode; + +static void init_tvenc_hw(int mode) +{ + /* Reset module */ + __raw_writel(BM_TVENC_CTRL_SFTRST, REGS_TVENC_BASE + HW_TVENC_CTRL_SET); + udelay(10); + + /* Take module out of reset */ + __raw_writel(BM_TVENC_CTRL_SFTRST | BM_TVENC_CTRL_CLKGATE, + REGS_TVENC_BASE + HW_TVENC_CTRL_CLR); + + if (mode == TVENC_MODE_NTSC) { + /* Config NTSC-M mode, 8-bit Y/C in, SYNC out */ + __raw_writel(BM_TVENC_CONFIG_SYNC_MODE | + BM_TVENC_CONFIG_PAL_SHAPE | + BM_TVENC_CONFIG_YGAIN_SEL | + BM_TVENC_CONFIG_CGAIN, + REGS_TVENC_BASE + HW_TVENC_CONFIG_CLR); + __raw_writel(BM_TVENC_CONFIG_FSYNC_PHS | + BF_TVENC_CONFIG_SYNC_MODE(0x4), + REGS_TVENC_BASE + HW_TVENC_CONFIG_SET); + + /* 859 pixels/line for NTSC */ + __raw_writel(857, REGS_TVENC_BASE + HW_TVENC_SYNCOFFSET); + + __raw_writel(0x21F07C1F, REGS_TVENC_BASE + HW_TVENC_COLORSUB0); + __raw_writel(BM_TVENC_COLORBURST_NBA | + BM_TVENC_COLORBURST_PBA, + REGS_TVENC_BASE + HW_TVENC_COLORBURST_CLR); + __raw_writel(BF_TVENC_COLORBURST_NBA(0xc8) | + BF_TVENC_COLORBURST_PBA(0x0), + REGS_TVENC_BASE + HW_TVENC_COLORBURST_SET); + } else if (mode == TVENC_MODE_PAL) { + /* Config PAL-B mode, 8-bit Y/C in, SYNC out */ + __raw_writel(BM_TVENC_CONFIG_SYNC_MODE | + BM_TVENC_CONFIG_ENCD_MODE | + BM_TVENC_CONFIG_YGAIN_SEL | + BM_TVENC_CONFIG_CGAIN | + BM_TVENC_CONFIG_FSYNC_PHS, + REGS_TVENC_BASE + HW_TVENC_CONFIG_CLR); + __raw_writel(BM_TVENC_CONFIG_PAL_SHAPE | + BF_TVENC_CONFIG_YGAIN_SEL(0x1) + | BF_TVENC_CONFIG_CGAIN(0x1) + | BF_TVENC_CONFIG_ENCD_MODE(0x1) + | BF_TVENC_CONFIG_SYNC_MODE(0x4), + REGS_TVENC_BASE + HW_TVENC_CONFIG_SET); + + /* 863 pixels/line for PAL */ + __raw_writel(863, REGS_TVENC_BASE + HW_TVENC_SYNCOFFSET); + + __raw_writel(0x2A098ACB, REGS_TVENC_BASE + HW_TVENC_COLORSUB0); + __raw_writel(BM_TVENC_COLORBURST_NBA | + BM_TVENC_COLORBURST_PBA, + REGS_TVENC_BASE + HW_TVENC_COLORBURST_CLR); + __raw_writel(BF_TVENC_COLORBURST_NBA(0xd6) | + BF_TVENC_COLORBURST_PBA(0x2a), + REGS_TVENC_BASE + HW_TVENC_COLORBURST_SET); + } + + /* Power up DAC */ + __raw_writel(BM_TVENC_DACCTRL_GAINDN | + BM_TVENC_DACCTRL_GAINUP | + BM_TVENC_DACCTRL_PWRUP1 | + BM_TVENC_DACCTRL_DUMP_TOVDD1 | + BF_TVENC_DACCTRL_RVAL(0x3), + REGS_TVENC_BASE + HW_TVENC_DACCTRL); + + /* set all to zero is a requirement for NTSC */ + __raw_writel(0, REGS_TVENC_BASE + HW_TVENC_MACROVISION0); + __raw_writel(0, REGS_TVENC_BASE + HW_TVENC_MACROVISION1); + __raw_writel(0, REGS_TVENC_BASE + HW_TVENC_MACROVISION2); + __raw_writel(0, REGS_TVENC_BASE + HW_TVENC_MACROVISION3); + __raw_writel(0, REGS_TVENC_BASE + HW_TVENC_MACROVISION4); +} + +static int init_panel(struct device *dev, dma_addr_t phys, int memsize, + struct mxs_platform_fb_entry *pentry) +{ + int ret = 0; + + lcd_clk = clk_get(dev, "lcdif"); + clk_enable(lcd_clk); + clk_set_rate(lcd_clk, 1000000000 / pentry->cycle_time_ns);/* kHz */ + + clk_tv108M_ng = clk_get(NULL, "tv108M_ng"); + clk_tv27M = clk_get(NULL, "tv27M"); + clk_enable(clk_tv108M_ng); + clk_enable(clk_tv27M); + + tvenc_mode = pentry->x_res == NTSC_Y_RES ? TVENC_MODE_NTSC : + TVENC_MODE_PAL; + + init_tvenc_hw(tvenc_mode); + + setup_dvi_panel(DVI_H_ACTIVE(tvenc_mode), DVI_V_ACTIVE(tvenc_mode), + DVI_H_BLANKING(tvenc_mode), DVI_V_LINES(tvenc_mode), + DVI_V1_BLANK_START(tvenc_mode), + DVI_V1_BLANK_END(tvenc_mode), + DVI_V2_BLANK_START(tvenc_mode), + DVI_V2_BLANK_END(tvenc_mode), + DVI_F1_START(tvenc_mode), DVI_F1_END(tvenc_mode), + DVI_F2_START(tvenc_mode), DVI_F2_END(tvenc_mode)); + + ret = mxs_lcdif_dma_init(dev, phys, memsize); + mxs_lcdif_notify_clients(MXS_LCDIF_PANEL_INIT, pentry); + + return ret; +} + +static void release_panel(struct device *dev, + struct mxs_platform_fb_entry *pentry) +{ + mxs_lcdif_notify_clients(MXS_LCDIF_PANEL_RELEASE, pentry); + release_dvi_panel(); + + mxs_lcdif_dma_release(); + + clk_disable(clk_tv108M_ng); + clk_disable(clk_tv27M); + clk_disable(lcd_clk); + clk_put(clk_tv108M_ng); + clk_put(clk_tv27M); + clk_put(lcd_clk); +} + +static int blank_panel(int blank) +{ + int ret = 0, count; + + switch (blank) { + case FB_BLANK_NORMAL: + case FB_BLANK_VSYNC_SUSPEND: + case FB_BLANK_HSYNC_SUSPEND: + case FB_BLANK_POWERDOWN: + __raw_writel(BM_LCDIF_CTRL_BYPASS_COUNT, + REGS_LCDIF_BASE + HW_LCDIF_CTRL_CLR); + + /* Wait until current transfer is complete, max 30ms */ + for (count = 30000; count > 0; count--) { + if (__raw_readl(REGS_LCDIF_BASE + HW_LCDIF_STAT) & + BM_LCDIF_STAT_TXFIFO_EMPTY) + break; + udelay(1); + } + break; + + case FB_BLANK_UNBLANK: + __raw_writel(BM_LCDIF_CTRL_BYPASS_COUNT, + REGS_LCDIF_BASE + HW_LCDIF_CTRL_SET); + break; + + default: + ret = -EINVAL; + } + + return ret; +} + +static struct mxs_platform_fb_entry ntsc_fb_entry = { + .name = "tvenc_ntsc", + /* x/y swapped */ + .x_res = NTSC_Y_RES, + .y_res = NTSC_X_RES, + .bpp = 32, + /* the pix_clk should be near 27Mhz for proper syncronization */ + .cycle_time_ns = 37, + .lcd_type = MXS_LCD_PANEL_DVI, + .init_panel = init_panel, + .release_panel = release_panel, + .blank_panel = blank_panel, + .run_panel = mxs_lcdif_run, + .pan_display = mxs_lcdif_pan_display, +}; + +static struct mxs_platform_fb_entry pal_fb_entry = { + .name = "tvenc_pal", + /* x/y swapped */ + .x_res = PAL_Y_RES, + .y_res = PAL_X_RES, + .bpp = 32, + /* the pix_clk should be near 27Mhz for proper syncronization */ + .cycle_time_ns = 37, + .lcd_type = MXS_LCD_PANEL_DVI, + .init_panel = init_panel, + .release_panel = release_panel, + .blank_panel = blank_panel, + .run_panel = mxs_lcdif_run, + .pan_display = mxs_lcdif_pan_display, +}; + +static int __init register_devices(void) +{ + struct platform_device *pdev; + pdev = mxs_get_device("mxs-fb", 0); + if (pdev == NULL || IS_ERR(pdev)) + return -ENODEV; + + mxs_lcd_register_entry(&ntsc_fb_entry, pdev->dev.platform_data); + mxs_lcd_register_entry(&pal_fb_entry, pdev->dev.platform_data); + return 0; +} + +subsys_initcall(register_devices); diff --git a/drivers/w1/masters/mxc_w1.c b/drivers/w1/masters/mxc_w1.c index d90e905e40e0..adc643827007 100644 --- a/drivers/w1/masters/mxc_w1.c +++ b/drivers/w1/masters/mxc_w1.c @@ -1,5 +1,5 @@ /* - * Copyright 2005-2008 Freescale Semiconductor, Inc. All Rights Reserved. + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. * Copyright 2008 Luotao Fu, kernel@pengutronix.de * * This program is free software; you can redistribute it and/or @@ -24,7 +24,7 @@ #include #include #include -#include +#include #include "../w1.h" #include "../w1_int.h" diff --git a/drivers/w1/slaves/Kconfig b/drivers/w1/slaves/Kconfig index 1f51366417b9..ad77126801f5 100644 --- a/drivers/w1/slaves/Kconfig +++ b/drivers/w1/slaves/Kconfig @@ -22,12 +22,34 @@ config W1_SLAVE_DS2431 Say Y here if you want to use a 1-wire 1kb EEPROM family device (DS2431) +config W1_SLAVE_DS2751 + tristate "Battery Level sensing support (DS2751)" + depends on W1 + help + Say Y here if you want to use a 1-wire + battery level sensing device (DS2751). + +config W1_SLAVE_DS2751_CRC + bool "Protect DS2751 data with a CRC16" + depends on W1_SLAVE_DS2751 + select CRC16 + help + Say Y here to protect DS2751 data with a CRC16. + Each block has 30 bytes of data and a two byte CRC16. + Full block writes are only allowed if the CRC is valid. + config W1_SLAVE_DS2433 tristate "4kb EEPROM family support (DS2433)" help Say Y here if you want to use a 1-wire 4kb EEPROM family device (DS2433). +config W1_SLAVE_DS2438 + tristate "Smart Battery Monitor (DS2438)" + help + Say Y here if you want to use a 1-wire + Smart Battery Monitor family device (DS2438). + config W1_SLAVE_DS2433_CRC bool "Protect DS2433 data with a CRC16" depends on W1_SLAVE_DS2433 diff --git a/drivers/w1/slaves/Makefile b/drivers/w1/slaves/Makefile index f1f51f19b129..fd53f53d8681 100644 --- a/drivers/w1/slaves/Makefile +++ b/drivers/w1/slaves/Makefile @@ -8,3 +8,5 @@ obj-$(CONFIG_W1_SLAVE_DS2431) += w1_ds2431.o obj-$(CONFIG_W1_SLAVE_DS2433) += w1_ds2433.o obj-$(CONFIG_W1_SLAVE_DS2760) += w1_ds2760.o obj-$(CONFIG_W1_SLAVE_BQ27000) += w1_bq27000.o +obj-$(CONFIG_W1_SLAVE_DS2751) += w1_ds2751.o +obj-$(CONFIG_W1_SLAVE_DS2438) += w1_ds2438.o diff --git a/drivers/w1/slaves/w1_ds2438.c b/drivers/w1/slaves/w1_ds2438.c new file mode 100644 index 000000000000..251ca0e7f914 --- /dev/null +++ b/drivers/w1/slaves/w1_ds2438.c @@ -0,0 +1,585 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../w1.h" +#include "../w1_int.h" +#include "../w1_family.h" +#include "w1_ds2438.h" + +struct ds2438_device_info { + /* DS2438 data, valid after calling ds2438_battery_read_status() */ + unsigned long update_time; /* jiffies when data read */ + char raw[DS2438_PAGE_SIZE]; /* raw DS2438 data */ + int voltage_uV; + int current_uA; + int accum_current_uAh; + int temp_C; + int charge_status; + u8 init:1; + u8 setup:1; + u8 calibrate:1; + u8 input_src:1; + u8 ee_flg:1; + u8 resv_bit:3; + u8 threshold:8; + u16 resv_bytes; + u32 senser; + + struct power_supply bat; + struct device *w1_dev; + struct ds2438_ops ops; + struct workqueue_struct *monitor_wqueue; + struct delayed_work monitor_work; +}; + +#define DS2438_SENSER 25 +#define to_ds2438_device_info(x) container_of((x), struct ds2438_device_info, \ + bat); + + +static enum power_supply_property ds2438_battery_props[] = { + POWER_SUPPLY_PROP_STATUS, + POWER_SUPPLY_PROP_VOLTAGE_NOW, + POWER_SUPPLY_PROP_CURRENT_NOW, + POWER_SUPPLY_PROP_TEMP, + POWER_SUPPLY_PROP_CHARGE_NOW, +}; + +static char ds2438_sensers_title[] = "DS2438 senserin thousands of resister:"; +static unsigned int cache_time = 1000; +module_param(cache_time, uint, 0644); +MODULE_PARM_DESC(cache_time, "cache time in milliseconds"); + +static ssize_t ds2438_show_input(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct power_supply *psy = dev_get_drvdata(dev); + struct ds2438_device_info *di = to_ds2438_device_info(psy); + + return sprintf(buf, "%s\n", di->input_src ? "1:VDD" : "0:VAD"); +} + +static ssize_t ds2438_show_senser(struct device *dev, + struct device_attribute *attr, char *buf) +{ + int len; + struct power_supply *psy = dev_get_drvdata(dev); + struct ds2438_device_info *di = to_ds2438_device_info(psy); + + len = sprintf(buf, "%s\n", ds2438_sensers_title); + len += sprintf(buf + len, "%d\n", di->senser); + return len; +} + +static ssize_t ds2438_show_ee(struct device *dev, struct device_attribute *attr, + char *buf) +{ + struct power_supply *psy = dev_get_drvdata(dev); + struct ds2438_device_info *di = to_ds2438_device_info(psy); + + return sprintf(buf, "%d\n", di->ee_flg); +} + +static ssize_t ds2438_show_threshold(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct power_supply *psy = dev_get_drvdata(dev); + struct ds2438_device_info *di = to_ds2438_device_info(psy); + + return sprintf(buf, "%d\n", di->threshold); +} + +static ssize_t ds2438_set_input(struct device *dev, + struct device_attribute *attr, const char *buf, + size_t count) +{ + struct power_supply *psy = dev_get_drvdata(dev); + struct ds2438_device_info *di = to_ds2438_device_info(psy); + di->input_src = !!simple_strtoul(buf, NULL, 0); + return count; +} + +static ssize_t ds2438_set_senser(struct device *dev, + struct device_attribute *attr, const char *buf, + size_t count) +{ + u32 resister; + struct power_supply *psy = dev_get_drvdata(dev); + struct ds2438_device_info *di = to_ds2438_device_info(psy); + resister = simple_strtoul(buf, NULL, 0); + if (resister) + di->senser = resister; + return count; +} + +static ssize_t ds2438_set_ee(struct device *dev, struct device_attribute *attr, + const char *buf, size_t count) +{ + struct power_supply *psy = dev_get_drvdata(dev); + struct ds2438_device_info *di = to_ds2438_device_info(psy); + + di->ee_flg = !!simple_strtoul(buf, NULL, 0); + di->setup = 1; + return count; +} + +static ssize_t ds2438_set_threshold(struct device *dev, + struct device_attribute *attr, + const char *buf, size_t count) +{ + int threshold; + struct power_supply *psy = dev_get_drvdata(dev); + struct ds2438_device_info *di = to_ds2438_device_info(psy); + + threshold = simple_strtoul(buf, NULL, 0); + if (threshold < 256) { + di->threshold = threshold; + di->setup = 1; + return count; + } + return -EINVAL; +} + +static ssize_t ds2438_set_calibrate(struct device *dev, + struct device_attribute *attr, + const char *buf, size_t count) +{ + struct power_supply *psy = dev_get_drvdata(dev); + struct ds2438_device_info *di = to_ds2438_device_info(psy); + + di->calibrate = !!simple_strtoul(buf, NULL, 0); + return count; +} + +static struct device_attribute ds2438_dev_attr[] = { + __ATTR(input_src, 0664, ds2438_show_input, ds2438_set_input), + __ATTR(senser, 0664, ds2438_show_senser, ds2438_set_senser), + __ATTR(ee_flg, 0664, ds2438_show_ee, ds2438_set_ee), + __ATTR(threshold, 0664, ds2438_show_threshold, ds2438_set_threshold), + __ATTR(calibrate, 0220, NULL, ds2438_set_calibrate), +}; + +static void ds2438_setup(struct ds2438_device_info *di) +{ + di->ops.load_sram(di->w1_dev, PAGE0_CONTROL); + di->ops.read_page(di->w1_dev, PAGE0_CONTROL, di->raw); + if (di->init && di->setup) { + if (di->ee_flg) + di->raw[PAGE0_STAT_CTRL] |= DS2438_CTRL_EE; + else + di->raw[PAGE0_STAT_CTRL] &= ~DS2438_CTRL_EE; + if (di->input_src) + di->raw[PAGE0_STAT_CTRL] |= DS2438_CTRL_AD; + else + di->raw[PAGE0_STAT_CTRL] &= ~DS2438_CTRL_AD; + di->raw[PAGE0_THRESHOLD] = di->threshold; + } else { + di->ee_flg = !!(di->raw[PAGE0_STAT_CTRL] & DS2438_CTRL_EE); + di->input_src = !!(di->raw[PAGE0_STAT_CTRL] & DS2438_CTRL_AD); + di->threshold = di->raw[PAGE0_THRESHOLD]; + di->raw[PAGE0_STAT_CTRL] |= DS2438_CTRL_IAD | DS2438_CTRL_CA; + } + di->ops.write_page(di->w1_dev, PAGE0_CONTROL, di->raw); + di->ops.drain_sram(di->w1_dev, PAGE0_CONTROL); + if (!di->init) { + di->calibrate = 1; + di->init = 1; + } + di->setup = 0; +} + +static void ds2438_calibrate(struct ds2438_device_info *di) +{ + int current_raw; + /* disable ICA */ + di->ops.load_sram(di->w1_dev, PAGE0_CONTROL); + di->ops.read_page(di->w1_dev, PAGE0_CONTROL, di->raw); + di->raw[PAGE0_STAT_CTRL] &= ~DS2438_CTRL_IAD; + di->ops.write_page(di->w1_dev, PAGE0_CONTROL, di->raw); + di->ops.drain_sram(di->w1_dev, PAGE0_CONTROL); + + /* Zero offset */ + di->ops.load_sram(di->w1_dev, PAGE1_ETM); + di->ops.read_page(di->w1_dev, PAGE1_ETM, di->raw); + ds2438_writew(di->raw + PAGE1_OFFSET_LSB, 0); + di->ops.drain_sram(di->w1_dev, PAGE1_ETM_BYTE0); + + /* enable ICA & read current */ + di->ops.load_sram(di->w1_dev, PAGE0_CONTROL); + di->ops.read_page(di->w1_dev, PAGE0_CONTROL, di->raw); + di->raw[PAGE0_STAT_CTRL] |= DS2438_CTRL_IAD; + di->ops.write_page(di->w1_dev, PAGE0_CONTROL, di->raw); + di->ops.drain_sram(di->w1_dev, PAGE0_CONTROL); + /*wait current convert about 36HZ */ + mdelay(30); + /* disable ICA */ + di->ops.load_sram(di->w1_dev, PAGE0_CONTROL); + di->ops.read_page(di->w1_dev, PAGE0_CONTROL, di->raw); + di->raw[PAGE0_STAT_CTRL] &= ~DS2438_CTRL_IAD; + di->ops.write_page(di->w1_dev, PAGE0_CONTROL, di->raw); + di->ops.drain_sram(di->w1_dev, PAGE0_CONTROL); + /* read current value */ + current_raw = ds2438_readw(di->raw + PAGE0_CURRENT_LSB); + /* write offset by current value */ + di->ops.load_sram(di->w1_dev, PAGE1_ETM); + di->ops.read_page(di->w1_dev, PAGE1_ETM, di->raw); + ds2438_writew(di->raw + PAGE1_OFFSET_LSB, current_raw << 8); + di->ops.write_page(di->w1_dev, PAGE1_ETM, di->raw); + di->ops.drain_sram(di->w1_dev, PAGE1_ETM); + + /*enable ICA again */ + di->ops.load_sram(di->w1_dev, PAGE0_CONTROL); + di->ops.read_page(di->w1_dev, PAGE0_CONTROL, di->raw); + di->raw[PAGE0_STAT_CTRL] |= DS2438_CTRL_IAD; + di->ops.write_page(di->w1_dev, PAGE0_CONTROL, di->raw); + di->ops.drain_sram(di->w1_dev, PAGE0_CONTROL); + di->calibrate = 0; +} + +/* + * power supply temperture is in tenths of degree. + */ +static inline int ds2438_get_temp(u16 raw) +{ + int degree, s; + s = !!(raw & 0x8000); + + if (s) + raw = ((~raw & 0x7FFF) + 1); + degree = ((raw >> 8) * 10) + (((raw & 0xFF) * 5) + 63) / 128; + return s ? -degree : degree; +} + +/* + * power supply current is in uA. + */ +static inline int ds2438_get_current(u32 senser, u16 raw) +{ + int s, current_uA; + s = !!(raw & 0xFC00); + /* (x * 1000 * 1000)uA / (4096 * (Rsens / 1000)) */ + raw &= 0x3FF; + current_uA = raw * 125 * 125 * 125; + current_uA /= (senser << 3); + return s ? -current_uA : current_uA; +} + +/* + * power supply current is in uAh. + */ +static inline int ds2438_get_ica(u32 senser, u8 raw) +{ + int charge_uAh; + /* (x * 1000 * 1000)uA / (2048 * (Rsens / 1000)) */ + charge_uAh = (raw * 125 * 125 * 125) >> 4; + charge_uAh /= (senser << 4); + return charge_uAh; +} + +static int ds2438_battery_update_page1(struct ds2438_device_info *di) +{ + int ica_raw; + di->ops.load_sram(di->w1_dev, PAGE1_ETM); + di->ops.read_page(di->w1_dev, PAGE1_ETM, di->raw); + ica_raw = di->raw[PAGE1_ICA]; + di->accum_current_uAh = ds2438_get_ica(di->senser, ica_raw); + return 0; +} + +static int ds2438_battery_read_status(struct ds2438_device_info *di) +{ + u8 status; + int temp_raw, voltage_raw, current_raw; + + if (!(di->init) || di->setup) + ds2438_setup(di); + + if (di->calibrate) + ds2438_calibrate(di); + + if (di->update_time && time_before(jiffies, di->update_time + + msecs_to_jiffies(cache_time))) + return 0; + + di->ops.load_sram(di->w1_dev, PAGE0_CONTROL); + di->ops.read_page(di->w1_dev, PAGE0_CONTROL, di->raw); + status = di->raw[PAGE0_STAT_CTRL]; + temp_raw = ds2438_readw(di->raw + PAGE0_TEMP_LSB); + voltage_raw = ds2438_readw(di->raw + PAGE0_VOLTAGE_LSB); + current_raw = ds2438_readw(di->raw + PAGE0_CURRENT_LSB); + di->temp_C = ds2438_get_temp(temp_raw); + di->voltage_uV = voltage_raw * 10000; + di->current_uA = ds2438_get_current(di->senser, current_raw); + + ds2438_battery_update_page1(di); + + if (!(status & DS2438_STAT_TB)) + di->ops.command(di->w1_dev, DS2438_CONVERT_TEMP, 0); + if (!(status & DS2438_STAT_ADB)) + di->ops.command(di->w1_dev, DS2438_CONVERT_VOLT, 0); + di->update_time = jiffies; + return 0; +} + +static void ds2438_battery_update_status(struct ds2438_device_info *di) +{ + int old_charge_status = di->charge_status; + + ds2438_battery_read_status(di); + + if (di->charge_status != old_charge_status) + power_supply_changed(&di->bat); +} + +static void ds2438_battery_work(struct work_struct *work) +{ + struct ds2438_device_info *di = container_of(work, + struct ds2438_device_info, + monitor_work.work); + const int interval = HZ * 60; + + dev_dbg(di->w1_dev, "%s\n", __func__); + + ds2438_battery_update_status(di); + queue_delayed_work(di->monitor_wqueue, &di->monitor_work, interval); +} + +static void ds2438_battery_external_power_changed(struct power_supply *psy) +{ + struct ds2438_device_info *di = to_ds2438_device_info(psy); + + dev_dbg(di->w1_dev, "%s\n", __func__); + + cancel_delayed_work(&di->monitor_work); + queue_delayed_work(di->monitor_wqueue, &di->monitor_work, HZ / 10); +} + +static int ds2438_battery_get_property(struct power_supply *psy, + enum power_supply_property psp, + union power_supply_propval *val) +{ + struct ds2438_device_info *di = to_ds2438_device_info(psy); + + switch (psp) { + case POWER_SUPPLY_PROP_STATUS: + val->intval = di->charge_status; + return 0; + default: + break; + } + + ds2438_battery_read_status(di); + + switch (psp) { + case POWER_SUPPLY_PROP_VOLTAGE_NOW: + val->intval = di->voltage_uV; + break; + case POWER_SUPPLY_PROP_CURRENT_NOW: + val->intval = di->current_uA; + break; + case POWER_SUPPLY_PROP_TEMP: + val->intval = di->temp_C; + break; + case POWER_SUPPLY_PROP_CHARGE_NOW: + val->intval = di->accum_current_uAh; + break; + default: + return -EINVAL; + } + + return 0; +} + +/* W1 slave DS2438 famliy operations */ +static int ds2438_read_page(struct device *dev, u8 page, u8 *buf) +{ + struct w1_slave *slave = container_of(dev, struct w1_slave, dev); + if ((page >= DS2438_PAGE_NUM) || (buf == NULL)) + return -EINVAL; + + mutex_lock(&slave->master->mutex); + if (!w1_reset_select_slave(slave)) { + w1_write_8(slave->master, W1_READ_SCRATCHPAD); + w1_write_8(slave->master, page); + w1_read_block(slave->master, buf, DS2438_PAGE_SIZE); + } + mutex_unlock(&slave->master->mutex); + return 0; +} + +static int ds2438_write_page(struct device *dev, u8 page, u8 *buf) +{ + struct w1_slave *slave = container_of(dev, struct w1_slave, dev); + if ((page >= DS2438_PAGE_NUM) || (buf == NULL)) + return -EINVAL; + + mutex_lock(&slave->master->mutex); + if (!w1_reset_select_slave(slave)) { + w1_write_8(slave->master, DS2438_WRITE_SCRATCHPAD); + w1_write_8(slave->master, page); + w1_write_block(slave->master, buf, DS2438_PAGE_SIZE); + } + mutex_unlock(&slave->master->mutex); + return 0; +} + +static int ds2438_command(struct device *dev, u8 command, u8 data) +{ + struct w1_slave *slave = container_of(dev, struct w1_slave, dev); + + mutex_lock(&slave->master->mutex); + if (!w1_reset_select_slave(slave)) { + w1_write_8(slave->master, command); + switch (command) { + case DS2438_COPY_SCRATCHPAD: + case DS2438_RECALL_MEMORY: + w1_write_8(slave->master, data); + } + } + mutex_unlock(&slave->master->mutex); + return 0; +} + +static int ds2438_drain_sram(struct device *dev, u8 page) +{ + return ds2438_command(dev, DS2438_COPY_SCRATCHPAD, page); +} + +static int ds2438_load_sram(struct device *dev, u8 page) +{ + return ds2438_command(dev, DS2438_RECALL_MEMORY, page); +} + +static inline void ds2438_defaut_ops(struct ds2438_ops *ops) +{ + ops->read_page = ds2438_read_page; + ops->write_page = ds2438_write_page; + ops->drain_sram = ds2438_drain_sram; + ops->load_sram = ds2438_load_sram; + ops->command = ds2438_command; +} + +static int ds2438_add_slave(struct w1_slave *slave) +{ + int i, retval = 0; + struct ds2438_device_info *di; + + di = kzalloc(sizeof(*di), GFP_KERNEL); + if (!di) { + retval = -ENOMEM; + goto di_alloc_failed; + } + + di->w1_dev = &slave->dev; + di->bat.name = dev_name(&slave->dev); + di->bat.type = POWER_SUPPLY_TYPE_BATTERY; + di->bat.properties = ds2438_battery_props; + di->bat.num_properties = ARRAY_SIZE(ds2438_battery_props); + di->bat.get_property = ds2438_battery_get_property; + di->bat.external_power_changed = ds2438_battery_external_power_changed; + ds2438_defaut_ops(&di->ops); + di->senser = DS2438_SENSER; + di->charge_status = POWER_SUPPLY_STATUS_UNKNOWN; + + retval = power_supply_register(&slave->dev, &di->bat); + if (retval) { + dev_err(&slave->dev, "failed to register battery\n"); + goto batt_failed; + } + + for (i = 0; i < ARRAY_SIZE(ds2438_dev_attr); i++) { + if (device_create_file(di->bat.dev, ds2438_dev_attr + i)) { + printk(KERN_ERR "Customize attribute file fail!\n"); + break; + } + } + + if (i != ARRAY_SIZE(ds2438_dev_attr)) { + for (; i >= 0; i++) + device_remove_file(di->bat.dev, ds2438_dev_attr + i); + goto workqueue_failed; + } + INIT_DELAYED_WORK(&di->monitor_work, ds2438_battery_work); + di->monitor_wqueue = create_singlethread_workqueue(dev_name(&slave->dev)); + if (!di->monitor_wqueue) { + retval = -ESRCH; + goto workqueue_failed; + } + dev_set_drvdata(&slave->dev, di); + queue_delayed_work(di->monitor_wqueue, &di->monitor_work, HZ / 2); + + goto success; + + workqueue_failed: + power_supply_unregister(&di->bat); + batt_failed: + kfree(di); + di_alloc_failed: + success: + return retval; +} + +static void ds2438_remove_slave(struct w1_slave *slave) +{ + struct ds2438_device_info *di = dev_get_drvdata(&slave->dev); + + cancel_rearming_delayed_workqueue(di->monitor_wqueue, + &di->monitor_work); + destroy_workqueue(di->monitor_wqueue); + power_supply_unregister(&di->bat); +} + +static struct w1_family_ops w1_ds2438_fops = { + .add_slave = ds2438_add_slave, + .remove_slave = ds2438_remove_slave, +}; + +static struct w1_family w1_family_ds2438 = { + .fid = W1_FAMILY_DS2438, + .fops = &w1_ds2438_fops, +}; + +static int __init w1_ds2438_init(void) +{ + pr_info("1-wire driver for the DS2438 smart battery monitor\n"); + return w1_register_family(&w1_family_ds2438); +} + +static void __exit w1_ds2438_fini(void) +{ + w1_unregister_family(&w1_family_ds2438); +} + +module_init(w1_ds2438_init); +module_exit(w1_ds2438_fini); + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Freescale Semiconductors Inc"); +MODULE_DESCRIPTION("1-wire DS2438 family, smart battery monitor."); diff --git a/drivers/w1/slaves/w1_ds2438.h b/drivers/w1/slaves/w1_ds2438.h new file mode 100644 index 000000000000..40d48f25cc10 --- /dev/null +++ b/drivers/w1/slaves/w1_ds2438.h @@ -0,0 +1,119 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#ifndef __W1_DS2438_H__ +#define __W1_DS2438_H__ + +#include + +#include +#include +#include +#include +#include + +#define DS2438_DEV_NAME "ds2438-battery" + +#define DS2438_PAGE_SIZE 8 +#define DS2438_PAGE_NUM 8 + +#define DS2438_CONVERT_TEMP 0x44 +#define DS2438_CONVERT_VOLT 0xB4 +#define DS2438_WRITE_SCRATCHPAD 0x4E +#define DS2438_COPY_SCRATCHPAD 0x48 +#define DS2438_RECALL_MEMORY 0xB8 + +enum DS2438_PAGE { + PAGE0_CONTROL = 0, + PAGE1_ETM, + PAGE2_STAMP, + PAGE3_RESV3, + PAGE4_RESV4, + PAGE5_RESV5, + PAGE6_RESV6, + PAGE7_CCA, +}; + +enum DS2438_REG { + /* PAGE 0 */ + PAGE0_STAT_CTRL = 0, + PAGE0_TEMP_LSB = 1, + PAGE0_TEMP_MSB = 2, + PAGE0_VOLTAGE_LSB = 3, + PAGE0_VOLTAGE_MSB = 4, + PAGE0_CURRENT_LSB = 5, + PAGE0_CURRENT_MSB = 6, + PAGE0_THRESHOLD = 7, + + /* PAGE 1 */ + PAGE1_ETM_BYTE0 = 0, + PAGE1_ETM_BYTE1 = 1, + PAGE1_ETM_BYTE2 = 2, + PAGE1_ETM_BYTE3 = 3, + PAGE1_ICA = 4, + PAGE1_OFFSET_LSB = 5, + PAGE1_OFFSET_MSB = 6, + + /* PAGE 2 */ + PAGE2_DISCONNECT_BYTE0 = 0, + PAGE2_DISCONNECT_BYTE1 = 1, + PAGE2_DISCONNECT_BYTE2 = 2, + PAGE2_DISCONNECT_BYTE3 = 3, + PAGE2_END_CHARGE_BYTE0 = 4, + PAGE2_END_CHARGE_BYTE1 = 5, + PAGE2_END_CHARGE_BYTE2 = 6, + PAGE2_END_CHARGE_BYTE3 = 7, + + /* PAGE 3 */ + /* PAGE 4 */ + /* PAGE 5 */ + /* PAGE 6 */ + /* PAGE 7 */ + PAGE7_CCA_LSB = 4, + PAGE7_CCA_MSB = 5, + PAGE7_DCA_LSB = 6, + PAGE7_DCA_MSB = 7, +}; + +#define DS2438_CTRL_IAD (1 << 0) +#define DS2438_CTRL_CA (1 << 1) +#define DS2438_CTRL_EE (1 << 2) +#define DS2438_CTRL_AD (1 << 3) +#define DS2438_STAT_TB (1 << 4) +#define DS2438_STAT_NVB (1 << 5) +#define DS2438_STAT_ADB (1 << 6) + +struct ds2438_ops { + int (*read_page) (struct device *, u8, u8 *); + int (*read_byte) (struct device *, u8, u8, u8 *); + int (*read_halfword) (struct device *, u8, u8, u16 *); + int (*read_word) (struct device *, u8, u8, u32 *); + int (*write_page) (struct device *, u8, u8 *); + int (*write_byte) (struct device *, u8, u8, u8); + int (*write_halfword) (struct device *, u8, u8, u16); + int (*write_word) (struct device *, u8, u8, u32); + int (*drain_sram) (struct device *, u8); + int (*load_sram) (struct device *, u8); + int (*command) (struct device *, u8, u8); +}; + +static inline u16 ds2438_readw(u8 *raw) +{ + return ((*(raw + 1)) << 8) | (*raw); +} + +static inline void ds2438_writew(u8 *raw, u16 data) +{ + *raw++ = data & 0xFF; + *raw = (data >> 8) & 0xFF; +} +#endif /* __W1_DS2438_H__ */ diff --git a/drivers/w1/slaves/w1_ds2751.c b/drivers/w1/slaves/w1_ds2751.c new file mode 100644 index 000000000000..9e5bf6faa4cb --- /dev/null +++ b/drivers/w1/slaves/w1_ds2751.c @@ -0,0 +1,320 @@ +/* + * Copyright 2005-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +/* + * Implementation based on w1_ds2433.c + */ + +#include +#include +#include +#include +#include +#include +#include +#ifdef CONFIG_W1_F51_CRC +#include + +#define CRC16_INIT 0 +#define CRC16_VALID 0xb001 + +#endif + +#include "../w1.h" +#include "../w1_int.h" +#include "../w1_family.h" + +#define W1_EEPROM_SIZE 32 +#define W1_PAGE_SIZE 32 +#define W1_PAGE_BITS 5 +#define W1_PAGE_MASK 0x1F + +#define W1_F51_TIME 300 + +#define W1_F51_READ_EEPROM 0xB8 +#define W1_F51_WRITE_SCRATCH 0x6C +#define W1_F51_READ_SCRATCH 0x69 +#define W1_F51_COPY_SCRATCH 0x48 +#define W1_STATUS_OFFSET 0x0001 +#define W1_EEPROM_OFFSET 0x0007 +#define W1_SPECIAL_OFFSET 0x0008 +#define W1_EEPROM_BLOCK_0 0x0020 +#define W1_EEPROM_BLOCK_1 0x0030 +#define W1_SRAM 0x0080 +struct w1_f51_data { + u8 memory[W1_EEPROM_SIZE]; + u32 validcrc; +}; + +/** + * Check the file size bounds and adjusts count as needed. + * This would not be needed if the file size didn't reset to 0 after a write. + */ +static inline size_t w1_f51_fix_count(loff_t off, size_t count, size_t size) +{ + if (off > size) + return 0; + + if ((off + count) > size) + return size - off; + + return count; +} + +#ifdef CONFIG_W1_F51_CRC +static int w1_f51_refresh_block(struct w1_slave *sl, struct w1_f51_data *data, + int block) +{ + u8 wrbuf[3]; + int off = block * W1_PAGE_SIZE; + if (data->validcrc & (1 << block)) + return 0; + + if (w1_reset_select_slave(sl)) { + data->validcrc = 0; + return -EIO; + } + wrbuf[0] = W1_F51_READ_EEPROM; + wrbuf[1] = off & 0xff; + wrbuf[2] = off >> 8; + w1_write_block(sl->master, wrbuf, 3); + w1_read_block(sl->master, &data->memory[off], W1_PAGE_SIZE); + + /* cache the block if the CRC is valid */ + if (crc16(CRC16_INIT, &data->memory[off], W1_PAGE_SIZE) == CRC16_VALID) + data->validcrc |= (1 << block); + + return 0; +} +#endif /* CONFIG_W1_F51_CRC */ + +static ssize_t w1_f51_read_bin(struct kobject *kobj, char *buf, loff_t off, + size_t count) +{ + struct w1_slave *sl = kobj_to_w1_slave(kobj); +#ifdef CONFIG_W1_F51_CRC + struct w1_f51_data *data = sl->family_data; + int i, min_page, max_page; +#else + u8 wrbuf[3]; +#endif + + count = w1_f51_fix_count(off, count, W1_EEPROM_SIZE) + if (count == 0) + return 0; + + mutex_lock(&sl->master->mutex); +#ifdef CONFIG_W1_F51_CRC + min_page = (off >> W1_PAGE_BITS); + max_page = (off + count - 1) >> W1_PAGE_BITS; + for (i = min_page; i <= max_page; i++) { + if (w1_f51_refresh_block(sl, data, i)) { + count = -EIO; + goto out_up; + } + } + memcpy(buf, &data->memory[off], count); + +#else /* CONFIG_W1_F51_CRC */ + + /* read directly from the EEPROM */ + if (w1_reset_select_slave(sl)) { + count = -EIO; + goto out_up; + } + off = (loff_t) W1_EEPROM_BLOCK_0; + wrbuf[0] = W1_F51_READ_EEPROM; + wrbuf[1] = off & 0xff; + wrbuf[2] = off >> 8; + w1_write_block(sl->master, wrbuf, 3); + if (w1_reset_select_slave(sl)) { + count = -EIO; + goto out_up; + } + + wrbuf[0] = W1_F51_READ_SCRATCH; + wrbuf[1] = off & 0xff; + wrbuf[2] = off >> 8; + w1_write_block(sl->master, wrbuf, 3); + w1_read_block(sl->master, buf, count); + +#endif /* CONFIG_W1_F51_CRC */ + + out_up: + mutex_unlock(&sl->master->mutex); + return count; +} + +/** + * Writes to the scratchpad and reads it back for verification. + * Then copies the scratchpad to EEPROM. + * The data must be on one page. + * The master must be locked. + * + * @param sl The slave structure + * @param addr Address for the write + * @param len length must be <= (W1_PAGE_SIZE - (addr & W1_PAGE_MASK)) + * @param data The data to write + * @return 0=Success -1=failure + */ +static int w1_f51_write(struct w1_slave *sl, int addr, int len, const u8 * data) +{ + u8 wrbuf[4]; + u8 rdbuf[W1_EEPROM_SIZE + 3]; + u8 es = (addr + len - 1) & 0x1f; + /* Write the data to the scratchpad */ + if (w1_reset_select_slave(sl)) + return -1; + wrbuf[0] = W1_F51_WRITE_SCRATCH; + wrbuf[1] = addr & 0xff; + wrbuf[2] = addr >> 8; + + w1_write_block(sl->master, wrbuf, 3); + w1_write_block(sl->master, data, len); + /* Read the scratchpad and verify */ + if (w1_reset_select_slave(sl)) + return -1; + wrbuf[0] = W1_F51_READ_SCRATCH; + w1_write_block(sl->master, wrbuf, 3); + w1_read_block(sl->master, rdbuf, len + 3); + /* Compare what was read against the data written */ + if (memcmp(data, &rdbuf[0], len) != 0) { + printk("Error reading the scratch Pad\n"); + return -1; + } + /* Copy the scratchpad to EEPROM */ + if (w1_reset_select_slave(sl)) + return -1; + wrbuf[0] = W1_F51_COPY_SCRATCH; + wrbuf[3] = es; + w1_write_block(sl->master, wrbuf, 4); + /* Sleep for 5 ms to wait for the write to complete */ + msleep(5); + + /* Reset the bus to wake up the EEPROM (this may not be needed) */ + w1_reset_bus(sl->master); + + return 0; +} + +static ssize_t w1_f51_write_bin(struct kobject *kobj, char *buf, loff_t off, + size_t count) +{ + struct w1_slave *sl = kobj_to_w1_slave(kobj); + int addr; + + count = w1_f51_fix_count(off, count, W1_EEPROM_SIZE); + if (count == 0) + return 0; + off = (loff_t) 0x0020; +#ifdef CONFIG_W1_F51_CRC + /* can only write full blocks in cached mode */ + if ((off & W1_PAGE_MASK) || (count & W1_PAGE_MASK)) { + dev_err(&sl->dev, "invalid offset/count off=%d cnt=%zd\n", + (int)off, count); + return -EINVAL; + } + + /* make sure the block CRCs are valid */ + for (idx = 0; idx < count; idx += W1_PAGE_SIZE) { + if (crc16(CRC16_INIT, &buf[idx], W1_PAGE_SIZE) != CRC16_VALID) { + dev_err(&sl->dev, "bad CRC at offset %d\n", (int)off); + return -EINVAL; + } + } +#endif /* CONFIG_W1_F51_CRC */ + + mutex_lock(&sl->master->mutex); + + /* Can only write data to one page at a time */ + addr = off; + if (w1_f51_write(sl, addr, count, buf) < 0) { + count = -EIO; + goto out_up; + } + + out_up: + mutex_unlock(&sl->master->mutex); + + return count; +} + +static struct bin_attribute w1_f51_bin_attr = { + .attr = { + .name = "eeprom", + .mode = S_IRUGO | S_IWUSR, + .owner = THIS_MODULE, + }, + .size = W1_EEPROM_SIZE, + .read = w1_f51_read_bin, + .write = w1_f51_write_bin, +}; + +static int w1_f51_add_slave(struct w1_slave *sl) +{ + int err; +#ifdef CONFIG_W1_F51_CRC + struct w1_f51_data *data; + data = kmalloc(sizeof(struct w1_f51_data), GFP_KERNEL); + if (!data) + return -ENOMEM; + memset(data, 0, sizeof(struct w1_f51_data)); + sl->family_data = data; + +#endif /* CONFIG_W1_F51_CRC */ + + err = sysfs_create_bin_file(&sl->dev.kobj, &w1_f51_bin_attr); + +#ifdef CONFIG_W1_F51_CRC + if (err) + kfree(data); +#endif /* CONFIG_W1_F51_CRC */ + + return err; +} + +static void w1_f51_remove_slave(struct w1_slave *sl) +{ +#ifdef CONFIG_W1_F51_CRC + kfree(sl->family_data); + sl->family_data = NULL; +#endif /* CONFIG_W1_F51_CRC */ + sysfs_remove_bin_file(&sl->dev.kobj, &w1_f51_bin_attr); +} + +static struct w1_family_ops w1_f51_fops = { + .add_slave = w1_f51_add_slave, + .remove_slave = w1_f51_remove_slave, +}; + +static struct w1_family w1_family_51 = { + .fid = W1_EEPROM_DS2751, + .fops = &w1_f51_fops, +}; + +static int __init w1_f51_init(void) +{ + return w1_register_family(&w1_family_51); +} + +static void __exit w1_f51_fini(void) +{ + w1_unregister_family(&w1_family_51); +} + +module_init(w1_f51_init); +module_exit(w1_f51_fini); + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Freescale Semiconductors Inc"); +MODULE_DESCRIPTION + ("w1 family 51 driver for DS2751, Battery Level Sensing Device"); diff --git a/drivers/w1/w1_family.h b/drivers/w1/w1_family.h index 3ca1b9298f21..c541f9215765 100644 --- a/drivers/w1/w1_family.h +++ b/drivers/w1/w1_family.h @@ -32,8 +32,10 @@ #define W1_THERM_DS18S20 0x10 #define W1_THERM_DS1822 0x22 #define W1_EEPROM_DS2433 0x23 +#define W1_EEPROM_DS2751 0x51 #define W1_THERM_DS18B20 0x28 #define W1_EEPROM_DS2431 0x2D +#define W1_FAMILY_DS2438 0x26 #define W1_FAMILY_DS2760 0x30 #define MAXNAMELEN 32 diff --git a/drivers/watchdog/Kconfig b/drivers/watchdog/Kconfig index afcfacc9bbe2..ffa00c2698d1 100644 --- a/drivers/watchdog/Kconfig +++ b/drivers/watchdog/Kconfig @@ -216,6 +216,27 @@ config PNX4008_WATCHDOG Say N if you are unsure. +config MXC_WATCHDOG + tristate "MXC watchdog" + depends on WATCHDOG && WATCHDOG_NOWAYOUT + depends on ARCH_MXC + help + Watchdog timer embedded into MXC chips. This will + reboot your system when timeout is reached. + + NOTE: once enabled, this timer cannot be disabled. + To compile this driver as a module, choose M here: the + module will be called mxc_wdt. + +config MXS_WATCHDOG + tristate "Freescale mxs watchdog" + depends on ARCH_MXS + help + Say Y here if to include support for the watchdog timer + for the Freescale mxs family SoC. + To compile this driver as a module, choose M here: the + module will be called mxs_wdt. + config IOP_WATCHDOG tristate "IOP Watchdog" depends on PLAT_IOP diff --git a/drivers/watchdog/Makefile b/drivers/watchdog/Makefile index 72f3e2073f8e..702b297e2cb7 100644 --- a/drivers/watchdog/Makefile +++ b/drivers/watchdog/Makefile @@ -38,6 +38,8 @@ obj-$(CONFIG_S3C2410_WATCHDOG) += s3c2410_wdt.o obj-$(CONFIG_SA1100_WATCHDOG) += sa1100_wdt.o obj-$(CONFIG_MPCORE_WATCHDOG) += mpcore_wdt.o obj-$(CONFIG_EP93XX_WATCHDOG) += ep93xx_wdt.o +obj-$(CONFIG_MXC_WATCHDOG) += mxc_wdt.o +obj-$(CONFIG_MXS_WATCHDOG) += mxs-wdt.o obj-$(CONFIG_PNX4008_WATCHDOG) += pnx4008_wdt.o obj-$(CONFIG_IOP_WATCHDOG) += iop_wdt.o obj-$(CONFIG_DAVINCI_WATCHDOG) += davinci_wdt.o diff --git a/drivers/watchdog/mxc_wdt.c b/drivers/watchdog/mxc_wdt.c new file mode 100644 index 000000000000..eab9cecb9464 --- /dev/null +++ b/drivers/watchdog/mxc_wdt.c @@ -0,0 +1,376 @@ +/* + * linux/drivers/char/watchdog/mxc_wdt.c + * + * Watchdog driver for FSL MXC. It is based on omap1610_wdt.c + * + * Copyright (C) 2004-2010 Freescale Semiconductor, Inc. + * 2005 (c) MontaVista Software, Inc. + + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * History: + * + * 20051207: + * Full rewrite based on + * linux-2.6.15-rc5/drivers/char/watchdog/omap_wdt.c + * Add platform resource support + * + */ + +/*! + * @defgroup WDOG Watchdog Timer (WDOG) Driver + */ +/*! + * @file mxc_wdt.c + * + * @brief Watchdog timer driver + * + * @ingroup WDOG + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "mxc_wdt.h" + +#define DVR_VER "2.0" + +#define WDOG_SEC_TO_COUNT(s) ((s * 2) << 8) +#define WDOG_COUNT_TO_SEC(c) ((c >> 8) / 2) + +static void __iomem *wdt_base_reg; +static int mxc_wdt_users; +static struct clk *mxc_wdt_clk; + +static unsigned timer_margin = TIMER_MARGIN_DEFAULT; +module_param(timer_margin, uint, 0); +MODULE_PARM_DESC(timer_margin, "initial watchdog timeout (in seconds)"); + +static unsigned dev_num; + +static void mxc_wdt_ping(void *base) +{ + /* issue the service sequence instructions */ + __raw_writew(WDT_MAGIC_1, base + MXC_WDT_WSR); + __raw_writew(WDT_MAGIC_2, base + MXC_WDT_WSR); +} + +static void mxc_wdt_config(void *base) +{ + u16 val; + + val = __raw_readw(base + MXC_WDT_WCR); + val |= 0xFF00 | WCR_WOE_BIT | WCR_WDA_BIT | WCR_SRS_BIT; + /* enable suspend WDT */ + val |= WCR_WDZST_BIT | WCR_WDBG_BIT; + /* generate reset if wdog times out */ + val &= ~WCR_WRE_BIT; + + __raw_writew(val, base + MXC_WDT_WCR); +} + +static void mxc_wdt_enable(void *base) +{ + u16 val; + + val = __raw_readw(base + MXC_WDT_WCR); + val |= WCR_WDE_BIT; + __raw_writew(val, base + MXC_WDT_WCR); +} + +static void mxc_wdt_disable(void *base) +{ + /* disable not supported by this chip */ +} + +static void mxc_wdt_adjust_timeout(unsigned new_timeout) +{ + if (new_timeout < TIMER_MARGIN_MIN) + new_timeout = TIMER_MARGIN_DEFAULT; + if (new_timeout > TIMER_MARGIN_MAX) + new_timeout = TIMER_MARGIN_MAX; + timer_margin = new_timeout; +} + +static u16 mxc_wdt_get_timeout(void *base) +{ + u16 val; + + val = __raw_readw(base + MXC_WDT_WCR); + return WDOG_COUNT_TO_SEC(val); +} + +static u16 mxc_wdt_get_bootreason(void *base) +{ + u16 val; + + val = __raw_readw(base + MXC_WDT_WRSR); + return val; +} + +static void mxc_wdt_set_timeout(void *base) +{ + u16 val; + val = __raw_readw(base + MXC_WDT_WCR); + val = (val & 0x00FF) | WDOG_SEC_TO_COUNT(timer_margin); + __raw_writew(val, base + MXC_WDT_WCR); + val = __raw_readw(base + MXC_WDT_WCR); + timer_margin = WDOG_COUNT_TO_SEC(val); +} + +/* + * Allow only one task to hold it open + */ + +static int mxc_wdt_open(struct inode *inode, struct file *file) +{ + + if (test_and_set_bit(1, (unsigned long *)&mxc_wdt_users)) + return -EBUSY; + + mxc_wdt_config(wdt_base_reg); + mxc_wdt_set_timeout(wdt_base_reg); + mxc_wdt_enable(wdt_base_reg); + mxc_wdt_ping(wdt_base_reg); + + return 0; +} + +static int mxc_wdt_release(struct inode *inode, struct file *file) +{ + /* + * Shut off the timer unless NOWAYOUT is defined. + */ +#ifndef CONFIG_WATCHDOG_NOWAYOUT + mxc_wdt_disable(wdt_base_reg); + +#else + printk(KERN_CRIT "mxc_wdt: Unexpected close, not stopping!\n"); +#endif + mxc_wdt_users = 0; + return 0; +} + +static ssize_t +mxc_wdt_write(struct file *file, const char __user *data, + size_t len, loff_t *ppos) +{ + /* Refresh LOAD_TIME. */ + if (len) + mxc_wdt_ping(wdt_base_reg); + return len; +} + +static int +mxc_wdt_ioctl(struct inode *inode, struct file *file, + unsigned int cmd, unsigned long arg) +{ + int new_margin; + int bootr; + + static struct watchdog_info ident = { + .identity = "MXC Watchdog", + .options = WDIOF_SETTIMEOUT, + .firmware_version = 0, + }; + + switch (cmd) { + default: + return -ENOIOCTLCMD; + case WDIOC_GETSUPPORT: + return copy_to_user((struct watchdog_info __user *)arg, &ident, + sizeof(ident)); + case WDIOC_GETSTATUS: + return put_user(0, (int __user *)arg); + case WDIOC_GETBOOTSTATUS: + bootr = mxc_wdt_get_bootreason(wdt_base_reg); + return put_user(bootr, (int __user *)arg); + case WDIOC_KEEPALIVE: + mxc_wdt_ping(wdt_base_reg); + return 0; + case WDIOC_SETTIMEOUT: + if (get_user(new_margin, (int __user *)arg)) + return -EFAULT; + + mxc_wdt_adjust_timeout(new_margin); + mxc_wdt_disable(wdt_base_reg); + mxc_wdt_set_timeout(wdt_base_reg); + mxc_wdt_enable(wdt_base_reg); + mxc_wdt_ping(wdt_base_reg); + return 0; + + case WDIOC_GETTIMEOUT: + mxc_wdt_ping(wdt_base_reg); + new_margin = mxc_wdt_get_timeout(wdt_base_reg); + return put_user(new_margin, (int __user *)arg); + } +} + +static struct file_operations mxc_wdt_fops = { + .owner = THIS_MODULE, + .write = mxc_wdt_write, + .ioctl = mxc_wdt_ioctl, + .open = mxc_wdt_open, + .release = mxc_wdt_release, +}; + +static struct miscdevice mxc_wdt_miscdev = { + .minor = WATCHDOG_MINOR, + .name = "watchdog", + .fops = &mxc_wdt_fops +}; + +static int __init mxc_wdt_probe(struct platform_device *pdev) +{ + struct resource *res, *mem; + int ret; + + /* reserve static register mappings */ + res = platform_get_resource(pdev, IORESOURCE_MEM, dev_num); + if (!res) + return -ENOENT; + + mem = request_mem_region(res->start, res->end - res->start + 1, + pdev->name); + if (mem == NULL) + return -EBUSY; + + platform_set_drvdata(pdev, mem); + + wdt_base_reg = ioremap(res->start, res->end - res->start + 1); + mxc_wdt_disable(wdt_base_reg); + mxc_wdt_adjust_timeout(timer_margin); + + mxc_wdt_users = 0; + + mxc_wdt_miscdev.this_device = &pdev->dev; + + mxc_wdt_clk = clk_get(NULL, "wdog_clk"); + clk_enable(mxc_wdt_clk); + + ret = misc_register(&mxc_wdt_miscdev); + if (ret) + goto fail; + + pr_info("MXC Watchdog # %d Timer: initial timeout %d sec\n", dev_num, + timer_margin); + + return 0; + + fail: + iounmap(wdt_base_reg); + release_resource(mem); + pr_info("MXC Watchdog Probe failed\n"); + return ret; +} + +static void mxc_wdt_shutdown(struct platform_device *pdev) +{ + mxc_wdt_disable(wdt_base_reg); + pr_info("MXC Watchdog # %d shutdown\n", dev_num); +} + +static int __exit mxc_wdt_remove(struct platform_device *pdev) +{ + struct resource *mem = platform_get_drvdata(pdev); + misc_deregister(&mxc_wdt_miscdev); + iounmap(wdt_base_reg); + release_resource(mem); + pr_info("MXC Watchdog # %d removed\n", dev_num); + return 0; +} + +#ifdef CONFIG_PM + +/* REVISIT ... not clear this is the best way to handle system suspend; and + * it's very inappropriate for selective device suspend (e.g. suspending this + * through sysfs rather than by stopping the watchdog daemon). Also, this + * may not play well enough with NOWAYOUT... + */ + +static int mxc_wdt_suspend(struct platform_device *pdev, pm_message_t state) +{ + if (mxc_wdt_users) { + mxc_wdt_disable(wdt_base_reg); + } + return 0; +} + +static int mxc_wdt_resume(struct platform_device *pdev) +{ + if (mxc_wdt_users) { + mxc_wdt_enable(wdt_base_reg); + mxc_wdt_ping(wdt_base_reg); + } + return 0; +} + +#else +#define mxc_wdt_suspend NULL +#define mxc_wdt_resume NULL +#endif + +static struct platform_driver mxc_wdt_driver = { + .driver = { + .owner = THIS_MODULE, + .name = "mxc_wdt", + }, + .probe = mxc_wdt_probe, + .shutdown = mxc_wdt_shutdown, + .remove = __exit_p(mxc_wdt_remove), + .suspend = mxc_wdt_suspend, + .resume = mxc_wdt_resume, +}; + +static int __init mxc_wdt_init(void) +{ + pr_info("MXC WatchDog Driver %s\n", DVR_VER); + + if ((timer_margin < TIMER_MARGIN_MIN) || + (timer_margin > TIMER_MARGIN_MAX)) { + pr_info("MXC watchdog error. wrong timer_margin %d\n", + timer_margin); + pr_info(" Range: %d to %d seconds\n", TIMER_MARGIN_MIN, + TIMER_MARGIN_MAX); + return -EINVAL; + } + + return platform_driver_register(&mxc_wdt_driver); +} + +static void __exit mxc_wdt_exit(void) +{ + platform_driver_unregister(&mxc_wdt_driver); + pr_info("MXC WatchDog Driver removed\n"); +} + +module_init(mxc_wdt_init); +module_exit(mxc_wdt_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); +MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR); diff --git a/drivers/watchdog/mxc_wdt.h b/drivers/watchdog/mxc_wdt.h new file mode 100644 index 000000000000..061731b46b61 --- /dev/null +++ b/drivers/watchdog/mxc_wdt.h @@ -0,0 +1,37 @@ +/* + * linux/drivers/char/watchdog/mxc_wdt.h + * + * BRIEF MODULE DESCRIPTION + * MXC Watchdog timer register definitions + * + * Author: MontaVista Software, Inc. + * or + * + * 2005 (c) MontaVista Software, Inc. + * Copyright 2007-2010 Freescale Semiconductor, Inc. + * This file is licensed under the terms of the GNU General Public License + * version 2. This program is licensed "as is" without any warranty of any + * kind, whether express or implied. + */ + +#ifndef __MXC_WDT_H__ +#define __MXC_WDT_H__ + +#define MXC_WDT_WCR 0x00 +#define MXC_WDT_WSR 0x02 +#define MXC_WDT_WRSR 0x04 +#define WCR_WOE_BIT (1 << 6) +#define WCR_WDA_BIT (1 << 5) +#define WCR_SRS_BIT (1 << 4) +#define WCR_WRE_BIT (1 << 3) +#define WCR_WDE_BIT (1 << 2) +#define WCR_WDBG_BIT (1 << 1) +#define WCR_WDZST_BIT (1 << 0) +#define WDT_MAGIC_1 0x5555 +#define WDT_MAGIC_2 0xAAAA + +#define TIMER_MARGIN_MAX 127 +#define TIMER_MARGIN_DEFAULT 60 /* 60 secs */ +#define TIMER_MARGIN_MIN 1 + +#endif /* __MXC_WDT_H__ */ diff --git a/drivers/watchdog/mxs-wdt.c b/drivers/watchdog/mxs-wdt.c new file mode 100644 index 000000000000..7f3615b833f6 --- /dev/null +++ b/drivers/watchdog/mxs-wdt.c @@ -0,0 +1,303 @@ +/* + * Watchdog driver for Freescale STMP37XX/STMP378X + * + * Author: Vitaly Wool + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. + * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#define DEFAULT_HEARTBEAT 19 +#define MAX_HEARTBEAT (0x10000000 >> 6) + +/* missing bitmask in headers */ +#define BV_RTC_PERSISTENT1_GENERAL__RTC_FORCE_UPDATER 0x80000000 + +#define WDT_IN_USE 0 +#define WDT_OK_TO_CLOSE 1 + +#define WDOG_COUNTER_RATE 1000 /* 1 kHz clock */ + +static unsigned long wdt_status; +static int heartbeat = DEFAULT_HEARTBEAT; +static unsigned long boot_status; +static unsigned long wdt_base; +static DEFINE_SPINLOCK(mxs_wdt_io_lock); + +static void wdt_enable(u32 value) +{ + spin_lock(&mxs_wdt_io_lock); + __raw_writel(value, wdt_base + HW_RTC_WATCHDOG); + __raw_writel(BV_RTC_PERSISTENT1_GENERAL__RTC_FORCE_UPDATER, + wdt_base + HW_RTC_PERSISTENT1_SET); + __raw_writel(BM_RTC_CTRL_WATCHDOGEN, wdt_base + HW_RTC_CTRL_SET); + spin_unlock(&mxs_wdt_io_lock); +} + +static void wdt_disable(void) +{ + spin_lock(&mxs_wdt_io_lock); + __raw_writel(BV_RTC_PERSISTENT1_GENERAL__RTC_FORCE_UPDATER, + wdt_base + HW_RTC_PERSISTENT1_CLR); + __raw_writel(BM_RTC_CTRL_WATCHDOGEN, wdt_base + HW_RTC_CTRL_CLR); + spin_unlock(&mxs_wdt_io_lock); +} + +static void wdt_ping(void) +{ + wdt_enable(heartbeat * WDOG_COUNTER_RATE); +} + +static int mxs_wdt_open(struct inode *inode, struct file *file) +{ + if (test_and_set_bit(WDT_IN_USE, &wdt_status)) + return -EBUSY; + + clear_bit(WDT_OK_TO_CLOSE, &wdt_status); + wdt_ping(); + + return nonseekable_open(inode, file); +} + +static ssize_t mxs_wdt_write(struct file *file, const char __user *data, + size_t len, loff_t *ppos) +{ + if (len) { + if (WATCHDOG_NOWAYOUT == 0) { + size_t i; + + clear_bit(WDT_OK_TO_CLOSE, &wdt_status); + + for (i = 0; i != len; i++) { + char c; + + if (get_user(c, data + i)) + return -EFAULT; + if (c == 'V') + set_bit(WDT_OK_TO_CLOSE, &wdt_status); + } + } + wdt_ping(); + } + + return len; +} + +static struct watchdog_info ident = { + .options = WDIOF_CARDRESET | + WDIOF_MAGICCLOSE | + WDIOF_SETTIMEOUT | + WDIOF_KEEPALIVEPING, + .identity = "MXS Watchdog", +}; + +static long mxs_wdt_ioctl(struct file *file, unsigned int cmd, + unsigned long arg) +{ + void __user *argp = (void __user *)arg; + int __user *p = argp; + int new_heartbeat, opts; + int ret = -ENOTTY; + + switch (cmd) { + case WDIOC_GETSUPPORT: + ret = copy_to_user(argp, &ident, sizeof(ident)) ? -EFAULT : 0; + break; + + case WDIOC_GETSTATUS: + ret = put_user(0, p); + break; + + case WDIOC_GETBOOTSTATUS: + ret = put_user(boot_status, p); + break; + + case WDIOC_SETOPTIONS: + if (get_user(opts, p)) { + ret = -EFAULT; + break; + } + if (opts & WDIOS_DISABLECARD) + wdt_disable(); + else if (opts & WDIOS_ENABLECARD) + wdt_ping(); + else { + pr_debug("%s: unknown option 0x%x\n", __func__, opts); + ret = -EINVAL; + break; + } + ret = 0; + break; + + case WDIOC_KEEPALIVE: + wdt_ping(); + ret = 0; + break; + + case WDIOC_SETTIMEOUT: + if (get_user(new_heartbeat, p)) { + ret = -EFAULT; + break; + } + if (new_heartbeat <= 0 || new_heartbeat > MAX_HEARTBEAT) { + ret = -EINVAL; + break; + } + + heartbeat = new_heartbeat; + wdt_ping(); + /* Fall through */ + + case WDIOC_GETTIMEOUT: + ret = put_user(heartbeat, p); + break; + } + return ret; +} + +static int mxs_wdt_release(struct inode *inode, struct file *file) +{ + int ret = 0; + + if (WATCHDOG_NOWAYOUT == 0) { + if (!test_bit(WDT_OK_TO_CLOSE, &wdt_status)) { + wdt_ping(); + pr_debug("%s: Device closed unexpectdly\n", __func__); + ret = -EINVAL; + } else { + wdt_disable(); + clear_bit(WDT_OK_TO_CLOSE, &wdt_status); + } + } + clear_bit(WDT_IN_USE, &wdt_status); + + return ret; +} + +static const struct file_operations mxs_wdt_fops = { + .owner = THIS_MODULE, + .llseek = no_llseek, + .write = mxs_wdt_write, + .unlocked_ioctl = mxs_wdt_ioctl, + .open = mxs_wdt_open, + .release = mxs_wdt_release, +}; + +static struct miscdevice mxs_wdt_miscdev = { + .minor = WATCHDOG_MINOR, + .name = "watchdog", + .fops = &mxs_wdt_fops, +}; + +static int __devinit mxs_wdt_probe(struct platform_device *pdev) +{ + int ret = 0; + struct resource *res; + + if (heartbeat < 1 || heartbeat > MAX_HEARTBEAT) + heartbeat = DEFAULT_HEARTBEAT; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (res == NULL) + return -ENODEV; + wdt_base = (unsigned long)IO_ADDRESS(res->start); + + boot_status = __raw_readl(wdt_base + HW_RTC_PERSISTENT1) & + BV_RTC_PERSISTENT1_GENERAL__RTC_FORCE_UPDATER; + boot_status = !!boot_status; + __raw_writel(BV_RTC_PERSISTENT1_GENERAL__RTC_FORCE_UPDATER, + wdt_base + HW_RTC_PERSISTENT1_CLR); + + wdt_disable(); /* disable for now */ + + ret = misc_register(&mxs_wdt_miscdev); + if (ret < 0) { + dev_err(&pdev->dev, "cannot register misc device\n"); + return ret; + } + + printk(KERN_INFO "mxs watchdog: initialized, heartbeat %d sec\n", + heartbeat); + + return ret; +} + +static int __devexit mxs_wdt_remove(struct platform_device *pdev) +{ + misc_deregister(&mxs_wdt_miscdev); + return 0; +} + +#ifdef CONFIG_PM +static int wdt_suspended; +static u32 wdt_saved_time; + +static int mxs_wdt_suspend(struct platform_device *pdev, + pm_message_t state) +{ + if (__raw_readl(wdt_base + HW_RTC_CTRL) & BM_RTC_CTRL_WATCHDOGEN) { + wdt_saved_time = __raw_readl(wdt_base + HW_RTC_WATCHDOG); + wdt_disable(); + wdt_suspended = 1; + } + return 0; +} + +static int mxs_wdt_resume(struct platform_device *pdev) +{ + if (wdt_suspended) { + wdt_suspended = 0; + wdt_enable(wdt_saved_time); + } + return 0; +} +#else +#define mxs_wdt_suspend NULL +#define mxs_wdt_resume NULL +#endif + +static struct platform_driver mxs_wdt_driver = { + .driver = { + .name = "mxs-wdt", + }, + .probe = mxs_wdt_probe, + .remove = __devexit_p(mxs_wdt_remove), + .suspend = mxs_wdt_suspend, + .resume = mxs_wdt_resume, +}; + +static int __init mxs_wdt_init(void) +{ + return platform_driver_register(&mxs_wdt_driver); +} + +static void __exit mxs_wdt_exit(void) +{ + return platform_driver_unregister(&mxs_wdt_driver); +} + +module_init(mxs_wdt_init); +module_exit(mxs_wdt_exit); + +MODULE_DESCRIPTION("MXS Watchdog Driver"); +MODULE_LICENSE("GPL"); + +module_param(heartbeat, int, 0); +MODULE_PARM_DESC(heartbeat, + "Watchdog heartbeat period in seconds from 1 to " + __MODULE_STRING(MAX_HEARTBEAT) ", default " + __MODULE_STRING(DEFAULT_HEARTBEAT)); + +MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR); diff --git a/net/core/dev.c b/net/core/dev.c index 1f466e82ac33..33a21d46dfcf 100644 --- a/net/core/dev.c +++ b/net/core/dev.c @@ -4531,6 +4531,9 @@ static int dev_ifsioc(struct net *net, struct ifreq *ifr, unsigned int cmd) default: if ((cmd >= SIOCDEVPRIVATE && cmd <= SIOCDEVPRIVATE + 15) || +#if defined(CONFIG_FEC_L2SWITCH) + (cmd >= 0x9101 && cmd <= 0x92ff) || +#endif cmd == SIOCBONDENSLAVE || cmd == SIOCBONDRELEASE || cmd == SIOCBONDSETHWADDR || @@ -4723,6 +4726,9 @@ int dev_ioctl(struct net *net, unsigned int cmd, void __user *arg) */ default: if (cmd == SIOCWANDEV || +#if defined(CONFIG_FEC_L2SWITCH) + (cmd >= 0x9101 && cmd <= 0x92ff) || +#endif (cmd >= SIOCDEVPRIVATE && cmd <= SIOCDEVPRIVATE + 15)) { dev_load(net, ifr.ifr_name); diff --git a/sound/arm/Kconfig b/sound/arm/Kconfig index 885683a3b0bd..ae88981852b0 100644 --- a/sound/arm/Kconfig +++ b/sound/arm/Kconfig @@ -39,5 +39,54 @@ config SND_PXA2XX_AC97 Say Y or M if you want to support any AC97 codec attached to the PXA2xx AC97 interface. +config SND_MXC_SPDIF + tristate "MXC SPDIF sound card spport" + select SND_PCM + help + Say Y here to enable SPDIF sound card + +config SND_MXC_PMIC + tristate "MXC PMIC sound system" + depends on ARCH_MXC && MXC_DAM && MXC_SSI && \ + (MXC_MC13783_AUDIO || MXC_PMIC_SC55112_AUDIO) + default y + select SND_PCM + help + Say Y here to include support for soundcards based on the + MC13783 chip. + + To compile this driver as a module, choose M here: the module + will be called snd-mc13783. + +config SND_MXC_PLAYBACK_MIXING + bool "Playback Stream Mixing" + depends on (!ARCH_MX27) && (!ARCH_MXC91131) && ARCH_MXC && MXC_DAM && MXC_SSI && \ + (MXC_MC13783_AUDIO) + default n + select SND_PCM + help + Say Y here to include support mixing for soundcards based on the + MC13783 chip. This supports audio stream mixing on VCODEC for mc13783 based platforms. + Analog mixng as well as Digital mixing can be tested on these platforms. + As of now , mixing of mono files only are supported in Digital Mixing since it is done on VCODEC. + SSI 2 channel mode is used to mix 2 streams on a single SSI. This is supported on all platforms except imx27ads(imx27ads - Analog mixing only). + +config HEADSET_DETECT_ENABLE + bool "Headset Detect Enable" + depends on (!ARCH_MXC91131) && ARCH_MXC && MXC_DAM && MXC_SSI && \ + (MXC_MC13783_AUDIO) + default n + select SND_PCM + help + Say Y here to enable Headset Detect Feature. + +config SND_MXC_PMIC_IRAM + bool "MXC PMIC sound system supports IRAM" + depends on SND_MXC_PMIC && SDMA_IRAM + default n + select SND_PCM + help + It will use IRAM as the DMA buffer of ALSA playback. + endif # SND_ARM diff --git a/sound/arm/Makefile b/sound/arm/Makefile index 8c0c851d4641..c943c65ba032 100644 --- a/sound/arm/Makefile +++ b/sound/arm/Makefile @@ -14,3 +14,14 @@ snd-pxa2xx-lib-$(CONFIG_SND_PXA2XX_LIB_AC97) += pxa2xx-ac97-lib.o obj-$(CONFIG_SND_PXA2XX_AC97) += snd-pxa2xx-ac97.o snd-pxa2xx-ac97-objs := pxa2xx-ac97.o + +# +# Define the header file locations for PMIC drivers. +# +CFLAGS_mxc-alsa-pmic.o = -I$(srctree)/drivers/mxc +obj-$(CONFIG_SND_MXC_PMIC) += snd-mxc-alsa.o +snd-mxc-alsa-objs := mxc-alsa-pmic.o mxc-alsa-mixer.o + +CFLGS_mxc_alsa_spdif.o = -I$(TOPDIR)/drivers/mxc +obj-$(CONFIG_SND_MXC_SPDIF) += snd-spdif.o +snd-spdif-objs := mxc-alsa-spdif.o diff --git a/sound/arm/mxc-alsa-common.h b/sound/arm/mxc-alsa-common.h new file mode 100644 index 000000000000..09d8d8de842a --- /dev/null +++ b/sound/arm/mxc-alsa-common.h @@ -0,0 +1,68 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + + /*! + * @file mxc-alsa-common.h + * @brief + * @ingroup SOUND_DRV + */ + +#ifndef __MXC_ALSA_COMMON_H__ +#define __MXC_ALSA_COMMON_H__ + +/* Enums typically used by the Mixer support APIs + * Emunerates IP, OP and mixer sources. + */ + +typedef enum { + CODEC_DIR_OUT, + MIXER_OUT +} OUTPUT_SOURCE; + +typedef enum { + OP_NODEV = -1, + OP_EARPIECE, + OP_HANDSFREE, + OP_HEADSET, + OP_LINEOUT, + OP_MAXDEV, + OP_MONO +} OUTPUT_DEVICES; + +typedef enum { + IP_NODEV = -1, + IP_HANDSET, + IP_HEADSET, + IP_LINEIN, + IP_MAXDEV +} INPUT_DEVICES; + +extern int mxc_alsa_create_ctl(struct snd_card *card, void *p_value); + +extern int set_mixer_output_device(PMIC_AUDIO_HANDLE handle, OUTPUT_SOURCE src, + OUTPUT_DEVICES dev, bool enable); +extern int set_mixer_output_volume(PMIC_AUDIO_HANDLE handle, int volume, + OUTPUT_DEVICES dev); +extern int set_mixer_input_device(PMIC_AUDIO_HANDLE handle, INPUT_DEVICES dev, + bool enable); +extern int set_mixer_output_mono_adder(PMIC_AUDIO_MONO_ADDER_MODE mode); +extern int set_mixer_input_gain(PMIC_AUDIO_HANDLE handle, int val); +extern int set_mixer_output_balance(int bal); + +extern int get_mixer_output_device(void); +extern int get_mixer_output_volume(void); +extern int get_mixer_output_mono_adder(void); +extern int get_mixer_output_balance(void); +extern int get_mixer_input_gain(void); +extern int get_mixer_input_device(void); +#endif /* __MXC_ALSA_COMMON_H__ */ diff --git a/sound/arm/mxc-alsa-mixer.c b/sound/arm/mxc-alsa-mixer.c new file mode 100644 index 000000000000..bd46d3a5f7f1 --- /dev/null +++ b/sound/arm/mxc-alsa-mixer.c @@ -0,0 +1,411 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + + /*! + * @file mxc-alsa-mixer.c + * @brief this file implements the mxc sound driver mixer interface for ALSA. + * The mxc sound driver supports mono/stereo recording (there are + * some limitations due to hardware), mono/stereo playback and + * audio mixing. This file implements output switching, volume/balance controls + * mono adder config, I/P dev switching and gain on the PCM streams. + * Recording supports 8000 khz and 16000 khz sample rate. + * Playback supports 8000, 11025, 16000, 22050, 24000, 32000, + * 44100 and 48000 khz for mono and stereo. + * + * @ingroup SOUND_DRV + */ + +#include +#include +#include +#include +#include +#include +#include "mxc-alsa-common.h" +/*! + * These are the functions implemented in the ALSA PCM driver that + * are used for mixer operations + * + */ + +/*! + * These are the callback functions for mixer controls + * + */ +/* Output device control*/ +static int pmic_mixer_output_info(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_info *uinfo) +{ + + uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; + uinfo->count = 1; + uinfo->value.integer.min = 0; + uinfo->value.integer.max = 15; + uinfo->value.integer.step = 1; + return 0; +} +static int pmic_mixer_output_put(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *uvalue) +{ + int dev, i; + dev = uvalue->value.integer.value[0]; + for (i = OP_EARPIECE; i < OP_MAXDEV; i++) { + if (dev & (1 << i)) { + set_mixer_output_device(NULL, MIXER_OUT, i, 1); + } else { + set_mixer_output_device(NULL, MIXER_OUT, i, 0); + } + } + return 0; +} +static int pmic_mixer_output_get(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *uvalue) +{ + int val, ret = 0, i = 0; + for (i = OP_EARPIECE; i < OP_MAXDEV; i++) { + val = get_mixer_output_device(); + if (val & SOUND_MASK_PHONEOUT) + ret = ret | 1; + if (val & SOUND_MASK_SPEAKER) + ret = ret | 2; + if (val & SOUND_MASK_VOLUME) + ret = ret | 4; + if (val & SOUND_MASK_PCM) + ret = ret | 8; + uvalue->value.integer.value[0] = ret; + } + return 0; + +} + +/* Input gain control*/ +static int pmic_cap_volume_info(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_info *uinfo) +{ + + uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; + uinfo->count = 1; + uinfo->value.integer.min = 0; + uinfo->value.integer.max = 100; + uinfo->value.integer.step = 1; + return 0; +} +static int pmic_cap_volume_get(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *uvalue) +{ + int val; + val = get_mixer_input_gain(); + val = val & 0xFF; + uvalue->value.integer.value[0] = val; + return 0; +} + +static int pmic_cap_volume_put(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *uvalue) +{ + + int vol; + vol = uvalue->value.integer.value[0]; + vol = vol | (vol << 8); + set_mixer_input_gain(NULL, vol); + return 0; +} + +/* Mono adder control*/ +static int pmic_pb_monoconfig_info(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_info *uinfo) +{ + + uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; + uinfo->count = 1; + uinfo->value.integer.min = 0; + uinfo->value.integer.max = 3; + uinfo->value.integer.step = 1; + return 0; +} +static int pmic_pb_monoconfig_put(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *uvalue) +{ + int mono; + mono = uvalue->value.integer.value[0]; + set_mixer_output_mono_adder(mono); + return 0; +} +static int pmic_pb_monoconfig_get(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *uvalue) +{ + uvalue->value.integer.value[0] = get_mixer_output_mono_adder(); + return 0; +} + +/*! + * These are the ALSA control structures with init values + * + */ + +/* Input device control*/ +static int pmic_cap_input_info(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_info *uinfo) +{ + + uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; + uinfo->count = 1; + uinfo->value.integer.min = 0; + uinfo->value.integer.max = 7; + uinfo->value.integer.step = 1; + return 0; +} +static int pmic_cap_input_put(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *uvalue) +{ + int dev, i; + dev = uvalue->value.integer.value[0]; + for (i = IP_HANDSET; i < IP_MAXDEV; i++) { + dev &= (1 << i); + if (dev) { + set_mixer_input_device(NULL, i, 1); + } else { + set_mixer_input_device(NULL, i, 0); + } + } + return 0; +} +static int pmic_cap_input_get(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *uvalue) +{ + int val, ret = 0, i = 0; + for (i = IP_HANDSET; i < IP_MAXDEV; i++) { + val = get_mixer_input_device(); + if (val & SOUND_MASK_PHONEIN) + ret = ret | 1; + if (val & SOUND_MASK_MIC) + ret = ret | 2; + if (val & SOUND_MASK_LINE) + ret = ret | 4; + uvalue->value.integer.value[0] = ret; + } + return 0; +} + +/* Volume control*/ +static int pmic_pb_volume_put(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *uvalue) +{ + int volume; + volume = uvalue->value.integer.value[0]; + volume = volume | (volume << 8); + set_mixer_output_volume(NULL, volume, OP_NODEV); + return 0; +} +static int pmic_pb_volume_info(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_info *uinfo) +{ + + uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; + uinfo->count = 1; + uinfo->value.integer.min = 1; + uinfo->value.integer.max = 100; + uinfo->value.integer.step = 1; + return 0; +} + +static int pmic_pb_volume_get(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *uvalue) +{ + int val; + val = get_mixer_output_volume(); + val = val & 0xFF; + uvalue->value.integer.value[0] = val; + return 0; +} + +/* Balance control start */ +static int pmic_pb_balance_info(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_info *uinfo) +{ + + uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; + uinfo->count = 1; + uinfo->value.integer.min = 0; + uinfo->value.integer.max = 100; + uinfo->value.integer.step = 1; + return 0; +} + +static int pmic_pb_balance_get(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *uvalue) +{ + uvalue->value.integer.value[0] = get_mixer_output_balance(); + return 0; + +} +static int pmic_pb_balance_put(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *uvalue) +{ + int bal; + bal = uvalue->value.integer.value[0]; + set_mixer_output_balance(bal); + return 0; +} + +/* Balance control end */ + +/* loopback control start */ +static int pmic_loopback_info(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_info *uinfo) +{ + + uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN; + uinfo->count = 1; + uinfo->value.integer.min = 0; + uinfo->value.integer.max = 1; + return 0; +} + +static int pmic_loopback_get(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *uvalue) +{ + uvalue->value.integer.value[0] = kcontrol->private_value; + return 0; + +} +static int pmic_loopback_put(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *uvalue) +{ + int changed; + long flag = uvalue->value.integer.value[0]; + changed = + (uvalue->value.integer.value[0] == kcontrol->private_value) ? 0 : 1; + kcontrol->private_value = uvalue->value.integer.value[0]; + if (flag) + pmic_audio_fm_output_enable(true); + else + pmic_audio_fm_output_enable(false); + + return changed; +} + +/* Loopback control end */ + +/* Kcontrol structure definitions */ +struct snd_kcontrol_new pmic_control_pb_vol __devinitdata = { + .iface = SNDRV_CTL_ELEM_IFACE_MIXER, + .name = "Master Playback Volume", + .index = 0x00, + .info = pmic_pb_volume_info, + .get = pmic_pb_volume_get, + .put = pmic_pb_volume_put, + .private_value = 0xffab1, +}; + +struct snd_kcontrol_new pmic_control_pb_bal __devinitdata = { + .iface = SNDRV_CTL_ELEM_IFACE_MIXER, + .name = "Master Balance Playback Volume", + .index = 0x00, + .info = pmic_pb_balance_info, + .get = pmic_pb_balance_get, + .put = pmic_pb_balance_put, + .private_value = 0xffab2, +}; +struct snd_kcontrol_new pmic_control_pb_monoconfig __devinitdata = { + .iface = SNDRV_CTL_ELEM_IFACE_MIXER, + .name = "Master Monoconfig Playback Volume", + .index = 0x00, + .info = pmic_pb_monoconfig_info, + .get = pmic_pb_monoconfig_get, + .put = pmic_pb_monoconfig_put, + .private_value = 0xffab2, +}; +struct snd_kcontrol_new pmic_control_op_sw __devinitdata = { + .iface = SNDRV_CTL_ELEM_IFACE_MIXER, + .name = "Master Output Playback Volume", + .index = 0x00, + .info = pmic_mixer_output_info, + .get = pmic_mixer_output_get, + .put = pmic_mixer_output_put, + .private_value = 0xffab4, +}; + +struct snd_kcontrol_new pmic_control_cap_vol __devinitdata = { + .iface = SNDRV_CTL_ELEM_IFACE_MIXER, + .name = "Master Capture Volume", + .index = 0x00, + .info = pmic_cap_volume_info, + .get = pmic_cap_volume_get, + .put = pmic_cap_volume_put, + .private_value = 0xffab5, +}; +struct snd_kcontrol_new pmic_control_ip_sw __devinitdata = { + .iface = SNDRV_CTL_ELEM_IFACE_MIXER, + .name = "Master Input Capture Volume", + .index = 0x00, + .info = pmic_cap_input_info, + .get = pmic_cap_input_get, + .put = pmic_cap_input_put, + .private_value = 0xffab5, +}; + +struct snd_kcontrol_new pmic_control_loop_out __devinitdata = { + .iface = SNDRV_CTL_ELEM_IFACE_MIXER, + .name = "Loopback Line-in", + .index = 0x00, + .info = pmic_loopback_info, + .get = pmic_loopback_get, + .put = pmic_loopback_put, + .private_value = 0, +}; + +/*! + * This function registers the control components of ALSA Mixer + * It is called by ALSA PCM init. + * + * @param card pointer to the ALSA sound card structure. + * + * @return 0 on success, -ve otherwise. + */ +int __devinit mxc_alsa_create_ctl(struct snd_card *card, void *p_value) +{ + int err = 0; + + err = snd_ctl_add(card, snd_ctl_new1(&pmic_control_op_sw, p_value)); + if (err < 0) + return err; + + err = snd_ctl_add(card, snd_ctl_new1(&pmic_control_pb_vol, p_value)); + if (err < 0) + return err; + + err = snd_ctl_add(card, snd_ctl_new1(&pmic_control_pb_monoconfig, p_value)); + if (err < 0) + return err; + + err = snd_ctl_add(card, snd_ctl_new1(&pmic_control_pb_bal, p_value)); + if (err < 0) + return err; + + err = snd_ctl_add(card, snd_ctl_new1(&pmic_control_cap_vol, p_value)); + if (err < 0) + return err; + + err = snd_ctl_add(card, snd_ctl_new1(&pmic_control_ip_sw, p_value)); + if (err < 0) + return err; + + err = snd_ctl_add(card, snd_ctl_new1(&pmic_control_loop_out, p_value)); + if (err < 0) + return err; + + return 0; +} + +EXPORT_SYMBOL(mxc_alsa_create_ctl); diff --git a/sound/arm/mxc-alsa-pmic.c b/sound/arm/mxc-alsa-pmic.c new file mode 100644 index 000000000000..c8785ccefc28 --- /dev/null +++ b/sound/arm/mxc-alsa-pmic.c @@ -0,0 +1,3793 @@ +/* + * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + + /*! + * @defgroup SOUND_DRV MXC Sound Driver for ALSA + */ + + /*! + * @file mxc-alsa-pmic.c + * @brief this fle mxc-alsa-pmic.c + * @brief this file implements the mxc sound driver interface for ALSA. + * The mxc sound driver supports mono/stereo recording (there are + * some limitations due to hardware), mono/stereo playback and + * audio mixing. + * Recording supports 8000 khz and 16000 khz sample rate. + * Playback supports 8000, 11025, 16000, 22050, 24000, 32000, + * 44100, 48000 and 96000 Hz for mono and stereo. + * This file also handles the software mixer and abstraction APIs + * that control the volume,balance,mono-adder,input and output + * devices for PMIC. + * These mixer controls shall be accessible thru alsa as well as + * OSS emulation modes + * + * @ingroup SOUND_DRV + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +#include "mxc-alsa-pmic.h" +#include "mxc-alsa-common.h" + +/* + * PMIC driver buffer policy. + * Customize here if the sound is not correct + */ +#define MAX_BUFFER_SIZE (32*1024) +#define DMA_BUF_SIZE (8*1024) +#define MIN_PERIOD_SIZE 64 +#define MIN_PERIOD 2 +#define MAX_PERIOD 255 + +#define AUD_MUX_CONF 0x0031010 +#define MASK_2_TS 0xfffffffc +#define MASK_1_TS 0xfffffffd +#define MASK_1_TS_MIX 0xfffffffc +#define MASK_1_TS_STDAC 0xfffffffe +#define MASK_1_TS_REC 0xfffffffe +#define SOUND_CARD_NAME "MXC" + +#ifdef CONFIG_SND_MXC_PMIC_IRAM +#define MAX_IRAM_SIZE (IRAM_SIZE - CONFIG_SDMA_IRAM_SIZE) +#define DMA_IRAM_SIZE (4*1024) +#define ADMA_BASE_PADDR (IRAM_BASE_ADDR + CONFIG_SDMA_IRAM_SIZE) +#define ADMA_BASE_VADDR (IRAM_BASE_ADDR_VIRT + CONFIG_SDMA_IRAM_SIZE) + +#if (MAX_IRAM_SIZE + CONFIG_SDMA_IRAM_SIZE) > IRAM_SIZE +#error "The IRAM size required has beyond the limitation of IC spec" +#endif + +#if (MAX_IRAM_SIZE&(DMA_IRAM_SIZE-1)) +#error "The IRAM size for DMA ring buffer should be multiples of dma buffer size" +#endif + +#endif /* CONFIG_SND_MXC_PMIC_IRAM */ + +/*! + * These defines enable DMA chaining for playback + * and capture respectively. + */ +#define MXC_SOUND_PLAYBACK_CHAIN_DMA_EN 1 +#define MXC_SOUND_CAPTURE_CHAIN_DMA_EN 1 + +/*! + * ID for this card + */ +static char *id; + +#define MXC_ALSA_MAX_PCM_DEV 3 +#define MXC_ALSA_MAX_PLAYBACK 3 +#define MXC_ALSA_MAX_CAPTURE 1 + +struct mxc_audio_platform_data *audio_data; +/*! + * This structure is the global configuration of the soundcard + * that are accessed by the mixer as well as by the playback/recording + * stream. This contains various volume, balance, mono adder settings + * + */ +typedef struct audio_mixer_control { + + /*! + * This variable holds the current active output device(s) + */ + int output_device; + + /*! + * This variable holds the current active input device. + */ + int input_device; + + /* Used only for playback/recording on codec .. Use 1 for playback + * and 0 for recording*/ + int direction; + + /*! + * This variable holds the current source for active ouput device(s) + */ + OUTPUT_SOURCE source_for_output[OP_MAXDEV]; + + /*! + * This variable says if a given output device is part of an ongoing + * playback. This variable will be set and reset by the playback stream + * when stream is activated and when stream is closed. This shall also + * be set and reset my mixer functions for enabling/disabling output devs + */ + int output_active[OP_MAXDEV]; + + /*! + * This variable holds the current volume for active input device. + * This maps to the input gain of recording device + */ + int input_volume; + + /*! + * This variable holds the current volume for playback devices. + */ + int master_volume_out; + + /*! + * This variable holds the balance setting for the mixer out. + * The range is 0 to 100. 50 means both L and R equal. + * < 50 attenuates left side and > 50 attenualtes right side + */ + int mixer_balance; + + /*! + * This variable holds the current mono adder config. + */ + PMIC_AUDIO_MONO_ADDER_MODE mixer_mono_adder; + + /*! + * Semaphore used to control the access to this structure. + */ + struct semaphore sem; + + /*! + * These variables are set by PCM stream and mixer when the voice codec's / ST dac's outputs are + * connected to the analog mixer of PMIC audio chip + */ + int codec_out_to_mixer; + int stdac_out_to_mixer; + + int codec_playback_active; + int codec_capture_active; + int stdac_playback_active; + int mixing_active; + + /*! + * This variable holds the configuration of the headset which was previously enabled. + */ + int old_prof; + + PMIC_AUDIO_HANDLE stdac_handle; + PMIC_AUDIO_HANDLE voice_codec_handle; + +} audio_mixer_control_t; + +/*! + * This structure stores current state of audio configuration + * soundcard wrt a specific stream (playback on different DACs, recording on the codec etc). + * It is used to set/get current values and are NOT accessed by the Mixer. This structure shall + * be retrieved thru pcm substream pointer and hence the mixer component will have no access + * to it. There will be as many structures as the number of streams. In our case it's 3. Codec playback + * STDAC playback and voice codec recording. + * This structure will be used at the beginning of activating a stream to configure audio chip. + * + */ +typedef struct pmic_audio_device { + + PMIC_AUDIO_HANDLE handle; + /*! + * This variable holds the sample rate currently being used. + */ + int sample_rate; + + /*! + * This variable holds the current protocol PMIC is using. + * PMIC can use one of three protocols at any given time: + * normal, network and I2S. + */ + int protocol; + + /*! + * This variables tells us whether PMIC runs in + * master mode (PMIC generates audio clocks)or slave mode (AP side + * generates audio clocks) + * + * Currently the default mode is master mode because PMIC clocks have + * higher precision. + */ + int mode; + + /* This variable holds the value representing the + * base clock PMIC will use to generate internal + * clocks (BCL clock and FrameSync clock) + */ + int pll; + + /*! + * This variable holds the SSI to which PMIC is currently connected. + */ + int ssi; + + /*! + * This variable tell us whether bit clock is inverted or not. + */ + int bcl_inverted; + + /*! + * This variable tell us whether frame clock is inverted or not. + */ + int fs_inverted; + + /*! + * This variable holds the pll used for PMIC audio operations. + */ + int pll_rate; + + /*! + * This variable holds the filter that PMIC is applying to + * CODEC operations. + */ + int codec_filter; + +} pmic_audio_device_t; + +/*! + * This structure represents an audio stream in term of + * channel DMA, HW configuration on PMIC and on AudioMux/SSI + */ +typedef struct audio_stream { + /*! + * identification string + */ + char *id; + + /*! + * numeric identification + */ + int stream_id; + + /*! + * SSI ID on the ARM side + */ + int ssi; + + /*! + * DAM port on the ARM side + */ + int dam_port; + + /*! + * device identifier for DMA + */ + int dma_wchannel; + + /*! + * we are using this stream for transfer now + */ + int active:1; + + /*! + * current transfer period + */ + int period; + + /*! + * current count of transfered periods + */ + int periods; + + /*! + * are we recording - flag used to do DMA trans. for sync + */ + int tx_spin; + + /*! + * Previous offset value for resume + */ + unsigned int old_offset; +#if 0 + /*! + * Path for this stream + */ + device_data_t stream_device; +#endif + + /*! + * pmic audio chip stream specific configuration + */ + pmic_audio_device_t pmic_audio_device; + + /*! + * for locking in DMA operations + */ + spinlock_t dma_lock; + + /*! + * Alsa substream pointer + */ + struct snd_pcm_substream *stream; +} audio_stream_t; + +/*! + * This structure represents the PMIC sound card with its + * 2 streams (StDac and Codecs) and its shared parameters + */ +typedef struct snd_card_mxc_pmic_audio { + /*! + * ALSA sound card handle + */ + struct snd_card *card; + + /*! + * ALSA pcm driver type handle + */ + struct snd_pcm *pcm[MXC_ALSA_MAX_PCM_DEV]; + + /*! + * playback & capture streams handle + * We can support a maximum of two playback streams (voice-codec + * and ST-DAC) and 1 recording stream + */ + audio_stream_t s[MXC_ALSA_MAX_CAPTURE + MXC_ALSA_MAX_PLAYBACK]; + +} mxc_pmic_audio_t; + +/*! + * pmic audio chip parameters for IP/OP and volume controls + */ +audio_mixer_control_t audio_mixer_control; + +/*! + * Global variable that represents the PMIC soundcard + * with its 2 availables stream devices: stdac and codec + */ +mxc_pmic_audio_t *mxc_audio; + +/*! + * Supported playback rates array + */ +static unsigned int playback_rates_stereo[] = { + 8000, + 11025, + 12000, + 16000, + 22050, + 24000, + 32000, + 44100, + 48000, + 64000, + 96000, +}; + +static unsigned int playback_rates_mono[] = { + 8000, + 16000, +}; + +/*! + * Supported capture rates array + */ +static unsigned int capture_rates[] = { + 8000, + 16000, +}; + +/*! + * this structure represents the sample rates supported + * by PMIC for playback operations on StDac. + */ +static struct snd_pcm_hw_constraint_list hw_playback_rates_stereo = { + .count = ARRAY_SIZE(playback_rates_stereo), + .list = playback_rates_stereo, + .mask = 0, +}; + +#ifdef CONFIG_SND_MXC_PMIC_IRAM +static DEFINE_SPINLOCK(g_audio_iram_lock); +static int g_audio_iram_en = 1; +static int g_device_opened; +extern void flush_cache_range(struct vm_area_struct *vma, unsigned long start, + unsigned long end); + +static inline int mxc_snd_enable_iram(int enable) +{ + int ret = -EBUSY; + unsigned long flags; + spin_lock_irqsave(&g_audio_iram_lock, flags); + if (!g_device_opened) { + g_audio_iram_en = (enable != 0); + ret = 0; + } + spin_unlock_irqrestore(&g_audio_iram_lock, flags); + return ret; +} + +static inline void mxc_snd_pcm_iram_get(void) +{ + unsigned long flags; + spin_lock_irqsave(&g_audio_iram_lock, flags); + g_audio_iram_en++; + spin_unlock_irqrestore(&g_audio_iram_lock, flags); +} + +static inline void mxc_snd_pcm_iram_put(void) +{ + unsigned long flags; + spin_lock_irqsave(&g_audio_iram_lock, flags); + g_audio_iram_en--; + spin_unlock_irqrestore(&g_audio_iram_lock, flags); +} + +struct snd_dma_buffer g_iram_dmab; + +#endif /* CONFIG_SND_MXC_PMIC_IRAM */ + +/*! + * this structure represents the sample rates supported + * by PMIC for playback operations on Voice codec. + */ +static struct snd_pcm_hw_constraint_list hw_playback_rates_mono = { + .count = ARRAY_SIZE(playback_rates_mono), + .list = playback_rates_mono, + .mask = 0, +}; + +/*! + * this structure represents the sample rates supported + * by PMIC for capture operations on Codec. + */ +static struct snd_pcm_hw_constraint_list hw_capture_rates = { + .count = ARRAY_SIZE(capture_rates), + .list = capture_rates, + .mask = 0, +}; + +#ifdef CONFIG_HEADSET_DETECT_ENABLE +static PMIC_HS_STATE hs_state; + +/*! + *This is used to maintain the state of the Headset*/ +static int headset_state; + +/*Callback for headset event. */ +static void HSCallback(const PMIC_HS_STATE hs_st) +{ + + msleep(10); + + if (headset_state == 1) { + pmic_audio_output_disable_phantom_ground(); + headset_state = 0; + if (audio_mixer_control.stdac_playback_active) + pmic_audio_output_clear_port(audio_mixer_control. + stdac_handle, + STEREO_HEADSET_LEFT | + STEREO_HEADSET_RIGHT); + else if (audio_mixer_control.voice_codec_handle) + pmic_audio_output_clear_port(audio_mixer_control. + voice_codec_handle, + STEREO_HEADSET_LEFT | + STEREO_HEADSET_RIGHT); + + if (audio_mixer_control.old_prof & (SOUND_MASK_PHONEOUT)) { + set_mixer_output_device(NULL, MIXER_OUT, OP_EARPIECE, + 1); + } + if (audio_mixer_control.old_prof & (SOUND_MASK_VOLUME)) { + set_mixer_output_device(NULL, MIXER_OUT, OP_HANDSFREE, + 1); + } + if (audio_mixer_control.old_prof & (SOUND_MASK_SPEAKER)) { +#ifdef CONFIG_HEADSET_DETECT_ENABLE + /*This is a temporary workaround which should be removed later */ + set_mixer_output_device(NULL, MIXER_OUT, OP_MONO, 1); +#else + set_mixer_output_device(NULL, MIXER_OUT, OP_HEADSET, 1); +#endif + } + if (audio_mixer_control.old_prof & (SOUND_MASK_PCM)) { + set_mixer_output_device(NULL, MIXER_OUT, OP_LINEOUT, 1); + } + + } else { + headset_state = 1; + + pmic_audio_output_enable_phantom_ground(); + + audio_mixer_control.old_prof = + audio_mixer_control.output_device; + + if (audio_mixer_control.old_prof & (SOUND_MASK_PHONEOUT)) { + set_mixer_output_device(NULL, MIXER_OUT, OP_EARPIECE, + 0); + } + if (audio_mixer_control.old_prof & (SOUND_MASK_VOLUME)) { + set_mixer_output_device(NULL, MIXER_OUT, OP_HANDSFREE, + 0); + } + if (audio_mixer_control.old_prof & (SOUND_MASK_SPEAKER)) { + set_mixer_output_device(NULL, MIXER_OUT, OP_HEADSET, 0); + } + if (audio_mixer_control.old_prof & (SOUND_MASK_PCM)) { + set_mixer_output_device(NULL, MIXER_OUT, OP_LINEOUT, 0); + } + /*This is a temporary workaround which should be removed later */ + set_mixer_output_device(NULL, MIXER_OUT, OP_MONO, 1); + + } +} + +#endif +/*! + * This function configures audio multiplexer to support + * audio data routing in PMIC master mode. + * + * @param ssi SSI of the ARM to connect to the DAM. + */ +void configure_dam_pmic_master(int ssi) +{ + int source_port; + int target_port; + + if (ssi == SSI1) { + pr_debug("DAM: port 1 -> port 4\n"); + source_port = audio_data->src_port; + + target_port = port_4; + } else { + pr_debug("DAM: port 2 -> port 5\n"); + source_port = port_2; + target_port = port_5; + } + + dam_reset_register(source_port); + dam_reset_register(target_port); + + dam_select_mode(source_port, normal_mode); + dam_select_mode(target_port, internal_network_mode); + + dam_set_synchronous(source_port, true); + dam_set_synchronous(target_port, true); + + dam_select_RxD_source(source_port, target_port); + dam_select_RxD_source(target_port, source_port); + + dam_select_TxFS_direction(source_port, signal_out); + dam_select_TxFS_source(source_port, false, target_port); + + dam_select_TxClk_direction(source_port, signal_out); + dam_select_TxClk_source(source_port, false, target_port); + + dam_select_RxFS_direction(source_port, signal_out); + dam_select_RxFS_source(source_port, false, target_port); + + dam_select_RxClk_direction(source_port, signal_out); + dam_select_RxClk_source(source_port, false, target_port); + + dam_set_internal_network_mode_mask(target_port, 0xfc); + + writel(AUD_MUX_CONF, IO_ADDRESS(AUDMUX_BASE_ADDR) + 0x38); +} + +/*! + * This function configures the SSI in order to receive audio + * from PMIC (recording). Configuration of SSI consists mainly in + * setting the following: + * + * 1) SSI to use (SSI1 or SSI2) + * 2) SSI mode (normal or network. We use always network mode) + * 3) SSI STCCR register settings, which control the sample rate (BCL and + * FS clocks) + * 4) Watermarks for SSI FIFOs as well as timeslots to be used. + * 5) Enable SSI. + * + * @param substream pointer to the structure of the current stream. + */ +void configure_ssi_rx(struct snd_pcm_substream *substream) +{ + mxc_pmic_audio_t *chip; + audio_stream_t *s; + int ssi; + + chip = snd_pcm_substream_chip(substream); + s = &chip->s[substream->pstr->stream]; + ssi = s->ssi; + + pr_debug("configure_ssi_rx: SSI %d\n", ssi + 1); + + ssi_enable(ssi, false); + ssi_synchronous_mode(ssi, true); + ssi_network_mode(ssi, true); + + if (machine_is_mx27ads()) { + ssi_tx_clock_divide_by_two(ssi, 0); + ssi_tx_clock_prescaler(ssi, 0); + ssi_tx_frame_rate(ssi, 2); + } + /* OJO */ + ssi_tx_frame_rate(ssi, 1); + + ssi_tx_early_frame_sync(ssi, ssi_frame_sync_one_bit_before); + ssi_tx_frame_sync_length(ssi, ssi_frame_sync_one_bit); + ssi_tx_word_length(ssi, ssi_16_bits); + + ssi_rx_early_frame_sync(ssi, ssi_frame_sync_one_bit_before); + ssi_rx_frame_sync_length(ssi, ssi_frame_sync_one_bit); + ssi_rx_fifo_enable(ssi, ssi_fifo_0, true); + ssi_rx_bit0(ssi, true); + + ssi_rx_fifo_full_watermark(ssi, ssi_fifo_0, RX_WATERMARK); + + /* We never use the divider by 2 implemented in SSI */ + ssi_rx_clock_divide_by_two(ssi, 0); + + /* Set prescaler range (a fixed divide-by-eight prescaler + * in series with the variable prescaler) to 0 as we don't + * need it. + */ + ssi_rx_clock_prescaler(ssi, 0); + + /* Currently, only supported sample length is 16 bits */ + ssi_rx_word_length(ssi, ssi_16_bits); + + /* set direction of clocks ("externally" means that clocks come + * from PMIC to MCU) + */ + ssi_rx_frame_direction(ssi, ssi_tx_rx_externally); + ssi_rx_clock_direction(ssi, ssi_tx_rx_externally); + + /* Frame Rate Divider Control. + * In Normal mode, this ratio determines the word + * transfer rate. In Network mode, this ration sets + * the number of words per frame. + */ + ssi_tx_frame_rate(ssi, 4); + ssi_rx_frame_rate(ssi, 4); + + ssi_enable(ssi, true); +} + +/*! + * This function configures the SSI in order to + * send data to PMIC. Configuration of SSI consists + * mainly in setting the following: + * + * 1) SSI to use (SSI1 or SSI2) + * 2) SSI mode (normal for normal use e.g. playback, network for mixing) + * 3) SSI STCCR register settings, which control the sample rate (BCL and + * FS clocks) + * 4) Watermarks for SSI FIFOs as well as timeslots to be used. + * 5) Enable SSI. + * + * @param substream pointer to the structure of the current stream. + */ +void configure_ssi_tx(struct snd_pcm_substream *substream) +{ + mxc_pmic_audio_t *chip; + audio_stream_t *s; + struct snd_pcm_runtime *runtime; + int ssi; + int device, stream_id = -1; + device = substream->pcm->device; + if (device == 0) + stream_id = 0; + else if (device == 1) + stream_id = 2; + else + stream_id = 3; + + chip = snd_pcm_substream_chip(substream); + s = &chip->s[stream_id]; + runtime = substream->runtime; + ssi = s->ssi; + + pr_debug("configure_ssi_tx: SSI %d\n", ssi + 1); + + ssi_enable(ssi, false); + ssi_synchronous_mode(ssi, true); + if (runtime->channels == 1) { + if (stream_id == 2) { + ssi_network_mode(ssi, true); + } else { +#ifndef CONFIG_SND_MXC_PLAYBACK_MIXING + ssi_network_mode(ssi, false); +#endif + } + } else { + ssi_network_mode(ssi, true); + } + +#ifdef CONFIG_SND_MXC_PLAYBACK_MIXING + ssi_two_channel_mode(ssi, true); + ssi_tx_fifo_enable(ssi, ssi_fifo_1, true); + ssi_tx_fifo_empty_watermark(ssi, ssi_fifo_1, TX_WATERMARK); +#endif + + ssi_tx_early_frame_sync(ssi, ssi_frame_sync_one_bit_before); + ssi_tx_frame_sync_length(ssi, ssi_frame_sync_one_bit); + ssi_tx_fifo_enable(ssi, ssi_fifo_0, true); + ssi_tx_bit0(ssi, true); + + ssi_tx_fifo_empty_watermark(ssi, ssi_fifo_0, TX_WATERMARK); + + /* We never use the divider by 2 implemented in SSI */ + ssi_tx_clock_divide_by_two(ssi, 0); + + ssi_tx_clock_prescaler(ssi, 0); + + /*Currently, only supported sample length is 16 bits */ + ssi_tx_word_length(ssi, ssi_16_bits); + + /* clocks are being provided by PMIC */ + ssi_tx_frame_direction(ssi, ssi_tx_rx_externally); + ssi_tx_clock_direction(ssi, ssi_tx_rx_externally); + + if (runtime->channels == 1) { +#ifndef CONFIG_SND_MXC_PLAYBACK_MIXING + if (stream_id == 2) { + ssi_tx_frame_rate(ssi, 4); + } else { + ssi_tx_frame_rate(ssi, 1); + } +#else + if (stream_id == 2) { + ssi_tx_frame_rate(ssi, 2); + } +#endif + + } else { + ssi_tx_frame_rate(ssi, 2); + } + + ssi_enable(ssi, true); +} + +/*! + * This function normalizes speed given by the user + * if speed is not supported, the function will + * calculate the nearest one. + * + * @param speed speed requested by the user. + * + * @return The normalized speed. + */ +int adapt_speed(int speed) +{ + + /* speeds from 8k to 96k */ + if (speed >= (64000 + 96000) / 2) { + speed = 96000; + } else if (speed >= (48000 + 64000) / 2) { + speed = 64000; + } else if (speed >= (44100 + 48000) / 2) { + speed = 48000; + } else if (speed >= (32000 + 44100) / 2) { + speed = 44100; + } else if (speed >= (24000 + 32000) / 2) { + speed = 32000; + } else if (speed >= (22050 + 24000) / 2) { + speed = 24000; + } else if (speed >= (16000 + 22050) / 2) { + speed = 22050; + } else if (speed >= (12000 + 16000) / 2) { + speed = 16000; + } else if (speed >= (11025 + 12000) / 2) { + speed = 12000; + } else if (speed >= (8000 + 11025) / 2) { + speed = 11025; + } else { + speed = 8000; + } + return speed; +} + +/*! + * This function get values to be put in PMIC registers. + * This values represents the sample rate that PMIC + * should use for current playback or recording. + * + * @param substream pointer to the structure of the current stream. + */ +void normalize_speed_for_pmic(struct snd_pcm_substream *substream) +{ + mxc_pmic_audio_t *chip; + audio_stream_t *s; + pmic_audio_device_t *pmic_device; + struct snd_pcm_runtime *runtime; + int device, stream_id = -1; + device = substream->pcm->device; + if (device == 0) { + if ((audio_mixer_control.codec_capture_active == 1) + && (substream->stream == 1)) { + stream_id = 1; + } else + stream_id = 0; + } else { + stream_id = 2; + } + + chip = snd_pcm_substream_chip(substream); + s = &chip->s[stream_id]; + pmic_device = &s->pmic_audio_device; + runtime = substream->runtime; + + /* As the driver allows continuous sample rate, we must adapt the rate */ + runtime->rate = adapt_speed(runtime->rate); + + if (pmic_device->handle == audio_mixer_control.voice_codec_handle) { + switch (runtime->rate) { + case 8000: + pmic_device->sample_rate = VCODEC_RATE_8_KHZ; + break; + case 16000: + pmic_device->sample_rate = VCODEC_RATE_16_KHZ; + break; + default: + pmic_device->sample_rate = VCODEC_RATE_8_KHZ; + break; + } + + } else if (pmic_device->handle == audio_mixer_control.stdac_handle) { + switch (runtime->rate) { + case 8000: + pmic_device->sample_rate = STDAC_RATE_8_KHZ; + break; + + case 11025: + pmic_device->sample_rate = STDAC_RATE_11_025_KHZ; + break; + + case 12000: + pmic_device->sample_rate = STDAC_RATE_12_KHZ; + break; + + case 16000: + pmic_device->sample_rate = STDAC_RATE_16_KHZ; + break; + + case 22050: + pmic_device->sample_rate = STDAC_RATE_22_050_KHZ; + break; + + case 24000: + pmic_device->sample_rate = STDAC_RATE_24_KHZ; + break; + + case 32000: + pmic_device->sample_rate = STDAC_RATE_32_KHZ; + break; + + case 44100: + pmic_device->sample_rate = STDAC_RATE_44_1_KHZ; + break; + + case 48000: + pmic_device->sample_rate = STDAC_RATE_48_KHZ; + break; + + case 64000: + pmic_device->sample_rate = STDAC_RATE_64_KHZ; + break; + + case 96000: + pmic_device->sample_rate = STDAC_RATE_96_KHZ; + break; + + default: + pmic_device->sample_rate = STDAC_RATE_8_KHZ; + } + } + +} + +/*! + * This function configures number of channels for next audio operation + * (recording/playback) Number of channels define if sound is stereo + * or mono. + * + * @param substream pointer to the structure of the current stream. + * + */ +void set_pmic_channels(struct snd_pcm_substream *substream) +{ + mxc_pmic_audio_t *chip; + audio_stream_t *s; + struct snd_pcm_runtime *runtime; + int device = -1, stream_id = -1; + + chip = snd_pcm_substream_chip(substream); + device = substream->pcm->device; + + if (device == 0) { + if (substream->pstr->stream == 1) { + stream_id = 1; + } else { + stream_id = 0; + } + } else { + stream_id = 2; + } + s = &chip->s[stream_id]; + runtime = substream->runtime; + + if (runtime->channels == 2) { + ssi_tx_mask_time_slot(s->ssi, MASK_2_TS); + ssi_rx_mask_time_slot(s->ssi, MASK_1_TS_REC); + } else { + if (stream_id == 2) { +#ifdef CONFIG_MXC_PMIC_SC55112 + ssi_tx_mask_time_slot(s->ssi, MASK_1_TS_REC); +#else + + if (audio_mixer_control.mixing_active == 1) + ssi_tx_mask_time_slot(s->ssi, MASK_1_TS_MIX); + else + ssi_tx_mask_time_slot(s->ssi, MASK_1_TS); + +#endif + } else { + + ssi_tx_mask_time_slot(s->ssi, MASK_1_TS_STDAC); + } +#ifndef CONFIG_SND_MXC_PLAYBACK_MIXING + ssi_rx_mask_time_slot(s->ssi, MASK_1_TS_REC); +#endif + + } + +} + +/*! + * This function sets the input device in PMIC. It takes an + * ALSA value and modifies registers using pmic-specific values. + * + * @param handle Handle to the PMIC device opened + * @param val ALSA value. This value defines the input device that + * PMIC should activate to get audio signal (recording) + * @param enable Whether to enable or diable the input + */ +int set_mixer_input_device(PMIC_AUDIO_HANDLE handle, INPUT_DEVICES dev, + bool enable) +{ + + if (down_interruptible(&audio_mixer_control.sem)) + return -EINTR; + if (handle != NULL) { + if (audio_mixer_control.input_device & SOUND_MASK_PHONEIN) { + pmic_audio_vcodec_set_mic(handle, MIC1_LEFT, + MIC1_RIGHT_MIC_MONO); + pmic_audio_vcodec_enable_micbias(handle, MIC_BIAS1); + } else { + pmic_audio_vcodec_set_mic_on_off(handle, + MIC1_LEFT, + MIC1_RIGHT_MIC_MONO); + pmic_audio_vcodec_disable_micbias(handle, MIC_BIAS1); + } + if (audio_mixer_control.input_device & SOUND_MASK_MIC) { + pmic_audio_vcodec_set_mic(handle, NO_MIC, MIC2_AUX); + pmic_audio_vcodec_enable_micbias(handle, MIC_BIAS2); + } else { + pmic_audio_vcodec_set_mic_on_off(handle, NO_MIC, + MIC2_AUX); + pmic_audio_vcodec_disable_micbias(handle, MIC_BIAS2); + } + if (audio_mixer_control.input_device & SOUND_MASK_LINE) { + pmic_audio_vcodec_set_mic(handle, NO_MIC, TXIN_EXT); + } else { + pmic_audio_vcodec_set_mic_on_off(handle, NO_MIC, + TXIN_EXT); + } + up(&audio_mixer_control.sem); + return 0; + + } + switch (dev) { + case IP_HANDSET: + pr_debug("Input: SOUND_MASK_PHONEIN \n"); + if (handle == NULL) { + if (enable) { + if (audio_mixer_control.codec_capture_active) { + handle = + audio_mixer_control. + voice_codec_handle; + pmic_audio_vcodec_set_mic(handle, + MIC1_LEFT, + MIC1_RIGHT_MIC_MONO); + pmic_audio_vcodec_enable_micbias(handle, + MIC_BIAS1); + } + audio_mixer_control.input_device |= + SOUND_MASK_PHONEIN; + } else { + if (audio_mixer_control.codec_capture_active) { + handle = + audio_mixer_control. + voice_codec_handle; + pmic_audio_vcodec_set_mic_on_off(handle, + MIC1_LEFT, + MIC1_RIGHT_MIC_MONO); + pmic_audio_vcodec_disable_micbias + (handle, MIC_BIAS1); + } + audio_mixer_control.input_device &= + ~SOUND_MASK_PHONEIN; + } + } + break; + + case IP_HEADSET: + if (handle == NULL) { + if (enable) { + if (audio_mixer_control.codec_capture_active) { + handle = + audio_mixer_control. + voice_codec_handle; + pmic_audio_vcodec_set_mic(handle, + NO_MIC, + MIC2_AUX); + pmic_audio_vcodec_enable_micbias(handle, + MIC_BIAS2); + } + audio_mixer_control.input_device |= + SOUND_MASK_MIC; + } else { + if (audio_mixer_control.codec_capture_active) { + handle = + audio_mixer_control. + voice_codec_handle; + pmic_audio_vcodec_set_mic_on_off(handle, + NO_MIC, + MIC2_AUX); + pmic_audio_vcodec_disable_micbias + (handle, MIC_BIAS2); + } + audio_mixer_control.input_device &= + ~SOUND_MASK_MIC; + } + /* Enable Mic with MIC2_AUX */ + } + break; + + case IP_LINEIN: + if (handle == NULL) { + if (enable) { + if (audio_mixer_control.codec_capture_active) { + handle = + audio_mixer_control. + voice_codec_handle; + pmic_audio_vcodec_set_mic(handle, + NO_MIC, + TXIN_EXT); + } + audio_mixer_control.input_device |= + SOUND_MASK_LINE; + } else { + if (audio_mixer_control.codec_capture_active) { + handle = + audio_mixer_control. + voice_codec_handle; + pmic_audio_vcodec_set_mic_on_off(handle, + NO_MIC, + TXIN_EXT); + } + audio_mixer_control.input_device &= + ~SOUND_MASK_LINE; + } + } + break; + + default: + up(&audio_mixer_control.sem); + return -1; + break; + } + up(&audio_mixer_control.sem); + return 0; +} + +EXPORT_SYMBOL(set_mixer_input_device); + +int get_mixer_input_device() +{ + int val; + val = audio_mixer_control.input_device; + return val; +} + +EXPORT_SYMBOL(get_mixer_input_device); + +/*! + * This function sets the PMIC input device's gain. + * Note that the gain is the input volume + * + * @param handle Handle to the opened PMIC device + * @param val gain to be applied. This value can go + * from 0 (mute) to 100 (max gain) + */ +int set_mixer_input_gain(PMIC_AUDIO_HANDLE handle, int val) +{ + int leftdb, rightdb; + int left, right; + + left = (val & 0x00ff); + right = ((val & 0xff00) >> 8); + if (down_interruptible(&audio_mixer_control.sem)) + return -EINTR; + leftdb = (left * PMIC_INPUT_VOLUME_MAX) / INPUT_VOLUME_MAX; + rightdb = (right * PMIC_INPUT_VOLUME_MAX) / INPUT_VOLUME_MAX; + audio_mixer_control.input_volume = val; + if (audio_mixer_control.voice_codec_handle == handle) { + pmic_audio_vcodec_set_record_gain(handle, VOLTAGE_TO_VOLTAGE, + leftdb, VOLTAGE_TO_VOLTAGE, + rightdb); + } else if ((handle == NULL) + && (audio_mixer_control.codec_capture_active)) { + pmic_audio_vcodec_set_record_gain(audio_mixer_control. + voice_codec_handle, + VOLTAGE_TO_VOLTAGE, leftdb, + VOLTAGE_TO_VOLTAGE, rightdb); + } + up(&audio_mixer_control.sem); + return 0; +} + +EXPORT_SYMBOL(set_mixer_input_gain); + +int get_mixer_input_gain() +{ + int val; + val = audio_mixer_control.input_volume; + return val; +} + +EXPORT_SYMBOL(get_mixer_input_gain); + +/*! + * This function sets the PMIC output device's volume. + * + * @param handle Handle to the PMIC device opened + * @param volume ALSA value. This value defines the playback volume + * @param dev which output device gets affected by this volume + * + */ + +int set_mixer_output_volume(PMIC_AUDIO_HANDLE handle, int volume, + OUTPUT_DEVICES dev) +{ + int leftdb, rightdb; + int right, left; + + if (down_interruptible(&audio_mixer_control.sem)) + return -EINTR; + left = (volume & 0x00ff); + right = ((volume & 0xff00) >> 8); + + leftdb = (left * PMIC_OUTPUT_VOLUME_MAX) / OUTPUT_VOLUME_MAX; + rightdb = (right * PMIC_OUTPUT_VOLUME_MAX) / OUTPUT_VOLUME_MAX; + if (handle == NULL) { + /* Invoked by mixer */ + audio_mixer_control.master_volume_out = volume; + if (audio_mixer_control.codec_playback_active) + pmic_audio_output_set_pgaGain(audio_mixer_control. + voice_codec_handle, + rightdb); + if (audio_mixer_control.stdac_playback_active) + pmic_audio_output_set_pgaGain(audio_mixer_control. + stdac_handle, rightdb); + + } else { + /* change the required volume */ + audio_mixer_control.master_volume_out = volume; + pmic_audio_output_set_pgaGain(handle, rightdb); + } + up(&audio_mixer_control.sem); + return 0; +} + +EXPORT_SYMBOL(set_mixer_output_volume); + +int get_mixer_output_volume() +{ + int val; + val = audio_mixer_control.master_volume_out; + return val; +} + +EXPORT_SYMBOL(get_mixer_output_volume); + +/*! + * This function sets the PMIC output device's balance. + * + * @param bal Balance to be applied. This value can go + * from 0 (Left atten) to 100 (Right atten) + * 50 is both equal + */ +int set_mixer_output_balance(int bal) +{ + int channel = 0; + PMIC_AUDIO_OUTPUT_BALANCE_GAIN b_gain; + PMIC_AUDIO_HANDLE handle; + if (down_interruptible(&audio_mixer_control.sem)) + return -EINTR; + /* Convert ALSA value to PMIC value i.e. atten and channel value */ + if (bal < 0) + bal = 0; + if (bal > 100) + bal = 100; + if (bal < 50) { + channel = 1; + } else { + bal = 100 - bal; + channel = 0; + } + + b_gain = bal / 8; + + audio_mixer_control.mixer_balance = bal; + if (audio_mixer_control.codec_playback_active) { + handle = audio_mixer_control.voice_codec_handle; + /* Use codec's handle to set balance */ + } else if (audio_mixer_control.stdac_playback_active) { + handle = audio_mixer_control.stdac_handle; + /* Use STDac's handle to set balance */ + } else { + up(&audio_mixer_control.sem); + return 0; + } + if (channel == 0) + pmic_audio_output_set_balance(handle, BAL_GAIN_0DB, b_gain); + else + pmic_audio_output_set_balance(handle, b_gain, BAL_GAIN_0DB); + up(&audio_mixer_control.sem); + return 0; +} + +EXPORT_SYMBOL(set_mixer_output_balance); + +int get_mixer_output_balance() +{ + int val; + val = audio_mixer_control.mixer_balance; + return val; +} + +EXPORT_SYMBOL(get_mixer_output_balance); + +/*! + * This function sets the PMIC output device's mono adder config. + * + * @param mode Mono adder mode to be set + */ +int set_mixer_output_mono_adder(PMIC_AUDIO_MONO_ADDER_MODE mode) +{ + PMIC_AUDIO_HANDLE handle; + if (down_interruptible(&audio_mixer_control.sem)) + return -EINTR; + audio_mixer_control.mixer_mono_adder = mode; + if (audio_mixer_control.codec_playback_active) { + handle = audio_mixer_control.voice_codec_handle; + /* Use codec's handle to set balance */ + pmic_audio_output_enable_mono_adder(audio_mixer_control. + voice_codec_handle, mode); + } else if (audio_mixer_control.stdac_playback_active) { + handle = audio_mixer_control.stdac_handle; + pmic_audio_output_enable_mono_adder(audio_mixer_control. + stdac_handle, mode); + /* Use STDac's handle to set balance */ + } + up(&audio_mixer_control.sem); + return 0; +} + +EXPORT_SYMBOL(set_mixer_output_mono_adder); + +int get_mixer_output_mono_adder() +{ + int val; + val = audio_mixer_control.mixer_mono_adder; + return val; +} + +EXPORT_SYMBOL(get_mixer_output_mono_adder); + +/*! + * This function sets the output device(s) in PMIC. It takes an + * ALSA value and modifies registers using PMIC-specific values. + * + * @param handle handle to the device already opened + * @param src Source connected to o/p device + * @param dev Output device to be enabled + * @param enable Enable or disable the device + * + */ +int set_mixer_output_device(PMIC_AUDIO_HANDLE handle, OUTPUT_SOURCE src, + OUTPUT_DEVICES dev, bool enable) +{ + PMIC_AUDIO_OUTPUT_PORT port; + if (down_interruptible(&audio_mixer_control.sem)) + return -EINTR; + if (!((src == CODEC_DIR_OUT) || (src == MIXER_OUT))) { + up(&audio_mixer_control.sem); + return -1; + } + if (handle != (PMIC_AUDIO_HANDLE) NULL) { + /* Invoked by playback stream */ + if (audio_mixer_control.output_device & SOUND_MASK_PHONEOUT) { + audio_mixer_control.output_active[OP_EARPIECE] = 1; + pmic_audio_output_set_port(handle, MONO_SPEAKER); + } else { + audio_mixer_control.output_active[OP_EARPIECE] = 0; + pmic_audio_output_clear_port(handle, MONO_SPEAKER); + } + if (audio_mixer_control.output_device & SOUND_MASK_SPEAKER) { + audio_mixer_control.output_active[OP_HANDSFREE] = 1; + pmic_audio_output_set_port(handle, MONO_LOUDSPEAKER); + } else { + audio_mixer_control.output_active[OP_HANDSFREE] = 0; + pmic_audio_output_clear_port(handle, MONO_LOUDSPEAKER); + } + if (audio_mixer_control.output_device & SOUND_MASK_VOLUME) { + audio_mixer_control.output_active[OP_HEADSET] = 1; + if (dev != OP_MONO) { + pmic_audio_output_set_port(handle, + STEREO_HEADSET_LEFT | + STEREO_HEADSET_RIGHT); + } else { + pmic_audio_output_set_port(handle, + STEREO_HEADSET_LEFT); + /*This is a temporary workaround which should be removed later */ + } + + } else { + audio_mixer_control.output_active[OP_HEADSET] = 0; + pmic_audio_output_clear_port(handle, + STEREO_HEADSET_LEFT | + STEREO_HEADSET_RIGHT); + } + if (audio_mixer_control.output_device & SOUND_MASK_PCM) { + audio_mixer_control.output_active[OP_LINEOUT] = 1; + pmic_audio_output_set_port(handle, + STEREO_OUT_LEFT | + STEREO_OUT_RIGHT); + } else { + audio_mixer_control.output_active[OP_LINEOUT] = 0; + pmic_audio_output_clear_port(handle, + STEREO_OUT_LEFT | + STEREO_OUT_RIGHT); + } + } else { + switch (dev) { + case OP_EARPIECE: + if (enable) { + audio_mixer_control.output_device |= + SOUND_MASK_PHONEOUT; + audio_mixer_control.source_for_output[dev] = + src; + } else { + audio_mixer_control.output_device &= + ~SOUND_MASK_PHONEOUT; + } + port = MONO_SPEAKER; + break; + case OP_HANDSFREE: + if (enable) { + audio_mixer_control.output_device |= + SOUND_MASK_SPEAKER; + audio_mixer_control.source_for_output[dev] = + src; + } else { + audio_mixer_control.output_device &= + ~SOUND_MASK_SPEAKER; + } + port = MONO_LOUDSPEAKER; + break; + case OP_HEADSET: + if (enable) { + audio_mixer_control.output_device |= + SOUND_MASK_VOLUME; + audio_mixer_control.source_for_output[dev] = + src; + } else { + audio_mixer_control.output_device &= + ~SOUND_MASK_VOLUME; + } + port = STEREO_HEADSET_LEFT | STEREO_HEADSET_RIGHT; + break; + case OP_MONO: + /*This is a temporary workaround which should be removed later */ + if (enable) { + audio_mixer_control.output_device |= + SOUND_MASK_VOLUME; + audio_mixer_control.source_for_output[dev] = + src; + } else { + audio_mixer_control.output_device &= + ~SOUND_MASK_VOLUME; + } + port = STEREO_HEADSET_LEFT; + break; + case OP_LINEOUT: + if (enable) { + audio_mixer_control.output_device |= + SOUND_MASK_PCM; + audio_mixer_control.source_for_output[dev] = + src; + } else { + audio_mixer_control.output_device &= + ~SOUND_MASK_PCM; + } + port = STEREO_OUT_LEFT | STEREO_OUT_RIGHT; + break; + default: + up(&audio_mixer_control.sem); + return -1; + break; + } + /* Invoked by mixer .. little tricky to handle over here */ + if (audio_mixer_control.codec_playback_active) { + if (enable) { + audio_mixer_control.output_active[dev] = 1; + pmic_audio_output_set_port(audio_mixer_control. + voice_codec_handle, + port); + } else { + audio_mixer_control.output_active[dev] = 0; + pmic_audio_output_clear_port + (audio_mixer_control.voice_codec_handle, + port); + } + } + if (audio_mixer_control.stdac_playback_active) { + if (enable) { + audio_mixer_control.output_active[dev] = 1; + pmic_audio_output_set_port(audio_mixer_control. + stdac_handle, port); + } else { + audio_mixer_control.output_active[dev] = 0; + pmic_audio_output_clear_port + (audio_mixer_control.stdac_handle, port); + } + } + + } + up(&audio_mixer_control.sem); + return 0; + /* Set O/P device with handle and port */ + +} + +EXPORT_SYMBOL(set_mixer_output_device); + +int get_mixer_output_device() +{ + int val; + val = audio_mixer_control.output_device; + return val; +} + +EXPORT_SYMBOL(get_mixer_output_device); + +/*! + * This function configures the CODEC for playback/recording. + * + * main configured elements are: + * - audio path on PMIC + * - external clock to generate BC and FS clocks + * - PMIC mode (master or slave) + * - protocol + * - sample rate + * + * @param substream pointer to the structure of the current stream. + * @param stream_id index into the audio_stream array. + */ +void configure_codec(struct snd_pcm_substream *substream, int stream_id) +{ + mxc_pmic_audio_t *chip; + audio_stream_t *s; + pmic_audio_device_t *pmic; + PMIC_AUDIO_HANDLE handle; + int ssi_bus; + + chip = snd_pcm_substream_chip(substream); + s = &chip->s[stream_id]; + pmic = &s->pmic_audio_device; + handle = audio_mixer_control.voice_codec_handle; + + ssi_bus = (pmic->ssi == SSI1) ? AUDIO_DATA_BUS_1 : AUDIO_DATA_BUS_2; + + pmic_audio_vcodec_set_rxtx_timeslot(handle, USE_TS0); + pmic_audio_vcodec_enable_mixer(handle, USE_TS1, VCODEC_MIX_IN_0DB, + VCODEC_MIX_OUT_0DB); + pmic_audio_set_protocol(handle, ssi_bus, pmic->protocol, pmic->mode, + USE_4_TIMESLOTS); + + msleep(20); + pmic_audio_vcodec_set_clock(handle, pmic->pll, pmic->pll_rate, + pmic->sample_rate, NO_INVERT); + msleep(20); + pmic_audio_vcodec_set_config(handle, VCODEC_MASTER_CLOCK_OUTPUTS); + pmic_audio_digital_filter_reset(handle); + msleep(15); + if (stream_id == 2) { + pmic_audio_output_enable_mixer(handle); + set_mixer_output_device(handle, MIXER_OUT, OP_NODEV, 1); + set_mixer_output_volume(handle, + audio_mixer_control.master_volume_out, + OP_HEADSET); + } else { + set_mixer_input_device(handle, IP_NODEV, 1); + set_mixer_input_gain(handle, audio_mixer_control.input_volume); + } + pmic_audio_enable(handle); +} + +/*! + * This function configures the STEREODAC for playback/recording. + * + * main configured elements are: + * - audio path on PMIC + * - external clock to generate BC and FS clocks + * - PMIC mode (master or slave) + * - protocol + * - sample rate + * + * @param substream pointer to the structure of the current stream. + */ +void configure_stereodac(struct snd_pcm_substream *substream) +{ + mxc_pmic_audio_t *chip; + int stream_id; + audio_stream_t *s; + pmic_audio_device_t *pmic; + int ssi_bus; + PMIC_AUDIO_HANDLE handle; + struct snd_pcm_runtime *runtime; + + chip = snd_pcm_substream_chip(substream); + stream_id = substream->pstr->stream; + s = &chip->s[stream_id]; + pmic = &s->pmic_audio_device; + handle = pmic->handle; + runtime = substream->runtime; + + if (runtime->channels == 1) { + audio_mixer_control.mixer_mono_adder = MONO_ADD_LEFT_RIGHT; + } else { + audio_mixer_control.mixer_mono_adder = MONO_ADDER_OFF; + } + + ssi_bus = (pmic->ssi == SSI1) ? AUDIO_DATA_BUS_1 : AUDIO_DATA_BUS_2; + pmic_audio_stdac_set_rxtx_timeslot(handle, USE_TS0_TS1); + pmic_audio_stdac_enable_mixer(handle, USE_TS2_TS3, STDAC_NO_MIX, + STDAC_MIX_OUT_0DB); +#ifdef CONFIG_MXC_PMIC_SC55112 + pmic_audio_set_protocol(handle, ssi_bus, pmic->protocol, pmic->mode, + USE_4_TIMESLOTS); +#else + pmic_audio_set_protocol(handle, ssi_bus, pmic->protocol, pmic->mode, + USE_2_TIMESLOTS); +#endif + pmic_audio_stdac_set_clock(handle, pmic->pll, pmic->pll_rate, + pmic->sample_rate, NO_INVERT); + + pmic_audio_stdac_set_config(handle, STDAC_MASTER_CLOCK_OUTPUTS); + pmic_audio_output_enable_mixer(handle); + audio_mixer_control.stdac_out_to_mixer = 1; + pmic_audio_digital_filter_reset(handle); + msleep(10); + pmic_audio_output_enable_phantom_ground(); + set_mixer_output_volume(handle, audio_mixer_control.master_volume_out, + OP_HEADSET); + pmic_audio_output_enable_mono_adder(handle, + audio_mixer_control. + mixer_mono_adder); +#ifdef CONFIG_HEADSET_DETECT_ENABLE + set_mixer_output_device(handle, MIXER_OUT, OP_MONO, 1); +#else + set_mixer_output_device(handle, MIXER_OUT, OP_NODEV, 1); +#endif + pmic_audio_enable(handle); + +} + +/*! + * This function disables CODEC's amplifiers, volume and clock. + * @param handle Handle of voice codec + */ + +void disable_codec(PMIC_AUDIO_HANDLE handle) +{ + pmic_audio_disable(handle); + pmic_audio_vcodec_clear_config(handle, VCODEC_MASTER_CLOCK_OUTPUTS); +} + +/*! + * This function disables STEREODAC's amplifiers, volume and clock. + * @param handle Handle of STdac + * @param + */ + +void disable_stereodac(void) +{ + + audio_mixer_control.stdac_out_to_mixer = 0; +} + +/*! + * This function configures PMIC for recording. + * + * @param substream pointer to the structure of the current stream. + * + * @return 0 on success, -1 otherwise. + */ +int configure_pmic_recording(struct snd_pcm_substream *substream) +{ + + configure_codec(substream, 1); + return 0; +} + +/*! + * This function configures PMIC for playing back. + * + * @param substream pointer to the structure of the current stream. + * @param stream_id Index into the audio_stream array . + * + * @return 0 on success, -1 otherwise. + */ + +int configure_pmic_playback(struct snd_pcm_substream *substream, int stream_id) +{ + if (stream_id == 0) { + configure_stereodac(substream); + } else if (stream_id == 2 || stream_id == 3) { + configure_codec(substream, stream_id); + } + return 0; +} + +/*! + * This function shutsdown the PMIC soundcard. + * Nothing to be done here + * + * @param mxc_audio pointer to the sound card structure. + * + * @return + */ +/* +static void mxc_pmic_audio_shutdown(mxc_pmic_audio_t * mxc_audio) +{ + +} +*/ + +/*! + * This function configures the DMA channel used to transfer + * audio from MCU to PMIC + * + * @param substream pointer to the structure of the current stream. + * @param callback pointer to function that will be + * called when a SDMA TX transfer finishes. + * + * @return 0 on success, -1 otherwise. + */ +static int +configure_write_channel(audio_stream_t *s, mxc_dma_callback_t callback, + int stream_id) +{ + int ret = -1; + int channel = -1; +#ifdef CONFIG_SND_MXC_PLAYBACK_MIXING + + int channel1 = -1; +#endif + + if (stream_id == 0) { + if (audio_data->ssi_num == 2) { + channel = + mxc_dma_request(MXC_DMA_SSI2_16BIT_TX0, + "ALSA TX DMA"); + ret = + mxc_dma_callback_set(channel, + (mxc_dma_callback_t) callback, + (void *)s); + if (ret != 0) { + mxc_dma_free(channel); + return -1; + } + s->dma_wchannel = channel; + + } else { + channel = + mxc_dma_request(MXC_DMA_SSI1_16BIT_TX0, + "ALSA TX DMA"); + ret = + mxc_dma_callback_set(channel, + (mxc_dma_callback_t) callback, + (void *)s); + if (ret != 0) { + mxc_dma_free(channel); + return -1; + } + s->dma_wchannel = channel; + } + + } + if (stream_id == 3) { + channel = + mxc_dma_request(MXC_DMA_SSI1_16BIT_TX0, "ALSA TX DMA"); + if (channel < 0) { + pr_debug("error requesting a write dma channel\n"); + return -1; + } + ret = + mxc_dma_callback_set(channel, (mxc_dma_callback_t) callback, + (void *)s); + if (ret != 0) { + mxc_dma_free(channel); + + return -1; + } + s->dma_wchannel = channel; + } +#ifdef CONFIG_SND_MXC_PLAYBACK_MIXING + else if (stream_id == 2) { + channel1 = + mxc_dma_request(MXC_DMA_SSI1_16BIT_TX1, "ALSA TX DMA"); + ret = + mxc_dma_callback_set(channel1, + (mxc_dma_callback_t) callback, + (void *)s); + if (ret != 0) { + mxc_dma_free(channel1); + return -1; + } + s->dma_wchannel = channel1; + } +#else + + if (stream_id == 2) { + channel = + mxc_dma_request(MXC_DMA_SSI1_16BIT_TX0, "ALSA TX DMA"); + ret = + mxc_dma_callback_set(channel, (mxc_dma_callback_t) callback, + (void *)s); + if (ret != 0) { + mxc_dma_free(channel); + return -1; + } + s->dma_wchannel = channel; + } +#endif + /*if (channel < 0) { + pr_debug("error requesting a write dma channel\n"); + return -1; + } */ + + return 0; +} + +/*! + * This function configures the DMA channel used to transfer + * audio from PMIC to MCU + * + * @param substream pointer to the structure of the current stream. + * @param callback pointer to function that will be + * called when a SDMA RX transfer finishes. + * + * @return 0 on success, -1 otherwise. + */ +static int configure_read_channel(audio_stream_t *s, + mxc_dma_callback_t callback) +{ + int ret = -1; + int channel = -1; + + channel = mxc_dma_request(MXC_DMA_SSI1_16BIT_RX0, "ALSA RX DMA"); + if (channel < 0) { + pr_debug("error requesting a read dma channel\n"); + return -1; + } + + ret = + mxc_dma_callback_set(channel, (mxc_dma_callback_t) callback, + (void *)s); + if (ret != 0) { + mxc_dma_free(channel); + return -1; + } + s->dma_wchannel = channel; + + return 0; +} + +/*! + * This function frees the stream structure + * + * @param s pointer to the structure of the current stream. + */ +static void audio_dma_free(audio_stream_t *s) +{ + /* + * There is nothing to be done here since the dma channel has been + * freed either in the callback or in the stop method + */ + +} + +/*! + * This function gets the dma pointer position during record. + * Our DMA implementation does not allow to retrieve this position + * when a transfert is active, so, it answers the middle of + * the current period beeing transfered + * + * @param s pointer to the structure of the current stream. + * + */ +static u_int audio_get_capture_dma_pos(audio_stream_t *s) +{ + struct snd_pcm_substream *substream; + struct snd_pcm_runtime *runtime; + unsigned int offset; + + substream = s->stream; + runtime = substream->runtime; + offset = 0; + + /* tx_spin value is used here to check if a transfert is active */ + if (s->tx_spin) { + offset = (runtime->period_size * (s->periods)) + 0; + if (offset >= runtime->buffer_size) + offset = 0; + pr_debug("MXC: audio_get_dma_pos offset %d\n", offset); + } else { + offset = (runtime->period_size * (s->periods)); + if (offset >= runtime->buffer_size) + offset = 0; + pr_debug("MXC: audio_get_dma_pos BIS offset %d\n", offset); + } + + return offset; +} + +/*! + * This function gets the dma pointer position during playback. + * Our DMA implementation does not allow to retrieve this position + * when a transfert is active, so, it answers the middle of + * the current period beeing transfered + * + * @param s pointer to the structure of the current stream. + * + */ +static u_int audio_get_playback_dma_pos(audio_stream_t *s) +{ + struct snd_pcm_substream *substream; + struct snd_pcm_runtime *runtime; + unsigned int offset; + + substream = s->stream; + runtime = substream->runtime; + offset = 0; + + /* tx_spin value is used here to check if a transfert is active */ + if (s->tx_spin) { + offset = (runtime->period_size * (s->periods)) + 0; + if (offset >= runtime->buffer_size) + offset = 0; + pr_debug("MXC: audio_get_dma_pos offset %d\n", offset); + } else { + offset = (runtime->period_size * (s->periods)); + if (offset >= runtime->buffer_size) + offset = 0; + pr_debug("MXC: audio_get_dma_pos BIS offset %d\n", offset); + } + + return offset; +} + +/*! + * This function is called whenever a new audio block needs to be + * transferred to PMIC. The function receives the address and the size + * of the new block and start a new DMA transfer. + * + * @param substream pointer to the structure of the current stream. + * + */ +static void audio_playback_dma(audio_stream_t *s) +{ + struct snd_pcm_substream *substream; + struct snd_pcm_runtime *runtime; + unsigned int dma_size = 0; + unsigned int offset; + int ret = 0; + mxc_dma_requestbuf_t dma_request; +#ifdef CONFIG_SND_MXC_PLAYBACK_MIXING + unsigned int dma_size_mix = 0, offset_mix; + mxc_dma_requestbuf_t dma_request_mix; + int ret1 = 0; +#endif + int device; + int stream_id; + + substream = s->stream; + runtime = substream->runtime; + device = substream->pcm->device; + if (device == 0) { + stream_id = 0; + } else if (device == 1) { + stream_id = 2; + } else { + stream_id = 3; + } + + pr_debug("\nDMA direction %d\(0 is playback 1 is capture)\n", + s->stream_id); + +#ifndef CONFIG_SND_MXC_PLAYBACK_MIXING + memset(&dma_request, 0, sizeof(mxc_dma_requestbuf_t)); + +#else + if (stream_id == 2) { + memset(&dma_request, 0, sizeof(mxc_dma_requestbuf_t)); + } else if (stream_id == 3) { + memset(&dma_request_mix, 0, sizeof(mxc_dma_requestbuf_t)); + } +#endif + if (s->active) { + if (ssi_get_status(s->ssi) & (ssi_transmitter_underrun_0)) { + ssi_enable(s->ssi, false); + ssi_transmit_enable(s->ssi, false); + ssi_enable(s->ssi, true); + } +#ifndef CONFIG_SND_MXC_PLAYBACK_MIXING + + dma_size = frames_to_bytes(runtime, runtime->period_size); + pr_debug("s->period (%x) runtime->periods (%d)\n", + s->period, runtime->periods); + pr_debug("runtime->period_size (%d) dma_size (%d)\n", + (unsigned int)runtime->period_size, + runtime->dma_bytes); + + offset = dma_size * s->period; + if (snd_BUG_ON(dma_size > DMA_BUF_SIZE)) + return; +#ifdef CONFIG_SND_MXC_PMIC_IRAM + + if (g_audio_iram_en && stream_id == 0) { + dma_request.src_addr = ADMA_BASE_PADDR + offset; + } else +#endif /*CONFIG_SND_MXC_PMIC_IRAM */ + { + + dma_request.src_addr = + (dma_addr_t) (dma_map_single + (NULL, runtime->dma_area + offset, + dma_size, DMA_TO_DEVICE)); + } + if (stream_id == 0) { + dma_request.dst_addr = + (dma_addr_t) get_ssi_fifo_addr(s->ssi, 1); + } else if (stream_id == 2) { + dma_request.dst_addr = + (dma_addr_t) get_ssi_fifo_addr(s->ssi, 1); + } + dma_request.num_of_bytes = dma_size; + pr_debug("MXC: Start DMA offset (%d) size (%d)\n", + offset, runtime->dma_bytes); + + mxc_dma_config(s->dma_wchannel, &dma_request, 1, + MXC_DMA_MODE_WRITE); + ret = mxc_dma_enable(s->dma_wchannel); + ssi_transmit_enable(s->ssi, true); + s->tx_spin = 1; /* FGA little trick to retrieve DMA pos */ + + if (ret) { + pr_debug("audio_process_dma: cannot queue DMA buffer\ + (%i)\n", ret); + return; + } + s->period++; + s->period %= runtime->periods; +#else + + if (stream_id == 2) { + dma_size = + frames_to_bytes(runtime, runtime->period_size); + pr_debug("s->period (%x) runtime->periods (%d)\n", + s->period, runtime->periods); + pr_debug("runtime->period_size (%d) dma_size (%d)\n", + (unsigned int)runtime->period_size, + runtime->dma_bytes); + + offset = dma_size * s->period; + if (snd_BUG_ON(dma_size > DMA_BUF_SIZE)) + return; + + dma_request.src_addr = + (dma_addr_t) (dma_map_single + (NULL, runtime->dma_area + offset, + dma_size, DMA_TO_DEVICE)); + dma_request.dst_addr = + (dma_addr_t) get_ssi_fifo_addr(s->ssi, 1); + dma_request.num_of_bytes = dma_size; + pr_debug("MXC: Start DMA offset (%d) size (%d)\n", + offset, runtime->dma_bytes); + + mxc_dma_config(s->dma_wchannel, &dma_request, 1, + MXC_DMA_MODE_WRITE); + ret = mxc_dma_enable(s->dma_wchannel); + ssi_transmit_enable(s->ssi, true); + s->tx_spin = 1; /* FGA little trick to retrieve DMA pos */ + + if (ret) { + pr_debug("audio_process_dma: cannot queue DMA buffer\ + (%i)\n", + ret); + return; + } + s->period++; + s->period %= runtime->periods; + + } else if (stream_id == 3) { + + dma_size_mix = + frames_to_bytes(runtime, runtime->period_size); + pr_debug("s->period (%x) runtime->periods (%d)\n", + s->period, runtime->periods); + pr_debug("runtime->period_size (%d) dma_size (%d)\n", + (unsigned int)runtime->period_size, + runtime->dma_bytes); + + offset_mix = dma_size_mix * s->period; + if (snd_BUG_ON(dma_size_mix > DMA_BUF_SIZE)) + return; + dma_request_mix.src_addr = + (dma_addr_t) (dma_map_single + (NULL, runtime->dma_area + offset_mix, + dma_size_mix, DMA_TO_DEVICE)); + dma_request_mix.dst_addr = + (dma_addr_t) get_ssi_fifo_addr(s->ssi, 1); + dma_request_mix.num_of_bytes = dma_size_mix; + + pr_debug("MXC: Start DMA offset (%d) size (%d)\n", + offset_mix, runtime->dma_bytes); + + mxc_dma_config(s->dma_wchannel, &dma_request_mix, 1, + MXC_DMA_MODE_WRITE); + ret1 = mxc_dma_enable(s->dma_wchannel); + ssi_transmit_enable(s->ssi, true); + s->tx_spin = 1; /* FGA little trick to retrieve DMA pos */ + + if (ret1) { + pr_debug("audio_process_dma: cannot queue DMA buffer\ + (%i)\n", + ret1); + return; + } + s->period++; + s->period %= runtime->periods; + + } +#endif +#ifdef MXC_SOUND_PLAYBACK_CHAIN_DMA_EN + + if ((s->period > s->periods) && ((s->period - s->periods) > 1)) { + pr_debug + ("audio playback chain dma: already double buffered\n"); + return; + } + + if ((s->period < s->periods) + && ((s->period + runtime->periods - s->periods) > 1)) { + pr_debug + ("audio playback chain dma: already double buffered\n"); + return; + } + + if (s->period == s->periods) { + pr_debug + ("audio playback chain dma: s->period == s->periods\n"); + return; + } + + if (snd_pcm_playback_hw_avail(runtime) < + 2 * runtime->period_size) { + pr_debug + ("audio playback chain dma: available data is not enough\n"); + return; + } + + pr_debug + ("audio playback chain dma:to set up the 2nd dma buffer\n"); + +#ifndef CONFIG_SND_MXC_PLAYBACK_MIXING + offset = dma_size * s->period; +#ifdef CONFIG_SND_MXC_PMIC_IRAM + if (g_audio_iram_en && stream_id == 0) { + dma_request.src_addr = ADMA_BASE_PADDR + offset; + } else +#endif /*CONFIG_SND_MXC_PMIC_IRAM */ + { + + dma_request.src_addr = + (dma_addr_t) (dma_map_single + (NULL, runtime->dma_area + offset, + dma_size, DMA_TO_DEVICE)); + } + mxc_dma_config(s->dma_wchannel, &dma_request, 1, + MXC_DMA_MODE_WRITE); +#else + if (stream_id == 3) { + offset_mix = dma_size_mix * s->period; + dma_request.src_addr = + (dma_addr_t) (dma_map_single + (NULL, + runtime->dma_area + offset_mix, + dma_size, DMA_TO_DEVICE)); + + mxc_dma_config(s->dma_wchannel, &dma_request_mix, 1, + MXC_DMA_MODE_WRITE); + } else { + offset = dma_size * s->period; + dma_request.src_addr = + (dma_addr_t) (dma_map_single + (NULL, + runtime->dma_area + offset, + dma_size, DMA_TO_DEVICE)); + + mxc_dma_config(s->dma_wchannel, &dma_request, 1, + MXC_DMA_MODE_WRITE); + } + +#endif + ret = mxc_dma_enable(s->dma_wchannel); + + s->period++; + s->period %= runtime->periods; +#endif /* MXC_SOUND_PLAYBACK_CHAIN_DMA_EN */ + } +} + +/*! + * This function is called whenever a new audio block needs to be + * transferred from PMIC. The function receives the address and the size + * of the block that will store the audio samples and start a new DMA transfer. + * + * @param substream pointer to the structure of the current stream. + * + */ +static void audio_capture_dma(audio_stream_t *s) +{ + struct snd_pcm_substream *substream; + struct snd_pcm_runtime *runtime; + unsigned int dma_size; + unsigned int offset; + int ret = 0; + mxc_dma_requestbuf_t dma_request; + + substream = s->stream; + runtime = substream->runtime; + + pr_debug("\nDMA direction %d\ + (0 is playback 1 is capture)\n", s->stream_id); + + memset(&dma_request, 0, sizeof(mxc_dma_requestbuf_t)); + + if (s->active) { + dma_size = frames_to_bytes(runtime, runtime->period_size); + pr_debug("s->period (%x) runtime->periods (%d)\n", + s->period, runtime->periods); + pr_debug("runtime->period_size (%d) dma_size (%d)\n", + (unsigned int)runtime->period_size, + runtime->dma_bytes); + + offset = dma_size * s->period; + snd_BUG_ON(dma_size > DMA_BUF_SIZE); + + dma_request.dst_addr = (dma_addr_t) (dma_map_single(NULL, + runtime-> + dma_area + + offset, + dma_size, + DMA_FROM_DEVICE)); + dma_request.src_addr = + (dma_addr_t) get_ssi_fifo_addr(s->ssi, 0); + dma_request.num_of_bytes = dma_size; + + pr_debug("MXC: Start DMA offset (%d) size (%d)\n", offset, + runtime->dma_bytes); + + mxc_dma_config(s->dma_wchannel, &dma_request, 1, + MXC_DMA_MODE_READ); + ret = mxc_dma_enable(s->dma_wchannel); + + s->tx_spin = 1; /* FGA little trick to retrieve DMA pos */ + + if (ret) { + pr_debug("audio_process_dma: cannot queue DMA buffer\ + (%i)\n", ret); + return; + } + s->period++; + s->period %= runtime->periods; + +#ifdef MXC_SOUND_CAPTURE_CHAIN_DMA_EN + if ((s->period > s->periods) && ((s->period - s->periods) > 1)) { + pr_debug + ("audio capture chain dma: already double buffered\n"); + return; + } + + if ((s->period < s->periods) + && ((s->period + runtime->periods - s->periods) > 1)) { + pr_debug + ("audio capture chain dma: already double buffered\n"); + return; + } + + if (s->period == s->periods) { + pr_debug + ("audio capture chain dma: s->period == s->periods\n"); + return; + } + + if (snd_pcm_capture_hw_avail(runtime) < + 2 * runtime->period_size) { + pr_debug + ("audio capture chain dma: available data is not enough\n"); + return; + } + + pr_debug + ("audio capture chain dma:to set up the 2nd dma buffer\n"); + offset = dma_size * s->period; + dma_request.dst_addr = (dma_addr_t) (dma_map_single(NULL, + runtime-> + dma_area + + offset, + dma_size, + DMA_FROM_DEVICE)); + mxc_dma_config(s->dma_wchannel, &dma_request, 1, + MXC_DMA_MODE_READ); + ret = mxc_dma_enable(s->dma_wchannel); + + s->period++; + s->period %= runtime->periods; +#endif /* MXC_SOUND_CAPTURE_CHAIN_DMA_EN */ + } +} + +/*! + * This is a callback which will be called + * when a TX transfer finishes. The call occurs + * in interrupt context. + * + * @param dat pointer to the structure of the current stream. + * + */ +static void audio_playback_dma_callback(void *data, int error, + unsigned int count) +{ + audio_stream_t *s; + struct snd_pcm_substream *substream; + struct snd_pcm_runtime *runtime; + unsigned int dma_size; + unsigned int previous_period; + unsigned int offset; + + s = data; + substream = s->stream; + runtime = substream->runtime; + previous_period = s->periods; + dma_size = frames_to_bytes(runtime, runtime->period_size); + offset = dma_size * previous_period; + + s->tx_spin = 0; + s->periods++; + s->periods %= runtime->periods; + + /* + * Give back to the CPU the access to the non cached memory + */ + dma_unmap_single(NULL, runtime->dma_addr + offset, dma_size, + DMA_TO_DEVICE); + + /* + * If we are getting a callback for an active stream then we inform + * the PCM middle layer we've finished a period + */ + if (s->active) + snd_pcm_period_elapsed(s->stream); + spin_lock(&s->dma_lock); + + /* + * Trig next DMA transfer + */ + audio_playback_dma(s); + + spin_unlock(&s->dma_lock); + +} + +/*! + * This is a callback which will be called + * when a RX transfer finishes. The call occurs + * in interrupt context. + * + * @param substream pointer to the structure of the current stream. + * + */ +static void audio_capture_dma_callback(void *data, int error, + unsigned int count) +{ + audio_stream_t *s; + struct snd_pcm_substream *substream; + struct snd_pcm_runtime *runtime; + unsigned int dma_size; + unsigned int previous_period; + unsigned int offset; + + s = data; + substream = s->stream; + runtime = substream->runtime; + previous_period = s->periods; + dma_size = frames_to_bytes(runtime, runtime->period_size); + offset = dma_size * previous_period; + + s->tx_spin = 0; + s->periods++; + s->periods %= runtime->periods; + + /* + * Give back to the CPU the access to the non cached memory + */ + dma_unmap_single(NULL, runtime->dma_addr + offset, dma_size, + DMA_FROM_DEVICE); + + /* + * If we are getting a callback for an active stream then we inform + * the PCM middle layer we've finished a period + */ + if (s->active) + snd_pcm_period_elapsed(s->stream); + + spin_lock(&s->dma_lock); + + /* + * Trig next DMA transfer + */ + audio_capture_dma(s); + + spin_unlock(&s->dma_lock); + +} + +/*! + * This function is a dispatcher of command to be executed + * by the driver for playback. + * + * @param substream pointer to the structure of the current stream. + * @param cmd command to be executed + * + * @return 0 on success, -1 otherwise. + */ +static int +snd_mxc_audio_playback_trigger(struct snd_pcm_substream *substream, int cmd) +{ + mxc_pmic_audio_t *chip; + int stream_id; + audio_stream_t *s; + int err; + int device; + device = substream->pcm->device; + if (device == 0) { + stream_id = 0; + } else if (device == 1) { + stream_id = 2; + } else { + stream_id = 3; + } + + chip = snd_pcm_substream_chip(substream); + + s = &chip->s[stream_id]; + err = 0; + + /* note local interrupts are already disabled in the midlevel code */ + spin_lock(&s->dma_lock); + switch (cmd) { + case SNDRV_PCM_TRIGGER_START: + case SNDRV_PCM_TRIGGER_RESUME: + case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: + s->tx_spin = 0; + s->active = 1; + audio_playback_dma(s); + break; + case SNDRV_PCM_TRIGGER_STOP: + case SNDRV_PCM_TRIGGER_SUSPEND: + case SNDRV_PCM_TRIGGER_PAUSE_PUSH: + s->active = 0; + break; + default: + err = -EINVAL; + break; + } + spin_unlock(&s->dma_lock); + return err; +} + +/*! + * This function is a dispatcher of command to be executed + * by the driver for capture. + * + * @param substream pointer to the structure of the current stream. + * @param cmd command to be executed + * + * @return 0 on success, -1 otherwise. + */ +static int +snd_mxc_audio_capture_trigger(struct snd_pcm_substream *substream, int cmd) +{ + mxc_pmic_audio_t *chip; + int stream_id; + audio_stream_t *s; + int err; + + chip = snd_pcm_substream_chip(substream); + stream_id = substream->pstr->stream; + s = &chip->s[stream_id]; + err = 0; + + /* note local interrupts are already disabled in the midlevel code */ + spin_lock(&s->dma_lock); + switch (cmd) { + case SNDRV_PCM_TRIGGER_START: + case SNDRV_PCM_TRIGGER_RESUME: + case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: + s->tx_spin = 0; + s->active = 1; + audio_capture_dma(s); + break; + case SNDRV_PCM_TRIGGER_STOP: + case SNDRV_PCM_TRIGGER_SUSPEND: + case SNDRV_PCM_TRIGGER_PAUSE_PUSH: + s->active = 0; + break; + default: + err = -EINVAL; + break; + } + spin_unlock(&s->dma_lock); + return err; +} + +/*! + * This function configures the hardware to allow audio + * playback operations. It is called by ALSA framework. + * + * @param substream pointer to the structure of the current stream. + * + * @return 0 on success, -1 otherwise. + */ +static int snd_mxc_audio_playback_prepare(struct snd_pcm_substream *substream) +{ + mxc_pmic_audio_t *chip; + audio_stream_t *s; + int ssi; + int device = -1, stream_id = -1; + + device = substream->pcm->device; + if (device == 0) + stream_id = 0; + else if (device == 1) + stream_id = 2; + else if (device == 2) + stream_id = 3; + + chip = snd_pcm_substream_chip(substream); + s = &chip->s[stream_id]; + ssi = s->ssi; + + normalize_speed_for_pmic(substream); + + configure_dam_pmic_master(ssi); + + configure_ssi_tx(substream); + + ssi_interrupt_enable(ssi, ssi_tx_dma_interrupt_enable); + ssi_interrupt_enable(ssi, ssi_tx_interrupt_enable); + + if (configure_pmic_playback(substream, stream_id) == -1) + pr_debug(KERN_ERR "MXC: PMIC Playback Config FAILED\n"); + ssi_interrupt_enable(ssi, ssi_tx_fifo_0_empty); + ssi_interrupt_enable(ssi, ssi_tx_fifo_1_empty); + /* + ssi_transmit_enable(ssi, true); + */ + msleep(20); + set_pmic_channels(substream); + s->period = 0; + s->periods = 0; + + msleep(100); + + return 0; +} + +/*! + * This function gets the current capture pointer position. + * It is called by ALSA framework. + * + * @param substream pointer to the structure of the current stream. + * + */ +static +snd_pcm_uframes_t snd_mxc_audio_capture_pointer(struct snd_pcm_substream + *substream) +{ + mxc_pmic_audio_t *chip; + + chip = snd_pcm_substream_chip(substream); + return audio_get_capture_dma_pos(&chip->s[substream->pstr->stream]); +} + +/*! + * This function gets the current playback pointer position. + * It is called by ALSA framework. + * + * @param substream pointer to the structure of the current stream. + * + */ +static snd_pcm_uframes_t +snd_mxc_audio_playback_pointer(struct snd_pcm_substream *substream) +{ + mxc_pmic_audio_t *chip; + int device; + int stream_id; + device = substream->pcm->device; + if (device == 0) + stream_id = 0; + else if (device == 1) + stream_id = 2; + else + stream_id = 3; + chip = snd_pcm_substream_chip(substream); + return audio_get_playback_dma_pos(&chip->s[stream_id]); +} + +/*! + * This structure reprensents the capabilities of the driver + * in capture mode. + * It is used by ALSA framework. + */ +static struct snd_pcm_hardware snd_mxc_pmic_capture = { + .info = (SNDRV_PCM_INFO_INTERLEAVED | + SNDRV_PCM_INFO_BLOCK_TRANSFER | + SNDRV_PCM_INFO_MMAP | + SNDRV_PCM_INFO_MMAP_VALID | + SNDRV_PCM_INFO_PAUSE | SNDRV_PCM_INFO_RESUME), + .formats = SNDRV_PCM_FMTBIT_S16_LE, + .rates = (SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000), + .rate_min = 8000, + .rate_max = 16000, + .channels_min = 1, + .channels_max = 1, + .buffer_bytes_max = MAX_BUFFER_SIZE, + .period_bytes_min = MIN_PERIOD_SIZE, + .period_bytes_max = DMA_BUF_SIZE, + .periods_min = MIN_PERIOD, + .periods_max = MAX_PERIOD, + .fifo_size = 0, + +}; + +/*! + * This structure reprensents the capabilities of the driver + * in playback mode for ST-Dac. + * It is used by ALSA framework. + */ +static struct snd_pcm_hardware snd_mxc_pmic_playback_stereo = { + .info = (SNDRV_PCM_INFO_INTERLEAVED | + SNDRV_PCM_INFO_BLOCK_TRANSFER | + SNDRV_PCM_INFO_MMAP | + SNDRV_PCM_INFO_MMAP_VALID | + SNDRV_PCM_INFO_PAUSE | SNDRV_PCM_INFO_RESUME), + .formats = SNDRV_PCM_FMTBIT_S16_LE, + .rates = (SNDRV_PCM_RATE_8000_48000 | SNDRV_PCM_RATE_CONTINUOUS), + .rate_min = 8000, + .rate_max = 96000, + .channels_min = 1, + .channels_max = 2, + .buffer_bytes_max = MAX_BUFFER_SIZE, + .period_bytes_min = MIN_PERIOD_SIZE, + .period_bytes_max = DMA_BUF_SIZE, + .periods_min = MIN_PERIOD, + .periods_max = MAX_PERIOD, + .fifo_size = 0, + +}; + +/*! + * This structure reprensents the capabilities of the driver + * in playback mode for Voice-codec. + * It is used by ALSA framework. + */ +static struct snd_pcm_hardware snd_mxc_pmic_playback_mono = { + .info = (SNDRV_PCM_INFO_INTERLEAVED | + SNDRV_PCM_INFO_BLOCK_TRANSFER | + SNDRV_PCM_INFO_MMAP | + SNDRV_PCM_INFO_MMAP_VALID | + SNDRV_PCM_INFO_PAUSE | SNDRV_PCM_INFO_RESUME), + .formats = SNDRV_PCM_FMTBIT_S16_LE, + .rates = (SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000), + .rate_min = 8000, + .rate_max = 16000, + .channels_min = 1, + .channels_max = 1, + .buffer_bytes_max = MAX_BUFFER_SIZE, + .period_bytes_min = MIN_PERIOD_SIZE, + .period_bytes_max = DMA_BUF_SIZE, + .periods_min = MIN_PERIOD, + .periods_max = MAX_PERIOD, + .fifo_size = 0, + +}; + +/*! + * This function opens a PMIC audio device in playback mode + * It is called by ALSA framework. + * + * @param substream pointer to the structure of the current stream. + * + * @return 0 on success, -1 otherwise. + */ +static int snd_card_mxc_audio_playback_open(struct snd_pcm_substream *substream) +{ + mxc_pmic_audio_t *chip; + struct snd_pcm_runtime *runtime; + int stream_id = -1; + int err; + audio_stream_t *s; + PMIC_AUDIO_HANDLE temp_handle; + int device = -1; + + device = substream->pcm->device; + + chip = snd_pcm_substream_chip(substream); + runtime = substream->runtime; + if (device == 0) + stream_id = 0; + else if (device == 1) + stream_id = 2; + else if (device == 2) { + stream_id = 3; + } + + s = &chip->s[stream_id]; + err = -1; + + if (stream_id == 0) { + if ((audio_data->ssi_num == 1) + && (audio_mixer_control.codec_playback_active + || audio_mixer_control.codec_capture_active)) { + return -EBUSY; + } + + if (PMIC_SUCCESS == pmic_audio_open(&temp_handle, STEREO_DAC)) { + audio_mixer_control.stdac_handle = temp_handle; + audio_mixer_control.stdac_playback_active = 1; + chip->s[stream_id].pmic_audio_device.handle = + temp_handle; + } else { + return -EBUSY; + } + } else if (stream_id == 2) { + if ((audio_data->ssi_num == 1) + && (audio_mixer_control.stdac_playback_active)) { + return -EBUSY; + } + + audio_mixer_control.codec_playback_active = 1; + if (PMIC_SUCCESS == pmic_audio_open(&temp_handle, VOICE_CODEC)) { + audio_mixer_control.voice_codec_handle = temp_handle; + chip->s[stream_id].pmic_audio_device.handle = + temp_handle; + } else { + if (audio_mixer_control.codec_capture_active) { + temp_handle = + audio_mixer_control.voice_codec_handle; + } else { + return -EBUSY; + } + } + + } else if (stream_id == 3) { + audio_mixer_control.mixing_active = 1; + + } + + pmic_audio_antipop_enable(ANTI_POP_RAMP_SLOW); + msleep(250); + + chip->s[stream_id].stream = substream; + + if (stream_id == 0) + runtime->hw = snd_mxc_pmic_playback_stereo; + else if (stream_id == 2) + runtime->hw = snd_mxc_pmic_playback_mono; + + else if (stream_id == 3) { + runtime->hw = snd_mxc_pmic_playback_mono; + + err = snd_pcm_hw_constraint_list(runtime, 0, + SNDRV_PCM_HW_PARAM_RATE, + &hw_playback_rates_mono); + if (err < 0) + return err; + } +#ifdef CONFIG_SND_MXC_PMIC_IRAM + if (g_audio_iram_en && stream_id == 0) { + runtime->hw.buffer_bytes_max = MAX_IRAM_SIZE; + runtime->hw.period_bytes_max = DMA_IRAM_SIZE; + } +#endif /*CONFIG_SND_MXC_PMIC_IRAM */ + + err = snd_pcm_hw_constraint_integer(runtime, + SNDRV_PCM_HW_PARAM_PERIODS)); + if (err < 0) + goto exit_err; + if (stream_id == 0) { + err = snd_pcm_hw_constraint_list(runtime, 0, + SNDRV_PCM_HW_PARAM_RATE, + &hw_playback_rates_stereo); + if (err < 0) + goto exit_err; + + } else if (stream_id == 2) { + err = snd_pcm_hw_constraint_list(runtime, 0, + SNDRV_PCM_HW_PARAM_RATE, + &hw_playback_rates_mono); + if (err < 0) + goto exit_err; + } + msleep(10); + + /* setup DMA controller for playback */ + err = configure_write_channel(&mxc_audio->s[stream_id], + audio_playback_dma_callback, + stream_id); + if (err < 0) + goto exit_err; + + /* enable ssi clock */ + clk_enable(audio_data->ssi_clk[s->ssi]); + + return 0; + exit_err: +#ifdef CONFIG_SND_MXC_PMIC_IRAM + if (stream_id == 0) + mxc_snd_pcm_iram_put(); +#endif /*CONFIG_SND_MXC_PMIC_IRAM */ + return err; + +} + +/*! + * This function closes an PMIC audio device for playback. + * It is called by ALSA framework. + * + * @param substream pointer to the structure of the current stream. + * + * @return 0 on success, -1 otherwise. + */ +static int snd_card_mxc_audio_playback_close(struct snd_pcm_substream + *substream) +{ + mxc_pmic_audio_t *chip; + audio_stream_t *s; + PMIC_AUDIO_HANDLE handle; + int ssi; + int device, stream_id = -1; + handle = (PMIC_AUDIO_HANDLE) NULL; + device = substream->pcm->device; + if (device == 0) { + stream_id = 0; + } else if (device == 1) { + stream_id = 2; + } else + stream_id = 3; + + chip = snd_pcm_substream_chip(substream); + s = &chip->s[stream_id]; + ssi = s->ssi; + + if (audio_mixer_control.mixing_active == 1) { + goto End; + + } else { + + if (stream_id == 0) { + disable_stereodac(); + audio_mixer_control.stdac_playback_active = 0; + handle = audio_mixer_control.stdac_handle; + audio_mixer_control.stdac_handle = NULL; + chip->s[stream_id].pmic_audio_device.handle = NULL; + } else if ((stream_id == 2) || (stream_id == 3)) { + + audio_mixer_control.codec_playback_active = 0; + handle = audio_mixer_control.voice_codec_handle; + disable_codec(handle); + audio_mixer_control.voice_codec_handle = NULL; + chip->s[stream_id].pmic_audio_device.handle = NULL; + } + + } + pmic_audio_close(handle); + + ssi_transmit_enable(ssi, false); + ssi_interrupt_disable(ssi, ssi_tx_dma_interrupt_enable); + ssi_tx_fifo_enable(ssi, ssi_fifo_0, false); + ssi_enable(ssi, false); + mxc_dma_free((mxc_audio->s[stream_id]).dma_wchannel); + + chip->s[stream_id].stream = NULL; + End: + audio_mixer_control.mixing_active = 0; +#ifdef CONFIG_SND_MXC_PMIC_IRAM + if (stream_id == 0) + mxc_snd_pcm_iram_put(); +#endif /*CONFIG_SND_MXC_PMIC_IRAM */ + /* disable ssi clock */ + clk_disable(audio_data->ssi_clk[ssi]); + + return 0; +} + +/*! + * This function closes a PMIC audio device for capture. + * It is called by ALSA framework. + * + * @param substream pointer to the structure of the current stream. + * + * @return 0 on success, -1 otherwise. + */ +static int snd_card_mxc_audio_capture_close(struct snd_pcm_substream *substream) +{ + PMIC_AUDIO_HANDLE handle; + mxc_pmic_audio_t *chip; + audio_stream_t *s; + int ssi; + + chip = snd_pcm_substream_chip(substream); + s = &chip->s[substream->pstr->stream]; + ssi = s->ssi; + + audio_mixer_control.codec_capture_active = 0; + handle = audio_mixer_control.voice_codec_handle; + disable_codec(handle); + audio_mixer_control.voice_codec_handle = NULL; + chip->s[SNDRV_PCM_STREAM_CAPTURE].pmic_audio_device.handle = NULL; + + pmic_audio_close(handle); + + ssi_receive_enable(ssi, false); + ssi_interrupt_disable(ssi, ssi_rx_dma_interrupt_enable); + ssi_rx_fifo_enable(ssi, ssi_fifo_0, false); + ssi_enable(ssi, false); + mxc_dma_free((mxc_audio->s[1]).dma_wchannel); + + chip->s[substream->pstr->stream].stream = NULL; + + /* disable ssi clock */ + clk_disable(audio_data->ssi_clk[ssi]); + + return 0; +} + +/*! + * This function configure the Audio HW in terms of memory allocation. + * It is called by ALSA framework. + * + * @param substream pointer to the structure of the current stream. + * + * @return 0 on success, -1 otherwise. + */ +static int snd_mxc_audio_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *hw_params) +{ + struct snd_pcm_runtime *runtime; + int ret = 0, size; + int device, stream_id = -1; +#ifdef CONFIG_SND_MXC_PMIC_IRAM + struct snd_dma_buffer *dmab; +#endif /*CONFIG_SND_MXC_PMIC_IRAM */ + + runtime = substream->runtime; + ret = + snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params)); + if (ret < 0) + return ret; + size = params_buffer_bytes(hw_params); + device = substream->pcm->device; + if (device == 0) + stream_id = 0; + else if (device == 1) + stream_id = 2; + + runtime->dma_addr = virt_to_phys(runtime->dma_area); + +#ifdef CONFIG_SND_MXC_PMIC_IRAM + if ((substream->stream == SNDRV_PCM_STREAM_PLAYBACK) && g_audio_iram_en + && stream_id == 0) { + if (runtime->dma_buffer_p + && (runtime->dma_buffer_p != &g_iram_dmab)) { + snd_pcm_lib_free_pages(substream); + } + dmab = &g_iram_dmab; + dmab->dev = substream->dma_buffer.dev; + dmab->area = (char *)ADMA_BASE_VADDR; + dmab->addr = ADMA_BASE_PADDR; + dmab->bytes = size; + snd_pcm_set_runtime_buffer(substream, dmab); + runtime->dma_bytes = size; + } else +#endif /* CONFIG_SND_MXC_PMIC_IRAM */ + { + ret = snd_pcm_lib_malloc_pages(substream, size); + if (ret < 0) + return ret; + + runtime->dma_addr = virt_to_phys(runtime->dma_area); + } + + pr_debug("MXC: snd_mxc_audio_hw_params runtime->dma_addr 0x(%x)\n", + (unsigned int)runtime->dma_addr); + pr_debug("MXC: snd_mxc_audio_hw_params runtime->dma_area 0x(%x)\n", + (unsigned int)runtime->dma_area); + pr_debug("MXC: snd_mxc_audio_hw_params runtime->dma_bytes 0x(%x)\n", + (unsigned int)runtime->dma_bytes); + + return ret; +} + +/*! + * This function frees the audio hardware at the end of playback/capture. + * + * @param substream pointer to the structure of the current stream. + * + * @return 0 on success, -1 otherwise. + */ +static int snd_mxc_audio_hw_free(struct snd_pcm_substream *substream) +{ +#ifdef CONFIG_SND_MXC_PMIC_IRAM + if (substream->runtime->dma_buffer_p == &g_iram_dmab) { + snd_pcm_set_runtime_buffer(substream, NULL); + return 0; + } else +#endif /* CONFIG_SND_MXC_PMIC_IRAM */ + { + return snd_pcm_lib_free_pages(substream); + } + return 0; +} + +/*! + * This function configures the hardware to allow audio + * capture operations. It is called by ALSA framework. + * + * @param substream pointer to the structure of the current stream. + * + * @return 0 on success, -1 otherwise. + */ +static int snd_mxc_audio_capture_prepare(struct snd_pcm_substream *substream) +{ + mxc_pmic_audio_t *chip; + audio_stream_t *s; + int ssi; + + chip = snd_pcm_substream_chip(substream); + s = &chip->s[substream->pstr->stream]; + ssi = s->ssi; + + normalize_speed_for_pmic(substream); + + pr_debug("substream->pstr->stream %d\n", substream->pstr->stream); + pr_debug("SSI %d\n", ssi + 1); + configure_dam_pmic_master(ssi); + + configure_ssi_rx(substream); + + ssi_interrupt_enable(ssi, ssi_rx_dma_interrupt_enable); + + if (configure_pmic_recording(substream) == -1) + pr_debug(KERN_ERR "MXC: PMIC Record Config FAILED\n"); + + ssi_interrupt_enable(ssi, ssi_rx_fifo_0_full); + ssi_receive_enable(ssi, true); + + msleep(20); + set_pmic_channels(substream); + + s->period = 0; + s->periods = 0; + + return 0; +} + +/*! + * This function opens an PMIC audio device in capture mode + * on Codec. + * It is called by ALSA framework. + * + * @param substream pointer to the structure of the current stream. + * + * @return 0 on success, -1 otherwise. + */ +static int snd_card_mxc_audio_capture_open(struct snd_pcm_substream *substream) +{ + mxc_pmic_audio_t *chip; + struct snd_pcm_runtime *runtime; + int stream_id; + int err; + PMIC_AUDIO_HANDLE temp_handle; + audio_stream_t *s; + + chip = snd_pcm_substream_chip(substream); + runtime = substream->runtime; + stream_id = substream->pstr->stream; + s = &chip->s[stream_id]; + err = -1; + + if ((audio_data->ssi_num == 1) + && (audio_mixer_control.stdac_playback_active)) { + return -EBUSY; + } + if (PMIC_SUCCESS == pmic_audio_open(&temp_handle, VOICE_CODEC)) { + audio_mixer_control.voice_codec_handle = temp_handle; + audio_mixer_control.codec_capture_active = 1; + chip->s[SNDRV_PCM_STREAM_CAPTURE].pmic_audio_device.handle = + temp_handle; + } else { + if (audio_mixer_control.codec_playback_active) { + temp_handle = audio_mixer_control.voice_codec_handle; + } else { + return -EBUSY; + } + } + pmic_audio_antipop_enable(ANTI_POP_RAMP_SLOW); + + chip->s[stream_id].stream = substream; + + if (stream_id == SNDRV_PCM_STREAM_CAPTURE) { + runtime->hw = snd_mxc_pmic_capture; + } else { + return err; + } + + err = snd_pcm_hw_constraint_integer(runtime, + SNDRV_PCM_HW_PARAM_PERIODS); + if (err < 0) + return err; + + err = snd_pcm_hw_constraint_list(runtime, 0, + SNDRV_PCM_HW_PARAM_RATE, + &hw_capture_rates); + if (err < 0) + return err; + + /* setup DMA controller for Record */ + err = configure_read_channel(&mxc_audio->s[SNDRV_PCM_STREAM_CAPTURE], + audio_capture_dma_callback); + if (err < 0) { + return err; + } + + /* enable ssi clock */ + clk_enable(audio_data->ssi_clk[s->ssi]); + + msleep(50); + + return 0; +} + +#ifdef CONFIG_SND_MXC_PMIC_IRAM +static struct page *snd_mxc_audio_playback_nopage(struct vm_area_struct *area, + unsigned long address, + int *type) +{ + struct snd_pcm_substream *substream = area->vm_private_data; + struct snd_pcm_runtime *runtime; + unsigned long offset; + struct page *page; + void *vaddr; + size_t dma_bytes; + + if (substream == NULL) + return NOPAGE_OOM; + runtime = substream->runtime; + if (g_audio_iram_en) { + return NOPAGE_SIGBUS; + } + offset = area->vm_pgoff << PAGE_SHIFT; + offset += address - area->vm_start; + if (snd_BUG_ON(offset % PAGE_SIZE) != 0) + return NOPAGE_OOM; + dma_bytes = PAGE_ALIGN(runtime->dma_bytes); + if (offset > dma_bytes - PAGE_SIZE) + return NOPAGE_SIGBUS; + if (substream->ops->page) { + page = substream->ops->page(substream, offset); + if (!page) + return NOPAGE_OOM; + } else { + vaddr = runtime->dma_area + offset; + page = virt_to_page(vaddr); + } + get_page(page); + if (type) + *type = VM_FAULT_MINOR; + return page; +} + +static struct vm_operations_struct snd_mxc_audio_playback_vm_ops = { + .open = snd_pcm_mmap_data_open, + .close = snd_pcm_mmap_data_close, + .nopage = snd_mxc_audio_playback_nopage, +}; + +#ifdef CONFIG_ARCH_MX3 +static inline int snd_mxc_set_pte_attr(struct mm_struct *mm, + pmd_t *pmd, + unsigned long addr, unsigned long end) +{ + pte_t *pte; + spinlock_t *ptl; + pte = pte_alloc_map_lock(mm, pmd, addr, &ptl); + + if (!pte) + return -ENOMEM; + do { + /* The mapping is created. It should not be none. */ + BUG_ON(pte_none(*pte)); + /* Directly modify to non-shared device */ + *(pte - 512) |= 0x83; + } while (pte++, addr += PAGE_SIZE, addr != end); + + pte_unmap_unlock(pte - 1, ptl); + + return 0; + +} + +static int snd_mxc_set_pmd_attr(struct mm_struct *mm, + pud_t *pud, + unsigned long addr, unsigned long end) +{ + + pmd_t *pmd; + unsigned long next; + pmd = pmd_alloc(mm, pud, addr); + + if (!pmd) + return -ENOMEM; + do { + + next = pmd_addr_end(addr, end); + if (snd_mxc_set_pte_attr(mm, pmd, addr, next)) + return -ENOMEM; + + } while (pmd++, addr = next, addr != end); + + return 0; + +} + +static int snd_mxc_set_pud_attr(struct mm_struct *mm, + pgd_t *pgd, + unsigned long addr, unsigned long end) +{ + + pud_t *pud; + unsigned long next; + pud = pud_alloc(mm, pgd, addr); + + if (!pud) + return -ENOMEM; + do { + + next = pud_addr_end(addr, end); + if (snd_mxc_set_pmd_attr(mm, pud, addr, next)) + return -ENOMEM; + + } while (pud++, addr = next, addr != end); + + return 0; + +} + +static inline int snd_mxc_set_pgd_attr(struct vm_area_struct *area) +{ + + int ret = 0; + pgd_t *pgd; + struct mm_struct *mm = current->mm; + unsigned long next, addr = area->vm_start; + + pgd = pgd_offset(mm, addr); + flush_cache_range(area, addr, area->vm_end); + + do { + if (!pgd_present(*pgd)) + return -1; + + next = pgd_addr_end(addr, area->vm_end); + ret = snd_mxc_set_pud_attr(mm, pgd, addr, next); + if (ret) + break; + + } while (pgd++, addr = next, addr != area->vm_end); + + return ret; + +} + +#else +#define snd_mxc_set_page_attr() (0) +#endif + +static int snd_mxc_audio_playback_mmap(struct snd_pcm_substream *substream, + struct vm_area_struct *area) +{ + int ret = 0; + area->vm_ops = &snd_mxc_audio_playback_vm_ops; + area->vm_private_data = substream; + if (g_audio_iram_en) { + unsigned long off = area->vm_pgoff << PAGE_SHIFT; + unsigned long phys = ADMA_BASE_PADDR + off; + unsigned long size = area->vm_end - area->vm_start; + if (off + size > MAX_IRAM_SIZE) { + return -EINVAL; + } + area->vm_page_prot = pgprot_nonshareddev(area->vm_page_prot); + area->vm_flags |= VM_IO; + ret = + remap_pfn_range(area, area->vm_start, phys >> PAGE_SHIFT, + size, area->vm_page_prot); + if (ret == 0) { + ret = snd_mxc_set_pgd_attr(area); + } + + } else { + area->vm_flags |= VM_RESERVED; + } + if (ret == 0) + area->vm_ops->open(area); + return ret; +} + +#endif /*CONFIG_SND_MXC_PMIC_IRAM */ + +/*! + * This structure is the list of operation that the driver + * must provide for the capture interface + */ +static struct snd_pcm_ops snd_card_mxc_audio_capture_ops = { + .open = snd_card_mxc_audio_capture_open, + .close = snd_card_mxc_audio_capture_close, + .ioctl = snd_pcm_lib_ioctl, + .hw_params = snd_mxc_audio_hw_params, + .hw_free = snd_mxc_audio_hw_free, + .prepare = snd_mxc_audio_capture_prepare, + .trigger = snd_mxc_audio_capture_trigger, + .pointer = snd_mxc_audio_capture_pointer, +}; + +/*! + * This structure is the list of operation that the driver + * must provide for the playback interface + */ +static struct snd_pcm_ops snd_card_mxc_audio_playback_ops = { + .open = snd_card_mxc_audio_playback_open, + .close = snd_card_mxc_audio_playback_close, + .ioctl = snd_pcm_lib_ioctl, + .hw_params = snd_mxc_audio_hw_params, + .hw_free = snd_mxc_audio_hw_free, + .prepare = snd_mxc_audio_playback_prepare, + .trigger = snd_mxc_audio_playback_trigger, + .pointer = snd_mxc_audio_playback_pointer, +#ifdef CONFIG_SND_MXC_PMIC_IRAM + .mmap = snd_mxc_audio_playback_mmap, +#endif /*CONFIG_SND_MXC_PMIC_IRAM */ +}; + +/*! + * This functions initializes the capture audio device supported by + * PMIC IC. + * + * @param mxc_audio pointer to the sound card structure + * + */ +void init_device_capture(mxc_pmic_audio_t *mxc_audio) +{ + audio_stream_t *audio_stream; + pmic_audio_device_t *pmic_device; + + audio_stream = &mxc_audio->s[SNDRV_PCM_STREAM_CAPTURE]; + pmic_device = &audio_stream->pmic_audio_device; + + /* These parameters defines the identity of + * the device (codec or stereodac) + */ + audio_stream->ssi = SSI1; + audio_stream->dam_port = DAM_PORT_4; + pmic_device->ssi = SSI1; + + pmic_device->mode = BUS_MASTER_MODE; + pmic_device->protocol = NETWORK_MODE; + +#ifdef CONFIG_MXC_PMIC_SC55112 + pmic_device->pll = CLOCK_IN_CLKIN; + pmic_device->pll_rate = VCODEC_CLI_33_6MHZ; +#else + if (machine_is_mx31ads()) { + pmic_device->pll = CLOCK_IN_CLIB; + } else { + pmic_device->pll = CLOCK_IN_CLIA; + } + pmic_device->pll_rate = VCODEC_CLI_26MHZ; +#endif + pmic_device->bcl_inverted = 0; + pmic_device->fs_inverted = 0; + +} + +/*! + * This functions initializes the playback audio device supported by + * PMIC IC. + * + * @param mxc_audio pointer to the sound card structure. + * @param device device ID of PCM instance. + * + */ +void init_device_playback(mxc_pmic_audio_t *mxc_audio, int device) +{ + audio_stream_t *audio_stream; + pmic_audio_device_t *pmic_device; + if (device == 0) + audio_stream = &mxc_audio->s[0]; + else + audio_stream = &mxc_audio->s[2]; + pmic_device = &audio_stream->pmic_audio_device; + + /* These parameters defines the identity of + * the device (codec or stereodac) + */ + if (device == 0) { + if (audio_data->ssi_num == 2) { + audio_stream->ssi = SSI2; + audio_stream->dam_port = DAM_PORT_5; + pmic_device->ssi = SSI2; + } else { + audio_stream->ssi = SSI1; + audio_stream->dam_port = DAM_PORT_4; + pmic_device->ssi = SSI1; + } + + pmic_device->mode = BUS_MASTER_MODE; + pmic_device->protocol = NETWORK_MODE; + +#ifdef CONFIG_MXC_PMIC_SC55112 + pmic_device->pll = CLOCK_IN_CLKIN; + pmic_device->pll_rate = STDAC_CLI_33_6MHZ; +#else + if (machine_is_mx31ads()) { + pmic_device->pll = CLOCK_IN_CLIB; + } else { + pmic_device->pll = CLOCK_IN_CLIA; + } + pmic_device->pll_rate = STDAC_CLI_26MHZ; +#endif + + pmic_device->bcl_inverted = 0; + pmic_device->fs_inverted = 0; + + } else if ((device == 1) || (device == 2)) { + audio_stream->ssi = SSI1; + audio_stream->dam_port = DAM_PORT_4; + pmic_device->ssi = SSI1; + + pmic_device->mode = BUS_MASTER_MODE; + pmic_device->protocol = NETWORK_MODE; + +#ifdef CONFIG_MXC_PMIC_SC55112 + pmic_device->pll = CLOCK_IN_CLKIN; + pmic_device->pll_rate = VCODEC_CLI_33_6MHZ; +#else + if (machine_is_mx31ads()) { + pmic_device->pll = CLOCK_IN_CLIB; + } else { + pmic_device->pll = CLOCK_IN_CLIA; + } + pmic_device->pll_rate = VCODEC_CLI_26MHZ; +#endif + pmic_device->bcl_inverted = 0; + pmic_device->fs_inverted = 0; + } + +} + +/*! + * This functions initializes the mixer related information + * + * @param mxc_audio pointer to the sound card structure. + * + */ +void mxc_pmic_mixer_controls_init(mxc_pmic_audio_t *mxc_audio) +{ + audio_mixer_control_t *audio_control; + int i = 0; + + audio_control = &audio_mixer_control; + + memset(audio_control, 0, sizeof(audio_mixer_control_t)); + sema_init(&audio_control->sem, 1); + + audio_control->input_device = SOUND_MASK_MIC; + audio_control->output_device = SOUND_MASK_VOLUME | SOUND_MASK_PCM; + + /* PMIC has to internal sources that can be routed to output + One is codec direct out and the other is mixer out + Initially we configure all outputs to have no source and + will be later configured either by PCM stream handler or mixer */ + for (i = 0; i < OP_MAXDEV && i != OP_HEADSET; i++) { + audio_control->source_for_output[i] = MIXER_OUT; + } + + /* These bits are initially reset and set when playback begins */ + audio_control->codec_out_to_mixer = 0; + audio_control->stdac_out_to_mixer = 0; + + audio_control->mixer_balance = 50; + if (machine_is_mx31ads()) + audio_control->mixer_mono_adder = STEREO_OPPOSITE_PHASE; + else + audio_control->mixer_mono_adder = MONO_ADDER_OFF; + /* Default values for input and output */ + audio_control->input_volume = ((40 << 8) & 0xff00) | (40 & 0x00ff); + audio_control->master_volume_out = ((50 << 8) & 0xff00) | (50 & 0x00ff); + + if (PMIC_SUCCESS != pmic_audio_set_autodetect(1)) + msleep(30); +} + +/*! + * This functions initializes the 2 audio devices supported by + * PMIC IC. The parameters define the type of device (CODEC or STEREODAC) + * + * @param mxc_audio pointer to the sound card structure. + * @param device device id of the PCM stream. + * + */ +void mxc_pmic_audio_init(mxc_pmic_audio_t *mxc_audio, int device) +{ + if (device == 0) { + mxc_audio->s[SNDRV_PCM_STREAM_PLAYBACK].id = "Audio out"; + mxc_audio->s[SNDRV_PCM_STREAM_PLAYBACK].stream_id = + SNDRV_PCM_STREAM_PLAYBACK; + mxc_audio->s[SNDRV_PCM_STREAM_CAPTURE].id = "Audio in"; + mxc_audio->s[SNDRV_PCM_STREAM_CAPTURE].stream_id = + SNDRV_PCM_STREAM_CAPTURE; + } else if (device == 1) { + mxc_audio->s[2].id = "Audio out"; + mxc_audio->s[2].stream_id = 2; + } else if (device == 2) { + mxc_audio->s[2].id = "Audio out"; + mxc_audio->s[2].stream_id = 3; + } + + init_device_playback(mxc_audio, device); + if (!device) { + init_device_capture(mxc_audio); + } +} + +/*! + * This function the soundcard structure. + * + * @param mxc_audio pointer to the sound card structure. + * @param device the device index (zero based) + * + * @return 0 on success, -1 otherwise. + */ +static int __devinit snd_card_mxc_audio_pcm(mxc_pmic_audio_t *mxc_audio, + int device) +{ + struct snd_pcm *pcm; + int err; + + /* + * Create a new PCM instance with 1 capture stream and 1 playback substream + */ + err = snd_pcm_new(mxc_audio->card, "MXC", device, 1, 1, &pcm); + if (err < 0) + return err; + + /* + * this sets up our initial buffers and sets the dma_type to isa. + * isa works but I'm not sure why (or if) it's the right choice + * this may be too large, trying it for now + */ + snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_CONTINUOUS, + snd_dma_continuous_data + (GFP_KERNEL), MAX_BUFFER_SIZE * 2, + MAX_BUFFER_SIZE * 2); + + snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, + &snd_card_mxc_audio_playback_ops); + snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, + &snd_card_mxc_audio_capture_ops); + + pcm->private_data = mxc_audio; + pcm->info_flags = 0; + strncpy(pcm->name, SOUND_CARD_NAME, sizeof(pcm->name)); + mxc_audio->pcm[device] = pcm; + mxc_pmic_audio_init(mxc_audio, device); + + /* Allocating a second device for PCM playback on voice codec */ + device = 1; + err = snd_pcm_new(mxc_audio->card, "MXC", device, 1, 0, &pcm); + if (err < 0) + return err; + + snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_CONTINUOUS, + snd_dma_continuous_data + (GFP_KERNEL), MAX_BUFFER_SIZE * 2, + MAX_BUFFER_SIZE * 2); + + snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, + &snd_card_mxc_audio_playback_ops); + pcm->private_data = mxc_audio; + pcm->info_flags = 0; + strncpy(pcm->name, SOUND_CARD_NAME, sizeof(pcm->name)); + mxc_audio->pcm[device] = pcm; + mxc_pmic_audio_init(mxc_audio, device); + + device = 2; + err = snd_pcm_new(mxc_audio->card, "MXC", device, 1, 0, &pcm); + if (err < 0) + return err; + + snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_CONTINUOUS, + snd_dma_continuous_data + (GFP_KERNEL), MAX_BUFFER_SIZE * 2, + MAX_BUFFER_SIZE * 2); + + snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, + &snd_card_mxc_audio_playback_ops); + pcm->private_data = mxc_audio; + pcm->info_flags = 0; + strncpy(pcm->name, SOUND_CARD_NAME, sizeof(pcm->name)); + mxc_audio->pcm[device] = pcm; + + /* End of allocation */ + /* FGA for record and not hard coded playback */ + mxc_pmic_mixer_controls_init(mxc_audio); + + return 0; +} + +#ifdef CONFIG_PM +/*! + * This function suspends all active streams. + * + * TBD + * + * @param card pointer to the sound card structure. + * @param state requested state + * + * @return 0 on success, -1 otherwise. + */ +static int snd_mxc_audio_suspend(struct platform_device *dev, + pm_message_t state) +{ + struct snd_card *card = platform_get_drvdata(dev); + mxc_pmic_audio_t *chip = card->private_data; + + snd_power_change_state(card, SNDRV_CTL_POWER_D3hot); + snd_pcm_suspend_all(chip->pcm[0]); + + return 0; +} + +/*! + * This function resumes all suspended streams. + * + * TBD + * + * @param card pointer to the sound card structure. + * @param state requested state + * + * @return 0 on success, -1 otherwise. + */ +static int snd_mxc_audio_resume(struct platform_device *dev) +{ + struct snd_card *card = platform_get_drvdata(dev); + + snd_power_change_state(card, SNDRV_CTL_POWER_D0); + + return 0; +} +#endif /* COMFIG_PM */ + +/*! + * This function frees the sound card structure + * + * @param card pointer to the sound card structure. + * + * @return 0 on success, -1 otherwise. + */ +void snd_mxc_audio_free(struct snd_card *card) +{ + mxc_pmic_audio_t *chip; + + chip = card->private_data; + audio_dma_free(&chip->s[SNDRV_PCM_STREAM_PLAYBACK]); + audio_dma_free(&chip->s[SNDRV_PCM_STREAM_CAPTURE]); + mxc_audio = NULL; + card->private_data = NULL; + kfree(chip); + +} + +/*! + * This function initializes the driver in terms of memory of the soundcard + * and some basic HW clock settings. + * + * @return 0 on success, -1 otherwise. + */ +static int __devinit mxc_alsa_audio_probe(struct platform_device *pdev) +{ + int err; + struct snd_card *card; + + audio_data = (struct mxc_audio_platform_data *)pdev->dev.platform_data; + if (!audio_data) { + dev_err(&pdev->dev, "Can't get the platform data for ALSA\n"); + return -EINVAL; + } + /* register the soundcard */ + err = snd_card_create(-1, id, THIS_MODULE, sizeof(mxc_pmic_audio_t), &card); + if (err < 0) { + return -ENOMEM; + } + + mxc_audio = kcalloc(1, sizeof(*mxc_audio), GFP_KERNEL); + if (mxc_audio == NULL) { + return -ENOMEM; + } + + card->private_data = (void *)mxc_audio; + card->private_free = snd_mxc_audio_free; + + mxc_audio->card = card; + card->dev = &pdev->dev; + err = snd_card_mxc_audio_pcm(mxc_audio, 0); + if (err < 0) + goto nodev; + + if (0 == mxc_alsa_create_ctl(card, (void *)&audio_mixer_control)) + printk(KERN_INFO "Control ALSA component registered\n"); + +#ifdef CONFIG_HEADSET_DETECT_ENABLE + pmic_audio_antipop_enable(ANTI_POP_RAMP_SLOW); + pmic_audio_set_callback((PMIC_AUDIO_CALLBACK) HSCallback, + HEADSET_DETECTED | HEADSET_REMOVED, &hs_state); +#endif + /* Set autodetect feature in order to allow audio operations */ + + spin_lock_init(&(mxc_audio->s[0].dma_lock)); + spin_lock_init(&(mxc_audio->s[1].dma_lock)); + spin_lock_init(&(mxc_audio->s[2].dma_lock)); + + strcpy(card->driver, "MXC"); + strcpy(card->shortname, "PMIC-audio"); + sprintf(card->longname, "MXC Freescale with PMIC"); + + err = snd_card_register(card); + if (err == 0) { + pr_debug(KERN_INFO "MXC audio support initialized\n"); + platform_set_drvdata(pdev, card); + return 0; + } + + nodev: + snd_card_free(card); + return err; +} + +static int __devexit mxc_alsa_audio_remove(struct platform_device *dev) +{ + snd_card_free(mxc_audio->card); + kfree(mxc_audio); + platform_set_drvdata(dev, NULL); + + return 0; +} + +static struct platform_driver mxc_alsa_audio_driver = { + .probe = mxc_alsa_audio_probe, + .remove = __devexit_p(mxc_alsa_audio_remove), +#ifdef CONFIG_PM + .suspend = snd_mxc_audio_suspend, + .resume = snd_mxc_audio_resume, +#endif + .driver = { + .name = "mxc_alsa", + }, +}; + +static int __init mxc_alsa_audio_init(void) +{ + return platform_driver_register(&mxc_alsa_audio_driver); +} + +/*! + * This function frees the sound driver structure. + * + */ + +static void __exit mxc_alsa_audio_exit(void) +{ + platform_driver_unregister(&mxc_alsa_audio_driver); +} + +module_init(mxc_alsa_audio_init); +module_exit(mxc_alsa_audio_exit); + +MODULE_AUTHOR("FREESCALE SEMICONDUCTOR"); +MODULE_LICENSE("GPL"); +MODULE_DESCRIPTION("MXC driver for ALSA"); +MODULE_SUPPORTED_DEVICE("{{PMIC}}"); + +module_param(id, charp, 0444); +MODULE_PARM_DESC(id, "ID string for MXC + PMIC soundcard."); diff --git a/sound/arm/mxc-alsa-pmic.h b/sound/arm/mxc-alsa-pmic.h new file mode 100644 index 000000000000..ccda66ecc70f --- /dev/null +++ b/sound/arm/mxc-alsa-pmic.h @@ -0,0 +1,110 @@ +/* + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * Copyright 2007-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + + /*! + * @file mxc-alsa-pmic.h + * @brief + * @ingroup SOUND_DRV + */ + +#ifndef __MXC_ALSA_PMIC_H__ +#define __MXC_ALSA_PMIC_H__ + +#ifdef __KERNEL__ + + /**/ +#define PMIC_MASTER 0x1 +#define PMIC_SLAVE 0x2 + /**/ +#define DAM_PORT_4 port_4 +#define DAM_PORT_5 port_5 + /**/ +#define PMIC_STEREODAC 0x1 +#define PMIC_CODEC 0x2 + /**/ +#define PMIC_AUDIO_ADDER_STEREO 0x1 +#define PMIC_AUDIO_ADDER_STEREO_OPPOSITE 0x2 +#define PMIC_AUDIO_ADDER_MONO 0x4 +#define PMIC_AUDIO_ADDER_MONO_OPPOSITE 0x8 +#define TX_WATERMARK 0x4 +#define RX_WATERMARK 0x6 + /**/ +#define SSI_DEFAULT_FIFO 0x0 +#define DEFAULT_MASTER_CLOCK 0x1 + /**/ +#define SDMA_TXFIFO_WATERMARK 0x4 +#define SDMA_RXFIFO_WATERMARK 0x6 + /**/ +#define TIMESLOTS_2 0x3 +#define TIMESLOTS_4 0x2 +#define SAMPLE_RATE_MAX 0x9 + /**/ +#define CLK_SELECT_SLAVE_BCL 0x7 +#define CLK_SELECT_SLAVE_CLI 0x5 +#define CLK_SELECT_MASTER_CLI 0x4 +/* Volume to balance ratio */ +#define VOLUME_BALANCE_RATIO ((6 + 39) / (21 + 21)) +/* -21dB */ +#define PMIC_BALANCE_MIN 0x0 +/* 0dB*/ +#define PMIC_BALANCE_MAX 0x7 +/* -21dB left */ +#define BALANCE_MIN 0x0 +/* 0db, no balance */ +#define NO_BALANCE 0x32 +/* -21dB right*/ +#define BALANCE_MAX 0x64 +/* -8dB */ +#define PMIC_INPUT_VOLUME_MIN 0x0 +/* +23dB */ +#define PMIC_INPUT_VOLUME_MAX 0x1f +/* -39dB */ +#define PMIC_OUTPUT_VOLUME_MIN PMIC_INPUT_VOLUME_MIN +/* +6dB */ +#define PMIC_OUTPUT_VOLUME_MAX 0xd +/* -8dB */ +#define INPUT_VOLUME_MIN 0x0 +/* +23dB */ +#define INPUT_VOLUME_MAX 0x64 +/* -39dB */ +#define OUTPUT_VOLUME_MIN 0x0 +/* +6dB */ +#define OUTPUT_VOLUME_MAX 0x64 +/* 96 Khz */ +#define SAMPLE_FREQ_MAX 96000 +/* 8 Khz */ +#define SAMPLE_FREQ_MIN 8000 +/*! + * Define channels available on MC13783. This is mainly used + * in mixer interface to control different input/output + * devices + */ +#define MXC_STEREO_OUTPUT (SOUND_MASK_VOLUME | SOUND_MASK_PCM) +#define MXC_STEREO_INPUT (SOUND_MASK_PHONEIN) +#define MXC_MONO_OUTPUT (SOUND_MASK_PHONEOUT | SOUND_MASK_SPEAKER) +#define MXC_MONO_INPUT (SOUND_MASK_LINE | SOUND_MASK_MIC) +#define SNDCTL_CLK_SET_MASTER _SIOR('Z', 30, int) +#define SNDCTL_PMIC_READ_OUT_BALANCE _SIOR('Z', 8, int) +/*#define SNDCTL_MC13783_WRITE_OUT_BALANCE _SIOWR('Z', 9, int)*/ +#define SNDCTL_PMIC_WRITE_OUT_ADDER _SIOWR('Z', 10, int) +#define SNDCTL_PMIC_READ_OUT_ADDER _SIOR('Z', 11, int) +#define SNDCTL_PMIC_WRITE_CODEC_FILTER _SIOWR('Z', 12, int) +#define SNDCTL_PMIC_READ_CODEC_FILTER _SIOR('Z', 13, int) +#define SNDCTL_DAM_SET_OUT_PORT _SIOWR('Z', 14, int) +#endif /* __KERNEL__ */ +#endif /* __MXC_ALSA_PMIC_H__ */ diff --git a/sound/arm/mxc-alsa-spdif.c b/sound/arm/mxc-alsa-spdif.c new file mode 100644 index 000000000000..ba7dc3ba1ad9 --- /dev/null +++ b/sound/arm/mxc-alsa-spdif.c @@ -0,0 +1,2263 @@ +/* + * Copyright (C) 2007-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @defgroup SOUND_DRV MXC Sound Driver for ALSA + */ + +/*! + * @file mxc-alsa-spdif.c + * @brief this fle mxc-alsa-spdif.c + * @brief this file implements mxc alsa driver for spdif. + * The spdif tx supports consumer channel for linear PCM and + * compressed audio data. The supported sample rates are + * 48KHz, 44.1KHz and 32KHz. + * + * @ingroup SOUND_DRV + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +#define MXC_SPDIF_NAME "MXC_SPDIF" +static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; +static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; +static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE; +module_param_array(index, int, NULL, 0444); +MODULE_PARM_DESC(index, "Index value for spdif sound card."); +module_param_array(id, charp, NULL, 0444); +MODULE_PARM_DESC(id, "ID string for spdif sound card."); +module_param_array(enable, bool, NULL, 0444); +MODULE_PARM_DESC(enable, "Enable spdif sound card."); + +#define SPDIF_MAX_BUF_SIZE (32*1024) +#define SPDIF_DMA_BUF_SIZE (8*1024) +#define SPDIF_MIN_PERIOD_SIZE 64 +#define SPDIF_MIN_PERIOD 2 +#define SPDIF_MAX_PERIOD 255 + +#define SPDIF_REG_SCR 0x00 +#define SPDIF_REG_SRCD 0x04 +#define SPDIF_REG_SRPC 0x08 +#define SPDIF_REG_SIE 0x0C +#define SPDIF_REG_SIS 0x10 +#define SPDIF_REG_SIC 0x10 +#define SPDIF_REG_SRL 0x14 +#define SPDIF_REG_SRR 0x18 +#define SPDIF_REG_SRCSLH 0x1C +#define SPDIF_REG_SRCSLL 0x20 +#define SPDIF_REG_SQU 0x24 +#define SPDIF_REG_SRQ 0x28 +#define SPDIF_REG_STL 0x2C +#define SPDIF_REG_STR 0x30 +#define SPDIF_REG_STCSCH 0x34 +#define SPDIF_REG_STCSCL 0x38 +#define SPDIF_REG_SRFM 0x44 +#define SPDIF_REG_STC 0x50 + +/* SPDIF Configuration register */ +#define SCR_RXFIFO_CTL_ZERO (1 << 23) +#define SCR_RXFIFO_OFF (1 << 22) +#define SCR_RXFIFO_RST (1 << 21) +#define SCR_RXFIFO_FSEL_BIT (19) +#define SCR_RXFIFO_FSEL_MASK (0x3 << SCR_RXFIFO_FSEL_BIT) +#define SCR_RXFIFO_AUTOSYNC (1 << 18) +#define SCR_TXFIFO_AUTOSYNC (1 << 17) +#define SCR_TXFIFO_ESEL_BIT (15) +#define SCR_TXFIFO_ESEL_MASK (0x3 << SCR_TXFIFO_FSEL_BIT) +#define SCR_LOW_POWER (1 << 13) +#define SCR_SOFT_RESET (1 << 12) +#define SCR_TXFIFO_ZERO (0 << 10) +#define SCR_TXFIFO_NORMAL (1 << 10) +#define SCR_TXFIFO_ONESAMPLE (1 << 11) +#define SCR_DMA_RX_EN (1 << 9) +#define SCR_DMA_TX_EN (1 << 8) +#define SCR_VAL_CLEAR (1 << 5) +#define SCR_TXSEL_OFF (0 << 2) +#define SCR_TXSEL_RX (1 << 2) +#define SCR_TXSEL_NORMAL (0x5 << 2) +#define SCR_USRC_SEL_NONE (0x0) +#define SCR_USRC_SEL_RECV (0x1) +#define SCR_USRC_SEL_CHIP (0x3) + +/* SPDIF CDText control */ +#define SRCD_CD_USER_OFFSET 1 +#define SRCD_CD_USER (1 << SRCD_CD_USER_OFFSET) + +/* SPDIF Phase Configuration register */ +#define SRPC_DPLL_LOCKED (1 << 6) +#define SRPC_CLKSRC_SEL_OFFSET 7 +#define SRPC_CLKSRC_SEL_LOCKED 5 +/* gain sel */ +#define SRPC_GAINSEL_OFFSET 3 + +enum spdif_gainsel { + GAINSEL_MULTI_24 = 0, + GAINSEL_MULTI_16, + GAINSEL_MULTI_12, + GAINSEL_MULTI_8, + GAINSEL_MULTI_6, + GAINSEL_MULTI_4, + GAINSEL_MULTI_3, + GAINSEL_MULTI_MAX, +}; + +#define SPDIF_DEFAULT_GAINSEL GAINSEL_MULTI_8 + +/* SPDIF interrupt mask define */ +#define INT_DPLL_LOCKED (1 << 20) +#define INT_TXFIFO_UNOV (1 << 19) +#define INT_TXFIFO_RESYNC (1 << 18) +#define INT_CNEW (1 << 17) +#define INT_VAL_NOGOOD (1 << 16) +#define INT_SYM_ERR (1 << 15) +#define INT_BIT_ERR (1 << 14) +#define INT_URX_FUL (1 << 10) +#define INT_URX_OV (1 << 9) +#define INT_QRX_FUL (1 << 8) +#define INT_QRX_OV (1 << 7) +#define INT_UQ_SYNC (1 << 6) +#define INT_UQ_ERR (1 << 5) +#define INT_RX_UNOV (1 << 4) +#define INT_RX_RESYNC (1 << 3) +#define INT_LOSS_LOCK (1 << 2) +#define INT_TX_EMPTY (1 << 1) +#define INT_RXFIFO_FUL (1 << 0) + +/* SPDIF Clock register */ +#define STC_SYSCLK_DIV_OFFSET 11 +#define STC_TXCLK_SRC_OFFSET 8 +#define STC_TXCLK_DIV_OFFSET 0 + +#define SPDIF_CSTATUS_BYTE 6 +#define SPDIF_UBITS_SIZE 96 +#define SPDIF_QSUB_SIZE (SPDIF_UBITS_SIZE/8) + +enum spdif_clk_accuracy { + SPDIF_CLK_ACCURACY_LEV2 = 0, + SPDIF_CLK_ACCURACY_LEV1 = 2, + SPDIF_CLK_ACCURACY_LEV3 = 1, + SPDIF_CLK_ACCURACY_RESV = 3 +}; + +/* SPDIF clock source */ +enum spdif_clk_src { + SPDIF_CLK_SRC1 = 0, + SPDIF_CLK_SRC2, + SPDIF_CLK_SRC3, + SPDIF_CLK_SRC4, + SPDIF_CLK_SRC5, +}; + +enum spdif_max_wdl { + SPDIF_MAX_WDL_20, + SPDIF_MAX_WDL_24 +}; + +enum spdif_wdl { + SPDIF_WDL_DEFAULT = 0, + SPDIF_WDL_FIFTH = 4, + SPDIF_WDL_FOURTH = 3, + SPDIF_WDL_THIRD = 2, + SPDIF_WDL_SECOND = 1, + SPDIF_WDL_MAX = 5 +}; + +static unsigned int gainsel_multi[GAINSEL_MULTI_MAX] = { + 24 * 1024, 16 * 1024, 12 * 1024, + 8 * 1024, 6 * 1024, 4 * 1024, + 3 * 1024, +}; + +/*! + * SPDIF control structure + * Defines channel status, subcode and Q sub + */ +struct spdif_mixer_control { + + /* spinlock to access control data */ + spinlock_t ctl_lock; + /* IEC958 channel tx status bit */ + unsigned char ch_status[4]; + /* User bits */ + unsigned char subcode[2 * SPDIF_UBITS_SIZE]; + /* Q subcode part of user bits */ + unsigned char qsub[2 * SPDIF_QSUB_SIZE]; + /* buffer ptrs for writer */ + unsigned int upos; + unsigned int qpos; + /* ready buffer index of the two buffers */ + unsigned int ready_buf; +}; + +/*! + * This structure represents an audio stream in term of + * channel DMA, HW configuration on spdif controller. + */ +struct mxc_spdif_stream { + + /*! + * identification string + */ + char *id; + /*! + * device identifier for DMA + */ + int dma_wchannel; + /*! + * we are using this stream for transfer now + */ + int active:1; + /*! + * current transfer period + */ + int period; + /*! + * current count of transfered periods + */ + int periods; + /*! + * for locking in DMA operations + */ + spinlock_t dma_lock; + /*! + * Alsa substream pointer + */ + struct snd_pcm_substream *stream; +}; + +struct mxc_spdif_device { + /*! + * SPDIF module register base address + */ + unsigned long __iomem *reg_base; + unsigned long reg_phys_base; + + /*! + * spdif tx available or not + */ + int mxc_spdif_tx; + + /*! + * spdif rx available or not + */ + int mxc_spdif_rx; + + /*! + * spdif 44100 clock src + */ + int spdif_txclk_44100; + + /*! + * spdif 48000 clock src + */ + int spdif_txclk_48000; + + /*! + * ALSA SPDIF sound card handle + */ + struct snd_card *card; + + /*! + * ALSA spdif driver type handle + */ + struct snd_pcm *pcm; + + /*! + * DPLL locked status + */ + atomic_t dpll_locked; + + /*! + * Playback/Capture substream + */ + struct mxc_spdif_stream s[2]; +}; + +static struct spdif_mixer_control mxc_spdif_control; + +static unsigned long spdif_base_addr; + +/* define each spdif interrupt handlers */ +typedef void (*spdif_irq_func_t) (unsigned int bit, void *desc); + +/* spdif irq functions declare */ +static void spdif_irq_fifo(unsigned int bit, void *devid); +static void spdif_irq_dpll_lock(unsigned int bit, void *devid); +static void spdif_irq_uq(unsigned int bit, void *devid); +static void spdif_irq_bit_error(unsigned int bit, void *devid); +static void spdif_irq_sym_error(unsigned int bit, void *devid); +static void spdif_irq_valnogood(unsigned int bit, void *devid); +static void spdif_irq_cnew(unsigned int bit, void *devid); + +/* irq function list */ +static spdif_irq_func_t spdif_irq_handlers[] = { + spdif_irq_fifo, + spdif_irq_fifo, + spdif_irq_dpll_lock, + NULL, + spdif_irq_fifo, + spdif_irq_uq, + spdif_irq_uq, + spdif_irq_uq, + spdif_irq_uq, + spdif_irq_uq, + spdif_irq_uq, + NULL, + NULL, + NULL, + spdif_irq_bit_error, + spdif_irq_sym_error, + spdif_irq_valnogood, + spdif_irq_cnew, + NULL, + spdif_irq_fifo, + spdif_irq_dpll_lock, +}; + +/*! + * @brief Enable/Disable spdif DMA request + * + * This function is called to enable or disable the dma transfer + */ +static void spdif_dma_enable(int txrx, int enable) +{ + unsigned long value; + + value = __raw_readl(SPDIF_REG_SCR + spdif_base_addr) & 0xfffeff; + if (enable) + value |= txrx; + + __raw_writel(value, SPDIF_REG_SCR + spdif_base_addr); + +} + +/*! + * @brief Enable spdif interrupt + * + * This function is called to enable relevant interrupts. + */ +static void spdif_intr_enable(unsigned long intr, int enable) +{ + unsigned long value; + + value = __raw_readl(spdif_base_addr + SPDIF_REG_SIE) & 0xffffff; + if (enable) + value |= intr; + else + value &= ~intr; + + __raw_writel(value, spdif_base_addr + SPDIF_REG_SIE); +} + +/*! + * @brief Set the clock accuracy level in the channel bit + * + * This function is called to set the clock accuracy level + */ +static int spdif_set_clk_accuracy(enum spdif_clk_accuracy level) +{ + unsigned long value; + + value = __raw_readl(SPDIF_REG_STCSCL + spdif_base_addr) & 0xffffcf; + value |= (level << 4); + __raw_writel(value, SPDIF_REG_STCSCL + spdif_base_addr); + + return 0; +} + +/*! + * set SPDIF PhaseConfig register for rx clock + */ +static int spdif_set_rx_clksrc(enum spdif_clk_src clksrc, + enum spdif_gainsel gainsel, int dpll_locked) +{ + unsigned long value; + if (clksrc > SPDIF_CLK_SRC5 || gainsel > GAINSEL_MULTI_3) + return 1; + + value = (dpll_locked ? (clksrc) : + (clksrc + SRPC_CLKSRC_SEL_LOCKED)) << SRPC_CLKSRC_SEL_OFFSET | + (gainsel << SRPC_GAINSEL_OFFSET); + __raw_writel(value, spdif_base_addr + SPDIF_REG_SRPC); + + return 0; +} + +/*! + * Get RX data clock rate + * given the SPDIF bus_clk + */ +static int spdif_get_rxclk_rate(struct clk *bus_clk, enum spdif_gainsel gainsel) +{ + unsigned long freqmeas, phaseconf, busclk_freq = 0; + u64 tmpval64; + enum spdif_clk_src clksrc; + + freqmeas = __raw_readl(spdif_base_addr + SPDIF_REG_SRFM); + phaseconf = __raw_readl(spdif_base_addr + SPDIF_REG_SRPC); + + clksrc = (phaseconf >> SRPC_CLKSRC_SEL_OFFSET) & 0x0F; + if (clksrc < 5 && (phaseconf & SRPC_DPLL_LOCKED)) { + /* get bus clock from system */ + busclk_freq = clk_get_rate(bus_clk); + } + + /* FreqMeas_CLK = (BUS_CLK*FreqMeas[23:0])/2^10/GAINSEL/128 */ + tmpval64 = (u64) busclk_freq * freqmeas; + do_div(tmpval64, gainsel_multi[gainsel]); + do_div(tmpval64, 128 * 1024); + return (int)tmpval64; +} + +/*! + * @brief Set the audio sample rate in the channel status bit + * + * This function is called to set the audio sample rate to be transfered. + */ +static int spdif_set_sample_rate(int src_44100, int src_48000, int sample_rate) +{ + unsigned long cstatus, stc; + + cstatus = __raw_readl(SPDIF_REG_STCSCL + spdif_base_addr) & 0xfffff0; + stc = __raw_readl(SPDIF_REG_STC + spdif_base_addr) & ~0x7FF; + + switch (sample_rate) { + case 44100: + __raw_writel(cstatus, SPDIF_REG_STCSCL + spdif_base_addr); + stc |= (src_44100 << 8) | 0x07; + __raw_writel(stc, SPDIF_REG_STC + spdif_base_addr); + pr_debug("set sample rate to 44100\n"); + break; + case 48000: + cstatus |= 0x04; + __raw_writel(cstatus, SPDIF_REG_STCSCL + spdif_base_addr); + stc |= (src_48000 << 8) | 0x07; + __raw_writel(stc, SPDIF_REG_STC + spdif_base_addr); + pr_debug("set sample rate to 48000\n"); + break; + case 32000: + cstatus |= 0x0c; + __raw_writel(cstatus, SPDIF_REG_STCSCL + spdif_base_addr); + stc |= (src_48000 << 8) | 0x0b; + __raw_writel(stc, SPDIF_REG_STC + spdif_base_addr); + pr_debug("set sample rate to 32000\n"); + break; + } + + return 0; +} + +/*! + * @brief Set the lchannel status bit + * + * This function is called to set the channel status + */ +static int spdif_set_channel_status(int value, unsigned long reg) +{ + __raw_writel(value & 0xffffff, reg + spdif_base_addr); + + return 0; +} + +/*! + * @brief Get spdif interrupt status and clear the interrupt + * + * This function is called to check relevant interrupt status + */ +static int spdif_intr_status(void) +{ + unsigned long value; + + value = __raw_readl(SPDIF_REG_SIS + spdif_base_addr) & 0xffffff; + value &= __raw_readl(spdif_base_addr + SPDIF_REG_SIE); + __raw_writel(value, SPDIF_REG_SIC + spdif_base_addr); + + return value; +} + +/*! + * @brief spdif interrupt handler + */ +static irqreturn_t spdif_isr(int irq, void *dev_id) +{ + unsigned long int_stat; + int line; + + int_stat = spdif_intr_status(); + + while ((line = ffs(int_stat)) != 0) { + int_stat &= ~(1UL << (line - 1)); + if (spdif_irq_handlers[line - 1] != NULL) + spdif_irq_handlers[line - 1] (line - 1, dev_id); + } + + return IRQ_HANDLED; +} + +/*! + * Interrupt handlers + * + */ +/*! + * FIFO related interrupts handler + * + * Rx FIFO Full, Underrun/Overrun interrupts + * Tx FIFO Empty, Underrun/Overrun interrupts + */ +static void spdif_irq_fifo(unsigned int bit, void *devid) +{ + +} + +/*! + * DPLL lock related interrupts handler + * + * DPLL locked and lock loss interrupts + */ +static void spdif_irq_dpll_lock(unsigned int bit, void *devid) +{ + struct mxc_spdif_device *chip = (struct mxc_spdif_device *)devid; + unsigned int locked = __raw_readl(spdif_base_addr + SPDIF_REG_SRPC); + + if (locked & SRPC_DPLL_LOCKED) { + pr_debug("SPDIF Rx dpll locked\n"); + atomic_set(&chip->dpll_locked, 1); + } else { + /* INT_LOSS_LOCK */ + pr_debug("SPDIF Rx dpll loss lock\n"); + atomic_set(&chip->dpll_locked, 0); + } +} + +/*! + * U/Q channel related interrupts handler + * + * U/QChannel full, overrun interrupts + * U/QChannel sync error and frame error interrupts + */ +static void spdif_irq_uq(unsigned int bit, void *devid) +{ + unsigned long val; + int index; + struct spdif_mixer_control *ctrl = &mxc_spdif_control; + + bit = 1 << bit; + /* get U/Q channel datas */ + switch (bit) { + + case INT_URX_OV: /* read U data */ + pr_debug("User bit receive overrun\n"); + case INT_URX_FUL: + pr_debug("U bit receive full\n"); + + if (ctrl->upos >= SPDIF_UBITS_SIZE * 2) { + ctrl->upos = 0; + } else if (unlikely((ctrl->upos % SPDIF_UBITS_SIZE) + 3 + > SPDIF_UBITS_SIZE)) { + pr_err("User bit receivce buffer overflow\n"); + break; + } + val = __raw_readl(spdif_base_addr + SPDIF_REG_SQU); + ctrl->subcode[ctrl->upos++] = val >> 16; + ctrl->subcode[ctrl->upos++] = val >> 8; + ctrl->subcode[ctrl->upos++] = val; + + break; + + case INT_QRX_OV: /* read Q data */ + pr_debug("Q bit receive overrun\n"); + case INT_QRX_FUL: + pr_debug("Q bit receive full\n"); + + if (ctrl->qpos >= SPDIF_QSUB_SIZE * 2) { + ctrl->qpos = 0; + } else if (unlikely((ctrl->qpos % SPDIF_QSUB_SIZE) + 3 + > SPDIF_QSUB_SIZE)) { + pr_err("Q bit receivce buffer overflow\n"); + break; + } + val = __raw_readl(spdif_base_addr + SPDIF_REG_SRQ); + ctrl->qsub[ctrl->qpos++] = val >> 16; + ctrl->qsub[ctrl->qpos++] = val >> 8; + ctrl->qsub[ctrl->qpos++] = val; + + break; + + case INT_UQ_ERR: /* read U/Q data and do buffer reset */ + pr_debug("U/Q bit receive error\n"); + val = __raw_readl(spdif_base_addr + SPDIF_REG_SQU); + val = __raw_readl(spdif_base_addr + SPDIF_REG_SRQ); + /* drop this U/Q buffer */ + ctrl->ready_buf = ctrl->upos = ctrl->qpos = 0; + break; + + case INT_UQ_SYNC: /* U/Q buffer reset */ + pr_debug("U/Q sync receive\n"); + + if (ctrl->qpos == 0) + break; + index = (ctrl->qpos - 1) / SPDIF_QSUB_SIZE; + /* set ready to this buffer */ + ctrl->ready_buf = index + 1; + break; + } +} + +/*! + * SPDIF receiver found parity bit error interrupt handler + */ +static void spdif_irq_bit_error(unsigned int bit, void *devid) +{ + pr_debug("SPDIF interrupt parity bit error\n"); +} + +/*! + * SPDIF receiver found illegal symbol interrupt handler + */ +static void spdif_irq_sym_error(unsigned int bit, void *devid) +{ + pr_debug("SPDIF interrupt symbol error\n"); +} + +/*! + * SPDIF validity flag no good interrupt handler + */ +static void spdif_irq_valnogood(unsigned int bit, void *devid) +{ + pr_debug("SPDIF interrupt validate is not good\n"); +} + +/*! + * SPDIF receive change in value of control channel + */ +static void spdif_irq_cnew(unsigned int bit, void *devid) +{ + pr_debug("SPDIF interrupt cstatus new\n"); +} + +/*! + * Do software reset to SPDIF + */ +static void spdif_softreset(void) +{ + unsigned long value = 1; + int cycle = 0; + __raw_writel(SCR_SOFT_RESET, spdif_base_addr + SPDIF_REG_SCR); + while (value && (cycle++ < 10)) { + value = __raw_readl(spdif_base_addr + SPDIF_REG_SCR) & 0x1000; + } + +} + +/*! + * SPDIF RX initial function + */ +static void spdif_rx_init(void) +{ + unsigned long regval; + + regval = __raw_readl(spdif_base_addr + SPDIF_REG_SCR); + /** + * initial and reset SPDIF configuration: + * RxFIFO off + * RxFIFO sel to 8 sample + * Autosync + * Valid bit set + */ + regval &= ~(SCR_RXFIFO_OFF | SCR_RXFIFO_CTL_ZERO | SCR_LOW_POWER); + regval |= (2 << SCR_RXFIFO_FSEL_BIT) | SCR_RXFIFO_AUTOSYNC; + __raw_writel(regval, spdif_base_addr + SPDIF_REG_SCR); +} + +/*! + * SPDIF RX un-initial function + */ +static void spdif_rx_uninit(void) +{ + unsigned long regval; + + /* turn off RX fifo, disable dma and autosync */ + regval = __raw_readl(spdif_base_addr + SPDIF_REG_SCR); + regval |= SCR_RXFIFO_OFF | SCR_RXFIFO_CTL_ZERO; + regval &= ~(SCR_DMA_RX_EN | SCR_RXFIFO_AUTOSYNC); + __raw_writel(regval, spdif_base_addr + SPDIF_REG_SCR); +} + +/*! + * @brief Initialize spdif module + * + * This function is called to set the spdif to initial state. + */ +static void spdif_tx_init(void) +{ + unsigned long regval; + + regval = __raw_readl(spdif_base_addr + SPDIF_REG_SCR); + + regval &= 0xfc32e3; + regval |= SCR_TXFIFO_AUTOSYNC | SCR_TXFIFO_NORMAL | + SCR_TXSEL_NORMAL | SCR_USRC_SEL_CHIP | (2 << SCR_TXFIFO_ESEL_BIT); + __raw_writel(regval, SPDIF_REG_SCR + spdif_base_addr); + + /* Default clock source from EXTAL, divider by 8, generate 44.1kHz + sample rate */ + regval = 0x07; + __raw_writel(regval, SPDIF_REG_STC + spdif_base_addr); + +} + +/*! + * @brief deinitialize spdif module + * + * This function is called to stop the spdif + */ +static void spdif_tx_uninit(void) +{ + unsigned long regval; + + regval = __raw_readl(SPDIF_REG_SCR + spdif_base_addr) & 0xffffe3; + regval |= SCR_TXSEL_OFF; + __raw_writel(regval, SPDIF_REG_SCR + spdif_base_addr); + regval = __raw_readl(SPDIF_REG_STC + spdif_base_addr) & ~0x7FF; + regval |= (0x7 << STC_TXCLK_SRC_OFFSET); + __raw_writel(regval, SPDIF_REG_STC + spdif_base_addr); + +} + +static unsigned int spdif_playback_rates[] = { 32000, 44100, 48000 }; +static unsigned int spdif_capture_rates[] = { + 16000, 32000, 44100, 48000, 64000, 96000 +}; + +/*! + * this structure represents the sample rates supported + * by SPDIF + */ +static struct snd_pcm_hw_constraint_list hw_playback_rates_stereo = { + .count = ARRAY_SIZE(spdif_playback_rates), + .list = spdif_playback_rates, + .mask = 0, +}; + +static struct snd_pcm_hw_constraint_list hw_capture_rates_stereo = { + .count = ARRAY_SIZE(spdif_capture_rates), + .list = spdif_capture_rates, + .mask = 0, +}; + +/*! + * This structure reprensents the capabilities of the driver + * in playback mode. + */ +static struct snd_pcm_hardware snd_spdif_playback_hw = { + .info = + (SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_BLOCK_TRANSFER | + SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_HALF_DUPLEX | + SNDRV_PCM_INFO_MMAP_VALID | SNDRV_PCM_INFO_PAUSE | + SNDRV_PCM_INFO_RESUME), + .formats = SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE | + SNDRV_PCM_FMTBIT_S24_LE, + .rates = + SNDRV_PCM_RATE_32000 | SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000, + .rate_min = 32000, + .rate_max = 48000, + .channels_min = 2, + .channels_max = 2, + .buffer_bytes_max = SPDIF_MAX_BUF_SIZE, + .period_bytes_min = SPDIF_MIN_PERIOD_SIZE, + .period_bytes_max = SPDIF_DMA_BUF_SIZE, + .periods_min = SPDIF_MIN_PERIOD, + .periods_max = SPDIF_MAX_PERIOD, + .fifo_size = 0, +}; + +/*! + * This structure reprensents the capabilities of the driver + * in capture mode. + */ +static struct snd_pcm_hardware snd_spdif_capture_hw = { + .info = (SNDRV_PCM_INFO_INTERLEAVED | + SNDRV_PCM_INFO_BLOCK_TRANSFER | + SNDRV_PCM_INFO_MMAP | + SNDRV_PCM_INFO_MMAP_VALID | + SNDRV_PCM_INFO_PAUSE | SNDRV_PCM_INFO_RESUME), + .formats = SNDRV_PCM_FMTBIT_S24_LE, + .rates = + (SNDRV_PCM_RATE_16000 | SNDRV_PCM_RATE_32000 | SNDRV_PCM_RATE_44100 + | SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_64000 | + SNDRV_PCM_RATE_96000), + .rate_min = 16000, + .rate_max = 96000, + .channels_min = 2, + .channels_max = 2, + .buffer_bytes_max = SPDIF_MAX_BUF_SIZE, + .period_bytes_min = SPDIF_MIN_PERIOD_SIZE, + .period_bytes_max = SPDIF_DMA_BUF_SIZE, + .periods_min = SPDIF_MIN_PERIOD, + .periods_max = SPDIF_MAX_PERIOD, + .fifo_size = 0, + +}; + +/*! + * This function configures the DMA channel used to transfer + * audio from MCU to SPDIF or from SPDIF to MCU + * + * @param s pointer to the structure of the current stream. + * @param callback pointer to function that will be + * called when a SDMA TX transfer finishes. + * + * @return 0 on success, -1 otherwise. + */ +static int +spdif_configure_dma_channel(struct mxc_spdif_stream *s, + mxc_dma_callback_t callback) +{ + int ret = -1; + int channel = -1; + + if (s->dma_wchannel != 0) + mxc_dma_free(s->dma_wchannel); + + if (s->stream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + + if (s->stream->runtime->sample_bits > 16) { + channel = + mxc_dma_request(MXC_DMA_SPDIF_32BIT_TX, + "SPDIF TX DMA"); + } else { + channel = + mxc_dma_request(MXC_DMA_SPDIF_16BIT_TX, + "SPDIF TX DMA"); + } + + } else if (s->stream->stream == SNDRV_PCM_STREAM_CAPTURE) { + + channel = mxc_dma_request(MXC_DMA_SPDIF_32BIT_RX, + "SPDIF RX DMA"); + + } + + pr_debug("spdif_configure_dma_channel: %d\n", channel); + + ret = mxc_dma_callback_set(channel, + (mxc_dma_callback_t) callback, (void *)s); + if (ret != 0) { + pr_info("spdif_configure_dma_channel - err\n"); + mxc_dma_free(channel); + return -1; + } + s->dma_wchannel = channel; + return 0; +} + +/*! + * This function gets the dma pointer position during playback/capture. + * Our DMA implementation does not allow to retrieve this position + * when a transfert is active, so, it answers the middle of + * the current period beeing transfered + * + * @param s pointer to the structure of the current stream. + * + */ +static u_int spdif_get_dma_pos(struct mxc_spdif_stream *s) +{ + struct snd_pcm_substream *substream; + struct snd_pcm_runtime *runtime; + unsigned int offset = 0; + substream = s->stream; + runtime = substream->runtime; + + offset = (runtime->period_size * (s->periods)); + if (offset >= runtime->buffer_size) + offset = 0; + pr_debug + ("MXC: spdif_get_dma_pos BIS offset %d, buffer_size %d\n", + offset, (int)runtime->buffer_size); + return offset; +} + +/*! + * This function stops the current dma transfert for playback + * and clears the dma pointers. + * + * @param s pointer to the structure of the current stream. + * + */ +static void spdif_stop_tx(struct mxc_spdif_stream *s) +{ + struct snd_pcm_substream *substream; + struct snd_pcm_runtime *runtime; + unsigned int dma_size; + unsigned int offset; + + substream = s->stream; + runtime = substream->runtime; + dma_size = frames_to_bytes(runtime, runtime->period_size); + offset = dma_size * s->periods; + + s->active = 0; + s->period = 0; + s->periods = 0; + + /* this stops the dma channel and clears the buffer ptrs */ + mxc_dma_disable(s->dma_wchannel); + spdif_dma_enable(SCR_DMA_TX_EN, 0); + dma_unmap_single(NULL, runtime->dma_addr + offset, dma_size, + DMA_TO_DEVICE); +} + +/*! + * This function is called whenever a new audio block needs to be + * transferred to SPDIF. The function receives the address and the size + * of the new block and start a new DMA transfer. + * + * @param s pointer to the structure of the current stream. + * + */ +static void spdif_start_tx(struct mxc_spdif_stream *s) +{ + struct snd_pcm_substream *substream = s->stream; + struct snd_pcm_runtime *runtime = substream->runtime; + struct mxc_spdif_device *chip = snd_pcm_substream_chip(substream); + unsigned int dma_size = 0; + unsigned int offset; + int ret = 0; + mxc_dma_requestbuf_t dma_request; + substream = s->stream; + runtime = substream->runtime; + memset(&dma_request, 0, sizeof(mxc_dma_requestbuf_t)); + if (s->active) { + dma_size = frames_to_bytes(runtime, runtime->period_size); + offset = dma_size * s->period; + dma_request.src_addr = + (dma_addr_t) (dma_map_single + (NULL, runtime->dma_area + offset, dma_size, + DMA_TO_DEVICE)); + + dma_request.dst_addr = (dma_addr_t) (chip->reg_phys_base + 0x2c); + + dma_request.num_of_bytes = dma_size; + mxc_dma_config(s->dma_wchannel, &dma_request, 1, + MXC_DMA_MODE_WRITE); + ret = mxc_dma_enable(s->dma_wchannel); + spdif_dma_enable(SCR_DMA_TX_EN, 1); + if (ret) { + pr_info("audio_process_dma: cannot queue DMA \ + buffer\n"); + return; + } + s->period++; + s->period %= runtime->periods; + + if ((s->period > s->periods) + && ((s->period - s->periods) > 1)) { + pr_debug("audio playback chain dma: already double \ + buffered\n"); + return; + } + + if ((s->period < s->periods) + && ((s->period + runtime->periods - s->periods) > 1)) { + pr_debug("audio playback chain dma: already double \ + buffered\n"); + return; + } + + if (s->period == s->periods) { + pr_debug("audio playback chain dma: s->period == \ + s->periods\n"); + return; + } + + if (snd_pcm_playback_hw_avail(runtime) < + 2 * runtime->period_size) { + pr_debug("audio playback chain dma: available data \ + is not enough\n"); + return; + } + + pr_debug + ("audio playback chain dma:to set up the 2nd dma buffer\n"); + pr_debug("SCR: 0x%08x\n", + __raw_readl(spdif_base_addr + SPDIF_REG_SCR)); + + offset = dma_size * s->period; + dma_request.src_addr = + (dma_addr_t) (dma_map_single + (NULL, runtime->dma_area + offset, dma_size, + DMA_TO_DEVICE)); + mxc_dma_config(s->dma_wchannel, &dma_request, 1, + MXC_DMA_MODE_WRITE); + ret = mxc_dma_enable(s->dma_wchannel); + s->period++; + s->period %= runtime->periods; + + } + return; +} + +/*! + * This is a callback which will be called + * when a TX transfer finishes. The call occurs + * in interrupt context. + * + * @param data pointer to the structure of the current stream + * @param error DMA error flag + * @param count number of bytes transfered by the DMA + */ +static void spdif_tx_callback(void *data, int error, unsigned int count) +{ + struct mxc_spdif_stream *s; + struct snd_pcm_substream *substream; + struct snd_pcm_runtime *runtime; + unsigned int dma_size; + unsigned int previous_period; + unsigned int offset; + s = data; + substream = s->stream; + runtime = substream->runtime; + previous_period = s->periods; + dma_size = frames_to_bytes(runtime, runtime->period_size); + offset = dma_size * previous_period; + + spin_lock(&s->dma_lock); + s->periods++; + s->periods %= runtime->periods; + dma_unmap_single(NULL, runtime->dma_addr + offset, dma_size, + DMA_TO_DEVICE); + spin_unlock(&s->dma_lock); + + if (s->active) + snd_pcm_period_elapsed(s->stream); + + spin_lock(&s->dma_lock); + spdif_start_tx(s); + spin_unlock(&s->dma_lock); +} + +/*! + * This function is a dispatcher of command to be executed + * by the driver for playback. + * + * @param substream pointer to the structure of the current stream. + * @param cmd command to be executed + * + * @return 0 on success, -1 otherwise. + */ +static int +snd_mxc_spdif_playback_trigger(struct snd_pcm_substream *substream, int cmd) +{ + struct mxc_spdif_device *chip; + struct mxc_spdif_stream *s; + int err = 0; + unsigned long flags; + chip = snd_pcm_substream_chip(substream); + s = &chip->s[SNDRV_PCM_STREAM_PLAYBACK]; + + spin_lock_irqsave(&s->dma_lock, flags); + switch (cmd) { + case SNDRV_PCM_TRIGGER_START: + s->active = 1; + spdif_start_tx(s); + break; + case SNDRV_PCM_TRIGGER_STOP: + spdif_stop_tx(s); + break; + case SNDRV_PCM_TRIGGER_SUSPEND: + s->active = 0; + s->periods = 0; + break; + case SNDRV_PCM_TRIGGER_RESUME: + s->active = 1; + spdif_start_tx(s); + break; + case SNDRV_PCM_TRIGGER_PAUSE_PUSH: + s->active = 0; + break; + case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: + s->active = 1; + spdif_start_tx(s); + break; + default: + err = -EINVAL; + break; + } + spin_unlock_irqrestore(&s->dma_lock, flags); + return err; +} + +/*! + * This function configures the hardware to allow audio + * playback operations. It is called by ALSA framework. + * + * @param substream pointer to the structure of the current stream. + * + * @return 0 on success, -1 otherwise. + */ +static int snd_mxc_spdif_playback_prepare(struct snd_pcm_substream *substream) +{ + struct mxc_spdif_device *chip; + struct snd_pcm_runtime *runtime; + int err; + unsigned int ch_status; + + chip = snd_pcm_substream_chip(substream); + runtime = substream->runtime; + + spdif_tx_init(); + + ch_status = + ((mxc_spdif_control.ch_status[2] << 16) | (mxc_spdif_control. + ch_status[1] << 8) | + mxc_spdif_control.ch_status[0]); + spdif_set_channel_status(ch_status, SPDIF_REG_STCSCH); + ch_status = mxc_spdif_control.ch_status[3]; + spdif_set_channel_status(ch_status, SPDIF_REG_STCSCL); + spdif_intr_enable(INT_TXFIFO_RESYNC, 1); + spdif_set_sample_rate(chip->spdif_txclk_44100, chip->spdif_txclk_48000, + runtime->rate); + spdif_set_clk_accuracy(SPDIF_CLK_ACCURACY_LEV2); + /* setup DMA controller for spdif tx */ + err = spdif_configure_dma_channel(&chip-> + s[SNDRV_PCM_STREAM_PLAYBACK], + spdif_tx_callback); + if (err < 0) { + pr_info("snd_mxc_spdif_playback_prepare - err < 0\n"); + return err; + } + + /** + * FIXME: dump registers + */ + pr_debug("SCR: 0x%08x\n", __raw_readl(spdif_base_addr + SPDIF_REG_SCR)); + pr_debug("SIE: 0x%08x\n", __raw_readl(spdif_base_addr + SPDIF_REG_SIE)); + pr_debug("STC: 0x%08x\n", __raw_readl(spdif_base_addr + SPDIF_REG_STC)); + return 0; +} + +/*! + * This function gets the current playback pointer position. + * It is called by ALSA framework. + * + * @param substream pointer to the structure of the current stream. + * + */ +static snd_pcm_uframes_t +snd_mxc_spdif_playback_pointer(struct snd_pcm_substream *substream) +{ + struct mxc_spdif_device *chip; + chip = snd_pcm_substream_chip(substream); + return spdif_get_dma_pos(&chip->s[SNDRV_PCM_STREAM_PLAYBACK]); +} + +static int snd_card_mxc_spdif_playback_open(struct snd_pcm_substream *substream) +{ + struct mxc_spdif_device *chip; + struct snd_pcm_runtime *runtime; + int err; + struct mxc_spdif_platform_data *spdif_data; + + chip = snd_pcm_substream_chip(substream); + + spdif_data = chip->card->dev->platform_data; + /* enable tx clock */ + clk_enable(spdif_data->spdif_clk); + clk_enable(spdif_data->spdif_audio_clk); + + runtime = substream->runtime; + chip->s[SNDRV_PCM_STREAM_PLAYBACK].stream = substream; + runtime->hw = snd_spdif_playback_hw; + err = snd_pcm_hw_constraint_list(runtime, 0, + SNDRV_PCM_HW_PARAM_RATE, + &hw_playback_rates_stereo); + if (err < 0) + goto failed; + err = + snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS); + if (err < 0) + goto failed; + + return 0; + failed: + clk_disable(spdif_data->spdif_clk); + return err; +} + +/*! + * This function closes an spdif device for playback. + * It is called by ALSA framework. + * + * @param substream pointer to the structure of the current stream. + * + * @return 0 on success, -1 otherwise. + */ +static int snd_card_mxc_spdif_playback_close(struct snd_pcm_substream + *substream) +{ + struct mxc_spdif_device *chip; + struct mxc_spdif_platform_data *spdif_data; + + chip = snd_pcm_substream_chip(substream); + spdif_data = chip->card->dev->platform_data; + + pr_debug("SIS: 0x%08x\n", __raw_readl(spdif_base_addr + SPDIF_REG_SIS)); + + spdif_intr_status(); + spdif_intr_enable(INT_TXFIFO_RESYNC, 0); + spdif_tx_uninit(); + clk_disable(spdif_data->spdif_audio_clk); + clk_disable(spdif_data->spdif_clk); + mxc_dma_free(chip->s[SNDRV_PCM_STREAM_PLAYBACK].dma_wchannel); + chip->s[SNDRV_PCM_STREAM_PLAYBACK].dma_wchannel = 0; + + return 0; +} + +/*! TODO: update the dma start/stop callback routine + * This function stops the current dma transfert for capture + * and clears the dma pointers. + * + * @param s pointer to the structure of the current stream. + * + */ +static void spdif_stop_rx(struct mxc_spdif_stream *s) +{ + struct snd_pcm_substream *substream; + struct snd_pcm_runtime *runtime; + unsigned int dma_size; + unsigned int offset; + + substream = s->stream; + runtime = substream->runtime; + dma_size = frames_to_bytes(runtime, runtime->period_size); + offset = dma_size * s->periods; + + s->active = 0; + s->period = 0; + s->periods = 0; + + /* this stops the dma channel and clears the buffer ptrs */ + mxc_dma_disable(s->dma_wchannel); + spdif_dma_enable(SCR_DMA_RX_EN, 0); + dma_unmap_single(NULL, runtime->dma_addr + offset, dma_size, + DMA_FROM_DEVICE); +} + +/*! + * This function is called whenever a new audio block needs to be + * received from SPDIF. The function receives the address and the size + * of the new block and start a new DMA transfer. + * + * @param s pointer to the structure of the current stream. + * + */ +static void spdif_start_rx(struct mxc_spdif_stream *s) +{ + struct snd_pcm_substream *substream = s->stream; + struct snd_pcm_runtime *runtime = substream->runtime; + struct mxc_spdif_device *chip = snd_pcm_substream_chip(substream); + unsigned int dma_size = 0; + unsigned int offset; + int ret = 0; + mxc_dma_requestbuf_t dma_request; + + memset(&dma_request, 0, sizeof(mxc_dma_requestbuf_t)); + + if (s->active) { + dma_size = frames_to_bytes(runtime, runtime->period_size); + pr_debug("s->period (%x) runtime->periods (%d)\n", + s->period, runtime->periods); + pr_debug("runtime->period_size (%d) dma_size (%d)\n", + (unsigned int)runtime->period_size, + runtime->dma_bytes); + + offset = dma_size * s->period; + dma_request.dst_addr = + (dma_addr_t) (dma_map_single + (NULL, runtime->dma_area + offset, dma_size, + DMA_FROM_DEVICE)); + + dma_request.src_addr = + (dma_addr_t) (chip->reg_phys_base + SPDIF_REG_SRL); + dma_request.num_of_bytes = dma_size; + /* config and enable sdma for RX */ + mxc_dma_config(s->dma_wchannel, &dma_request, 1, + MXC_DMA_MODE_READ); + ret = mxc_dma_enable(s->dma_wchannel); + /* enable SPDIF dma */ + spdif_dma_enable(SCR_DMA_RX_EN, 1); + + if (ret) { + pr_info("audio_process_dma: cannot queue DMA \ + buffer\n"); + return; + } + s->period++; + s->period %= runtime->periods; + + if ((s->period > s->periods) + && ((s->period - s->periods) > 1)) { + pr_debug("audio capture chain dma: already double \ + buffered\n"); + return; + } + + if ((s->period < s->periods) + && ((s->period + runtime->periods - s->periods) > 1)) { + pr_debug("audio capture chain dma: already double \ + buffered\n"); + return; + } + + if (s->period == s->periods) { + pr_debug("audio capture chain dma: s->period == \ + s->periods\n"); + return; + } + + if (snd_pcm_capture_hw_avail(runtime) < + 2 * runtime->period_size) { + pr_debug("audio capture chain dma: available data \ + is not enough\n"); + return; + } + + pr_debug + ("audio playback chain dma:to set up the 2nd dma buffer\n"); + + offset = dma_size * s->period; + dma_request.dst_addr = + (dma_addr_t) (dma_map_single + (NULL, runtime->dma_area + offset, dma_size, + DMA_FROM_DEVICE)); + mxc_dma_config(s->dma_wchannel, &dma_request, 1, + MXC_DMA_MODE_READ); + ret = mxc_dma_enable(s->dma_wchannel); + s->period++; + s->period %= runtime->periods; + + } + return; +} + +/*! + * This is a callback which will be called + * when a RX transfer finishes. The call occurs + * in interrupt context. + * + * @param data pointer to the structure of the current stream + * @param error DMA error flag + * @param count number of bytes transfered by the DMA + */ +static void spdif_rx_callback(void *data, int error, unsigned int count) +{ + struct mxc_spdif_stream *s; + struct snd_pcm_substream *substream; + struct snd_pcm_runtime *runtime; + unsigned int dma_size; + unsigned int previous_period; + unsigned int offset; + + s = data; + substream = s->stream; + runtime = substream->runtime; + previous_period = s->periods; + dma_size = frames_to_bytes(runtime, runtime->period_size); + offset = dma_size * previous_period; + + spin_lock(&s->dma_lock); + s->periods++; + s->periods %= runtime->periods; + + dma_unmap_single(NULL, runtime->dma_addr + offset, dma_size, + DMA_FROM_DEVICE); + spin_unlock(&s->dma_lock); + + if (s->active) + snd_pcm_period_elapsed(s->stream); + spin_lock(&s->dma_lock); + spdif_start_rx(s); + spin_unlock(&s->dma_lock); +} + +/*! + * This function is a dispatcher of command to be executed + * by the driver for capture. + * + * @param substream pointer to the structure of the current stream. + * @param cmd command to be executed + * + * @return 0 on success, -1 otherwise. + */ +static int +snd_mxc_spdif_capture_trigger(struct snd_pcm_substream *substream, int cmd) +{ + struct mxc_spdif_device *chip; + struct mxc_spdif_stream *s; + int err = 0; + unsigned long flags; + chip = snd_pcm_substream_chip(substream); + s = &chip->s[SNDRV_PCM_STREAM_CAPTURE]; + + spin_lock_irqsave(&s->dma_lock, flags); + switch (cmd) { + case SNDRV_PCM_TRIGGER_START: + s->active = 1; + spdif_start_rx(s); + break; + case SNDRV_PCM_TRIGGER_STOP: + spdif_stop_rx(s); + break; + case SNDRV_PCM_TRIGGER_SUSPEND: + s->active = 0; + s->periods = 0; + break; + case SNDRV_PCM_TRIGGER_RESUME: + s->active = 1; + spdif_start_rx(s); + break; + case SNDRV_PCM_TRIGGER_PAUSE_PUSH: + s->active = 0; + break; + case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: + s->active = 1; + spdif_start_rx(s); + break; + default: + err = -EINVAL; + break; + } + spin_unlock_irqrestore(&s->dma_lock, flags); + return err; +} + +/*! + * This function configures the hardware to allow audio + * capture operations. It is called by ALSA framework. + * + * @param substream pointer to the structure of the current stream. + * + * @return 0 on success, -1 otherwise. + */ +static int snd_mxc_spdif_capture_prepare(struct snd_pcm_substream *substream) +{ + struct mxc_spdif_device *chip; + struct mxc_spdif_platform_data *spdif_data; + struct snd_pcm_runtime *runtime; + int err; + + chip = snd_pcm_substream_chip(substream); + runtime = substream->runtime; + spdif_data = chip->card->dev->platform_data; + + spdif_rx_init(); + /* enable interrupts, include DPLL lock */ + spdif_intr_enable(INT_SYM_ERR | INT_BIT_ERR | INT_URX_FUL | + INT_URX_OV | INT_QRX_FUL | INT_QRX_OV | + INT_UQ_SYNC | INT_UQ_ERR | INT_RX_RESYNC | + INT_LOSS_LOCK, 1); + + /* setup rx clock source */ + spdif_set_rx_clksrc(spdif_data->spdif_clkid, SPDIF_DEFAULT_GAINSEL, 1); + + /* setup DMA controller for spdif rx */ + err = spdif_configure_dma_channel(&chip-> + s[SNDRV_PCM_STREAM_CAPTURE], + spdif_rx_callback); + if (err < 0) { + pr_info("snd_mxc_spdif_playback_prepare - err < 0\n"); + return err; + } + + /* Debug: dump registers */ + pr_debug("SCR: 0x%08x\n", __raw_readl(spdif_base_addr + SPDIF_REG_SCR)); + pr_debug("SIE: 0x%08x\n", __raw_readl(spdif_base_addr + SPDIF_REG_SIE)); + pr_debug("SRPC: 0x%08x\n", + __raw_readl(spdif_base_addr + SPDIF_REG_SRPC)); + pr_debug("FreqMeas: 0x%08x\n", + __raw_readl(spdif_base_addr + SPDIF_REG_SRFM)); + + return 0; +} + +/*! + * This function gets the current capture pointer position. + * It is called by ALSA framework. + * + * @param substream pointer to the structure of the current stream. + * + */ +static snd_pcm_uframes_t +snd_mxc_spdif_capture_pointer(struct snd_pcm_substream *substream) +{ + struct mxc_spdif_device *chip; + chip = snd_pcm_substream_chip(substream); + return spdif_get_dma_pos(&chip->s[SNDRV_PCM_STREAM_CAPTURE]); +} + +/*! + * This function opens a spdif device in capture mode + * It is called by ALSA framework. + * + * @param substream pointer to the structure of the current stream. + * + * @return 0 on success, -1 otherwise. + */ +static int snd_card_mxc_spdif_capture_open(struct snd_pcm_substream *substream) +{ + struct mxc_spdif_device *chip; + struct snd_pcm_runtime *runtime; + int err = 0; + struct mxc_spdif_platform_data *spdif_data; + + chip = snd_pcm_substream_chip(substream); + + spdif_data = chip->card->dev->platform_data; + /* enable rx bus clock */ + clk_enable(spdif_data->spdif_clk); + + runtime = substream->runtime; + chip->s[SNDRV_PCM_STREAM_CAPTURE].stream = substream; + runtime->hw = snd_spdif_capture_hw; + + /* set hw param constraints */ + err = snd_pcm_hw_constraint_list(runtime, 0, + SNDRV_PCM_HW_PARAM_RATE, + &hw_capture_rates_stereo); + if (err < 0) + goto failed; + err = + snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS); + if (err < 0) + goto failed; + + /* enable spdif dpll lock interrupt */ + spdif_intr_enable(INT_DPLL_LOCKED, 1); + + return 0; + + failed: + clk_disable(spdif_data->spdif_clk); + return err; +} + +/*! + * This function closes an spdif device for capture. + * It is called by ALSA framework. + * + * @param substream pointer to the structure of the current stream. + * + * @return 0 on success, -1 otherwise. + */ +static int snd_card_mxc_spdif_capture_close(struct snd_pcm_substream + *substream) +{ + struct mxc_spdif_device *chip; + struct mxc_spdif_platform_data *spdif_data; + + chip = snd_pcm_substream_chip(substream); + spdif_data = chip->card->dev->platform_data; + + pr_debug("SIS: 0x%08x\n", __raw_readl(spdif_base_addr + SPDIF_REG_SIS)); + pr_debug("SRPC: 0x%08x\n", + __raw_readl(spdif_base_addr + SPDIF_REG_SRPC)); + pr_debug("FreqMeas: 0x%08x\n", + __raw_readl(spdif_base_addr + SPDIF_REG_SRFM)); + + spdif_intr_enable(INT_DPLL_LOCKED | INT_SYM_ERR | INT_BIT_ERR | + INT_URX_FUL | INT_URX_OV | INT_QRX_FUL | INT_QRX_OV | + INT_UQ_SYNC | INT_UQ_ERR | INT_RX_RESYNC | + INT_LOSS_LOCK, 0); + spdif_rx_uninit(); + clk_disable(spdif_data->spdif_clk); + mxc_dma_free(chip->s[SNDRV_PCM_STREAM_CAPTURE].dma_wchannel); + chip->s[SNDRV_PCM_STREAM_CAPTURE].dma_wchannel = 0; + return 0; +} + +/*! + * This function configure the Audio HW in terms of memory allocation. + * It is called by ALSA framework. + * + * @param substream pointer to the structure of the current stream. + * @param hw_params Pointer to hardware paramters structure + * + * @return 0 on success, -1 otherwise. + */ +static int snd_mxc_spdif_hw_params(struct snd_pcm_substream + *substream, struct snd_pcm_hw_params + *hw_params) +{ + struct snd_pcm_runtime *runtime; + int ret = 0; + runtime = substream->runtime; + ret = + snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params)); + if (ret < 0) { + pr_info("snd_mxc_spdif_hw_params - ret: %d\n", ret); + return ret; + } + runtime->dma_addr = virt_to_phys(runtime->dma_area); + return ret; +} + +/*! + * This function frees the spdif hardware at the end of playback. + * + * @param substream pointer to the structure of the current stream. + * + * @return 0 on success, -1 otherwise. + */ +static int snd_mxc_spdif_hw_free(struct snd_pcm_substream *substream) +{ + return snd_pcm_lib_free_pages(substream); +} + +/*! + * This structure is the list of operation that the driver + * must provide for the playback interface + */ +static struct snd_pcm_ops snd_card_mxc_spdif_playback_ops = { + .open = snd_card_mxc_spdif_playback_open, + .close = snd_card_mxc_spdif_playback_close, + .ioctl = snd_pcm_lib_ioctl, + .hw_params = snd_mxc_spdif_hw_params, + .hw_free = snd_mxc_spdif_hw_free, + .prepare = snd_mxc_spdif_playback_prepare, + .trigger = snd_mxc_spdif_playback_trigger, + .pointer = snd_mxc_spdif_playback_pointer, +}; + +static struct snd_pcm_ops snd_card_mxc_spdif_capture_ops = { + .open = snd_card_mxc_spdif_capture_open, + .close = snd_card_mxc_spdif_capture_close, + .ioctl = snd_pcm_lib_ioctl, + .hw_params = snd_mxc_spdif_hw_params, + .hw_free = snd_mxc_spdif_hw_free, + .prepare = snd_mxc_spdif_capture_prepare, + .trigger = snd_mxc_spdif_capture_trigger, + .pointer = snd_mxc_spdif_capture_pointer, +}; + +/*! + * This functions initializes the playback audio device supported by + * spdif + * + * @param mxc_spdif pointer to the sound card structure. + * + */ +void mxc_init_spdif_device(struct mxc_spdif_device *mxc_spdif) +{ + + /* initial spinlock for control data */ + spin_lock_init(&mxc_spdif_control.ctl_lock); + + if (mxc_spdif->mxc_spdif_tx) { + + mxc_spdif->s[SNDRV_PCM_STREAM_PLAYBACK].id = "spdif tx"; + /* init tx channel status default value */ + mxc_spdif_control.ch_status[0] = + IEC958_AES0_CON_NOT_COPYRIGHT | + IEC958_AES0_CON_EMPHASIS_5015; + mxc_spdif_control.ch_status[1] = IEC958_AES1_CON_DIGDIGCONV_ID; + mxc_spdif_control.ch_status[2] = 0x00; + mxc_spdif_control.ch_status[3] = + IEC958_AES3_CON_FS_44100 | IEC958_AES3_CON_CLOCK_1000PPM; + } + if (mxc_spdif->mxc_spdif_rx) { + + /* TODO: Add code here if capture is available */ + mxc_spdif->s[SNDRV_PCM_STREAM_CAPTURE].id = "spdif rx"; + } + +} + +/*! + * MXC SPDIF IEC958 controller(mixer) functions + * + * Channel status get/put control + * User bit value get/put control + * Valid bit value get control + * DPLL lock status get control + * User bit sync mode selection control + * + */ +static int mxc_pb_spdif_info(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_info *uinfo) +{ + uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958; + uinfo->count = 1; + return 0; +} + +static int mxc_pb_spdif_get(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *uvalue) +{ + uvalue->value.iec958.status[0] = mxc_spdif_control.ch_status[0]; + uvalue->value.iec958.status[1] = mxc_spdif_control.ch_status[1]; + uvalue->value.iec958.status[2] = mxc_spdif_control.ch_status[2]; + uvalue->value.iec958.status[3] = mxc_spdif_control.ch_status[3]; + return 0; +} + +static int mxc_pb_spdif_put(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *uvalue) +{ + unsigned int ch_status; + mxc_spdif_control.ch_status[0] = uvalue->value.iec958.status[0]; + mxc_spdif_control.ch_status[1] = uvalue->value.iec958.status[1]; + mxc_spdif_control.ch_status[2] = uvalue->value.iec958.status[2]; + mxc_spdif_control.ch_status[3] = uvalue->value.iec958.status[3]; + ch_status = + ((mxc_spdif_control.ch_status[2] << 16) | (mxc_spdif_control. + ch_status[1] << 8) | + mxc_spdif_control.ch_status[0]); + spdif_set_channel_status(ch_status, SPDIF_REG_STCSCH); + ch_status = mxc_spdif_control.ch_status[3]; + spdif_set_channel_status(ch_status, SPDIF_REG_STCSCL); + return 0; +} + +static int snd_mxc_spdif_info(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_info *uinfo) +{ + uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958; + uinfo->count = 1; + return 0; +} + +/*! + * Get channel status from SPDIF_RX_CCHAN register + */ +static int snd_mxc_spdif_capture_get(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + unsigned int cstatus; + + if (!(__raw_readl(spdif_base_addr + SPDIF_REG_SIS) & INT_CNEW)) + return -EAGAIN; + + cstatus = __raw_readl(spdif_base_addr + SPDIF_REG_SRCSLH); + ucontrol->value.iec958.status[0] = (cstatus >> 16) & 0xFF; + ucontrol->value.iec958.status[1] = (cstatus >> 8) & 0xFF; + ucontrol->value.iec958.status[2] = cstatus & 0xFF; + cstatus = __raw_readl(spdif_base_addr + SPDIF_REG_SRCSLL); + ucontrol->value.iec958.status[3] = (cstatus >> 16) & 0xFF; + ucontrol->value.iec958.status[4] = (cstatus >> 8) & 0xFF; + ucontrol->value.iec958.status[5] = cstatus & 0xFF; + + /* clear intr */ + __raw_writel(INT_CNEW, spdif_base_addr + SPDIF_REG_SIC); + + return 0; +} + +/*! + * Get User bits (subcode) from chip value which readed out + * in UChannel register. + */ +static int snd_mxc_spdif_subcode_get(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + unsigned long flags; + int ret = 0; + + spin_lock_irqsave(&mxc_spdif_control.ctl_lock, flags); + if (mxc_spdif_control.ready_buf) { + memcpy(&ucontrol->value.iec958.subcode[0], + &mxc_spdif_control. + subcode[(mxc_spdif_control.ready_buf - + 1) * SPDIF_UBITS_SIZE], SPDIF_UBITS_SIZE); + } else { + ret = -EAGAIN; + } + spin_unlock_irqrestore(&mxc_spdif_control.ctl_lock, flags); + + return ret; +} + +/*! + * Q-subcode infomation. + * the byte size is SPDIF_UBITS_SIZE/8 + */ +static int snd_mxc_spdif_qinfo(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_info *uinfo) +{ + uinfo->type = SNDRV_CTL_ELEM_TYPE_BYTES; + uinfo->count = SPDIF_QSUB_SIZE; + return 0; +} + +/*! + * Get Q subcode from chip value which readed out + * in QChannel register. + */ +static int snd_mxc_spdif_qget(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + unsigned long flags; + int ret = 0; + + spin_lock_irqsave(&mxc_spdif_control.ctl_lock, flags); + if (mxc_spdif_control.ready_buf) { + memcpy(&ucontrol->value.bytes.data[0], + &mxc_spdif_control. + qsub[(mxc_spdif_control.ready_buf - + 1) * SPDIF_QSUB_SIZE], SPDIF_QSUB_SIZE); + } else { + ret = -EAGAIN; + } + spin_unlock_irqrestore(&mxc_spdif_control.ctl_lock, flags); + + return ret; +} + +/*! + * Valid bit infomation. + */ +static int snd_mxc_spdif_vbit_info(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_info *uinfo) +{ + uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN; + uinfo->count = 1; + uinfo->value.integer.min = 0; + uinfo->value.integer.max = 1; + return 0; +} + +/*! + * Get valid good bit from interrupt status register. + */ +static int snd_mxc_spdif_vbit_get(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + unsigned int int_val; + + int_val = __raw_readl(spdif_base_addr + SPDIF_REG_SIS); + ucontrol->value.integer.value[0] = (int_val & INT_VAL_NOGOOD) != 0; + __raw_writel(INT_VAL_NOGOOD, spdif_base_addr + SPDIF_REG_SIC); + + return 0; +} + +/*! + * DPLL lock infomation. + */ +static int snd_mxc_spdif_rxrate_info(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_info *uinfo) +{ + uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; + uinfo->count = 1; + uinfo->value.integer.min = 16000; + uinfo->value.integer.max = 96000; + return 0; +} + +/*! + * Get DPLL lock or not info from stable interrupt status register. + * User application must use this control to get locked, + * then can do next PCM operation + */ +static int snd_mxc_spdif_rxrate_get(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct mxc_spdif_device *chip = snd_kcontrol_chip(kcontrol); + struct mxc_spdif_platform_data *spdif_data; + + spdif_data = chip->card->dev->platform_data; + + if (atomic_read(&chip->dpll_locked)) { + ucontrol->value.integer.value[0] = + spdif_get_rxclk_rate(spdif_data->spdif_clk, + SPDIF_DEFAULT_GAINSEL); + } else { + ucontrol->value.integer.value[0] = 0; + } + return 0; +} + +/*! + * User bit sync mode info + */ +static int snd_mxc_spdif_usync_info(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_info *uinfo) +{ + uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN; + uinfo->count = 1; + uinfo->value.integer.min = 0; + uinfo->value.integer.max = 1; + return 0; +} + +/*! + * User bit sync mode: + * 1 CD User channel subcode + * 0 Non-CD data + */ +static int snd_mxc_spdif_usync_get(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + unsigned int int_val; + + int_val = __raw_readl(spdif_base_addr + SPDIF_REG_SRCD); + ucontrol->value.integer.value[0] = (int_val & SRCD_CD_USER) != 0; + return 0; +} + +/*! + * User bit sync mode: + * 1 CD User channel subcode + * 0 Non-CD data + */ +static int snd_mxc_spdif_usync_put(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + unsigned int int_val; + + int_val = ucontrol->value.integer.value[0] << SRCD_CD_USER_OFFSET; + __raw_writel(int_val, spdif_base_addr + SPDIF_REG_SRCD); + return 0; +} + +/*! + * MXC SPDIF IEC958 controller defines + */ +static struct snd_kcontrol_new snd_mxc_spdif_ctrls[] = { + /* status cchanel controller */ + { + .iface = SNDRV_CTL_ELEM_IFACE_MIXER, + .name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, DEFAULT), + .access = SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_WRITE | + SNDRV_CTL_ELEM_ACCESS_VOLATILE, + .info = mxc_pb_spdif_info, + .get = mxc_pb_spdif_get, + .put = mxc_pb_spdif_put, + }, + { + .iface = SNDRV_CTL_ELEM_IFACE_PCM, + .name = SNDRV_CTL_NAME_IEC958("", CAPTURE, DEFAULT), + .access = SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_VOLATILE, + .info = snd_mxc_spdif_info, + .get = snd_mxc_spdif_capture_get, + }, + /* user bits controller */ + { + .iface = SNDRV_CTL_ELEM_IFACE_PCM, + .name = "IEC958 Subcode Capture Default", + .access = SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_VOLATILE, + .info = snd_mxc_spdif_info, + .get = snd_mxc_spdif_subcode_get, + }, + { + .iface = SNDRV_CTL_ELEM_IFACE_PCM, + .name = "IEC958 Q-subcode Capture Default", + .access = SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_VOLATILE, + .info = snd_mxc_spdif_qinfo, + .get = snd_mxc_spdif_qget, + }, + /* valid bit error controller */ + { + .iface = SNDRV_CTL_ELEM_IFACE_PCM, + .name = "IEC958 V-Bit Errors", + .access = SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_VOLATILE, + .info = snd_mxc_spdif_vbit_info, + .get = snd_mxc_spdif_vbit_get, + }, + /* DPLL lock info get controller */ + { + .iface = SNDRV_CTL_ELEM_IFACE_PCM, + .name = "RX Sample Rate", + .access = SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_VOLATILE, + .info = snd_mxc_spdif_rxrate_info, + .get = snd_mxc_spdif_rxrate_get, + }, + /* User bit sync mode set/get controller */ + { + .iface = SNDRV_CTL_ELEM_IFACE_PCM, + .name = "IEC958 USyncMode CDText", + .access = + SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_WRITE | + SNDRV_CTL_ELEM_ACCESS_VOLATILE, + .info = snd_mxc_spdif_usync_info, + .get = snd_mxc_spdif_usync_get, + .put = snd_mxc_spdif_usync_put, + }, +}; + +/*! + * This function the soundcard structure. + * + * @param mxc_spdif pointer to the sound card structure. + * + * @return 0 on success, -1 otherwise. + */ +static int snd_card_mxc_spdif_pcm(struct mxc_spdif_device *mxc_spdif) +{ + struct snd_pcm *pcm; + int err; + err = snd_pcm_new(mxc_spdif->card, MXC_SPDIF_NAME, 0, + mxc_spdif->mxc_spdif_tx, + mxc_spdif->mxc_spdif_rx, &pcm); + if (err < 0) + return err; + + snd_pcm_lib_preallocate_pages_for_all(pcm, + SNDRV_DMA_TYPE_CONTINUOUS, + snd_dma_continuous_data + (GFP_KERNEL), + SPDIF_MAX_BUF_SIZE * 2, + SPDIF_MAX_BUF_SIZE * 2); + if (mxc_spdif->mxc_spdif_tx) + snd_pcm_set_ops(pcm, + SNDRV_PCM_STREAM_PLAYBACK, + &snd_card_mxc_spdif_playback_ops); + if (mxc_spdif->mxc_spdif_rx) + snd_pcm_set_ops(pcm, + SNDRV_PCM_STREAM_CAPTURE, + &snd_card_mxc_spdif_capture_ops); + pcm->private_data = mxc_spdif; + pcm->info_flags = 0; + strncpy(pcm->name, MXC_SPDIF_NAME, sizeof(pcm->name)); + mxc_spdif->pcm = pcm; + mxc_init_spdif_device(mxc_spdif); + return 0; +} + +extern void gpio_spdif_active(void); + +/*! + * This function initializes the driver in terms of memory of the soundcard + * and some basic HW clock settings. + * + * @param pdev Pointer to the platform device + * @return 0 on success, -1 otherwise. + */ +static int mxc_alsa_spdif_probe(struct platform_device + *pdev) +{ + int err, idx, irq; + static int dev; + struct snd_card *card; + struct mxc_spdif_device *chip; + struct resource *res; + struct snd_kcontrol *kctl; + struct mxc_spdif_platform_data *plat_data; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!res) + return -ENOENT; + + if (dev >= SNDRV_CARDS) + return -ENODEV; + if (!enable[dev]) { + dev++; + return -ENOENT; + } + + /* register the soundcard */ + err = snd_card_create(index[dev], id[dev], THIS_MODULE, + sizeof(struct mxc_spdif_device), &card); + if (err < 0) + return err; + chip = card->private_data; + chip->card = card; + card->dev = &pdev->dev; + chip->reg_phys_base = res->start; + chip->reg_base = ioremap(res->start, res->end - res->start + 1); + spdif_base_addr = (unsigned long)chip->reg_base; + plat_data = (struct mxc_spdif_platform_data *)pdev->dev.platform_data; + chip->mxc_spdif_tx = plat_data->spdif_tx; + chip->mxc_spdif_rx = plat_data->spdif_rx; + chip->spdif_txclk_44100 = plat_data->spdif_clk_44100; + chip->spdif_txclk_48000 = plat_data->spdif_clk_48000; + atomic_set(&chip->dpll_locked, 0); + + err = snd_card_mxc_spdif_pcm(chip); + if (err < 0) + goto nodev; + + /*! + * Add controls to the card + */ + for (idx = 0; idx < ARRAY_SIZE(snd_mxc_spdif_ctrls); idx++) { + + kctl = snd_ctl_new1(&snd_mxc_spdif_ctrls[idx], chip); + if (kctl == NULL) { + err = -ENOMEM; + goto nodev; + } + /* check to add control to corresponding substream */ + if (strstr(kctl->id.name, "Playback")) + kctl->id.device = 0; + else + kctl->id.device = 1; + + err = snd_ctl_add(card, kctl); + if (err < 0) + goto nodev; + } + + clk_enable(plat_data->spdif_core_clk); + /*! + * SPDIF interrupt initialization + * software reset to SPDIF + */ + spdif_softreset(); + /* disable all the interrupts */ + spdif_intr_enable(0xffffff, 0); + /* spdif interrupt register and disable */ + irq = platform_get_irq(pdev, 0); + if ((irq <= 0) || request_irq(irq, spdif_isr, 0, "spdif", chip)) { + pr_err("MXC spdif: failed to request irq\n"); + err = -EBUSY; + goto nodev; + } + + if (chip->mxc_spdif_tx) + spin_lock_init(&chip->s[SNDRV_PCM_STREAM_PLAYBACK].dma_lock); + if (chip->mxc_spdif_rx) + spin_lock_init(&chip->s[SNDRV_PCM_STREAM_CAPTURE].dma_lock); + strcpy(card->driver, MXC_SPDIF_NAME); + strcpy(card->shortname, "MXC SPDIF TX/RX"); + sprintf(card->longname, "MXC Freescale with SPDIF"); + + err = snd_card_register(card); + if (err == 0) { + pr_info("MXC spdif support initialized\n"); + platform_set_drvdata(pdev, card); + gpio_spdif_active(); + return 0; + } + + nodev: + snd_card_free(card); + return err; +} + +extern void gpio_spdif_inactive(void); + +/*! + * This function releases the sound card and unmap the io address + * + * @param pdev Pointer to the platform device + * @return 0 on success, -1 otherwise. + */ + +static int mxc_alsa_spdif_remove(struct platform_device *pdev) +{ + struct mxc_spdif_device *chip; + struct snd_card *card; + struct mxc_spdif_platform_data *plat_data; + + card = platform_get_drvdata(pdev); + plat_data = pdev->dev.platform_data; + chip = card->private_data; + free_irq(platform_get_irq(pdev, 0), chip); + iounmap(chip->reg_base); + + snd_card_free(card); + platform_set_drvdata(pdev, NULL); + + clk_disable(plat_data->spdif_core_clk); + gpio_spdif_inactive(); + + return 0; +} + +#ifdef CONFIG_PM +/*! + * This function suspends all active streams. + * + * TBD + * + * @param card pointer to the sound card structure. + * @param state requested state + * + * @return 0 on success, -1 otherwise. + */ +static int mxc_alsa_spdif_suspend(struct platform_device *pdev, + pm_message_t state) +{ + return 0; +} + +/*! + * This function resumes all suspended streams. + * + * TBD + * + * @param card pointer to the sound card structure. + * @param state requested state + * + * @return 0 on success, -1 otherwise. + */ +static int mxc_alsa_spdif_resume(struct platform_device *pdev) +{ + return 0; +} +#endif + +static struct platform_driver mxc_alsa_spdif_driver = { + .probe = mxc_alsa_spdif_probe, + .remove = mxc_alsa_spdif_remove, +#ifdef CONFIG_PM + .suspend = mxc_alsa_spdif_suspend, + .resume = mxc_alsa_spdif_resume, +#endif + .driver = { + .name = "mxc_alsa_spdif", + }, +}; + +/*! + * This function registers the sound driver structure. + * + */ +static int __init mxc_alsa_spdif_init(void) +{ + return platform_driver_register(&mxc_alsa_spdif_driver); +} + +/*! + * This function frees the sound driver structure. + * + */ +static void __exit mxc_alsa_spdif_exit(void) +{ + platform_driver_unregister(&mxc_alsa_spdif_driver); +} + +module_init(mxc_alsa_spdif_init); +module_exit(mxc_alsa_spdif_exit); +MODULE_AUTHOR("FREESCALE SEMICONDUCTOR"); +MODULE_LICENSE("GPL"); +MODULE_DESCRIPTION("MXC ALSA driver for SPDIF"); diff --git a/sound/soc/Kconfig b/sound/soc/Kconfig index b1749bc67979..e2b2406ab8e7 100644 --- a/sound/soc/Kconfig +++ b/sound/soc/Kconfig @@ -36,6 +36,7 @@ source "sound/soc/s3c24xx/Kconfig" source "sound/soc/s6000/Kconfig" source "sound/soc/sh/Kconfig" source "sound/soc/txx9/Kconfig" +source "sound/soc/mxs/Kconfig" # Supported codecs source "sound/soc/codecs/Kconfig" diff --git a/sound/soc/Makefile b/sound/soc/Makefile index 1470141d4167..6f3109485742 100644 --- a/sound/soc/Makefile +++ b/sound/soc/Makefile @@ -14,3 +14,4 @@ obj-$(CONFIG_SND_SOC) += s3c24xx/ obj-$(CONFIG_SND_SOC) += s6000/ obj-$(CONFIG_SND_SOC) += sh/ obj-$(CONFIG_SND_SOC) += txx9/ +obj-$(CONFIG_SND_SOC) += mxs/ diff --git a/sound/soc/codecs/Kconfig b/sound/soc/codecs/Kconfig index 5da30eb6ad00..bf8151a4f07b 100644 --- a/sound/soc/codecs/Kconfig +++ b/sound/soc/codecs/Kconfig @@ -23,6 +23,7 @@ config SND_SOC_ALL_CODECS select SND_SOC_AK4671 if I2C select SND_SOC_CQ0093VC if MFD_DAVINCI_VOICECODEC select SND_SOC_CS4270 if I2C + select SND_SOC_CS42888 if I2C select SND_SOC_MAX9877 if I2C select SND_SOC_DA7210 if I2C select SND_SOC_PCM3008 @@ -117,6 +118,10 @@ config SND_SOC_AK4642 config SND_SOC_AK4671 tristate +config SND_SOC_AK5702 + tristate + depends on I2C + config SND_SOC_CQ0093VC tristate @@ -138,6 +143,9 @@ config SND_SOC_CS4270_VD33_ERRATA config SND_SOC_CX20442 tristate +config SND_SOC_CS42888 + tristate + config SND_SOC_L3 tristate @@ -269,6 +277,21 @@ config SND_SOC_WM9712 config SND_SOC_WM9713 tristate +config SND_SOC_SGTL5000 + tristate + +config SND_SOC_AK4647 + tristate + +config SND_SOC_MXS_ADC_CODEC + tristate + +config SND_SOC_BLUETOOTH + tristate + +config SND_SOC_MXS_SPDIF + tristate + # Amp config SND_SOC_MAX9877 tristate diff --git a/sound/soc/codecs/Makefile b/sound/soc/codecs/Makefile index 91429eab0707..4c0ade6bd995 100644 --- a/sound/soc/codecs/Makefile +++ b/sound/soc/codecs/Makefile @@ -10,6 +10,7 @@ snd-soc-ak4642-objs := ak4642.o snd-soc-ak4671-objs := ak4671.o snd-soc-cq93vc-objs := cq93vc.o snd-soc-cs4270-objs := cs4270.o +snd-soc-cs42888-objs := cs42888.o snd-soc-cx20442-objs := cx20442.o snd-soc-da7210-objs := da7210.o snd-soc-l3-objs := l3.o @@ -56,6 +57,12 @@ snd-soc-wm9705-objs := wm9705.o snd-soc-wm9712-objs := wm9712.o snd-soc-wm9713-objs := wm9713.o snd-soc-wm-hubs-objs := wm_hubs.o +snd-soc-sgtl5000-objs := sgtl5000.o +snd-soc-ak4647-objs := ak4647.o +snd-soc-ak5702-objs := ak5702.o +snd-soc-bluetooth-objs := bluetooth.o +snd-soc-mxs-spdif-objs := mxs_spdif.o +snd-soc-mxs-adc-objs := mxs-adc-codec.o # Amp snd-soc-max9877-objs := max9877.o @@ -75,6 +82,7 @@ obj-$(CONFIG_SND_SOC_AK4642) += snd-soc-ak4642.o obj-$(CONFIG_SND_SOC_AK4671) += snd-soc-ak4671.o obj-$(CONFIG_SND_SOC_CQ0093VC) += snd-soc-cq93vc.o obj-$(CONFIG_SND_SOC_CS4270) += snd-soc-cs4270.o +obj-$(CONFIG_SND_SOC_CS42888) += snd-soc-cs42888.o obj-$(CONFIG_SND_SOC_CX20442) += snd-soc-cx20442.o obj-$(CONFIG_SND_SOC_DA7210) += snd-soc-da7210.o obj-$(CONFIG_SND_SOC_L3) += snd-soc-l3.o @@ -121,6 +129,12 @@ obj-$(CONFIG_SND_SOC_WM9705) += snd-soc-wm9705.o obj-$(CONFIG_SND_SOC_WM9712) += snd-soc-wm9712.o obj-$(CONFIG_SND_SOC_WM9713) += snd-soc-wm9713.o obj-$(CONFIG_SND_SOC_WM_HUBS) += snd-soc-wm-hubs.o +obj-$(CONFIG_SND_SOC_SGTL5000) += snd-soc-sgtl5000.o +obj-$(CONFIG_SND_SOC_AK4647) += snd-soc-ak4647.o +obj-$(CONFIG_SND_SOC_AK5702) += snd-soc-ak5702.o +obj-$(CONFIG_SND_SOC_BLUETOOTH) += snd-soc-bluetooth.o +obj-$(CONFIG_SND_SOC_MXS_SPDIF) += snd-soc-mxs-spdif.o +obj-$(CONFIG_SND_SOC_MXS_ADC_CODEC) += snd-soc-mxs-adc.o # Amp obj-$(CONFIG_SND_SOC_MAX9877) += snd-soc-max9877.o diff --git a/sound/soc/codecs/ak4647.c b/sound/soc/codecs/ak4647.c new file mode 100644 index 000000000000..98865daf772a --- /dev/null +++ b/sound/soc/codecs/ak4647.c @@ -0,0 +1,800 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file ak4647.c + * @brief Driver for AK4647 + * + * @ingroup Sound + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "ak4647.h" + +#define SET_BIT_IN_BYTE(byte, pos) (byte |= (0x01 << pos)) +#define CLEAR_BIT_IN_BYTE(byte, pos) (byte &= ~(0x01 << pos)) + +static struct i2c_client *ak4647_i2c_client; + +int ak4647_read_reg(unsigned int reg, u8 *value) +{ + s32 retval; + retval = i2c_smbus_read_byte_data(ak4647_i2c_client, reg); + if (retval < 0) { + pr_err("%s:read reg errorr:reg=%x,val=%x\n", + __func__, reg, retval); + return -1; + } else { + *value = (u8) retval; + return 0; + } +} + +int ak4647_write_reg(unsigned int reg, u8 value) +{ + if (i2c_smbus_write_byte_data(ak4647_i2c_client, reg, value) < 0) { + pr_err("%s:write reg errorr:reg=%x,val=%x\n", + __func__, reg, value); + return -1; + } + return 0; +} + +static unsigned int ak4647_codec_read(struct snd_soc_codec *codec, + unsigned int reg) +{ + u8 value; + ak4647_read_reg(reg, &value); + return value; +} + +static int ak4647_codec_write(struct snd_soc_codec *codec, unsigned int reg, + unsigned int value) +{ + return ak4647_write_reg(reg, value); +} + +#define DEBUG_AK4647 0 + +#if DEBUG_AK4647 + +static char *ak4647_reg_names[] = { + "AK4647_PM1", + "AK4647_PM2", + "AK4647_SIG1", + "AK4647_SIG2", + "AK4647_MODE1", + "AK4647_MODE2", + "AK4647_TIMER", + "AK4647_ALC1", + "AK4647_ALC2", + "AK4647_LEFT_INPUT_VOLUME", + "AK4647_LEFT_DGT_VOLUME", + "AK4647_ALC3", + "AK4647_RIGHT_INPUT_VOLUME", + "AK4647_RIGHT_DGT_VOLUME", + "AK4647_MODE3", + "AK4647_MODE4", + "AK4647_PM3", + "AK4647_DGT_FIL_SEL", + "AK4647_FIL3_COEF0", + "AK4647_FIL3_COEF1", + "AK4647_FIL3_COEF2", + "AK4647_FIL3_COEF3", + "AK4647_EQ_COEF0", + "AK4647_EQ_COEF1", + "AK4647_EQ_COEF2", + "AK4647_EQ_COEF3", + "AK4647_EQ_COEF4", + "AK4647_EQ_COEF5", + "AK4647_FIL1_COEF0", + "AK4647_FIL1_COEF1", + "AK4647_FIL1_COEF2", + "AK4647_FIL1_COEF3", +}; + +static void dump_all_regs(void) +{ + int i; + u8 value; + + for (i = AK4647_REG_START; i < AK4647_REG_NUMBER; i++) { + ak4647_read_reg(i, &value); + pr_info("%s = 0x%x\n", ak4647_reg_names[i], value); + } +} +#endif + +static int loopback_xhandle_get(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol); +static int loopback_xhandle_put(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol); + +static const char *ak4647_hp_out[] = { "Stereo", "Mono" }; + +static const char *ak4647_left_in[] = { "LIN1", "LIN2" }; + +static const char *ak4647_right_in[] = { "RIN1", "RIN2" }; + +static const char *ak4647_deemp[] = { "44.1kHz", "Off", "48kHz", "32kHz" }; + +static const struct soc_enum ak4647_enum[] = { + SOC_ENUM_SINGLE(AK4647_MODE4, 2, 2, ak4647_hp_out), + SOC_ENUM_SINGLE(AK4647_MODE3, 0, 4, ak4647_deemp), + SOC_ENUM_SINGLE(AK4647_PM3, 1, 2, ak4647_left_in), + SOC_ENUM_SINGLE(AK4647_PM3, 2, 2, ak4647_right_in), +}; + +#undef snd_soc_info_bool_ext +#define snd_soc_info_bool_ext snd_ctl_boolean_mono_info +static const struct snd_kcontrol_new ak4647_snd_controls[] = { + SOC_ENUM("Headphone Output", ak4647_enum[0]), + SOC_ENUM("Playback Deemphasis", ak4647_enum[1]), + SOC_ENUM("Left Capture Select", ak4647_enum[2]), + SOC_ENUM("Right Capture Select", ak4647_enum[3]), + SOC_SINGLE("Bass Volume", AK4647_MODE3, 2, 3, 0), + SOC_SINGLE("Mic Boost (+20dB) Switch", AK4647_SIG1, 0, 1, 0), + SOC_SINGLE("Mic Bias", AK4647_SIG1, 2, 1, 0), + SOC_SINGLE("ALC Switch", AK4647_ALC1, 5, 1, 0), + SOC_SINGLE("ALC Recovery Time", AK4647_TIMER, 2, 3, 0), + SOC_SINGLE("ALC ZC Time", AK4647_TIMER, 4, 3, 0), + SOC_SINGLE("ALC Volume", AK4647_ALC2, 0, 127, 0), + SOC_SINGLE("Left Capture Volume", AK4647_LEFT_INPUT_VOLUME, 0, 242, 0), + SOC_SINGLE("Right Capture Volume", + AK4647_RIGHT_INPUT_VOLUME, 0, 242, 0), + SOC_SINGLE("Left Playback Volume", AK4647_LEFT_DGT_VOLUME, 0, 255, 1), + SOC_SINGLE("Right Playback Volume", AK4647_RIGHT_DGT_VOLUME, 0, 255, 1), + SOC_SINGLE_BOOL_EXT("Loopback Line-in", 0, + loopback_xhandle_get, loopback_xhandle_put), +}; + +/* Stereo Mixer for HP*/ +static const struct snd_kcontrol_new ak4647_hp_stereo_mixer_controls[] = { + SOC_DAPM_SINGLE("Playback Switch", AK4647_MODE4, 0, 1, 0), + SOC_DAPM_SINGLE("Mic Sidetone Switch", AK4647_MODE4, 1, 1, 0), +}; + +/* Stereo Mixer for Line out*/ +static const struct snd_kcontrol_new ak4647_line_stereo_mixer_controls[] = { + SOC_DAPM_SINGLE("Playback Switch", AK4647_SIG1, 4, 1, 0), + SOC_DAPM_SINGLE("Mic Sidetone Switch", AK4647_SIG2, 2, 1, 0), +}; + +/* ak4647 dapm widgets */ +static const struct snd_soc_dapm_widget ak4647_dapm_widgets[] = { + SND_SOC_DAPM_MIXER("Headphone Mixer", SND_SOC_NOPM, 0, 0, + &ak4647_hp_stereo_mixer_controls[0], + ARRAY_SIZE(ak4647_hp_stereo_mixer_controls)), + SND_SOC_DAPM_MIXER("Lineout Mixer", SND_SOC_NOPM, 0, 0, + &ak4647_line_stereo_mixer_controls[0], + ARRAY_SIZE(ak4647_line_stereo_mixer_controls)), + SND_SOC_DAPM_DAC("DAC", "Playback", AK4647_PM1, 2, 0), + SND_SOC_DAPM_OUTPUT("HPL"), + SND_SOC_DAPM_OUTPUT("HPR"), + SND_SOC_DAPM_OUTPUT("LOUT"), + + SND_SOC_DAPM_ADC("Left ADC", "Capture", AK4647_PM1, 0, 0), + SND_SOC_DAPM_ADC("Right ADC", "Capture", AK4647_PM3, 0, 0), + SND_SOC_DAPM_PGA("HP R Amp", AK4647_PM2, 4, 0, NULL, 0), + SND_SOC_DAPM_PGA("HP L Amp", AK4647_PM2, 5, 0, NULL, 0), + SND_SOC_DAPM_PGA("Mic", AK4647_PM1, 5, 0, NULL, 0), + SND_SOC_DAPM_PGA("Line Out Amp", AK4647_PM1, 3, 0, NULL, 0), + + SND_SOC_DAPM_MICBIAS("Mic Bias", AK4647_SIG1, 2, 0), + SND_SOC_DAPM_INPUT("Left Input"), + SND_SOC_DAPM_INPUT("Right Input"), +}; + +static const struct snd_soc_dapm_route audio_map[] = { + /*headphone stereo mixer */ + {"Headphone Mixer", "Playback Switch", "DAC"}, + {"Headphone Mixer", "Mic Sidetone Switch", "Mic"}, + + /*lineout stereo mixer */ + {"Lineout Mixer", "Playback Switch", "DAC"}, + {"Lineout Mixer", "Mic Sidetone Switch", "Mic"}, + + /* headphone amp */ + {"HP R Amp", NULL, "Headphone Mixer"}, + {"HP L Amp", NULL, "Headphone Mixer"}, + + /* headphone */ + {"HPR", NULL, "HP R Amp"}, + {"HPL", NULL, "HP L Amp"}, + + /* line out */ + {"Line Out Amp", NULL, "Lineout Mixer"}, + {"LOUT", NULL, "Line Out Amp"}, + + /* ADC */ + {"Left ADC", NULL, "Left Input"}, + {"Right ADC", NULL, "Right Input"}, + +}; + +static int ak4647_add_widgets(struct snd_soc_codec *codec) +{ + snd_soc_dapm_new_controls(codec, ak4647_dapm_widgets, + ARRAY_SIZE(ak4647_dapm_widgets)); + + /* set up audio path audio_mapnects */ + snd_soc_dapm_add_routes(codec, audio_map, ARRAY_SIZE(audio_map)); + + snd_soc_dapm_new_widgets(codec); + return 0; +} + +#define AK4647_RATES (SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_11025 | \ + SNDRV_PCM_RATE_16000 | SNDRV_PCM_RATE_22050 | \ + SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_32000 | \ + SNDRV_PCM_RATE_48000) + +#define AK4647_FORMATS SNDRV_PCM_FMTBIT_S16_LE + +static int ak4647_set_dai_sysclk(struct snd_soc_dai *codec_dai, + int clk_id, unsigned int freq, int dir) +{ + u8 value; + u8 fs = 0; + + /* FS3 is on D5 */ + switch (freq) { + case 8000: + fs = 0x0; + break; + case 11025: + fs = 0x5; + break; + case 16000: + fs = 0x2; + break; + case 22050: + fs = 0x7; + break; + case 32000: + fs = 0x22; + break; + case 44100: + fs = 0x27; + break; + case 48000: + fs = 0x23; + break; + default: + pr_err("unsupported sample rate"); + return -1; + } + + ak4647_read_reg(AK4647_MODE2, &value); + value &= 0xC0; + value |= fs; + ak4647_write_reg(AK4647_MODE2, value); + return 0; +} + +static int ak4647_set_dai_fmt(struct snd_soc_dai *codec_dai, unsigned int fmt) +{ + u8 reg_mode1, reg_pm2; + + /* get current values */ + ak4647_read_reg(AK4647_MODE1, ®_mode1); + ak4647_read_reg(AK4647_PM2, ®_pm2); + + /* set master/slave audio interface */ + switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) { + case SND_SOC_DAIFMT_CBM_CFM: + SET_BIT_IN_BYTE(reg_pm2, 3); + break; + case SND_SOC_DAIFMT_CBS_CFS: + CLEAR_BIT_IN_BYTE(reg_pm2, 3); + break; + default: + return -EINVAL; + } + + /* interface format */ + switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { + case SND_SOC_DAIFMT_I2S: + SET_BIT_IN_BYTE(reg_mode1, 0); + SET_BIT_IN_BYTE(reg_mode1, 1); + break; + case SND_SOC_DAIFMT_RIGHT_J: + SET_BIT_IN_BYTE(reg_mode1, 0); + CLEAR_BIT_IN_BYTE(reg_mode1, 1); + break; + case SND_SOC_DAIFMT_LEFT_J: + CLEAR_BIT_IN_BYTE(reg_mode1, 0); + SET_BIT_IN_BYTE(reg_mode1, 1); + break; + case SND_SOC_DAIFMT_DSP_A: + case SND_SOC_DAIFMT_DSP_B: + default: + pr_err("dai format %d not supported", fmt); + return -EINVAL; + } + + ak4647_write_reg(AK4647_MODE1, reg_mode1); + ak4647_write_reg(AK4647_PM2, reg_pm2); + return 0; +} + +static int ak4647_set_clkdiv(struct snd_soc_dai *codec_dai, int div_id, int div) +{ + int retval = 0; + u8 value; + if (AK4647_BCLK_CLKDIV == div_id) { + ak4647_read_reg(AK4647_MODE1, &value); + switch (div) { + case AK4647_BCLK_DIV_32: + CLEAR_BIT_IN_BYTE(value, 3); + ak4647_write_reg(AK4647_MODE1, value); + break; + case AK4647_BCLK_DIV_64: + SET_BIT_IN_BYTE(value, 3); + ak4647_write_reg(AK4647_MODE1, value); + break; + default: + retval = -1; + pr_err("wrong div value for divid %d", div_id); + break; + } + } else if (AK4647_MCLK_CLKDIV == div_id) { + ak4647_read_reg(AK4647_MODE2, &value); + switch (div) { + case AK4647_MCLK_DIV_32: + SET_BIT_IN_BYTE(value, 7); + SET_BIT_IN_BYTE(value, 6); + ak4647_write_reg(AK4647_MODE2, value); + break; + case AK4647_MCLK_DIV_64: + SET_BIT_IN_BYTE(value, 7); + CLEAR_BIT_IN_BYTE(value, 6); + ak4647_write_reg(AK4647_MODE2, value); + break; + case AK4647_MCLK_DIV_128: + CLEAR_BIT_IN_BYTE(value, 7); + SET_BIT_IN_BYTE(value, 6); + ak4647_write_reg(AK4647_MODE2, value); + break; + case AK4647_MCLK_DIV_256: + CLEAR_BIT_IN_BYTE(value, 7); + CLEAR_BIT_IN_BYTE(value, 6); + ak4647_write_reg(AK4647_MODE2, value); + break; + default: + retval = -1; + pr_err("wrong div value for div id %d", div_id); + break; + } + } else { + retval = -1; + pr_err("wrong div id"); + } + + return retval; +} + +static int ak4647_digital_mute(struct snd_soc_dai *dai, int mute) +{ + u8 value; + + ak4647_read_reg(AK4647_MODE3, &value); + + if (mute) + SET_BIT_IN_BYTE(value, 5); + else + CLEAR_BIT_IN_BYTE(value, 5); + ak4647_write_reg(AK4647_MODE3, value); + return 0; +} + +struct ak4647_state_data { + u8 left_capture_vol; + u8 right_capture_vol; +}; +static struct ak4647_state_data ak4647_state; + +static int ak4647_pcm_startup(struct snd_pcm_substream *substream, + struct snd_soc_dai *dai) +{ + u8 value; + /* for playback, save down capture volume */ + if (SNDRV_PCM_STREAM_PLAYBACK == substream->stream) { + ak4647_read_reg(AK4647_LEFT_INPUT_VOLUME, &value); + ak4647_state.left_capture_vol = value; + ak4647_read_reg(AK4647_RIGHT_INPUT_VOLUME, &value); + ak4647_state.right_capture_vol = value; + + /* when PMADL=PMADR=0 set IVL &IVR to be 0x91 (0db) */ + ak4647_write_reg(AK4647_LEFT_INPUT_VOLUME, 0x91); + ak4647_write_reg(AK4647_RIGHT_INPUT_VOLUME, 0x91); + } + + /* output digital volume independent */ + ak4647_read_reg(AK4647_MODE3, &value); + CLEAR_BIT_IN_BYTE(value, 4); + ak4647_write_reg(AK4647_MODE3, value); + return 0; +} + +static void ak4647_pcm_shutdown(struct snd_pcm_substream *substream, + struct snd_soc_dai *dai) +{ + u8 value; + ak4647_read_reg(AK4647_PM2, &value); + /* mute */ + CLEAR_BIT_IN_BYTE(value, 6); + ak4647_write_reg(AK4647_PM2, value); + + /* after playback, restore capture volume */ + if (SNDRV_PCM_STREAM_PLAYBACK == substream->stream) { + ak4647_write_reg(AK4647_LEFT_INPUT_VOLUME, + ak4647_state.left_capture_vol); + ak4647_write_reg(AK4647_RIGHT_INPUT_VOLUME, + ak4647_state.right_capture_vol); + } +} + +static int ak4647_pcm_prepare(struct snd_pcm_substream *substream, + struct snd_soc_dai *dai) +{ + u8 value; + + /* VCOM power on */ + ak4647_write_reg(AK4647_PM1, 0x44); + msleep(30); + + ak4647_read_reg(AK4647_PM2, &value); + /* PLL enabled */ + SET_BIT_IN_BYTE(value, 0); + + ak4647_write_reg(AK4647_PM2, value); + /* wait for PLL locked */ + msleep(40); + + /* don't mute */ + SET_BIT_IN_BYTE(value, 6); + ak4647_write_reg(AK4647_PM2, value); + return 0; +} + +struct snd_soc_dai_ops ak4647_ops = { + .prepare = ak4647_pcm_prepare, + .startup = ak4647_pcm_startup, + .shutdown = ak4647_pcm_shutdown, + .digital_mute = ak4647_digital_mute, + .set_fmt = ak4647_set_dai_fmt, + .set_sysclk = ak4647_set_dai_sysclk, + .set_clkdiv = ak4647_set_clkdiv, +}; + +struct snd_soc_dai ak4647_hifi_dai = { + .name = "ak4647", + .playback = { + .stream_name = "Playback", + .channels_min = 2, + .channels_max = 2, + .rates = AK4647_RATES, + .formats = AK4647_FORMATS, + }, + .capture = { + .stream_name = "Capture", + .channels_min = 1, + .channels_max = 2, + .rates = AK4647_RATES, + .formats = AK4647_FORMATS, + }, + .ops = &ak4647_ops, +}; +EXPORT_SYMBOL_GPL(ak4647_hifi_dai); + +static struct snd_soc_codec *ak4647_codec; + +static int ak4647_probe(struct platform_device *pdev) +{ + struct snd_soc_device *socdev = platform_get_drvdata(pdev); + struct snd_soc_codec *codec = ak4647_codec; + int ret = 0; + + socdev->card->codec = ak4647_codec; + + ret = snd_soc_new_pcms(socdev, SNDRV_DEFAULT_IDX1, SNDRV_DEFAULT_STR1); + if (ret < 0) { + dev_err(&ak4647_i2c_client->dev, "failed to create pcms\n"); + return ret; + } + + /* setup init value for audio path controls here */ + /* enable DAC to headphone */ + ak4647_write_reg(AK4647_MODE4, 0x9); + /* capture source to be LIN2 and RIN2 */ + ak4647_write_reg(AK4647_PM3, 0x6); + /* MPWR pin up */ + ak4647_write_reg(AK4647_SIG1, 0x5); + + /* MCKI = 12M, default audio interface format as "left-justified" */ + ak4647_write_reg(AK4647_MODE1, 0x62); + + /* ALC disabled */ + ak4647_write_reg(AK4647_ALC1, 0x0); + + ak4647_state.left_capture_vol = 0x91; + ak4647_state.right_capture_vol = 0x91; + + snd_soc_add_controls(codec, ak4647_snd_controls, + ARRAY_SIZE(ak4647_snd_controls)); + ak4647_add_widgets(codec); + + ret = snd_soc_init_card(socdev); + if (ret < 0) { + pr_err("ak4647: failed to register card\n"); + snd_soc_free_pcms(socdev); + snd_soc_dapm_free(socdev); + return ret; + } + + return 0; +} + +static __devexit int ak4647_i2c_remove(struct i2c_client *client) +{ + struct snd_soc_codec *codec = i2c_get_clientdata(client); + + snd_soc_unregister_dai(&ak4647_hifi_dai); + snd_soc_unregister_codec(codec); + kfree(codec); + ak4647_codec = NULL; + return 0; +} + +static int ak4647_i2c_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + struct snd_soc_codec *codec; + int ret; + u8 val; + + if (ak4647_codec) { + dev_err(&client->dev, + "Multiple AK4647 devices not supported\n"); + return -ENOMEM; + } + + codec = kzalloc(sizeof(struct snd_soc_codec), GFP_KERNEL); + if (codec == NULL) + return -ENOMEM; + + mutex_init(&codec->mutex); + INIT_LIST_HEAD(&codec->dapm_widgets); + INIT_LIST_HEAD(&codec->dapm_paths); + + i2c_set_clientdata(client, codec); + ak4647_i2c_client = client; + codec->control_data = client; + ret = ak4647_read_reg(AK4647_REG_START, &val); + if (ret < 0) { + pr_err("Device with ID register %x is not a AK4647\n", val); + return -ENODEV; + } + + codec->dev = &client->dev; + codec->name = "ak4647", codec->owner = THIS_MODULE; + codec->owner = THIS_MODULE; + codec->read = ak4647_codec_read; + codec->write = ak4647_codec_write; + codec->dai = &ak4647_hifi_dai; + codec->num_dai = 1; + + ak4647_codec = codec; + ak4647_hifi_dai.dev = &client->dev; + + ret = snd_soc_register_codec(codec); + if (ret != 0) { + dev_err(codec->dev, "Failed to register codec: %d\n", ret); + return ret; + } + + ret = snd_soc_register_dai(&ak4647_hifi_dai); + if (ret != 0) { + dev_err(codec->dev, "Failed to register DAIs: %d\n", ret); + return ret; + } + + return ret; +} + +static const struct i2c_device_id ak4647_id[] = { + {"ak4647-i2c", 0}, + {}, +}; + +MODULE_DEVICE_TABLE(i2c, ak4647_id); + +static struct i2c_driver ak4647_i2c_driver = { + .driver = { + .owner = THIS_MODULE, + .name = "ak4647-i2c", + }, + .probe = ak4647_i2c_probe, + .remove = __devexit_p(ak4647_i2c_remove), + .id_table = ak4647_id, +}; + +int pmic_audio_fm_output_enable(bool enable) +{ + u8 val; + if (enable) { + ak4647_set_dai_fmt(NULL, + SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | + SND_SOC_DAIFMT_CBM_CFM); + ak4647_set_dai_sysclk(NULL, 0, 44100, 0); + ak4647_set_clkdiv(NULL, 0, 0); + /* VCOM power on */ + ak4647_write_reg(AK4647_PM1, 0x44); + msleep(30); + + ak4647_read_reg(AK4647_PM2, &val); + /* PLL enabled */ + SET_BIT_IN_BYTE(val, 0); + + ak4647_write_reg(AK4647_PM2, val); + /* wait for PLL locked */ + msleep(40); + + /* don't mute */ + SET_BIT_IN_BYTE(val, 6); + ak4647_write_reg(AK4647_PM2, val); + + /* loopback STDO to DAC */ + ak4647_read_reg(AK4647_MODE3, &val); + SET_BIT_IN_BYTE(val, 6); + ak4647_write_reg(AK4647_MODE3, val); + + /* switch to R/L 1 */ + ak4647_read_reg(AK4647_PM3, &val); + CLEAR_BIT_IN_BYTE(val, 1); + CLEAR_BIT_IN_BYTE(val, 2); + ak4647_write_reg(AK4647_PM3, val); + + /* power up ADC */ + ak4647_read_reg(AK4647_PM1, &val); + SET_BIT_IN_BYTE(val, 0); + ak4647_write_reg(AK4647_PM1, val); + ak4647_read_reg(AK4647_PM3, &val); + SET_BIT_IN_BYTE(val, 0); + ak4647_write_reg(AK4647_PM3, val); + + /* power up DAC */ + ak4647_read_reg(AK4647_PM1, &val); + SET_BIT_IN_BYTE(val, 2); + ak4647_write_reg(AK4647_PM1, val); + + msleep(30); + + /* headphone output switch on */ + ak4647_read_reg(AK4647_MODE4, &val); + SET_BIT_IN_BYTE(val, 0); + ak4647_write_reg(AK4647_MODE4, val); + + /* power on headphone amp */ + ak4647_read_reg(AK4647_PM2, &val); + SET_BIT_IN_BYTE(val, 4); + SET_BIT_IN_BYTE(val, 5); + ak4647_write_reg(AK4647_PM2, val); + + ak4647_digital_mute(NULL, 0); + } else { + ak4647_digital_mute(NULL, 1); + + /* disbale loopback */ + ak4647_read_reg(AK4647_MODE3, &val); + CLEAR_BIT_IN_BYTE(val, 6); + SET_BIT_IN_BYTE(val, 5); + ak4647_write_reg(AK4647_MODE3, val); + + /* switch to R/L 2 */ + ak4647_read_reg(AK4647_PM3, &val); + SET_BIT_IN_BYTE(val, 1); + SET_BIT_IN_BYTE(val, 2); + ak4647_write_reg(AK4647_PM3, val); + } + return 0; +} + +static int loopback_xhandle_get(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + ucontrol->value.integer.value[0] = kcontrol->private_value; + return 0; +} + +static int loopback_xhandle_put(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + int changed; + long flag = ucontrol->value.integer.value[0]; + changed = + (ucontrol->value.integer.value[0] == + kcontrol->private_value) ? 0 : 1; + kcontrol->private_value = flag; + if (flag) + pmic_audio_fm_output_enable(true); + else + pmic_audio_fm_output_enable(false); + + return changed; +} + +/* power down chip */ +static int ak4647_remove(struct platform_device *pdev) +{ + struct snd_soc_device *socdev = platform_get_drvdata(pdev); + struct snd_soc_codec *codec = socdev->card->codec; + + snd_soc_free_pcms(socdev); + snd_soc_dapm_free(socdev); + i2c_del_driver(&ak4647_i2c_driver); + kfree(codec); + + return 0; +} + +static int ak4647_suspend(struct platform_device *pdev, pm_message_t state) +{ + return 0; +} + +static int ak4647_resume(struct platform_device *pdev) +{ + return 0; +} + +struct snd_soc_codec_device soc_codec_dev_ak4647 = { + .probe = ak4647_probe, + .remove = ak4647_remove, + .suspend = ak4647_suspend, + .resume = ak4647_resume, +}; +EXPORT_SYMBOL_GPL(soc_codec_dev_ak4647); + +static int __init ak4647_modinit(void) +{ + return i2c_add_driver(&ak4647_i2c_driver); +} +module_init(ak4647_modinit); + +static void __exit ak4647_exit(void) +{ + i2c_del_driver(&ak4647_i2c_driver); +} +module_exit(ak4647_exit); + +MODULE_DESCRIPTION("ASoC ak4647 driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/codecs/ak4647.h b/sound/soc/codecs/ak4647.h new file mode 100644 index 000000000000..d32a758c427b --- /dev/null +++ b/sound/soc/codecs/ak4647.h @@ -0,0 +1,92 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file ak4647.h + * @brief Driver for AK4647 + * + * @ingroup Sound + */ +#ifndef _AK4647_H_ +#define _AK4647_H_ + +#ifdef __KERNEL__ + +/*! + * AK4647 registers + */ + +#define AK4647_PM1 0x00 +#define AK4647_PM2 0x01 +#define AK4647_SIG1 0x02 +#define AK4647_SIG2 0x03 +#define AK4647_MODE1 0x04 +#define AK4647_MODE2 0x05 +#define AK4647_TIMER 0x06 +#define AK4647_ALC1 0x07 +#define AK4647_ALC2 0x08 + +#define AK4647_LEFT_INPUT_VOLUME 0x09 +#define AK4647_LEFT_DGT_VOLUME 0x0A +#define AK4647_ALC3 0x0B +#define AK4647_RIGHT_INPUT_VOLUME 0x0C +#define AK4647_RIGHT_DGT_VOLUME 0x0D +#define AK4647_MODE3 0x0E +#define AK4647_MODE4 0x0F +#define AK4647_PM3 0x10 +#define AK4647_DGT_FIL_SEL 0x11 + +/* filter 3 coeffecient*/ + +#define AK4647_FIL3_COEF0 0x12 +#define AK4647_FIL3_COEF1 0x13 +#define AK4647_FIL3_COEF2 0x14 +#define AK4647_FIL3_COEF3 0x15 + +/* eq coeffecient*/ + +#define AK4647_EQ_COEF0 0x16 +#define AK4647_EQ_COEF1 0x17 +#define AK4647_EQ_COEF2 0x18 +#define AK4647_EQ_COEF3 0x19 +#define AK4647_EQ_COEF4 0x1A +#define AK4647_EQ_COEF5 0x1B + +/* filter 3 coeffecient*/ + +#define AK4647_FIL1_COEF0 0x1C +#define AK4647_FIL1_COEF1 0x1D +#define AK4647_FIL1_COEF2 0x1E +#define AK4647_FIL1_COEF3 0x1F + +#define AK4647_REG_START 0x00 +#define AK4647_REG_END 0x1F +#define AK4647_REG_NUMBER 0x20 + +/* clock divider id's */ +#define AK4647_BCLK_CLKDIV 0 +#define AK4647_MCLK_CLKDIV 1 + +/* bit clock div values (AK4647_BCLK_CLKDIV)*/ +#define AK4647_BCLK_DIV_32 0 +#define AK4647_BCLK_DIV_64 1 + +/* m clock div values (AK4647_MCLK_CLKDIV)*/ +#define AK4647_MCLK_DIV_32 0 +#define AK4647_MCLK_DIV_64 1 +#define AK4647_MCLK_DIV_128 2 +#define AK4647_MCLK_DIV_256 3 + +#endif /* __KERNEL__ */ + +#endif /* _AK4647_H_ */ diff --git a/sound/soc/codecs/ak5702.c b/sound/soc/codecs/ak5702.c new file mode 100644 index 000000000000..f3fdbd0d14e5 --- /dev/null +++ b/sound/soc/codecs/ak5702.c @@ -0,0 +1,608 @@ +/* + * ak5702.c -- AK5702 Soc Audio driver + * + * Copyright 2009-2010 Freescale Semiconductor, Inc. All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ak5702.h" + +#define AK5702_VERSION "0.1" + +/* codec private data */ +struct ak5702_priv { + unsigned int sysclk; +}; + +/* + * ak5702 register cache + */ +static const u16 ak5702_reg[AK5702_CACHEREGNUM] = { + 0x0000, 0x0024, 0x0000, 0x0001, 0x0023, 0x001f, + 0x0000, 0x0001, 0x0091, 0x0000, 0x00e1, 0x0000, + 0x00a0, 0x0000, 0x0000, 0x0000, 0x0001, 0x0020, + 0x0000, 0x0000, 0x0001, 0x0091, 0x0000, 0x00e1, + 0x0000, +}; + +/* + * read ak5702 register cache + */ +static inline unsigned int ak5702_read_reg_cache(struct snd_soc_codec *codec, + unsigned int reg) +{ + u16 *cache = codec->reg_cache; + + if (reg >= AK5702_CACHEREGNUM) + return -1; + return cache[reg]; +} + +static inline unsigned int ak5702_read(struct snd_soc_codec *codec, + unsigned int reg) +{ + u8 data; + data = reg; + + if (codec->hw_write(codec->control_data, &data, 1) != 1) + return -EIO; + if (codec->hw_read(codec->control_data, &data, 1) != 1) + return -EIO; + + return data; +}; + +/* + * write ak5702 register cache + */ +static inline void ak5702_write_reg_cache(struct snd_soc_codec *codec, + u16 reg, unsigned int value) +{ + u16 *cache = codec->reg_cache; + + if (reg >= AK5702_CACHEREGNUM) + return; + cache[reg] = value; +} + +/* + * write to the AK5702 register space + */ +static int ak5702_write(struct snd_soc_codec *codec, unsigned int reg, + unsigned int value) +{ + u8 data[2]; + + data[0] = reg & 0xff; + data[1] = value & 0xff; + + ak5702_write_reg_cache(codec, reg, value); + if (codec->hw_write(codec->control_data, data, 2) == 2) + return 0; + else + return -EIO; +} + +static const char *ak5702_mic_gain[] = { "0dB", "+15dB", "+30dB", "+36dB" }; +static const char *ak5702_adca_left_type[] = { + "Single-ended", "Full-differential" }; +static const char *ak5702_adca_right_type[] = { + "Single-ended", "Full-differential" }; +static const char *ak5702_adcb_left_type[] = { + "Single-ended", "Full-differential" }; +static const char *ak5702_adcb_right_type[] = { + "Single-ended", "Full-differential" }; +static const char *ak5702_adca_left_input[] = { "LIN1", "LIN2" }; +static const char *ak5702_adca_right_input[] = { "RIN1", "RIN2" }; +static const char *ak5702_adcb_left_input[] = { "LIN3", "LIN4" }; +static const char *ak5702_adcb_right_input[] = { "RIN3", "RIN4" }; + +static const struct soc_enum ak5702_enum[] = { + SOC_ENUM_SINGLE(AK5702_MICG1, 0, 4, ak5702_mic_gain), + SOC_ENUM_SINGLE(AK5702_MICG2, 0, 4, ak5702_mic_gain), + + SOC_ENUM_SINGLE(AK5702_SIG1, 0, 2, ak5702_adca_left_input), + SOC_ENUM_SINGLE(AK5702_SIG1, 1, 2, ak5702_adca_right_input), + SOC_ENUM_SINGLE(AK5702_SIG2, 0, 2, ak5702_adcb_left_input), + SOC_ENUM_SINGLE(AK5702_SIG1, 1, 2, ak5702_adcb_right_input), + + SOC_ENUM_SINGLE(AK5702_SIG1, 2, 2, ak5702_adca_left_type), + SOC_ENUM_SINGLE(AK5702_SIG1, 3, 2, ak5702_adca_right_type), + SOC_ENUM_SINGLE(AK5702_SIG2, 2, 2, ak5702_adcb_left_type), + SOC_ENUM_SINGLE(AK5702_SIG2, 3, 2, ak5702_adcb_right_type), +}; + +static const struct snd_kcontrol_new ak5702_snd_controls[] = { + SOC_SINGLE("ADCA Left Vol", AK5702_LVOL1, 0, 242, 0), + SOC_SINGLE("ADCA Right Vol", AK5702_RVOL1, 0, 242, 0), + SOC_SINGLE("ADCB Left Vol", AK5702_LVOL2, 0, 242, 0), + SOC_SINGLE("ADCB Right Vol", AK5702_RVOL2, 0, 242, 0), + + SOC_ENUM("MIC-AmpA Gain", ak5702_enum[0]), + SOC_ENUM("MIC-AmpB Gain", ak5702_enum[1]), + + SOC_ENUM("ADCA Left Source", ak5702_enum[2]), + SOC_ENUM("ADCA Right Source", ak5702_enum[3]), + SOC_ENUM("ADCB Left Source", ak5702_enum[4]), + SOC_ENUM("ADCB Right Source", ak5702_enum[5]), + + SOC_ENUM("ADCA Left Type", ak5702_enum[6]), + SOC_ENUM("ADCA Right Type", ak5702_enum[7]), + SOC_ENUM("ADCB Left Type", ak5702_enum[8]), + SOC_ENUM("ADCB Right Type", ak5702_enum[9]), +}; + +/* ak5702 dapm widgets */ +static const struct snd_soc_dapm_widget ak5702_dapm_widgets[] = { + SND_SOC_DAPM_ADC("ADCA Left", "Capture", AK5702_PM1, 0, 0), + SND_SOC_DAPM_ADC("ADCA Right", "Capture", AK5702_PM1, 1, 0), + SND_SOC_DAPM_ADC("ADCB Left", "Capture", AK5702_PM2, 0, 0), + SND_SOC_DAPM_ADC("ADCB Right", "Capture", AK5702_PM2, 1, 0), + + SND_SOC_DAPM_INPUT("ADCA Left Input"), + SND_SOC_DAPM_INPUT("ADCA Right Input"), + SND_SOC_DAPM_INPUT("ADCB Left Input"), + SND_SOC_DAPM_INPUT("ADCB Right Input"), +}; + +static const struct snd_soc_dapm_route audio_map[] = { + {"ADCA Left", NULL, "ADCA Left Input"}, + {"ADCA Right", NULL, "ADCA Right Input"}, + {"ADCB Left", NULL, "ADCB Left Input"}, + {"ADCB Right", NULL, "ADCB Right Input"}, +}; + +static int ak5702_add_widgets(struct snd_soc_codec *codec) +{ + snd_soc_dapm_new_controls(codec, ak5702_dapm_widgets, + ARRAY_SIZE(ak5702_dapm_widgets)); + snd_soc_dapm_add_routes(codec, audio_map, ARRAY_SIZE(audio_map)); + + snd_soc_dapm_new_widgets(codec); + return 0; +} + +static int ak5702_set_dai_sysclk(struct snd_soc_dai *codec_dai, + int clk_id, unsigned int freq, int dir) +{ + struct snd_soc_codec *codec = codec_dai->codec; + u8 fs = 0; + u8 value; + + switch (freq) { + case 8000: + fs = 0x0; + break; + case 11025: + fs = 0x05; + break; + case 12000: + fs = 0x01; + break; + case 16000: + fs = 0x02; + break; + case 22050: + fs = 0x07; + break; + case 24000: + fs = 0x03; + break; + case 32000: + fs = 0x0a; + break; + case 44100: + fs = 0x0f; + break; + case 48000: + fs = 0x0b; + break; + default: + return -EINVAL; + } + + value = ak5702_read_reg_cache(codec, AK5702_FS1); + value &= (~AK5702_FS1_FS_MASK); + value |= fs; + ak5702_write(codec, AK5702_FS1, value); + return 0; +} + +static int ak5702_set_dai_fmt(struct snd_soc_dai *codec_dai, unsigned int fmt) +{ + struct snd_soc_codec *codec = codec_dai->codec; + u8 fmt1 = 0; + + switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { + case SND_SOC_DAIFMT_I2S: + fmt1 = AK5702_FMT1_I2S; + break; + case SND_SOC_DAIFMT_LEFT_J: + fmt1 = AK5702_FMT1_MSB; + break; + default: + return -EINVAL; + } + + ak5702_write(codec, AK5702_FMT1, fmt1); + ak5702_write(codec, AK5702_FMT2, AK5702_FMT2_STEREO); + return 0; +} + +static int ak5702_set_dai_pll(struct snd_soc_dai *codec_dai, int pll_id, + unsigned int freq_in, unsigned int freq_out) +{ + struct snd_soc_codec *codec = codec_dai->codec; + u8 reg = 0; + + reg = ak5702_read_reg_cache(codec, AK5702_PLL1); + switch (pll_id) { + case AK5702_PLL_POWERDOWN: + reg &= (~AK5702_PLL1_PM_MASK); + reg |= AK5702_PLL1_POWERDOWN; + break; + case AK5702_PLL_MASTER: + reg &= (~AK5702_PLL1_MODE_MASK); + reg |= AK5702_PLL1_MASTER; + reg |= AK5702_PLL1_POWERUP; + break; + case AK5702_PLL_SLAVE: + reg &= (~AK5702_PLL1_MODE_MASK); + reg |= AK5702_PLL1_SLAVE; + reg |= AK5702_PLL1_POWERUP; + break; + default: + return -ENODEV; + } + + switch (freq_in) { + case 11289600: + reg &= (~AK5702_PLL1_PLL_MASK); + reg |= AK5702_PLL1_11289600; + break; + case 12000000: + reg &= (~AK5702_PLL1_PLL_MASK); + reg |= AK5702_PLL1_12000000; + break; + case 12288000: + reg &= (~AK5702_PLL1_PLL_MASK); + reg |= AK5702_PLL1_12288000; + break; + case 19200000: + reg &= (~AK5702_PLL1_PLL_MASK); + reg |= AK5702_PLL1_19200000; + break; + default: + return -ENODEV; + } + + ak5702_write(codec, AK5702_PLL1, reg); + return 0; +} + +static int ak5702_set_dai_clkdiv(struct snd_soc_dai *codec_dai, + int div_id, int div) +{ + struct snd_soc_codec *codec = codec_dai->codec; + u8 reg = 0; + + if (div_id == AK5702_BCLK_CLKDIV) { + reg = ak5702_read_reg_cache(codec, AK5702_FS1); + switch (div) { + case AK5702_BCLK_DIV_32: + reg &= (~AK5702_FS1_BCKO_MASK); + reg |= AK5702_FS1_BCKO_32FS; + ak5702_write(codec, AK5702_FS1, reg); + break; + case AK5702_BCLK_DIV_64: + reg &= (~AK5702_FS1_BCKO_MASK); + reg |= AK5702_FS1_BCKO_64FS; + ak5702_write(codec, AK5702_FS1, reg); + break; + default: + return -EINVAL; + } + } + return 0; +} + +static int ak5702_set_bias_level(struct snd_soc_codec *codec, + enum snd_soc_bias_level level) +{ + u8 reg = 0; + + switch (level) { + case SND_SOC_BIAS_ON: + case SND_SOC_BIAS_PREPARE: + reg = ak5702_read_reg_cache(codec, AK5702_PM1); + ak5702_write(codec, AK5702_PM1, reg | AK5702_PM1_PMVCM); + reg = ak5702_read_reg_cache(codec, AK5702_PLL1); + reg = reg | AK5702_PLL1_POWERUP | AK5702_PLL1_MASTER; + ak5702_write(codec, AK5702_PLL1, reg); + break; + case SND_SOC_BIAS_STANDBY: + reg = ak5702_read_reg_cache(codec, AK5702_PM1); + ak5702_write(codec, AK5702_PM1, reg | AK5702_PM1_PMVCM); + reg = ak5702_read_reg_cache(codec, AK5702_PLL1); + ak5702_write(codec, AK5702_PLL1, reg & (~AK5702_PLL1_POWERUP)); + break; + case SND_SOC_BIAS_OFF: + reg = ak5702_read_reg_cache(codec, AK5702_PM1); + ak5702_write(codec, AK5702_PM1, reg & (~AK5702_PM1_PMVCM)); + break; + } + + codec->bias_level = level; + return 0; +} + +static int ak5702_suspend(struct platform_device *pdev, pm_message_t state) +{ + struct snd_soc_device *socdev = platform_get_drvdata(pdev); + struct snd_soc_codec *codec = socdev->card->codec; + + ak5702_set_bias_level(codec, SND_SOC_BIAS_OFF); + return 0; +} + +static int ak5702_resume(struct platform_device *pdev) +{ + struct snd_soc_device *socdev = platform_get_drvdata(pdev); + struct snd_soc_codec *codec = socdev->card->codec; + int i; + + /* Bring the codec back up to standby first to minimise pop/clicks */ + ak5702_set_bias_level(codec, SND_SOC_BIAS_STANDBY); + ak5702_set_bias_level(codec, codec->suspend_bias_level); + + /* Sync back everything else */ + for (i = 0; i < ARRAY_SIZE(ak5702_reg); i++) + ak5702_write(codec, i, ak5702_reg[i]); + + return 0; +} + +#define AK5702_RATES SNDRV_PCM_RATE_8000_48000 +#define AK5702_FORMATS SNDRV_PCM_FMTBIT_S16_LE + +struct snd_soc_dai_ops ak5702_ops = { + .set_fmt = ak5702_set_dai_fmt, + .set_sysclk = ak5702_set_dai_sysclk, + .set_clkdiv = ak5702_set_dai_clkdiv, + .set_pll = ak5702_set_dai_pll, +}; + +struct snd_soc_dai ak5702_dai = { + .name = "AK5702", + .capture = { + .stream_name = "Capture", + .channels_min = 1, + .channels_max = 4, + .rates = AK5702_RATES, + .formats = AK5702_FORMATS, + }, + .ops = &ak5702_ops, +}; +EXPORT_SYMBOL_GPL(ak5702_dai); + +static struct snd_soc_codec *ak5702_codec; + +static int ak5702_probe(struct platform_device *pdev) +{ + struct snd_soc_device *socdev = platform_get_drvdata(pdev); + struct snd_soc_codec *codec = ak5702_codec; + int ret = 0; + u8 reg = 0; + + socdev->card->codec = ak5702_codec; + + /* register pcms */ + ret = snd_soc_new_pcms(socdev, SNDRV_DEFAULT_IDX1, SNDRV_DEFAULT_STR1); + if (ret < 0) { + printk(KERN_ERR "ak5702: failed to create pcms\n"); + goto pcm_err; + } + + /* power on device */ + reg = ak5702_read_reg_cache(codec, AK5702_PM1); + reg |= AK5702_PM1_PMVCM; + ak5702_write(codec, AK5702_PM1, reg); + + /* initialize ADC */ + reg = AK5702_SIG1_L_LIN1 | AK5702_SIG1_R_RIN2; + ak5702_write(codec, AK5702_SIG1, reg); + reg = AK5702_SIG2_L_LIN3 | AK5702_SIG2_R_RIN4; + ak5702_write(codec, AK5702_SIG2, reg); + + reg = ak5702_read_reg_cache(codec, AK5702_PM1); + reg = reg | AK5702_PM1_PMADAL | AK5702_PM1_PMADAR; + ak5702_write(codec, AK5702_PM1, reg); + reg = ak5702_read_reg_cache(codec, AK5702_PM2); + reg = reg | AK5702_PM2_PMADBL | AK5702_PM2_PMADBR; + ak5702_write(codec, AK5702_PM2, reg); + + /* initialize volume */ + ak5702_write(codec, AK5702_MICG1, AK5702_MICG1_INIT); + ak5702_write(codec, AK5702_MICG2, AK5702_MICG2_INIT); + ak5702_write(codec, AK5702_VOL1, AK5702_VOL1_IVOLAC); + ak5702_write(codec, AK5702_VOL2, AK5702_VOL2_IVOLBC); + ak5702_write(codec, AK5702_LVOL1, AK5702_LVOL1_INIT); + ak5702_write(codec, AK5702_RVOL1, AK5702_RVOL1_INIT); + ak5702_write(codec, AK5702_LVOL2, AK5702_LVOL2_INIT); + ak5702_write(codec, AK5702_RVOL2, AK5702_RVOL2_INIT); + + snd_soc_add_controls(codec, ak5702_snd_controls, + ARRAY_SIZE(ak5702_snd_controls)); + ak5702_add_widgets(codec); + + ret = snd_soc_init_card(socdev); + if (ret < 0) { + printk(KERN_ERR "ak5702: failed to register card\n"); + goto card_err; + } + + return ret; +card_err: + snd_soc_free_pcms(socdev); + snd_soc_dapm_free(socdev); +pcm_err: + kfree(codec->reg_cache); + return ret; +} + +#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE) +static int ak5702_i2c_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + struct ak5702_priv *ak5702; + struct snd_soc_codec *codec; + int ret; + + if (ak5702_codec) { + dev_err(&client->dev, + "Multiple AK5702 devices not supported\n"); + return -ENOMEM; + } + + codec = kzalloc(sizeof(struct snd_soc_codec), GFP_KERNEL); + if (codec == NULL) + return -ENOMEM; + + ak5702 = kzalloc(sizeof(struct ak5702_priv), GFP_KERNEL); + if (ak5702 == NULL) { + kfree(codec); + return -ENOMEM; + } + + codec->private_data = ak5702; + mutex_init(&codec->mutex); + INIT_LIST_HEAD(&codec->dapm_widgets); + INIT_LIST_HEAD(&codec->dapm_paths); + + i2c_set_clientdata(client, codec); + codec->control_data = client; + + codec->dev = &client->dev; + codec->name = "AK5702"; + codec->owner = THIS_MODULE; + codec->read = ak5702_read_reg_cache; + codec->write = ak5702_write; + codec->set_bias_level = ak5702_set_bias_level; + codec->dai = &ak5702_dai; + codec->num_dai = 1; + codec->reg_cache_size = ARRAY_SIZE(ak5702_reg); + codec->reg_cache = (void *)&ak5702_reg; + if (codec->reg_cache == NULL) + return -ENOMEM; + + codec->hw_write = (hw_write_t) i2c_master_send; + codec->hw_read = (hw_read_t) i2c_master_recv; + + ak5702_codec = codec; + ak5702_dai.dev = &client->dev; + + ret = snd_soc_register_codec(codec); + if (ret != 0) { + dev_err(codec->dev, "Failed to register codec: %d\n", ret); + return ret; + } + + ret = snd_soc_register_dai(&ak5702_dai); + if (ret != 0) { + dev_err(codec->dev, "Failed to register DAIs: %d\n", ret); + return ret; + } + + return ret; +} + +static __devexit int ak5702_i2c_remove(struct i2c_client *client) +{ + struct snd_soc_codec *codec = i2c_get_clientdata(client); + struct ak5702_priv *ak5702 = codec->private_data; + + snd_soc_unregister_dai(&ak5702_dai); + snd_soc_unregister_codec(codec); + kfree(codec); + kfree(ak5702); + ak5702_codec = NULL; + return 0; +} + +static const struct i2c_device_id ak5702_i2c_id[] = { + {"ak5702-i2c", 0}, + {} +}; + +MODULE_DEVICE_TABLE(i2c, ak5702_i2c_id); + +static struct i2c_driver ak5702_i2c_driver = { + .driver = { + .name = "ak5702-i2c", + .owner = THIS_MODULE, + }, + .probe = ak5702_i2c_probe, + .remove = __devexit_p(ak5702_i2c_remove), + .id_table = ak5702_i2c_id, +}; +#endif + +static int ak5702_remove(struct platform_device *pdev) +{ + struct snd_soc_device *socdev = platform_get_drvdata(pdev); + struct snd_soc_codec *codec = socdev->card->codec; + + if (codec->control_data) + ak5702_set_bias_level(codec, SND_SOC_BIAS_OFF); + + snd_soc_free_pcms(socdev); + snd_soc_dapm_free(socdev); +#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE) + i2c_del_driver(&ak5702_i2c_driver); +#endif + kfree(codec->private_data); + kfree(codec); + return 0; +} + +struct snd_soc_codec_device soc_codec_dev_ak5702 = { + .probe = ak5702_probe, + .remove = ak5702_remove, + .suspend = ak5702_suspend, + .resume = ak5702_resume, +}; +EXPORT_SYMBOL_GPL(soc_codec_dev_ak5702); + +static int __init ak5702_modinit(void) +{ + return i2c_add_driver(&ak5702_i2c_driver); +} +module_init(ak5702_modinit); + +static void __exit ak5702_exit(void) +{ + i2c_del_driver(&ak5702_i2c_driver); +} +module_exit(ak5702_exit); + +MODULE_DESCRIPTION("Soc AK5702 driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/codecs/ak5702.h b/sound/soc/codecs/ak5702.h new file mode 100644 index 000000000000..74b893ca2e8f --- /dev/null +++ b/sound/soc/codecs/ak5702.h @@ -0,0 +1,130 @@ +/* + * ak5702.h -- AK5702 Soc Audio driver + * + * Copyright 2009-2010 Freescale Semiconductor, Inc. All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ + +#ifndef _AK5702_H +#define _AK5702_H + +/* AK5702 register space */ + +#define AK5702_PM1 0x00 +#define AK5702_PLL1 0x01 +#define AK5702_SIG1 0x02 +#define AK5702_MICG1 0x03 +#define AK5702_FMT1 0x04 +#define AK5702_FS1 0x05 +#define AK5702_CLK1 0x06 +#define AK5702_VOL1 0x07 +#define AK5702_LVOL1 0x08 +#define AK5702_RVOL1 0x09 +#define AK5702_TIMER1 0x0a +#define AK5702_ALC11 0x0b +#define AK5702_ALC12 0x0c +#define AK5702_MODE11 0x0d +#define AK5702_MODE12 0x0e +#define AK5702_MODE13 0x0f + +#define AK5702_PM2 0x10 +#define AK5702_PLL2 0x11 +#define AK5702_SIG2 0x12 +#define AK5702_MICG2 0x13 +#define AK5702_FMT2 0x14 +#define AK5702_FS2 0x15 +#define AK5702_CLK2 0x16 +#define AK5702_VOL2 0x17 +#define AK5702_LVOL2 0x18 +#define AK5702_RVOL2 0x19 +#define AK5702_TIMER2 0x1a +#define AK5702_ALC21 0x1b +#define AK5702_ALC22 0x1c +#define AK5702_MODE21 0x1d +#define AK5702_MODE22 0x1e + +#define AK5702_CACHEREGNUM 0x1F + +#define AK5702_PM1_PMADAL 0x01 +#define AK5702_PM1_PMADAR 0x02 +#define AK5702_PM1_PMVCM 0x04 +#define AK5702_PM2_PMADBL 0x01 +#define AK5702_PM2_PMADBR 0x02 + +#define AK5702_PLL1_POWERDOWN 0x0 +#define AK5702_PLL1_POWERUP 0x01 +#define AK5702_PLL1_MASTER 0x02 +#define AK5702_PLL1_SLAVE 0x0 +#define AK5702_PLL1_11289600 0x10 +#define AK5702_PLL1_12000000 0x24 +#define AK5702_PLL1_12288000 0x14 +#define AK5702_PLL1_19200000 0x20 + +#define AK5702_SIG1_L_LIN1 0x0 +#define AK5702_SIG1_L_LIN2 0x01 +#define AK5702_SIG1_R_RIN1 0x0 +#define AK5702_SIG1_R_RIN2 0x02 +#define AK5702_SIG1_PMMPA 0x10 +#define AK5702_SIG2_L_LIN3 0x0 +#define AK5702_SIG2_L_LIN4 0x01 +#define AK5702_SIG2_R_RIN3 0x0 +#define AK5702_SIG2_R_RIN4 0x02 +#define AK5702_SIG2_PMMPB 0x10 + +#define AK5702_MICG1_INIT 0x0 +#define AK5702_MICG2_INIT 0x0 + +#define AK5702_FMT1_I2S 0x23 +#define AK5702_FMT1_MSB 0x22 +#define AK5702_FMT2_STEREO 0x20 +#define AK5702_FS1_BCKO_32FS 0x10 +#define AK5702_FS1_BCKO_64FS 0x20 +#define AK5702_CLK1_PS_256FS 0x0 +#define AK5702_CLK1_PS_128FS 0x01 +#define AK5702_CLK1_PS_64FS 0x02 +#define AK5702_CLK1_PS_32FS 0x03 +#define AK5702_VOL1_IVOLAC 0x01 +#define AK5702_VOL2_IVOLBC 0x01 +#define AK5702_LVOL1_INIT 0x91 +#define AK5702_RVOL1_INIT 0x91 +#define AK5702_LVOL2_INIT 0x91 +#define AK5702_RVOL2_INIT 0x91 + +#define AK5702_PLL1_PM_MASK 0x01 +#define AK5702_PLL1_MODE_MASK 0x02 +#define AK5702_PLL1_PLL_MASK 0x3c +#define AK5702_FS1_BCKO_MASK 0x30 +#define AK5702_FS1_FS_MASK 0x0f +#define AK5702_CLK1_PS_MASK 0x03 + +/* clock divider id */ +#define AK5702_BCLK_CLKDIV 0 +#define AK5702_MCLK_CLKDIV 1 + +/* bit clock div values */ +#define AK5702_BCLK_DIV_32 0 +#define AK5702_BCLK_DIV_64 1 + +/* m clock div values */ +#define AK5702_MCLK_DIV_32 0 +#define AK5702_MCLK_DIV_64 1 +#define AK5702_MCLK_DIV_128 2 +#define AK5702_MCLK_DIV_256 3 + +/* PLL master and slave modes */ +#define AK5702_PLL_POWERDOWN 0 +#define AK5702_PLL_MASTER 1 +#define AK5702_PLL_SLAVE 2 + +struct ak5702_setup_data { + int i2c_bus; + unsigned short i2c_address; +}; + +extern struct snd_soc_dai ak5702_dai; +extern struct snd_soc_codec_device soc_codec_dev_ak5702; + +#endif diff --git a/sound/soc/codecs/bluetooth.c b/sound/soc/codecs/bluetooth.c new file mode 100644 index 000000000000..1b065f7653ad --- /dev/null +++ b/sound/soc/codecs/bluetooth.c @@ -0,0 +1,162 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +/*! + * @file bluetooth.c + * @brief Driver for bluetooth PCM interface + * + * @ingroup Sound + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define BLUETOOTH_RATES SNDRV_PCM_RATE_8000 + +#define BLUETOOTH_FORMATS SNDRV_PCM_FMTBIT_S16_LE + +struct snd_soc_dai bt_dai = { + .name = "bluetooth", + .playback = { + .stream_name = "Playback", + .channels_min = 1, + .channels_max = 2, + .rates = BLUETOOTH_RATES, + .formats = BLUETOOTH_FORMATS, + }, + .capture = { + .stream_name = "Capture", + .channels_min = 1, + .channels_max = 2, + .rates = BLUETOOTH_RATES, + .formats = BLUETOOTH_FORMATS, + }, +}; +EXPORT_SYMBOL_GPL(bt_dai); + +static int bt_init(struct snd_soc_device *socdev) +{ + struct snd_soc_codec *codec = socdev->card->codec; + int ret = 0; + + codec->name = "bluetooth"; + codec->owner = THIS_MODULE; + codec->dai = &bt_dai; + codec->num_dai = 1; + + snd_soc_new_pcms(socdev, SNDRV_DEFAULT_IDX1, SNDRV_DEFAULT_STR1); + if (ret < 0) { + pr_err("failed to create bluetooth pcms\n"); + return ret; + } + + ret = snd_soc_init_card(socdev); + strcpy(codec->card->id, "bluetooth"); + + if (ret < 0) { + pr_err("bluetooth: failed to register card\n"); + snd_soc_free_pcms(socdev); + snd_soc_dapm_free(socdev); + return ret; + } + return 0; +} + +static struct snd_soc_device *bt_socdev; + +static int bt_probe(struct platform_device *pdev) +{ + struct snd_soc_device *socdev = platform_get_drvdata(pdev); + struct snd_soc_codec *codec = socdev->card->codec; + int ret = 0; + + codec = kzalloc(sizeof(struct snd_soc_codec), GFP_KERNEL); + if (codec == NULL) + return -ENOMEM; + + socdev->card->codec = codec; + mutex_init(&codec->mutex); + INIT_LIST_HEAD(&codec->dapm_widgets); + INIT_LIST_HEAD(&codec->dapm_paths); + + bt_socdev = socdev; + + ret = bt_init(socdev); + if (ret < 0) { + pr_err("Bluetooth codec initialisation failed\n"); + kfree(codec); + } + + return ret; +} + +/* power down chip */ +static int bt_remove(struct platform_device *pdev) +{ + struct snd_soc_device *socdev = platform_get_drvdata(pdev); + struct snd_soc_codec *codec = socdev->card->codec; + + snd_soc_free_pcms(socdev); + snd_soc_dapm_free(socdev); + kfree(codec); + + return 0; +} + +static int bt_suspend(struct platform_device *pdev, pm_message_t state) +{ + return 0; +} + +static int bt_resume(struct platform_device *pdev) +{ + return 0; +} + +struct snd_soc_codec_device soc_codec_dev_bt = { + .probe = bt_probe, + .remove = bt_remove, + .suspend = bt_suspend, + .resume = bt_resume, +}; +EXPORT_SYMBOL_GPL(soc_codec_dev_bt); + +static int __init bluetooth_modinit(void) +{ + return snd_soc_register_dai(&bt_dai); +} + +module_init(bluetooth_modinit); + +static void __exit bluetooth_exit(void) +{ + snd_soc_unregister_dai(&bt_dai); +} + +module_exit(bluetooth_exit); + +MODULE_DESCRIPTION("ASoC bluetooth codec driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/codecs/cs42888.c b/sound/soc/codecs/cs42888.c new file mode 100644 index 000000000000..e9288cc9a1ca --- /dev/null +++ b/sound/soc/codecs/cs42888.c @@ -0,0 +1,1196 @@ +/* + * Copyright (C) 2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cs42888.h" + +#define CS42888_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE |\ + SNDRV_PCM_FMTBIT_S24_LE | SNDRV_PCM_FMTBIT_S32_LE) + +/* CS42888 registers addresses */ +#define CS42888_CHIPID 0x01 /* Chip ID */ +#define CS42888_PWRCTL 0x02 /* Power Control */ +#define CS42888_MODE 0x03 /* Functional Mode */ +#define CS42888_FORMAT 0x04 /* Interface Formats */ +#define CS42888_ADCCTL 0x05 /* ADC Control */ +#define CS42888_TRANS 0x06 /* Transition Control */ +#define CS42888_MUTE 0x07 /* Mute Control */ +#define CS42888_VOLAOUT1 0x08 /* Volume Control AOUT1*/ +#define CS42888_VOLAOUT2 0x09 /* Volume Control AOUT2*/ +#define CS42888_VOLAOUT3 0x0A /* Volume Control AOUT3*/ +#define CS42888_VOLAOUT4 0x0B /* Volume Control AOUT4*/ +#define CS42888_VOLAOUT5 0x0C /* Volume Control AOUT5*/ +#define CS42888_VOLAOUT6 0x0D /* Volume Control AOUT6*/ +#define CS42888_VOLAOUT7 0x0E /* Volume Control AOUT7*/ +#define CS42888_VOLAOUT8 0x0F /* Volume Control AOUT8*/ +#define CS42888_DACINV 0x10 /* DAC Channel Invert */ +#define CS42888_VOLAIN1 0x11 /* Volume Control AIN1 */ +#define CS42888_VOLAIN2 0x12 /* Volume Control AIN2 */ +#define CS42888_VOLAIN3 0x13 /* Volume Control AIN3 */ +#define CS42888_VOLAIN4 0x14 /* Volume Control AIN4 */ +#define CS42888_ADCINV 0x17 /* ADC Channel Invert */ +#define CS42888_STATUSCTL 0x18 /* Status Control */ +#define CS42888_STATUS 0x19 /* Status */ +#define CS42888_STATUSMASK 0x1A /* Status Mask */ + +#define CS42888_FIRSTREG 0x01 +#define CS42888_LASTREG 0x1A +#define CS42888_NUMREGS (CS42888_LASTREG - CS42888_FIRSTREG + 1) +#define CS42888_I2C_INCR 0x80 + +/* Bit masks for the CS42888 registers */ +#define CS42888_CHIPID_ID_MASK 0xF0 +#define CS42888_CHIPID_REV 0x0F +#define CS42888_PWRCTL_PDN_ADC2_OFFSET 6 +#define CS42888_PWRCTL_PDN_ADC1_OFFSET 5 +#define CS42888_PWRCTL_PDN_DAC4_OFFSET 4 +#define CS42888_PWRCTL_PDN_DAC3_OFFSET 3 +#define CS42888_PWRCTL_PDN_DAC2_OFFSET 2 +#define CS42888_PWRCTL_PDN_DAC1_OFFSET 1 +#define CS42888_PWRCTL_PDN_OFFSET 0 +#define CS42888_PWRCTL_PDN_ADC2_MASK (1 << CS42888_PWRCTL_PDN_ADC2_OFFSET) +#define CS42888_PWRCTL_PDN_ADC1_MASK (1 << CS42888_PWRCTL_PDN_ADC1_OFFSET) +#define CS42888_PWRCTL_PDN_DAC4_MASK (1 << CS42888_PWRCTL_PDN_DAC4_OFFSET) +#define CS42888_PWRCTL_PDN_DAC3_MASK (1 << CS42888_PWRCTL_PDN_DAC3_OFFSET) +#define CS42888_PWRCTL_PDN_DAC2_MASK (1 << CS42888_PWRCTL_PDN_DAC2_OFFSET) +#define CS42888_PWRCTL_PDN_DAC1_MASK (1 << CS42888_PWRCTL_PDN_DAC1_OFFSET) +#define CS42888_PWRCTL_PDN_MASK (1 << CS42888_PWRCTL_PDN_OFFSET) + +#define CS42888_MODE_SPEED_MASK 0xF0 +#define CS42888_MODE_1X 0x00 +#define CS42888_MODE_2X 0x50 +#define CS42888_MODE_4X 0xA0 +#define CS42888_MODE_SLAVE 0xF0 +#define CS42888_MODE_DIV_MASK 0x0E +#define CS42888_MODE_DIV1 0x00 +#define CS42888_MODE_DIV2 0x02 +#define CS42888_MODE_DIV3 0x04 +#define CS42888_MODE_DIV4 0x06 +#define CS42888_MODE_DIV5 0x08 + +#define CS42888_FORMAT_FREEZE_OFFSET 7 +#define CS42888_FORMAT_AUX_DIF_OFFSET 6 +#define CS42888_FORMAT_DAC_DIF_OFFSET 3 +#define CS42888_FORMAT_ADC_DIF_OFFSET 0 +#define CS42888_FORMAT_FREEZE_MASK (1 << CS42888_FORMAT_FREEZE_OFFSET) +#define CS42888_FORMAT_AUX_DIF_MASK (1 << CS42888_FORMAT_AUX_DIF_OFFSET) +#define CS42888_FORMAT_DAC_DIF_MASK (7 << CS42888_FORMAT_DAC_DIF_OFFSET) +#define CS42888_FORMAT_ADC_DIF_MASK (7 << CS42888_FORMAT_ADC_DIF_OFFSET) + +#define CS42888_TRANS_DAC_SNGVOL_OFFSET 7 +#define CS42888_TRANS_DAC_SZC_OFFSET 5 +#define CS42888_TRANS_AMUTE_OFFSET 4 +#define CS42888_TRANS_MUTE_ADC_SP_OFFSET 3 +#define CS42888_TRANS_ADC_SNGVOL_OFFSET 2 +#define CS42888_TRANS_ADC_SZC_OFFSET 0 +#define CS42888_TRANS_DAC_SNGVOL_MASK (1 << CS42888_TRANS_DAC_SNGVOL_OFFSET) +#define CS42888_TRANS_DAC_SZC_MASK (3 << CS42888_TRANS_DAC_SZC_OFFSET) +#define CS42888_TRANS_AMUTE_MASK (1 << CS42888_TRANS_AMUTE_OFFSET) +#define CS42888_TRANS_MUTE_ADC_SP_MASK (1 << CS42888_TRANS_MUTE_ADC_SP_OFFSET) +#define CS42888_TRANS_ADC_SNGVOL_MASK (1 << CS42888_TRANS_ADC_SNGVOL_OFFSET) +#define CS42888_TRANS_ADC_SZC_MASK (3 << CS42888_TRANS_ADC_SZC_OFFSET) + +#define CS42888_MUTE_AOUT8 (0x1 << 7) +#define CS42888_MUTE_AOUT7 (0x1 << 6) +#define CS42888_MUTE_AOUT6 (0x1 << 5) +#define CS42888_MUTE_AOUT5 (0x1 << 4) +#define CS42888_MUTE_AOUT4 (0x1 << 3) +#define CS42888_MUTE_AOUT3 (0x1 << 2) +#define CS42888_MUTE_AOUT2 (0x1 << 1) +#define CS42888_MUTE_AOUT1 (0x1 << 0) +#define CS42888_MUTE_ALL (CS42888_MUTE_AOUT1 | CS42888_MUTE_AOUT2 | \ + CS42888_MUTE_AOUT3 | CS42888_MUTE_AOUT4 | \ + CS42888_MUTE_AOUT5 | CS42888_MUTE_AOUT6 | \ + CS42888_MUTE_AOUT7 | CS42888_MUTE_AOUT8) + +#define DIF_LEFT_J 0 +#define DIF_I2S 1 +#define DIF_RIGHT_J 2 +#define DIF_TDM 6 + +/* Private data for the CS42888 */ +struct cs42888_private { + struct snd_soc_codec codec; + u8 reg_cache[CS42888_NUMREGS]; + unsigned int mclk; /* Input frequency of the MCLK pin */ + unsigned int mode; /* The mode (I2S or left-justified) */ + unsigned int slave_mode; + unsigned int manual_mute; + struct regulator *regulator_vsd; +}; + +static struct i2c_client *cs42888_i2c_client; + +int cs42888_read_reg(unsigned int reg, u8 *value) +{ + s32 retval; + retval = i2c_smbus_read_byte_data(cs42888_i2c_client, reg); + if (retval < 0) { + pr_err("%s:read reg errorr:reg=%x,val=%x\n", + __func__, reg, retval); + return -1; + } else { + *value = (u8) retval; + return 0; + } +} + +int cs42888_write_reg(unsigned int reg, u8 value) +{ + if (i2c_smbus_write_byte_data(cs42888_i2c_client, reg, value) < 0) { + pr_err("%s:write reg errorr:reg=%x,val=%x\n", + __func__, reg, value); + return -1; + } + return 0; +} +/** + * cs42888_fill_cache - pre-fill the CS42888 register cache. + * @codec: the codec for this CS42888 + * + * This function fills in the CS42888 register cache by reading the register + * values from the hardware. + * + * This CS42888 registers are cached to avoid excessive I2C I/O operations. + * After the initial read to pre-fill the cache, the CS42888 never updates + * the register values, so we won't have a cache coherency problem. + * + * We use the auto-increment feature of the CS42888 to read all registers in + * one shot. + */ +static int cs42888_fill_cache(struct snd_soc_codec *codec) +{ + u8 *cache = codec->reg_cache; + struct i2c_client *i2c_client = codec->control_data; + s32 length; + + length = i2c_smbus_read_i2c_block_data(i2c_client, + CS42888_FIRSTREG | CS42888_I2C_INCR, CS42888_NUMREGS, cache); + + if (length != CS42888_NUMREGS) { + dev_err(codec->dev, "i2c read failure, addr=0x%x\n", + i2c_client->addr); + return -EIO; + } + + return 0; +} + +/** + * cs42888_read_reg_cache - read from the CS42888 register cache. + * @codec: the codec for this CS42888 + * @reg: the register to read + * + * This function returns the value for a given register. It reads only from + * the register cache, not the hardware itself. + * + * This CS42888 registers are cached to avoid excessive I2C I/O operations. + * After the initial read to pre-fill the cache, the CS42888 never updates + * the register values, so we won't have a cache coherency problem. + */ +static u8 cs42888_read_reg_cache(struct snd_soc_codec *codec, + unsigned int reg) +{ + u8 *cache = codec->reg_cache; + + if ((reg < CS42888_FIRSTREG) || (reg > CS42888_LASTREG)) + return -EIO; + + return cache[reg - CS42888_FIRSTREG]; +} + +/** + * cs42888_i2c_write - write to a CS42888 register via the I2C bus. + * @codec: the codec for this CS42888 + * @reg: the register to write + * @value: the value to write to the register + * + * This function writes the given value to the given CS42888 register, and + * also updates the register cache. + * + * Note that we don't use the hw_write function pointer of snd_soc_codec. + * That's because it's too clunky: the hw_write_t prototype does not match + * i2c_smbus_write_byte_data(), and it's just another layer of overhead. + */ +static int cs42888_i2c_write(struct snd_soc_codec *codec, unsigned int reg, + u8 value) +{ + u8 *cache = codec->reg_cache; + + if ((reg < CS42888_FIRSTREG) || (reg > CS42888_LASTREG)) + return -EIO; + + /* Only perform an I2C operation if the new value is different */ + if (cache[reg - CS42888_FIRSTREG] != value) { + if (i2c_smbus_write_byte_data(cs42888_i2c_client, reg, value) + < 0) { + dev_err(codec->dev, "i2c write failed\n"); + return -EIO; + } + + /* We've written to the hardware, so update the cache */ + cache[reg - CS42888_FIRSTREG] = value; + } + + return 0; +} + +#ifdef CS42888_DEBUG +static void dump_reg(struct snd_soc_codec *codec) +{ + int i, reg; + int ret; + printk(KERN_DEBUG "dump begin\n"); + printk(KERN_DEBUG "reg value in cache\n"); + for (i = 0; i < CS42888_NUMREGS; i++) + printk(KERN_DEBUG "reg[%d] = 0x%x\n", i, cache[i]); + + printk(KERN_DEBUG "real reg value\n"); + ret = cs42888_fill_cache(codec); + if (ret < 0) { + pr_err("failed to fill register cache\n"); + return ret; + } + for (i = 0; i < CS42888_NUMREGS; i++) + printk(KERN_DEBUG "reg[%d] = 0x%x\n", i, cache[i]); + + printk(KERN_DEBUG "dump end\n"); +} +#else +static void dump_reg(struct snd_soc_codec *codec) +{ +} +#endif + +/* -127.5dB to 0dB with step of 0.5dB */ +static const DECLARE_TLV_DB_SCALE(dac_tlv, -12750, 50, 1); +/* -64dB to 24dB with step of 0.5dB */ +static const DECLARE_TLV_DB_SCALE(adc_tlv, -6400, 50, 1); + +static int cs42888_out_vu(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct soc_mixer_control *mc = + (struct soc_mixer_control *)kcontrol->private_value; + struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); + unsigned int reg = mc->reg; + unsigned int reg2 = mc->rreg; + int ret; + u16 val; + + ret = snd_soc_put_volsw_2r(kcontrol, ucontrol); + if (ret < 0) + return ret; + + /* Now write again with the volume update bit set */ + val = cs42888_read_reg_cache(codec, reg); + ret = cs42888_i2c_write(codec, reg, val); + + val = cs42888_read_reg_cache(codec, reg2); + ret = cs42888_i2c_write(codec, reg2, val); + return 0; +} + +int cs42888_info_volsw_s8(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_info *uinfo) +{ + struct soc_mixer_control *mc = + (struct soc_mixer_control *)kcontrol->private_value; + int max = mc->max; + int min = mc->min; + + uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; + uinfo->count = 2; + uinfo->value.integer.min = 0; + uinfo->value.integer.max = max-min; + return 0; +} + +int cs42888_get_volsw_s8(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct soc_mixer_control *mc = + (struct soc_mixer_control *)kcontrol->private_value; + struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); + unsigned int reg = mc->reg; + unsigned int reg2 = mc->rreg; + int min = mc->min; + int val = cs42888_read_reg_cache(codec, reg); + + ucontrol->value.integer.value[0] = + ((signed char)(val))-min; + + val = cs42888_read_reg_cache(codec, reg2); + ucontrol->value.integer.value[1] = + ((signed char)(val))-min; + return 0; +} + +int cs42888_put_volsw_s8(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct soc_mixer_control *mc = + (struct soc_mixer_control *)kcontrol->private_value; + struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); + unsigned int reg = mc->reg; + unsigned int reg2 = mc->rreg; + int min = mc->min; + unsigned short val; + int ret; + + val = (ucontrol->value.integer.value[0]+min); + ret = cs42888_i2c_write(codec, reg, val); + if (ret < 0) { + pr_err("i2c write failed\n"); + return ret; + } + + val = ((ucontrol->value.integer.value[1]+min)); + ret = cs42888_i2c_write(codec, reg2, val); + if (ret < 0) { + pr_err("i2c write failed\n"); + return ret; + } + + return 0; +} + +#define SOC_CS42888_DOUBLE_R_TLV(xname, reg_left, reg_right, xshift, xmax, \ + xinvert, tlv_array) \ +{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, \ + .name = (xname), \ + .access = SNDRV_CTL_ELEM_ACCESS_TLV_READ |\ + SNDRV_CTL_ELEM_ACCESS_READWRITE, \ + .tlv.p = (tlv_array), \ + .info = snd_soc_info_volsw_2r, \ + .get = snd_soc_get_volsw_2r, \ + .put = cs42888_out_vu, \ + .private_value = (unsigned long)&(struct soc_mixer_control) \ + {.reg = reg_left, \ + .rreg = reg_right, \ + .shift = xshift, \ + .max = xmax, \ + .invert = xinvert} \ +} + +#define SOC_CS42888_DOUBLE_R_S8_TLV(xname, reg_left, reg_right, xmin, xmax, \ + tlv_array) \ +{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = (xname), \ + .access = SNDRV_CTL_ELEM_ACCESS_TLV_READ | \ + SNDRV_CTL_ELEM_ACCESS_READWRITE, \ + .tlv.p = (tlv_array), \ + .info = cs42888_info_volsw_s8, .get = cs42888_get_volsw_s8, \ + .put = cs42888_put_volsw_s8, \ + .private_value = (unsigned long)&(struct soc_mixer_control) \ + {.reg = reg_left, \ + .rreg = reg_right, \ + .min = xmin, \ + .max = xmax} \ +} + +static const char *cs42888_adcfilter[] = { "None", "High Pass" }; +static const char *cs42888_dacinvert[] = { "Disabled", "Enabled" }; +static const char *cs42888_adcinvert[] = { "Disabled", "Enabled" }; +static const char *cs42888_dacamute[] = { "Disabled", "AutoMute" }; +static const char *cs42888_dac_sngvol[] = { "Disabled", "Enabled" }; +static const char *cs42888_dac_szc[] = { "Immediate Change", "Zero Cross", + "Soft Ramp", "Soft Ramp on Zero Cross" }; +static const char *cs42888_mute_adc[] = { "UnMute", "Mute" }; +static const char *cs42888_adc_sngvol[] = { "Disabled", "Enabled" }; +static const char *cs42888_adc_szc[] = { "Immediate Change", "Zero Cross", + "Soft Ramp", "Soft Ramp on Zero Cross" }; +static const char *cs42888_dac_dem[] = { "No-De-Emphasis", "De-Emphasis" }; +static const char *cs42888_adc_single[] = { "Differential", "Single-Ended" }; + +static const struct soc_enum cs42888_enum[] = { + SOC_ENUM_SINGLE(CS42888_ADCCTL, 7, 2, cs42888_adcfilter), + SOC_ENUM_DOUBLE(CS42888_DACINV, 0, 1, 2, cs42888_dacinvert), + SOC_ENUM_DOUBLE(CS42888_DACINV, 2, 3, 2, cs42888_dacinvert), + SOC_ENUM_DOUBLE(CS42888_DACINV, 4, 5, 2, cs42888_dacinvert), + SOC_ENUM_DOUBLE(CS42888_DACINV, 6, 7, 2, cs42888_dacinvert), + SOC_ENUM_DOUBLE(CS42888_ADCINV, 0, 1, 2, cs42888_adcinvert), + SOC_ENUM_DOUBLE(CS42888_ADCINV, 2, 3, 2, cs42888_adcinvert), + SOC_ENUM_SINGLE(CS42888_TRANS, 4, 2, cs42888_dacamute), + SOC_ENUM_SINGLE(CS42888_TRANS, 7, 2, cs42888_dac_sngvol), + SOC_ENUM_SINGLE(CS42888_TRANS, 5, 4, cs42888_dac_szc), + SOC_ENUM_SINGLE(CS42888_TRANS, 3, 2, cs42888_mute_adc), + SOC_ENUM_SINGLE(CS42888_TRANS, 2, 2, cs42888_adc_sngvol), + SOC_ENUM_SINGLE(CS42888_TRANS, 0, 4, cs42888_adc_szc), + SOC_ENUM_SINGLE(CS42888_ADCCTL, 5, 2, cs42888_dac_dem), + SOC_ENUM_SINGLE(CS42888_ADCCTL, 4, 2, cs42888_adc_single), + SOC_ENUM_SINGLE(CS42888_ADCCTL, 3, 2, cs42888_adc_single), +}; + +static const struct snd_kcontrol_new cs42888_snd_controls[] = { +SOC_CS42888_DOUBLE_R_TLV("DAC1 Playback Volume", + CS42888_VOLAOUT1, + CS42888_VOLAOUT2, + 0, 0xff, 1, dac_tlv), +SOC_CS42888_DOUBLE_R_TLV("DAC2 Playback Volume", + CS42888_VOLAOUT3, + CS42888_VOLAOUT4, + 0, 0xff, 1, dac_tlv), +SOC_CS42888_DOUBLE_R_TLV("DAC3 Playback Volume", + CS42888_VOLAOUT5, + CS42888_VOLAOUT6, + 0, 0xff, 1, dac_tlv), +SOC_CS42888_DOUBLE_R_TLV("DAC4 Playback Volume", + CS42888_VOLAOUT7, + CS42888_VOLAOUT8, + 0, 0xff, 1, dac_tlv), +SOC_CS42888_DOUBLE_R_S8_TLV("ADC1 Capture Volume", + CS42888_VOLAIN1, + CS42888_VOLAIN2, + -128, 48, adc_tlv), +SOC_CS42888_DOUBLE_R_S8_TLV("ADC2 Capture Volume", + CS42888_VOLAIN3, + CS42888_VOLAIN4, + -128, 48, adc_tlv), +SOC_ENUM("ADC High-Pass Filter Switch", cs42888_enum[0]), +SOC_ENUM("DAC1 Invert Switch", cs42888_enum[1]), +SOC_ENUM("DAC2 Invert Switch", cs42888_enum[2]), +SOC_ENUM("DAC3 Invert Switch", cs42888_enum[3]), +SOC_ENUM("DAC4 Invert Switch", cs42888_enum[4]), +SOC_ENUM("ADC1 Invert Switch", cs42888_enum[5]), +SOC_ENUM("ADC2 Invert Switch", cs42888_enum[6]), +SOC_ENUM("DAC Auto Mute Switch", cs42888_enum[7]), +SOC_ENUM("DAC Single Volume Control Switch", cs42888_enum[8]), +SOC_ENUM("DAC Soft Ramp and Zero Cross Control Switch", cs42888_enum[9]), +SOC_ENUM("Mute ADC Serial Port Switch", cs42888_enum[10]), +SOC_ENUM("ADC Single Volume Control Switch", cs42888_enum[11]), +SOC_ENUM("ADC Soft Ramp and Zero Cross Control Switch", cs42888_enum[12]), +SOC_ENUM("DAC Deemphasis Switch", cs42888_enum[13]), +SOC_ENUM("ADC1 Single Ended Mode Switch", cs42888_enum[14]), +SOC_ENUM("ADC2 Single Ended Mode Switch", cs42888_enum[15]), +}; + + +static const struct snd_soc_dapm_widget cs42888_dapm_widgets[] = { +SND_SOC_DAPM_DAC("DAC1", "Playback", CS42888_PWRCTL, 1, 1), +SND_SOC_DAPM_DAC("DAC2", "Playback", CS42888_PWRCTL, 2, 1), +SND_SOC_DAPM_DAC("DAC3", "Playback", CS42888_PWRCTL, 3, 1), +SND_SOC_DAPM_DAC("DAC4", "Playback", CS42888_PWRCTL, 4, 1), + +SND_SOC_DAPM_OUTPUT("AOUT1L"), +SND_SOC_DAPM_OUTPUT("AOUT1R"), +SND_SOC_DAPM_OUTPUT("AOUT2L"), +SND_SOC_DAPM_OUTPUT("AOUT2R"), +SND_SOC_DAPM_OUTPUT("AOUT3L"), +SND_SOC_DAPM_OUTPUT("AOUT3R"), +SND_SOC_DAPM_OUTPUT("AOUT4L"), +SND_SOC_DAPM_OUTPUT("AOUT4R"), + +SND_SOC_DAPM_ADC("ADC1", "Capture", CS42888_PWRCTL, 5, 1), +SND_SOC_DAPM_ADC("ADC2", "Capture", CS42888_PWRCTL, 6, 1), + +SND_SOC_DAPM_INPUT("AIN1L"), +SND_SOC_DAPM_INPUT("AIN1R"), +SND_SOC_DAPM_INPUT("AIN2L"), +SND_SOC_DAPM_INPUT("AIN2R"), +}; + +static const struct snd_soc_dapm_route audio_map[] = { + /* Playback */ + { "AOUT1L", NULL, "DAC1" }, + { "AOUT1R", NULL, "DAC1" }, + + { "AOUT2L", NULL, "DAC2" }, + { "AOUT2R", NULL, "DAC2" }, + + { "AOUT3L", NULL, "DAC3" }, + { "AOUT3R", NULL, "DAC3" }, + + { "AOUT4L", NULL, "DAC4" }, + { "AOUT4R", NULL, "DAC4" }, + + /* Capture */ + { "ADC1", NULL, "AIN1L" }, + { "ADC1", NULL, "AIN1R" }, + + { "ADC2", NULL, "AIN2L" }, + { "ADC2", NULL, "AIN2R" }, +}; + + +static int ca42888_add_widgets(struct snd_soc_codec *codec) +{ + snd_soc_dapm_new_controls(codec, cs42888_dapm_widgets, + ARRAY_SIZE(cs42888_dapm_widgets)); + + snd_soc_dapm_add_routes(codec, audio_map, ARRAY_SIZE(audio_map)); + + snd_soc_dapm_new_widgets(codec); + return 0; +} + +/** + * struct cs42888_mode_ratios - clock ratio tables + * @ratio: the ratio of MCLK to the sample rate + * @speed_mode: the Speed Mode bits to set in the Mode Control register for + * this ratio + * @mclk: the Ratio Select bits to set in the Mode Control register for this + * ratio + * + * The data for this chart is taken from Table 10 of the CS42888 reference + * manual. + * + * This table is used to determine how to program the Functional Mode register. + * It is also used by cs42888_set_dai_sysclk() to tell ALSA which sampling + * rates the CS42888 currently supports. + * + * @speed_mode is the corresponding bit pattern to be written to the + * MODE bits of the Mode Control Register + * + * @mclk is the corresponding bit pattern to be wirten to the MCLK bits of + * the Mode Control Register. + * + */ +struct cs42888_mode_ratios { + unsigned int ratio; + u8 speed_mode; + u8 mclk; +}; + +static struct cs42888_mode_ratios cs42888_mode_ratios[] = { + {64, CS42888_MODE_4X, CS42888_MODE_DIV1}, + {96, CS42888_MODE_4X, CS42888_MODE_DIV2}, + {128, CS42888_MODE_2X, CS42888_MODE_DIV1}, + {192, CS42888_MODE_2X, CS42888_MODE_DIV2}, + {256, CS42888_MODE_1X, CS42888_MODE_DIV1}, + {384, CS42888_MODE_2X, CS42888_MODE_DIV4}, + {512, CS42888_MODE_1X, CS42888_MODE_DIV3}, + {768, CS42888_MODE_1X, CS42888_MODE_DIV4}, + {1024, CS42888_MODE_1X, CS42888_MODE_DIV5} +}; + +/* The number of MCLK/LRCK ratios supported by the CS42888 */ +#define NUM_MCLK_RATIOS ARRAY_SIZE(cs42888_mode_ratios) + +/** + * cs42888_set_dai_sysclk - determine the CS42888 samples rates. + * @codec_dai: the codec DAI + * @clk_id: the clock ID (ignored) + * @freq: the MCLK input frequency + * @dir: the clock direction (ignored) + * + * This function is used to tell the codec driver what the input MCLK + * frequency is. + * + */ +static int cs42888_set_dai_sysclk(struct snd_soc_dai *codec_dai, + int clk_id, unsigned int freq, int dir) +{ + struct snd_soc_codec *codec = codec_dai->codec; + struct cs42888_private *cs42888 = codec->private_data; + + cs42888->mclk = freq; + + return 0; +} + +/** + * cs42888_set_dai_fmt - configure the codec for the selected audio format + * @codec_dai: the codec DAI + * @format: a SND_SOC_DAIFMT_x value indicating the data format + * + * This function takes a bitmask of SND_SOC_DAIFMT_x bits and programs the + * codec accordingly. + * + * Currently, this function only supports SND_SOC_DAIFMT_I2S and + * SND_SOC_DAIFMT_LEFT_J. The CS42888 codec also supports right-justified + * data for playback only, but ASoC currently does not support different + * formats for playback vs. record. + */ +static int cs42888_set_dai_fmt(struct snd_soc_dai *codec_dai, + unsigned int format) +{ + struct snd_soc_codec *codec = codec_dai->codec; + struct cs42888_private *cs42888 = codec->private_data; + int ret = 0; + u8 val; + val = cs42888_read_reg_cache(codec, CS42888_FORMAT); + val &= ~CS42888_FORMAT_DAC_DIF_MASK; + val &= ~CS42888_FORMAT_ADC_DIF_MASK; + /* set DAI format */ + switch (format & SND_SOC_DAIFMT_FORMAT_MASK) { + case SND_SOC_DAIFMT_LEFT_J: + val |= DIF_LEFT_J << CS42888_FORMAT_DAC_DIF_OFFSET; + val |= DIF_LEFT_J << CS42888_FORMAT_ADC_DIF_OFFSET; + break; + case SND_SOC_DAIFMT_I2S: + val |= DIF_I2S << CS42888_FORMAT_DAC_DIF_OFFSET; + val |= DIF_I2S << CS42888_FORMAT_ADC_DIF_OFFSET; + break; + case SND_SOC_DAIFMT_RIGHT_J: + val |= DIF_RIGHT_J << CS42888_FORMAT_DAC_DIF_OFFSET; + val |= DIF_RIGHT_J << CS42888_FORMAT_ADC_DIF_OFFSET; + break; + default: + dev_err(codec->dev, "invalid dai format\n"); + ret = -EINVAL; + return ret; + } + + ret = cs42888_i2c_write(codec, CS42888_FORMAT, val); + if (ret < 0) { + pr_err("i2c write failed\n"); + return ret; + } + + val = cs42888_read_reg_cache(codec, CS42888_MODE); + /* set master/slave audio interface */ + switch (format & SND_SOC_DAIFMT_MASTER_MASK) { + case SND_SOC_DAIFMT_CBS_CFS: + cs42888->slave_mode = 1; + val &= ~CS42888_MODE_SPEED_MASK; + val |= CS42888_MODE_SLAVE; + break; + case SND_SOC_DAIFMT_CBM_CFM: + cs42888->slave_mode = 0; + break; + default: + /* all other modes are unsupported by the hardware */ + ret = -EINVAL; + return ret; + } + + ret = cs42888_i2c_write(codec, CS42888_MODE, val); + if (ret < 0) { + pr_err("i2c write failed\n"); + return ret; + } + + return ret; +} + +/** + * cs42888_hw_params - program the CS42888 with the given hardware parameters. + * @substream: the audio stream + * @params: the hardware parameters to set + + * @dai: the SOC DAI (ignored) + * + * This function programs the hardware with the values provided. + * Specifically, the sample rate and the data format. + * + * The .ops functions are used to provide board-specific data, like input + * frequencies, to this driver. This function takes that information, + * combines it with the hardware parameters provided, and programs the + * hardware accordingly. + */ +static int cs42888_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params, + struct snd_soc_dai *dai) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_device *socdev = rtd->socdev; + struct snd_soc_codec *codec = socdev->card->codec; + struct cs42888_private *cs42888 = codec->private_data; + int ret; + unsigned int i; + unsigned int rate; + unsigned int ratio; + u8 val; + + rate = params_rate(params); /* Sampling rate, in Hz */ + ratio = cs42888->mclk / rate; /* MCLK/LRCK ratio */ + + for (i = 0; i < NUM_MCLK_RATIOS; i++) { + if (cs42888_mode_ratios[i].ratio == ratio) + break; + } + + if (i == NUM_MCLK_RATIOS) { + /* We did not find a matching ratio */ + dev_err(codec->dev, "could not find matching ratio\n"); + return -EINVAL; + } + + if (!cs42888->slave_mode) { + val = cs42888_read_reg_cache(codec, CS42888_MODE); + val &= ~CS42888_MODE_SPEED_MASK; + val |= cs42888_mode_ratios[i].speed_mode; + val &= ~CS42888_MODE_DIV_MASK; + val |= cs42888_mode_ratios[i].mclk; + } else { + val = cs42888_read_reg_cache(codec, CS42888_MODE); + val &= ~CS42888_MODE_SPEED_MASK; + val |= CS42888_MODE_SLAVE; + } + ret = cs42888_i2c_write(codec, CS42888_MODE, val); + if (ret < 0) { + pr_err("i2c write failed\n"); + return ret; + } + + /* Out of low power state */ + val = cs42888_read_reg_cache(codec, CS42888_PWRCTL); + val &= ~CS42888_PWRCTL_PDN_MASK; + ret = cs42888_i2c_write(codec, CS42888_PWRCTL, val); + if (ret < 0) { + pr_err("i2c write failed\n"); + return ret; + } + + /* Unmute all the channels */ + val = cs42888_read_reg_cache(codec, CS42888_MUTE); + val &= ~CS42888_MUTE_ALL; + ret = cs42888_i2c_write(codec, CS42888_MUTE, val); + if (ret < 0) { + pr_err("i2c write failed\n"); + return ret; + } + + ret = cs42888_fill_cache(codec); + if (ret < 0) { + pr_err("failed to fill register cache\n"); + return ret; + } + + return ret; +} + +/** + * cs42888_shutdown - cs42888 enters into low power mode again. + * @substream: the audio stream + * @dai: the SOC DAI (ignored) + * + * The .ops functions are used to provide board-specific data, like input + * frequencies, to this driver. This function takes that information, + * combines it with the hardware parameters provided, and programs the + * hardware accordingly. + */ +static void cs42888_shutdown(struct snd_pcm_substream *substream, + struct snd_soc_dai *dai) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_device *socdev = rtd->socdev; + struct snd_soc_codec *codec = socdev->card->codec; + int ret; + u8 val; + + /* Mute all the channels */ + val = cs42888_read_reg_cache(codec, CS42888_MUTE); + val |= CS42888_MUTE_ALL; + ret = cs42888_i2c_write(codec, CS42888_MUTE, val); + if (ret < 0) + pr_err("i2c write failed\n"); + + /* Enter low power state */ + val = cs42888_read_reg_cache(codec, CS42888_PWRCTL); + val |= CS42888_PWRCTL_PDN_MASK; + ret = cs42888_i2c_write(codec, CS42888_PWRCTL, val); + if (ret < 0) + pr_err("i2c write failed\n"); +} + +/* + * cs42888_codec - global variable to store codec for the ASoC probe function + * + * If struct i2c_driver had a private_data field, we wouldn't need to use + * cs42888_codec. This is the only way to pass the codec structure from + * cs42888_i2c_probe() to cs42888_probe(). Unfortunately, there is no good + * way to synchronize these two functions. cs42888_i2c_probe() can be called + * multiple times before cs42888_probe() is called even once. So for now, we + * also only allow cs42888_i2c_probe() to be run once. That means that we do + * not support more than one cs42888 device in the system, at least for now. + */ +static struct snd_soc_codec *cs42888_codec; + +static struct snd_soc_dai_ops cs42888_dai_ops = { + .set_fmt = cs42888_set_dai_fmt, + .set_sysclk = cs42888_set_dai_sysclk, + .hw_params = cs42888_hw_params, + .shutdown = cs42888_shutdown, +}; + +struct snd_soc_dai cs42888_dai = { + .name = "CS42888", + .playback = { + .stream_name = "Playback", + .channels_min = 1, + .channels_max = 8, + .rates = (SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_88200 |\ + SNDRV_PCM_RATE_176400), + .formats = CS42888_FORMATS, + }, + .capture = { + .stream_name = "Capture", + .channels_min = 1, + .channels_max = 4, + .rates = (SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_88200 |\ + SNDRV_PCM_RATE_176400), + .formats = CS42888_FORMATS, + }, + .ops = &cs42888_dai_ops, +}; +EXPORT_SYMBOL_GPL(cs42888_dai); + +/** + * cs42888_probe - ASoC probe function + * @pdev: platform device + * + * This function is called when ASoC has all the pieces it needs to + * instantiate a sound driver. + */ +static int cs42888_probe(struct platform_device *pdev) +{ + struct snd_soc_device *socdev = platform_get_drvdata(pdev); + struct snd_soc_codec *codec = cs42888_codec; + int ret; + + /* Connect the codec to the socdev. snd_soc_new_pcms() needs this. */ + socdev->card->codec = codec; + + /* Register PCMs */ + ret = snd_soc_new_pcms(socdev, SNDRV_DEFAULT_IDX1, SNDRV_DEFAULT_STR1); + if (ret < 0) { + dev_err(codec->dev, "failed to create pcms\n"); + return ret; + } + + /* Add the non-DAPM controls */ + ret = snd_soc_add_controls(codec, cs42888_snd_controls, + ARRAY_SIZE(cs42888_snd_controls)); + if (ret < 0) { + dev_err(codec->dev, "failed to add controls\n"); + goto error_free_pcms; + } + + /* Add DAPM controls */ + ca42888_add_widgets(codec); + + /* And finally, register the socdev */ + ret = snd_soc_init_card(socdev); + if (ret < 0) { + dev_err(codec->dev, "failed to register card\n"); + goto error_free_pcms; + } + + return 0; + +error_free_pcms: + snd_soc_free_pcms(socdev); + snd_soc_dapm_free(socdev); + + return ret; +} + +/** + * cs42888_remove - ASoC remove function + * @pdev: platform device + * + * This function is the counterpart to cs42888_probe(). + */ +static int cs42888_remove(struct platform_device *pdev) +{ + struct snd_soc_device *socdev = platform_get_drvdata(pdev); + + snd_soc_free_pcms(socdev); + snd_soc_dapm_free(socdev); + + return 0; +}; + + +/** + * cs42888_i2c_probe - initialize the I2C interface of the CS42888 + * @i2c_client: the I2C client object + * @id: the I2C device ID (ignored) + * + * This function is called whenever the I2C subsystem finds a device that + * matches the device ID given via a prior call to i2c_add_driver(). + */ +static int cs42888_i2c_probe(struct i2c_client *i2c_client, + const struct i2c_device_id *id) +{ + struct snd_soc_codec *codec; + struct cs42888_private *cs42888; + int ret; + struct regulator *regulator_vsd; + u8 val; + + if (cs42888_codec) { + dev_err(&i2c_client->dev, + "Multiple CS42888 devices not supported\n"); + return -ENOMEM; + } + + cs42888_i2c_client = i2c_client; + + /* Allocate enough space for the snd_soc_codec structure + and our private data together. */ + cs42888 = kzalloc(sizeof(struct cs42888_private), GFP_KERNEL); + if (!cs42888) { + dev_err(&i2c_client->dev, "could not allocate codec\n"); + return -ENOMEM; + } + + /* hold on reset */ + gpio_cs42888_pdwn(1); + + regulator_vsd = regulator_get(&i2c_client->dev, "VSD"); + if (!IS_ERR(regulator_vsd)) + cs42888->regulator_vsd = regulator_vsd; + + if (cs42888->regulator_vsd) { + regulator_set_voltage(cs42888->regulator_vsd, + 2800000, 2800000); + if (regulator_enable(cs42888->regulator_vsd) != 0) { + pr_err("%s:VSD set voltage error\n", __func__); + } else { + dev_dbg(&i2c_client->dev, + "%s:io set voltage ok\n", __func__); + } + } + + msleep(1); + /* out of reset state */ + gpio_cs42888_pdwn(0); + + /* Verify that we have a CS42888 */ + ret = cs42888_read_reg(CS42888_CHIPID, &val); + if (ret < 0) { + pr_err("Device with ID register %x is not a CS42888", val); + return -ENODEV; + } + /* The top four bits of the chip ID should be 0000. */ + if ((val & CS42888_CHIPID_ID_MASK) != 0x00) { + dev_err(&i2c_client->dev, "device is not a CS42888\n"); + return -ENODEV; + } + + dev_info(&i2c_client->dev, "found device at i2c address %X\n", + i2c_client->addr); + dev_info(&i2c_client->dev, "hardware revision %X\n", val & 0xF); + + codec = &cs42888->codec; + codec->hw_write = (hw_write_t)i2c_master_send; + + i2c_set_clientdata(i2c_client, cs42888); + codec->control_data = i2c_client; + + codec->dev = &i2c_client->dev; + + mutex_init(&codec->mutex); + INIT_LIST_HEAD(&codec->dapm_widgets); + INIT_LIST_HEAD(&codec->dapm_paths); + + codec->private_data = cs42888; + codec->name = "CS42888"; + codec->owner = THIS_MODULE; + codec->read = cs42888_read_reg_cache; + codec->write = cs42888_i2c_write; + codec->dai = &cs42888_dai; + codec->num_dai = 1; + codec->reg_cache = cs42888->reg_cache; + codec->reg_cache_size = ARRAY_SIZE(cs42888->reg_cache); + + /* The I2C interface is set up, so pre-fill our register cache */ + ret = cs42888_fill_cache(codec); + if (ret < 0) { + dev_err(&i2c_client->dev, "failed to fill register cache\n"); + goto error_free_codec; + } + + /* Enter low power state */ + val = cs42888_read_reg_cache(codec, CS42888_PWRCTL); + val |= CS42888_PWRCTL_PDN_MASK; + ret = cs42888_i2c_write(codec, CS42888_PWRCTL, val); + if (ret < 0) { + dev_err(&i2c_client->dev, "i2c write failed\n"); + return ret; + } + + /* Disable auto-mute */ + val = cs42888_read_reg_cache(codec, CS42888_TRANS); + val &= ~CS42888_TRANS_AMUTE_MASK; + ret = cs42888_i2c_write(codec, CS42888_TRANS, val); + if (ret < 0) { + pr_err("i2c write failed\n"); + return ret; + } + + cs42888_dai.dev = &i2c_client->dev; + + cs42888_codec = codec; + ret = snd_soc_register_codec(codec); + if (ret != 0) { + dev_err(&i2c_client->dev, + "Failed to register codec: %d\n", ret); + goto error_free_codec; + } + + ret = snd_soc_register_dai(&cs42888_dai); + if (ret < 0) { + dev_err(&i2c_client->dev, "failed to register DAIe\n"); + goto error_codec; + } + + return 0; + +error_codec: + snd_soc_unregister_codec(codec); +error_free_codec: + kfree(cs42888); + cs42888_codec = NULL; + cs42888_dai.dev = NULL; + + return ret; +} + +/** + * cs42888_i2c_remove - remove an I2C device + * @i2c_client: the I2C client object + * + * This function is the counterpart to cs42888_i2c_probe(). + */ +static int cs42888_i2c_remove(struct i2c_client *i2c_client) +{ + struct cs42888_private *cs42888 = i2c_get_clientdata(i2c_client); + + snd_soc_unregister_dai(&cs42888_dai); + snd_soc_unregister_codec(&cs42888->codec); + kfree(cs42888); + cs42888_codec = NULL; + cs42888_dai.dev = NULL; + + return 0; +} + +/* + * cs42888_i2c_id - I2C device IDs supported by this driver + */ +static struct i2c_device_id cs42888_i2c_id[] = { + {"cs42888", 0}, + {} +}; +MODULE_DEVICE_TABLE(i2c, cs42888_i2c_id); + +#ifdef CONFIG_PM + +/* This suspend/resume implementation can handle both - a simple standby + * where the codec remains powered, and a full suspend, where the voltage + * domain the codec is connected to is teared down and/or any other hardware + * reset condition is asserted. + * + * The codec's own power saving features are enabled in the suspend callback, + * and all registers are written back to the hardware when resuming. + */ + +static int cs42888_i2c_suspend(struct i2c_client *client, pm_message_t mesg) +{ + struct cs42888_private *cs42888 = i2c_get_clientdata(client); + struct snd_soc_codec *codec = &cs42888->codec; + int reg = snd_soc_read(codec, CS42888_PWRCTL) | CS42888_PWRCTL_PDN_MASK; + + return snd_soc_write(codec, CS42888_PWRCTL, reg); +} + +static int cs42888_i2c_resume(struct i2c_client *client) +{ + struct cs42888_private *cs42888 = i2c_get_clientdata(client); + struct snd_soc_codec *codec = &cs42888->codec; + int reg; + + /* In case the device was put to hard reset during sleep, we need to + * wait 500ns here before any I2C communication. */ + ndelay(500); + + /* first restore the entire register cache ... */ + for (reg = CS42888_FIRSTREG; reg <= CS42888_LASTREG; reg++) { + u8 val = snd_soc_read(codec, reg); + + if (i2c_smbus_write_byte_data(client, reg, val)) { + dev_err(codec->dev, "i2c write failed\n"); + return -EIO; + } + } + + /* ... then disable the power-down bits */ + reg = snd_soc_read(codec, CS42888_PWRCTL); + reg &= ~CS42888_PWRCTL_PDN_MASK; + + return snd_soc_write(codec, CS42888_PWRCTL, reg); +} +#else +#define cs42888_i2c_suspend NULL +#define cs42888_i2c_resume NULL +#endif /* CONFIG_PM */ + +/* + * cs42888_i2c_driver - I2C device identification + * + * This structure tells the I2C subsystem how to identify and support a + * given I2C device type. + */ +static struct i2c_driver cs42888_i2c_driver = { + .driver = { + .name = "cs42888", + .owner = THIS_MODULE, + }, + .id_table = cs42888_i2c_id, + .probe = cs42888_i2c_probe, + .remove = cs42888_i2c_remove, + .suspend = cs42888_i2c_suspend, + .resume = cs42888_i2c_resume, +}; + +/* + * ASoC codec device structure + * + * Assign this variable to the codec_dev field of the machine driver's + * snd_soc_device structure. + */ +struct snd_soc_codec_device soc_codec_device_cs42888 = { + .probe = cs42888_probe, + .remove = cs42888_remove +}; +EXPORT_SYMBOL_GPL(soc_codec_device_cs42888); + +static int __init cs42888_init(void) +{ + pr_info("Cirrus Logic CS42888 ALSA SoC Codec Driver\n"); + + return i2c_add_driver(&cs42888_i2c_driver); +} +module_init(cs42888_init); + +static void __exit cs42888_exit(void) +{ + i2c_del_driver(&cs42888_i2c_driver); +} +module_exit(cs42888_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("Cirrus Logic CS42888 ALSA SoC Codec Driver"); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/codecs/cs42888.h b/sound/soc/codecs/cs42888.h new file mode 100644 index 000000000000..a2c8562c17c5 --- /dev/null +++ b/sound/soc/codecs/cs42888.h @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#ifndef _CS42888_H +#define _CS42888_H + +/* + * The ASoC codec DAI structure for the CS42888. Assign this structure to + * the .codec_dai field of your machine driver's snd_soc_dai_link structure. + */ +extern struct snd_soc_dai cs42888_dai; + +/* + * The ASoC codec device structure for the CS42888. Assign this structure + * to the .codec_dev field of your machine driver's snd_soc_device + * structure. + */ +extern struct snd_soc_codec_device soc_codec_device_cs42888; + +extern void gpio_cs42888_pdwn(int pdwn); +#endif diff --git a/sound/soc/codecs/mxs-adc-codec.c b/sound/soc/codecs/mxs-adc-codec.c new file mode 100644 index 000000000000..c5a223e8b170 --- /dev/null +++ b/sound/soc/codecs/mxs-adc-codec.c @@ -0,0 +1,1221 @@ +/* + * ALSA codec for Freescale MXS ADC/DAC Audio + * + * Author: Vladislav Buzov + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. + * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "mxs-adc-codec.h" + +#define BV_AUDIOIN_ADCVOL_SELECT__MIC 0x00 /* missing define */ + +#ifndef BF +#define BF(value, field) (((value) << BP_##field) & BM_##field) +#endif + +#define BM_RTC_PERSISTENT0_RELEASE_GND BF(0x2, RTC_PERSISTENT0_SPARE_ANALOG) + +#define REGS_RTC_BASE (IO_ADDRESS(RTC_PHYS_ADDR)) + +struct mxs_codec_priv { + struct clk *clk; + struct snd_soc_codec codec; +}; + +/* + * ALSA API + */ +static void __iomem *adc_regmap[] = { + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_CTRL, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_STAT, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_DACSRR, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_DACVOLUME, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_DACDEBUG, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_HPVOL, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_PWRDN, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_REFCTRL, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_ANACTRL, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_TEST, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_BISTCTRL, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_BISTSTAT0, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_BISTSTAT1, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_ANACLKCTRL, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_DATA, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_SPEAKERCTRL, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_VERSION, + REGS_AUDIOIN_BASE + HW_AUDIOIN_CTRL, + REGS_AUDIOIN_BASE + HW_AUDIOIN_STAT, + REGS_AUDIOIN_BASE + HW_AUDIOIN_ADCSRR, + REGS_AUDIOIN_BASE + HW_AUDIOIN_ADCVOLUME, + REGS_AUDIOIN_BASE + HW_AUDIOIN_ADCDEBUG, + REGS_AUDIOIN_BASE + HW_AUDIOIN_ADCVOL, + REGS_AUDIOIN_BASE + HW_AUDIOIN_MICLINE, + REGS_AUDIOIN_BASE + HW_AUDIOIN_ANACLKCTRL, + REGS_AUDIOIN_BASE + HW_AUDIOIN_DATA, +}; + +static u16 mxs_audio_regs[ADC_REGNUM]; + +static u8 dac_volumn_control_word[] = { + 0x37, 0x5e, 0x7e, 0x8e, + 0x9e, 0xae, 0xb6, 0xbe, + 0xc6, 0xce, 0xd6, 0xde, + 0xe6, 0xee, 0xf6, 0xfe, +}; + +/* + * ALSA core supports only 16 bit registers. It means we have to simulate it + * by virtually splitting a 32bit ADC/DAC registers into two halves + * high (bits 31:16) and low (bits 15:0). The routins abow detects which part + * of 32bit register is accessed. + */ +static void mxs_codec_write_cache(struct snd_soc_codec *codec, + unsigned int reg, unsigned int value) +{ + u16 *cache = codec->reg_cache; + if (reg < ADC_REGNUM) + cache[reg] = value; +} + +static int mxs_codec_write(struct snd_soc_codec *codec, + unsigned int reg, unsigned int value) +{ + unsigned int reg_val; + unsigned int mask = 0xffff; + + if (reg >= ADC_REGNUM) + return -EIO; + + mxs_codec_write_cache(codec, reg, value); + + if (reg & 0x1) { + mask <<= 16; + value <<= 16; + } + + reg_val = __raw_readl(adc_regmap[reg >> 1]); + reg_val = (reg_val & ~mask) | value; + __raw_writel(reg_val, adc_regmap[reg >> 1]); + + return 0; +} + +static unsigned int mxs_codec_read(struct snd_soc_codec *codec, + unsigned int reg) +{ + unsigned int reg_val; + + if (reg >= ADC_REGNUM) + return -1; + + reg_val = __raw_readl(adc_regmap[reg >> 1]); + if (reg & 1) + reg_val >>= 16; + + return reg_val & 0xffff; +} + +static unsigned int mxs_codec_read_cache(struct snd_soc_codec *codec, + unsigned int reg) +{ + u16 *cache = codec->reg_cache; + if (reg >= ADC_REGNUM) + return -EINVAL; + return cache[reg]; +} + +static void mxs_codec_sync_reg_cache(struct snd_soc_codec *codec) +{ + int reg; + for (reg = 0; reg < ADC_REGNUM; reg += 1) + mxs_codec_write_cache(codec, reg, + mxs_codec_read(codec, reg)); +} + +static int mxs_codec_restore_reg(struct snd_soc_codec *codec, + unsigned int reg) +{ + unsigned int cached_val, hw_val; + + cached_val = mxs_codec_read_cache(codec, reg); + hw_val = mxs_codec_read(codec, reg); + + if (hw_val != cached_val) + return mxs_codec_write(codec, reg, cached_val); + + return 0; +} + +static int dac_info_volsw(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_info *uinfo) +{ + uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; + uinfo->count = 2; + uinfo->value.integer.min = 0; + uinfo->value.integer.max = 0xf; + return 0; +} + +static int dac_get_volsw(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + int reg, l, r; + int i; + + reg = __raw_readl(REGS_AUDIOOUT_BASE + HW_AUDIOOUT_DACVOLUME); + + l = (reg & BM_AUDIOOUT_DACVOLUME_VOLUME_LEFT) >> + BP_AUDIOOUT_DACVOLUME_VOLUME_LEFT; + r = (reg & BM_AUDIOOUT_DACVOLUME_VOLUME_RIGHT) >> + BP_AUDIOOUT_DACVOLUME_VOLUME_RIGHT; + /*Left channel */ + i = 0; + while (i < 16) { + if (l == dac_volumn_control_word[i]) { + ucontrol->value.integer.value[0] = i; + break; + } + i++; + } + if (i == 16) + ucontrol->value.integer.value[0] = i; + /*Right channel */ + i = 0; + while (i < 16) { + if (r == dac_volumn_control_word[i]) { + ucontrol->value.integer.value[1] = i; + break; + } + i++; + } + if (i == 16) + ucontrol->value.integer.value[1] = i; + + return 0; +} + +static int dac_put_volsw(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + int reg, l, r; + int i; + + i = ucontrol->value.integer.value[0]; + l = dac_volumn_control_word[i]; + /*Get dac volume for left channel */ + reg = BF(l, AUDIOOUT_DACVOLUME_VOLUME_LEFT); + + i = ucontrol->value.integer.value[1]; + r = dac_volumn_control_word[i]; + /*Get dac volume for right channel */ + reg = reg | BF(r, AUDIOOUT_DACVOLUME_VOLUME_RIGHT); + + /*Clear left/right dac volume */ + __raw_writel(BM_AUDIOOUT_DACVOLUME_VOLUME_LEFT | + BM_AUDIOOUT_DACVOLUME_VOLUME_RIGHT, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_DACVOLUME_CLR); + __raw_writel(reg, REGS_AUDIOOUT_BASE + HW_AUDIOOUT_DACVOLUME_SET); + + return 0; +} + +static int pga_event(struct snd_soc_dapm_widget *w, + struct snd_kcontrol *kcontrol, int event) +{ + switch (event) { + case SND_SOC_DAPM_PRE_PMU: + /* Prepare powering up HP and SPEAKER output */ + __raw_writel(BM_AUDIOOUT_ANACTRL_HP_HOLD_GND, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_ANACTRL_SET); + __raw_writel(BM_RTC_PERSISTENT0_RELEASE_GND, + REGS_RTC_BASE + HW_RTC_PERSISTENT0_SET); + msleep(100); + break; + case SND_SOC_DAPM_POST_PMU: + __raw_writel(BM_AUDIOOUT_ANACTRL_HP_HOLD_GND, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_ANACTRL_CLR); + break; + case SND_SOC_DAPM_POST_PMD: + __raw_writel(BM_RTC_PERSISTENT0_RELEASE_GND, + REGS_RTC_BASE + HW_RTC_PERSISTENT0_CLR); + break; + } + return 0; +} + +static int adc_event(struct snd_soc_dapm_widget *w, + struct snd_kcontrol *kcontrol, int event) +{ + switch (event) { + case SND_SOC_DAPM_PRE_PMU: + __raw_writel(BM_RTC_PERSISTENT0_RELEASE_GND, + REGS_RTC_BASE + HW_RTC_PERSISTENT0_SET); + msleep(100); + break; + case SND_SOC_DAPM_POST_PMD: + __raw_writel(BM_RTC_PERSISTENT0_RELEASE_GND, + REGS_RTC_BASE + HW_RTC_PERSISTENT0_CLR); + break; + } + return 0; +} + +static const char *mxs_codec_adc_input_sel[] = { + "Mic", "Line In 1", "Head Phone", "Line In 2" }; + +static const char *mxs_codec_hp_output_sel[] = { "DAC Out", "Line In 1" }; + +static const char *mxs_codec_adc_3d_sel[] = { + "Off", "Low", "Medium", "High" }; + +static const struct soc_enum mxs_codec_enum[] = { + SOC_ENUM_SINGLE(ADC_ADCVOL_L, 12, 4, mxs_codec_adc_input_sel), + SOC_ENUM_SINGLE(ADC_ADCVOL_L, 4, 4, mxs_codec_adc_input_sel), + SOC_ENUM_SINGLE(DAC_HPVOL_H, 0, 2, mxs_codec_hp_output_sel), + SOC_ENUM_SINGLE(DAC_CTRL_L, 8, 4, mxs_codec_adc_3d_sel), +}; + +/* Codec controls */ +static const struct snd_kcontrol_new mxs_snd_controls[] = { + /* Playback Volume */ + {.iface = SNDRV_CTL_ELEM_IFACE_MIXER, + .name = "DAC Playback Volume", + .access = SNDRV_CTL_ELEM_ACCESS_READWRITE | + SNDRV_CTL_ELEM_ACCESS_VOLATILE, + .info = dac_info_volsw, + .get = dac_get_volsw, + .put = dac_put_volsw, + }, + + SOC_DOUBLE_R("DAC Playback Switch", + DAC_VOLUME_H, DAC_VOLUME_L, 8, 0x01, 1), + SOC_DOUBLE("HP Playback Volume", DAC_HPVOL_L, 8, 0, 0x7F, 1), + + /* Capture Volume */ + SOC_DOUBLE_R("ADC Capture Volume", + ADC_VOLUME_H, ADC_VOLUME_L, 0, 0xFF, 0), + SOC_DOUBLE("ADC PGA Capture Volume", ADC_ADCVOL_L, 8, 0, 0x0F, 0), + SOC_SINGLE("ADC PGA Capture Switch", ADC_ADCVOL_H, 8, 0x1, 1), + SOC_SINGLE("Mic PGA Capture Volume", ADC_MICLINE_L, 0, 0x03, 0), + + /* Virtual 3D effect */ + SOC_ENUM("3D effect", mxs_codec_enum[3]), +}; + +/* Left ADC Mux */ +static const struct snd_kcontrol_new mxs_left_adc_controls = +SOC_DAPM_ENUM("Route", mxs_codec_enum[0]); + +/* Right ADC Mux */ +static const struct snd_kcontrol_new mxs_right_adc_controls = +SOC_DAPM_ENUM("Route", mxs_codec_enum[1]); + +/* Head Phone Mux */ +static const struct snd_kcontrol_new mxs_hp_controls = +SOC_DAPM_ENUM("Route", mxs_codec_enum[2]); + +static const struct snd_soc_dapm_widget mxs_codec_widgets[] = { + + SND_SOC_DAPM_ADC_E("ADC", "Capture", DAC_PWRDN_L, 8, 1, adc_event, + SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), + + SND_SOC_DAPM_DAC("DAC", "Playback", DAC_PWRDN_L, 12, 1), + + SND_SOC_DAPM_MUX("Left ADC Mux", SND_SOC_NOPM, 0, 0, + &mxs_left_adc_controls), + SND_SOC_DAPM_MUX("Right ADC Mux", SND_SOC_NOPM, 0, 0, + &mxs_right_adc_controls), + SND_SOC_DAPM_MUX("HP Mux", SND_SOC_NOPM, 0, 0, + &mxs_hp_controls), + SND_SOC_DAPM_PGA_E("HP AMP", DAC_PWRDN_L, 0, 1, NULL, 0, pga_event, + SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | + SND_SOC_DAPM_POST_PMD), + SND_SOC_DAPM_PGA("SPEAKER AMP", DAC_PWRDN_H, 8, 1, NULL, 0), + SND_SOC_DAPM_INPUT("LINE1L"), + SND_SOC_DAPM_INPUT("LINE1R"), + SND_SOC_DAPM_INPUT("LINE2L"), + SND_SOC_DAPM_INPUT("LINE2R"), + SND_SOC_DAPM_INPUT("MIC"), + + SND_SOC_DAPM_OUTPUT("SPEAKER"), + SND_SOC_DAPM_OUTPUT("HPL"), + SND_SOC_DAPM_OUTPUT("HPR"), +}; + +static const struct snd_soc_dapm_route intercon[] = { + + /* Left ADC Mux */ + {"Left ADC Mux", "Mic", "MIC"}, + {"Left ADC Mux", "Line In 1", "LINE1L"}, + {"Left ADC Mux", "Line In 2", "LINE2L"}, + {"Left ADC Mux", "Head Phone", "HPL"}, + + /* Right ADC Mux */ + {"Right ADC Mux", "Mic", "MIC"}, + {"Right ADC Mux", "Line In 1", "LINE1R"}, + {"Right ADC Mux", "Line In 2", "LINE2R"}, + {"Right ADC Mux", "Head Phone", "HPR"}, + + /* ADC */ + {"ADC", NULL, "Left ADC Mux"}, + {"ADC", NULL, "Right ADC Mux"}, + + /* HP Mux */ + {"HP Mux", "DAC Out", "DAC"}, + {"HP Mux", "Line In 1", "LINE1L"}, + {"HP Mux", "Line In 1", "LINE1R"}, + + /* HP amp */ + {"HP AMP", NULL, "HP Mux"}, + /* HP output */ + {"HPR", NULL, "HP AMP"}, + {"HPL", NULL, "HP AMP"}, + + /* Speaker amp */ + {"SPEAKER AMP", NULL, "DAC"}, + {"SPEAKER", NULL, "SPEAKER AMP"}, +}; + +static int mxs_codec_add_widgets(struct snd_soc_codec *codec) +{ + int ret = 0; + + snd_soc_dapm_new_controls(codec, mxs_codec_widgets, + ARRAY_SIZE(mxs_codec_widgets)); + + if (ret) { + dev_err(codec->dev, "dapm control register failed\n"); + return ret; + } + /* set up audio path interconnects */ + snd_soc_dapm_add_routes(codec, intercon, ARRAY_SIZE(intercon)); + + if (ret) { + dev_err(codec->dev, "DAPM route register failed\n"); + return ret; + } + + return snd_soc_dapm_new_widgets(codec); +} + +struct dac_srr { + u32 rate; + u32 basemult; + u32 src_hold; + u32 src_int; + u32 src_frac; +}; + +static struct dac_srr srr_values[] = { + {192000, 0x4, 0x0, 0x0F, 0x13FF}, + {176400, 0x4, 0x0, 0x11, 0x0037}, + {128000, 0x4, 0x0, 0x17, 0x0E00}, + {96000, 0x2, 0x0, 0x0F, 0x13FF}, + {88200, 0x2, 0x0, 0x11, 0x0037}, + {64000, 0x2, 0x0, 0x17, 0x0E00}, + {48000, 0x1, 0x0, 0x0F, 0x13FF}, + {44100, 0x1, 0x0, 0x11, 0x0037}, + {32000, 0x1, 0x0, 0x17, 0x0E00}, + {24000, 0x1, 0x1, 0x0F, 0x13FF}, + {22050, 0x1, 0x1, 0x11, 0x0037}, + {16000, 0x1, 0x1, 0x17, 0x0E00}, + {12000, 0x1, 0x3, 0x0F, 0x13FF}, + {11025, 0x1, 0x3, 0x11, 0x0037}, + {8000, 0x1, 0x3, 0x17, 0x0E00} +}; + +static inline int get_srr_values(int rate) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(srr_values); i++) + if (srr_values[i].rate == rate) + return i; + + return -1; +} + +static int mxs_codec_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params, + struct snd_soc_dai *dai) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_device *socdev = rtd->socdev; + struct snd_soc_codec *codec = socdev->card->codec; + int playback = substream->stream == SNDRV_PCM_STREAM_PLAYBACK ? 1 : 0; + int i; + u32 srr_value = 0; + u32 src_hold = 0; + + i = get_srr_values(params_rate(params)); + if (i < 0) + dev_warn(socdev->dev, "%s doesn't support rate %d\n", + codec->name, params_rate(params)); + else { + src_hold = srr_values[i].src_hold; + + srr_value = + BF(srr_values[i].basemult, AUDIOOUT_DACSRR_BASEMULT) | + BF(srr_values[i].src_int, AUDIOOUT_DACSRR_SRC_INT) | + BF(srr_values[i].src_frac, AUDIOOUT_DACSRR_SRC_FRAC) | + BF(src_hold, AUDIOOUT_DACSRR_SRC_HOLD); + + if (playback) + __raw_writel(srr_value, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_DACSRR); + else + __raw_writel(srr_value, + REGS_AUDIOIN_BASE + HW_AUDIOIN_ADCSRR); + } + + switch (params_format(params)) { + case SNDRV_PCM_FORMAT_S16_LE: + if (playback) + __raw_writel(BM_AUDIOOUT_CTRL_WORD_LENGTH, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_CTRL_SET); + else + __raw_writel(BM_AUDIOIN_CTRL_WORD_LENGTH, + REGS_AUDIOIN_BASE + HW_AUDIOIN_CTRL_SET); + + break; + + case SNDRV_PCM_FORMAT_S32_LE: + if (playback) + __raw_writel(BM_AUDIOOUT_CTRL_WORD_LENGTH, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_CTRL_CLR); + else + __raw_writel(BM_AUDIOIN_CTRL_WORD_LENGTH, + REGS_AUDIOIN_BASE + HW_AUDIOIN_CTRL_CLR); + + break; + + default: + dev_warn(socdev->dev, "%s doesn't support format %d\n", + codec->name, params_format(params)); + + } + + return 0; +} + +static int mxs_codec_dig_mute(struct snd_soc_dai *dai, int mute) +{ + int l, r; + int ll, rr; + u32 reg, reg1, reg2; + u32 dac_mask = BM_AUDIOOUT_DACVOLUME_MUTE_LEFT | + BM_AUDIOOUT_DACVOLUME_MUTE_RIGHT; + + if (mute) { + reg = __raw_readl(REGS_AUDIOOUT_BASE + \ + HW_AUDIOOUT_DACVOLUME); + + reg1 = reg & ~BM_AUDIOOUT_DACVOLUME_VOLUME_LEFT; + reg1 = reg1 & ~BM_AUDIOOUT_DACVOLUME_VOLUME_RIGHT; + + l = (reg & BM_AUDIOOUT_DACVOLUME_VOLUME_LEFT) >> + BP_AUDIOOUT_DACVOLUME_VOLUME_LEFT; + r = (reg & BM_AUDIOOUT_DACVOLUME_VOLUME_RIGHT) >> + BP_AUDIOOUT_DACVOLUME_VOLUME_RIGHT; + + /* fade out dac vol */ + while ((l > DAC_VOLUME_MIN) || (r > DAC_VOLUME_MIN)) { + l -= 0x8; + r -= 0x8; + ll = l > DAC_VOLUME_MIN ? l : DAC_VOLUME_MIN; + rr = r > DAC_VOLUME_MIN ? r : DAC_VOLUME_MIN; + reg2 = reg1 | BF_AUDIOOUT_DACVOLUME_VOLUME_LEFT(ll) + | BF_AUDIOOUT_DACVOLUME_VOLUME_RIGHT(rr); + __raw_writel(reg2, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_DACVOLUME); + msleep(1); + } + + __raw_writel(dac_mask, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_DACVOLUME_SET); + reg = reg | dac_mask; + __raw_writel(reg, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_DACVOLUME); + } else + __raw_writel(dac_mask, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_DACVOLUME_CLR); + + return 0; +} + +static int mxs_codec_set_bias_level(struct snd_soc_codec *codec, + enum snd_soc_bias_level level) +{ + pr_debug("dapm level %d\n", level); + switch (level) { + case SND_SOC_BIAS_ON: /* full On */ + if (codec->bias_level == SND_SOC_BIAS_ON) + break; + break; + + case SND_SOC_BIAS_PREPARE: /* partial On */ + if (codec->bias_level == SND_SOC_BIAS_PREPARE) + break; + /* Set Capless mode */ + __raw_writel(BM_AUDIOOUT_PWRDN_CAPLESS, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_PWRDN_CLR); + break; + + case SND_SOC_BIAS_STANDBY: /* Off, with power */ + if (codec->bias_level == SND_SOC_BIAS_STANDBY) + break; + /* Unset Capless mode */ + __raw_writel(BM_AUDIOOUT_PWRDN_CAPLESS, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_PWRDN_SET); + break; + + case SND_SOC_BIAS_OFF: /* Off, without power */ + if (codec->bias_level == SND_SOC_BIAS_OFF) + break; + /* Unset Capless mode */ + __raw_writel(BM_AUDIOOUT_PWRDN_CAPLESS, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_PWRDN_SET); + break; + } + codec->bias_level = level; + return 0; +} + +/* + * Codec initialization + */ +#define VAG_BASE_VALUE ((1400/2 - 625)/25) +static void mxs_codec_dac_set_vag(void) +{ + u32 refctrl_val = __raw_readl(REGS_AUDIOOUT_BASE + HW_AUDIOOUT_REFCTRL); + + refctrl_val &= ~(BM_AUDIOOUT_REFCTRL_VAG_VAL); + refctrl_val &= ~(BM_AUDIOOUT_REFCTRL_VBG_ADJ); + refctrl_val |= BF(VAG_BASE_VALUE, AUDIOOUT_REFCTRL_VAG_VAL) | + BM_AUDIOOUT_REFCTRL_ADJ_VAG | + BF(0xF, AUDIOOUT_REFCTRL_ADC_REFVAL) | + BM_AUDIOOUT_REFCTRL_ADJ_ADC | + BF(0x3, AUDIOOUT_REFCTRL_VBG_ADJ) | BM_AUDIOOUT_REFCTRL_RAISE_REF; + + __raw_writel(refctrl_val, REGS_AUDIOOUT_BASE + HW_AUDIOOUT_REFCTRL); +} + +static bool mxs_codec_dac_is_capless() +{ + if ((__raw_readl(REGS_AUDIOOUT_BASE + HW_AUDIOOUT_PWRDN) + & BM_AUDIOOUT_PWRDN_CAPLESS) == 0) + return false; + else + return true; +} +static void mxs_codec_dac_arm_short_cm(bool bShort) +{ + __raw_writel(BF(3, AUDIOOUT_ANACTRL_SHORTMODE_CM), + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_ANACTRL_CLR); + __raw_writel(BM_AUDIOOUT_ANACTRL_SHORT_CM_STS, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_ANACTRL_CLR); + if (bShort) + __raw_writel(BF(1, AUDIOOUT_ANACTRL_SHORTMODE_CM), + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_ANACTRL_SET); +} +static void mxs_codec_dac_arm_short_lr(bool bShort) +{ + __raw_writel(BF(3, AUDIOOUT_ANACTRL_SHORTMODE_LR), + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_ANACTRL_CLR); + __raw_writel(BM_AUDIOOUT_ANACTRL_SHORT_LR_STS, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_ANACTRL_CLR); + if (bShort) + __raw_writel(BF(1, AUDIOOUT_ANACTRL_SHORTMODE_LR), + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_ANACTRL_SET); +} +static void mxs_codec_dac_set_short_trip_level(u8 u8level) +{ + __raw_writel(__raw_readl(REGS_AUDIOOUT_BASE + + HW_AUDIOOUT_ANACTRL) + & (~BM_AUDIOOUT_ANACTRL_SHORT_LVLADJL) + & (~BM_AUDIOOUT_ANACTRL_SHORT_LVLADJR) + | BF(u8level, AUDIOOUT_ANACTRL_SHORT_LVLADJL) + | BF(u8level, AUDIOOUT_ANACTRL_SHORT_LVLADJR), + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_ANACTRL); +} +static void mxs_codec_dac_arm_short(bool bLatchCM, bool bLatchLR) +{ + if (bLatchCM) { + if (mxs_codec_dac_is_capless()) + mxs_codec_dac_arm_short_cm(true); + } else + mxs_codec_dac_arm_short_cm(false); + + if (bLatchLR) + mxs_codec_dac_arm_short_lr(true); + else + mxs_codec_dac_arm_short_lr(false); + +} +static void +mxs_codec_dac_power_on(struct mxs_codec_priv *mxs_adc) +{ + /* Ungate DAC clocks */ + __raw_writel(BM_AUDIOOUT_CTRL_CLKGATE, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_CTRL_CLR); + __raw_writel(BM_AUDIOOUT_ANACLKCTRL_CLKGATE, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_ANACLKCTRL_CLR); + + /* 16 bit word length */ + __raw_writel(BM_AUDIOOUT_CTRL_WORD_LENGTH, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_CTRL_SET); + + /* Arm headphone LR short protect */ + mxs_codec_dac_set_short_trip_level(0); + mxs_codec_dac_arm_short(false, true); + + /* Update DAC volume over zero crossings */ + __raw_writel(BM_AUDIOOUT_DACVOLUME_EN_ZCD, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_DACVOLUME_SET); + /* Mute DAC */ + __raw_writel(BM_AUDIOOUT_DACVOLUME_MUTE_LEFT | + BM_AUDIOOUT_DACVOLUME_MUTE_RIGHT, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_DACVOLUME_SET); + + /* Update HP volume over zero crossings */ + __raw_writel(BM_AUDIOOUT_HPVOL_EN_MSTR_ZCD, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_HPVOL_SET); + + __raw_writel(BM_AUDIOOUT_ANACTRL_HP_CLASSAB, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_ANACTRL_SET); + + /* Mute HP output */ + __raw_writel(BM_AUDIOOUT_HPVOL_MUTE, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_HPVOL_SET); + /* Mute speaker amp */ + __raw_writel(BM_AUDIOOUT_SPEAKERCTRL_MUTE, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_SPEAKERCTRL_SET); + /* Enable the audioout */ + __raw_writel(BM_AUDIOOUT_CTRL_RUN, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_CTRL_SET); +} + +static void +mxs_codec_dac_power_down(struct mxs_codec_priv *mxs_adc) +{ + /* Disable the audioout */ + __raw_writel(BM_AUDIOOUT_CTRL_RUN, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_CTRL_CLR); + /* Disable class AB */ + __raw_writel(BM_AUDIOOUT_ANACTRL_HP_CLASSAB, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_ANACTRL_CLR); + + /* Set hold to ground */ + __raw_writel(BM_AUDIOOUT_ANACTRL_HP_HOLD_GND, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_ANACTRL_SET); + + /* Mute HP output */ + __raw_writel(BM_AUDIOOUT_HPVOL_MUTE, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_HPVOL_SET); + /* Power down HP output */ + __raw_writel(BM_AUDIOOUT_PWRDN_HEADPHONE, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_PWRDN_SET); + + /* Mute speaker amp */ + __raw_writel(BM_AUDIOOUT_SPEAKERCTRL_MUTE, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_SPEAKERCTRL_SET); + /* Power down speaker amp */ + __raw_writel(BM_AUDIOOUT_PWRDN_SPEAKER, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_PWRDN_SET); + + /* Mute DAC */ + __raw_writel(BM_AUDIOOUT_DACVOLUME_MUTE_LEFT | + BM_AUDIOOUT_DACVOLUME_MUTE_RIGHT, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_DACVOLUME_SET); + /* Power down DAC */ + __raw_writel(BM_AUDIOOUT_PWRDN_DAC, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_PWRDN_SET); + + /* Gate DAC clocks */ + __raw_writel(BM_AUDIOOUT_ANACLKCTRL_CLKGATE, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_ANACLKCTRL_SET); + __raw_writel(BM_AUDIOOUT_CTRL_CLKGATE, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_CTRL_SET); +} + +static void +mxs_codec_adc_power_on(struct mxs_codec_priv *mxs_adc) +{ + u32 reg; + + /* Ungate ADC clocks */ + __raw_writel(BM_AUDIOIN_CTRL_CLKGATE, + REGS_AUDIOIN_BASE + HW_AUDIOIN_CTRL_CLR); + __raw_writel(BM_AUDIOIN_ANACLKCTRL_CLKGATE, + REGS_AUDIOIN_BASE + HW_AUDIOIN_ANACLKCTRL_CLR); + + /* 16 bit word length */ + __raw_writel(BM_AUDIOIN_CTRL_WORD_LENGTH, + REGS_AUDIOIN_BASE + HW_AUDIOIN_CTRL_SET); + + /* Unmute ADC channels */ + __raw_writel(BM_AUDIOIN_ADCVOL_MUTE, + REGS_AUDIOIN_BASE + HW_AUDIOIN_ADCVOL_CLR); + + /* + * The MUTE_LEFT and MUTE_RIGHT fields need to be cleared. + * They aren't presented in the datasheet, so this is hardcode. + */ + __raw_writel(0x01000100, REGS_AUDIOIN_BASE + HW_AUDIOIN_ADCVOLUME_CLR); + + /* Set the Input channel gain 3dB */ + __raw_writel(BM_AUDIOIN_ADCVOL_GAIN_LEFT, + REGS_AUDIOIN_BASE + HW_AUDIOIN_ADCVOL_CLR); + __raw_writel(BM_AUDIOIN_ADCVOL_GAIN_RIGHT, + REGS_AUDIOIN_BASE + HW_AUDIOIN_ADCVOL_CLR); + __raw_writel(BF(2, AUDIOIN_ADCVOL_GAIN_LEFT), + REGS_AUDIOIN_BASE + HW_AUDIOIN_ADCVOL_SET); + __raw_writel(BF(2, AUDIOIN_ADCVOL_GAIN_RIGHT), + REGS_AUDIOIN_BASE + HW_AUDIOIN_ADCVOL_SET); + + /* Select default input - Microphone */ + __raw_writel(BM_AUDIOIN_ADCVOL_SELECT_LEFT, + REGS_AUDIOIN_BASE + HW_AUDIOIN_ADCVOL_CLR); + __raw_writel(BM_AUDIOIN_ADCVOL_SELECT_RIGHT, + REGS_AUDIOIN_BASE + HW_AUDIOIN_ADCVOL_CLR); + __raw_writel(BF + (BV_AUDIOIN_ADCVOL_SELECT__MIC, + AUDIOIN_ADCVOL_SELECT_LEFT), + REGS_AUDIOIN_BASE + HW_AUDIOIN_ADCVOL_SET); + __raw_writel(BF + (BV_AUDIOIN_ADCVOL_SELECT__MIC, + AUDIOIN_ADCVOL_SELECT_RIGHT), + REGS_AUDIOIN_BASE + HW_AUDIOIN_ADCVOL_SET); + + /* Supply bias voltage to microphone */ + __raw_writel(BF(1, AUDIOIN_MICLINE_MIC_RESISTOR), + REGS_AUDIOIN_BASE + HW_AUDIOIN_MICLINE_SET); + __raw_writel(BM_AUDIOIN_MICLINE_MIC_SELECT, + REGS_AUDIOIN_BASE + HW_AUDIOIN_MICLINE_SET); + __raw_writel(BF(1, AUDIOIN_MICLINE_MIC_GAIN), + REGS_AUDIOIN_BASE + HW_AUDIOIN_MICLINE_SET); + __raw_writel(BF(7, AUDIOIN_MICLINE_MIC_BIAS), + REGS_AUDIOIN_BASE + HW_AUDIOIN_MICLINE_SET); + + /* Set max ADC volume */ + reg = __raw_readl(REGS_AUDIOIN_BASE + HW_AUDIOIN_ADCVOLUME); + reg &= ~BM_AUDIOIN_ADCVOLUME_VOLUME_LEFT; + reg &= ~BM_AUDIOIN_ADCVOLUME_VOLUME_RIGHT; + reg |= BF(ADC_VOLUME_MAX, AUDIOIN_ADCVOLUME_VOLUME_LEFT); + reg |= BF(ADC_VOLUME_MAX, AUDIOIN_ADCVOLUME_VOLUME_RIGHT); + __raw_writel(reg, REGS_AUDIOIN_BASE + HW_AUDIOIN_ADCVOLUME); +} + +static void +mxs_codec_adc_power_down(struct mxs_codec_priv *mxs_adc) +{ + /* Mute ADC channels */ + __raw_writel(BM_AUDIOIN_ADCVOL_MUTE, + REGS_AUDIOIN_BASE + HW_AUDIOIN_ADCVOL_SET); + + /* Power Down ADC */ + __raw_writel(BM_AUDIOOUT_PWRDN_ADC | BM_AUDIOOUT_PWRDN_RIGHT_ADC, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_PWRDN_SET); + + /* Gate ADC clocks */ + __raw_writel(BM_AUDIOIN_CTRL_CLKGATE, + REGS_AUDIOIN_BASE + HW_AUDIOIN_CTRL_SET); + __raw_writel(BM_AUDIOIN_ANACLKCTRL_CLKGATE, + REGS_AUDIOIN_BASE + HW_AUDIOIN_ANACLKCTRL_SET); + + /* Disable bias voltage to microphone */ + __raw_writel(BF(0, AUDIOIN_MICLINE_MIC_RESISTOR), + REGS_AUDIOIN_BASE + HW_AUDIOIN_MICLINE_SET); +} + +static void mxs_codec_dac_enable(struct mxs_codec_priv *mxs_adc) +{ + /* Move DAC codec out of reset */ + __raw_writel(BM_AUDIOOUT_CTRL_SFTRST, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_CTRL_CLR); + + /* Reduce analog power */ + __raw_writel(BM_AUDIOOUT_TEST_HP_I1_ADJ, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_TEST_CLR); + __raw_writel(BF(0x1, AUDIOOUT_TEST_HP_I1_ADJ), + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_TEST_SET); + __raw_writel(BM_AUDIOOUT_REFCTRL_LOW_PWR, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_REFCTRL_SET); + __raw_writel(BM_AUDIOOUT_REFCTRL_XTAL_BGR_BIAS, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_REFCTRL_SET); + __raw_writel(BM_AUDIOOUT_REFCTRL_BIAS_CTRL, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_REFCTRL_CLR); + __raw_writel(BF(0x1, AUDIOOUT_REFCTRL_BIAS_CTRL), + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_REFCTRL_CLR); + + /* Set Vag value */ + mxs_codec_dac_set_vag(); + + /* Power on DAC codec */ + mxs_codec_dac_power_on(mxs_adc); +} + +static void mxs_codec_dac_disable(struct mxs_codec_priv *mxs_adc) +{ + mxs_codec_dac_power_down(mxs_adc); +} + +static void mxs_codec_adc_enable(struct mxs_codec_priv *mxs_adc) +{ + /* Move ADC codec out of reset */ + __raw_writel(BM_AUDIOIN_CTRL_SFTRST, + REGS_AUDIOIN_BASE + HW_AUDIOIN_CTRL_CLR); + + /* Power on ADC codec */ + mxs_codec_adc_power_on(mxs_adc); +} + +static void mxs_codec_adc_disable(struct mxs_codec_priv *mxs_adc) +{ + mxs_codec_adc_power_down(mxs_adc); +} + +static void mxs_codec_startup(struct snd_soc_codec *codec) +{ + struct mxs_codec_priv *mxs_adc = codec->private_data; + + /* Soft reset DAC block */ + __raw_writel(BM_AUDIOOUT_CTRL_SFTRST, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_CTRL_SET); + while (!(__raw_readl(REGS_AUDIOOUT_BASE + HW_AUDIOOUT_CTRL) + & BM_AUDIOOUT_CTRL_CLKGATE)){ + } + + /* Soft reset ADC block */ + __raw_writel(BM_AUDIOIN_CTRL_SFTRST, + REGS_AUDIOIN_BASE + HW_AUDIOIN_CTRL_SET); + while (!(__raw_readl(REGS_AUDIOIN_BASE + HW_AUDIOIN_CTRL) + & BM_AUDIOIN_CTRL_CLKGATE)){ + } + + mxs_codec_dac_enable(mxs_adc); + mxs_codec_adc_enable(mxs_adc); + + /*Sync regs and cache */ + mxs_codec_sync_reg_cache(codec); + + snd_soc_add_controls(codec, mxs_snd_controls, + ARRAY_SIZE(mxs_snd_controls)); + + mxs_codec_add_widgets(codec); +} + +static void mxs_codec_stop(struct snd_soc_codec *codec) +{ + struct mxs_codec_priv *mxs_adc = codec->private_data; + mxs_codec_dac_disable(mxs_adc); + mxs_codec_adc_disable(mxs_adc); +} + +#define MXS_ADC_RATES SNDRV_PCM_RATE_8000_192000 +#define MXS_ADC_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | \ + SNDRV_PCM_FMTBIT_S32_LE) + +static struct snd_soc_dai_ops mxs_dai_ops = { + .hw_params = mxs_codec_hw_params, + .digital_mute = mxs_codec_dig_mute, +}; + +struct snd_soc_dai mxs_codec_dai = { + .name = "mxs adc/dac", + .playback = { + .stream_name = "Playback", + .channels_min = 2, + .channels_max = 2, + .rates = MXS_ADC_RATES, + .formats = MXS_ADC_FORMATS, + }, + .capture = { + .stream_name = "Capture", + .channels_min = 2, + .channels_max = 2, + .rates = MXS_ADC_RATES, + .formats = MXS_ADC_FORMATS, + }, + .ops = &mxs_dai_ops, +}; +EXPORT_SYMBOL_GPL(mxs_codec_dai); + +static struct snd_soc_codec *mxs_codec; + +static int mxs_codec_probe(struct platform_device *pdev) +{ + struct snd_soc_device *socdev = platform_get_drvdata(pdev); + struct snd_soc_codec *codec; + int ret = 0; + + socdev->card->codec = mxs_codec; + codec = mxs_codec; + + /* register pcms */ + ret = snd_soc_new_pcms(socdev, SNDRV_DEFAULT_IDX1, SNDRV_DEFAULT_STR1); + if (ret < 0) { + dev_err(codec->dev, "failed to create pcms\n"); + return ret; + } + + mxs_codec_startup(codec); + + /* Register the socdev */ + ret = snd_soc_init_card(socdev); + if (ret < 0) { + dev_err(codec->dev, "failed to register card\n"); + snd_soc_dapm_free(socdev); + snd_soc_free_pcms(socdev); + return ret; + } + /* Set default bias level*/ + mxs_codec_set_bias_level(codec, SND_SOC_BIAS_STANDBY); + return 0; +} + +static int mxs_codec_remove(struct platform_device *pdev) +{ + struct snd_soc_device *socdev = platform_get_drvdata(pdev); + struct snd_soc_codec *codec = socdev->card->codec; + + mxs_codec_stop(codec); + + snd_soc_dapm_free(socdev); + snd_soc_free_pcms(socdev); + + return 0; +} + +#ifdef CONFIG_PM +static int mxs_codec_suspend(struct platform_device *pdev, + pm_message_t state) +{ + struct snd_soc_device *socdev = platform_get_drvdata(pdev); + struct snd_soc_codec *codec = socdev->card->codec; + struct mxs_codec_priv *mxs_adc; + int ret = -EINVAL; + + if (codec == NULL) + goto out; + + mxs_adc = codec->private_data; + + mxs_codec_dac_disable(mxs_adc); + mxs_codec_adc_disable(mxs_adc); + clk_disable(mxs_adc->clk); + ret = 0; + +out: + return ret; +} + +static int mxs_codec_resume(struct platform_device *pdev) +{ + struct snd_soc_device *socdev = platform_get_drvdata(pdev); + struct snd_soc_codec *codec = socdev->card->codec; + struct mxs_codec_priv *mxs_adc; + int ret = -EINVAL; + + if (codec == NULL) + goto out; + + mxs_adc = codec->private_data; + clk_enable(mxs_adc->clk); + + /* Soft reset DAC block */ + __raw_writel(BM_AUDIOOUT_CTRL_SFTRST, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_CTRL_SET); + while (! + (__raw_readl(REGS_AUDIOOUT_BASE + HW_AUDIOOUT_CTRL) + & BM_AUDIOOUT_CTRL_CLKGATE)){ + } + + /* Soft reset ADC block */ + __raw_writel(BM_AUDIOIN_CTRL_SFTRST, + REGS_AUDIOIN_BASE + HW_AUDIOIN_CTRL_SET); + while (! + (__raw_readl(REGS_AUDIOIN_BASE + HW_AUDIOIN_CTRL) + & BM_AUDIOIN_CTRL_CLKGATE)){ + } + + mxs_codec_dac_enable(mxs_adc); + mxs_codec_adc_enable(mxs_adc); + + /*restore registers relevant to amixer controls */ + mxs_codec_restore_reg(codec, DAC_CTRL_L); + mxs_codec_restore_reg(codec, DAC_VOLUME_L); + mxs_codec_restore_reg(codec, DAC_VOLUME_H); + mxs_codec_restore_reg(codec, DAC_HPVOL_L); + mxs_codec_restore_reg(codec, DAC_HPVOL_H); + mxs_codec_restore_reg(codec, DAC_SPEAKERCTRL_H); + mxs_codec_restore_reg(codec, ADC_VOLUME_L); + mxs_codec_restore_reg(codec, ADC_VOLUME_H); + mxs_codec_restore_reg(codec, ADC_ADCVOL_L); + mxs_codec_restore_reg(codec, ADC_ADCVOL_H); + mxs_codec_restore_reg(codec, ADC_MICLINE_L); + + ret = 0; + +out: + return ret; +} +#else +#define mxs_codec_suspend NULL +#define mxs_codec_resume NULL +#endif /* CONFIG_PM */ + +struct snd_soc_codec_device soc_codec_dev_mxs = { + .probe = mxs_codec_probe, + .remove = mxs_codec_remove, + .suspend = mxs_codec_suspend, + .resume = mxs_codec_resume, +}; +EXPORT_SYMBOL_GPL(soc_codec_dev_mxs); + +/* codec register, unregister function */ +static int __init mxs_codec_audio_probe(struct platform_device *pdev) +{ + struct mxs_codec_priv *mxs_adc; + struct snd_soc_codec *codec; + int ret = 0; + + dev_info(&pdev->dev, + "MXS ADC/DAC Audio Codec \n"); + + mxs_adc = kzalloc(sizeof(struct mxs_codec_priv), GFP_KERNEL); + if (mxs_adc == NULL) + return -ENOMEM; + + codec = &mxs_adc->codec; + codec->dev = &pdev->dev; + codec->name = "mxs adc/dac"; + codec->owner = THIS_MODULE; + codec->private_data = mxs_adc; + codec->read = mxs_codec_read; + codec->write = mxs_codec_write; + codec->bias_level = SND_SOC_BIAS_OFF; + codec->set_bias_level = mxs_codec_set_bias_level; + codec->dai = &mxs_codec_dai; + codec->num_dai = 1; + codec->reg_cache_size = sizeof(mxs_audio_regs) >> 1; + codec->reg_cache_step = 1; + codec->reg_cache = (void *)&mxs_audio_regs; + + platform_set_drvdata(pdev, mxs_adc); + + mxs_codec = codec; + + mutex_init(&codec->mutex); + INIT_LIST_HEAD(&codec->dapm_widgets); + INIT_LIST_HEAD(&codec->dapm_paths); + + /* Turn on audio clock */ + mxs_adc->clk = clk_get(&pdev->dev, "audio"); + if (IS_ERR(mxs_adc->clk)) { + ret = PTR_ERR(mxs_adc->clk); + dev_err(&pdev->dev, "%s: Clocks initialization failed\n", + __func__); + goto clk_err; + } + clk_enable(mxs_adc->clk); + + ret = snd_soc_register_codec(codec); + if (ret) { + dev_err(&pdev->dev, "failed to register card\n"); + goto card_err; + } + + ret = snd_soc_register_dai(&mxs_codec_dai); + if (ret) { + dev_err(&pdev->dev, "failed to register codec dai\n"); + goto dai_err; + } + + return 0; + +dai_err: + snd_soc_unregister_codec(codec); +card_err: + clk_disable(mxs_adc->clk); + clk_put(mxs_adc->clk); +clk_err: + kfree(mxs_adc); + return ret; +} + +static int __devexit mxs_codec_audio_remove(struct platform_device *pdev) +{ + struct mxs_codec_priv *mxs_adc = platform_get_drvdata(pdev); + struct snd_soc_codec *codec = &mxs_adc->codec; + + snd_soc_unregister_codec(codec); + + clk_disable(mxs_adc->clk); + clk_put(mxs_adc->clk); + + kfree(mxs_adc); + + return 0; +} + +struct platform_driver mxs_codec_audio_driver = { + .driver = { + .name = "mxs-adc-audio", + }, + .probe = mxs_codec_audio_probe, + .remove = __devexit_p(mxs_codec_audio_remove), +}; + +static int __init mxs_codec_init(void) +{ + return platform_driver_register(&mxs_codec_audio_driver); +} + +static void __exit mxs_codec_exit(void) +{ + return platform_driver_unregister(&mxs_codec_audio_driver); +} + +module_init(mxs_codec_init); +module_exit(mxs_codec_exit); + +MODULE_DESCRIPTION("MXS ADC/DAC codec"); +MODULE_AUTHOR("Vladislav Buzov"); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/codecs/mxs-adc-codec.h b/sound/soc/codecs/mxs-adc-codec.h new file mode 100644 index 000000000000..129c1c7bdf66 --- /dev/null +++ b/sound/soc/codecs/mxs-adc-codec.h @@ -0,0 +1,87 @@ +/* + * ALSA codec for Freescale MXS ADC/DAC Audio + * + * Author: Vladislav Buzov + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. + * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#ifndef __MXS_ADC_CODEC_H +#define __MXS_ADC_CODEC_H + +#define DAC_CTRL_L 0 +#define DAC_CTRL_H 1 +#define DAC_STAT_L 2 +#define DAC_STAT_H 3 +#define DAC_SRR_L 4 +#define DAC_VOLUME_L 6 +#define DAC_VOLUME_H 7 +#define DAC_DEBUG_L 8 +#define DAC_DEBUG_H 9 +#define DAC_HPVOL_L 10 +#define DAC_HPVOL_H 11 +#define DAC_PWRDN_L 12 +#define DAC_PWRDN_H 13 +#define DAC_REFCTRL_L 14 +#define DAC_REFCTRL_H 15 +#define DAC_ANACTRL_L 16 +#define DAC_ANACTRL_H 17 +#define DAC_TEST_L 18 +#define DAC_TEST_H 19 +#define DAC_BISTCTRL_L 20 +#define DAC_BISTCTRL_H 21 +#define DAC_BISTSTAT0_L 22 +#define DAC_BISTSTAT0_H 23 +#define DAC_BISTSTAT1_L 24 +#define DAC_BISTSTAT1_H 25 +#define DAC_ANACLKCTRL_L 26 +#define DAC_ANACLKCTRL_H 27 +#define DAC_DATA_L 28 +#define DAC_DATA_H 29 +#define DAC_SPEAKERCTRL_L 30 +#define DAC_SPEAKERCTRL_H 31 +#define DAC_VERSION_L 32 +#define DAC_VERSION_H 33 +#define ADC_CTRL_L 34 +#define ADC_CTRL_H 35 +#define ADC_STAT_L 36 +#define ADC_STAT_H 37 +#define ADC_SRR_L 38 +#define ADC_SRR_H 39 +#define ADC_VOLUME_L 40 +#define ADC_VOLUME_H 41 +#define ADC_DEBUG_L 42 +#define ADC_DEBUG_H 43 +#define ADC_ADCVOL_L 44 +#define ADC_ADCVOL_H 45 +#define ADC_MICLINE_L 46 +#define ADC_MICLINE_H 47 +#define ADC_ANACLKCTRL_L 48 +#define ADC_ANACLKCTRL_H 49 +#define ADC_DATA_L 50 +#define ADC_DATA_H 51 + +#define ADC_REGNUM 52 + +#define DAC_VOLUME_MIN 0x37 +#define DAC_VOLUME_MAX 0xFE +#define ADC_VOLUME_MIN 0x37 +#define ADC_VOLUME_MAX 0xFE +#define HP_VOLUME_MAX 0x0 +#define HP_VOLUME_MIN 0x7F +#define LO_VOLUME_MAX 0x0 +#define LO_VOLUME_MIN 0x1F + +extern struct snd_soc_dai mxs_codec_dai; +extern struct snd_soc_codec_device soc_codec_dev_mxs; + +#endif /* __MXS_ADC_CODEC_H */ diff --git a/sound/soc/codecs/mxs_spdif.c b/sound/soc/codecs/mxs_spdif.c new file mode 100644 index 000000000000..3a08912fbc00 --- /dev/null +++ b/sound/soc/codecs/mxs_spdif.c @@ -0,0 +1,455 @@ +/* + * ALSA SoC MXS SPDIF codec driver + * + * Copyright (C) 2008-2010 Freescale Semiconductor, Inc. + * + * Based on stmp3xxx_spdif.h by: + * Vladimir Barinov + * + * Copyright 2008 SigmaTel, Inc + * Copyright 2008 Embedded Alley Solutions, Inc + * + * This file is licensed under the terms of the GNU General Public License + * version 2. This program is licensed "as is" without any warranty of any + * kind, whether express or implied. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "mxs_spdif.h" + +#define REGS_SPDIF_BASE IO_ADDRESS(SPDIF_PHYS_ADDR) + +#define BF(value, field) (((value) << BP_##field) & BM_##field) + +struct mxs_codec_priv { + struct clk *clk; + struct snd_soc_codec codec; +}; + +/* + * ALSA API + */ +static void __iomem *spdif_regmap[] = { + REGS_SPDIF_BASE + HW_SPDIF_CTRL, + REGS_SPDIF_BASE + HW_SPDIF_STAT, + REGS_SPDIF_BASE + HW_SPDIF_FRAMECTRL, + REGS_SPDIF_BASE + HW_SPDIF_SRR, + REGS_SPDIF_BASE + HW_SPDIF_DEBUG, + REGS_SPDIF_BASE + HW_SPDIF_DATA, + REGS_SPDIF_BASE + HW_SPDIF_VERSION, +}; + +/* + * ALSA core supports only 16 bit registers. It means we have to simulate it + * by virtually splitting a 32bit SPDIF registers into two halves + * high (bits 31:16) and low (bits 15:0). The routins abow detects which part + * of 32bit register is accessed. + */ +static int mxs_codec_write(struct snd_soc_codec *codec, + unsigned int reg, unsigned int value) +{ + unsigned int reg_val; + unsigned int mask = 0xffff; + + if (reg >= SPDIF_REGNUM) + return -EIO; + + if (reg & 0x1) { + mask <<= 16; + value <<= 16; + } + + reg_val = __raw_readl(spdif_regmap[reg >> 1]); + reg_val = (reg_val & ~mask) | value; + __raw_writel(reg_val, spdif_regmap[reg >> 1]); + + return 0; +} + +static unsigned int mxs_codec_read(struct snd_soc_codec *codec, + unsigned int reg) +{ + unsigned int reg_val; + + if (reg >= SPDIF_REGNUM) + return -1; + + reg_val = __raw_readl(spdif_regmap[reg >> 1]); + if (reg & 1) + reg_val >>= 16; + + return reg_val & 0xffff; +} + +/* Codec controls */ +static const struct snd_kcontrol_new mxs_snd_controls[] = { + SOC_SINGLE("PRO", SPDIF_FRAMECTRL_L, 0, 0x1, 0), + SOC_SINGLE("AUDIO", SPDIF_FRAMECTRL_L, 1, 0x1, 0), + SOC_SINGLE("COPY", SPDIF_FRAMECTRL_L, 2, 0x1, 0), + SOC_SINGLE("PRE", SPDIF_FRAMECTRL_L, 3, 0x1, 0), + SOC_SINGLE("CC", SPDIF_FRAMECTRL_L, 4, 0x7F, 0), + SOC_SINGLE("L", SPDIF_FRAMECTRL_L, 12, 0x1, 0), + SOC_SINGLE("V", SPDIF_FRAMECTRL_L, 13, 0x1, 0), + SOC_SINGLE("USER DATA", SPDIF_FRAMECTRL_L, 14, 0x1, 0), + SOC_SINGLE("AUTO MUTE", SPDIF_FRAMECTRL_H, 16, 0x1, 0), + SOC_SINGLE("V CONFIG", SPDIF_FRAMECTRL_H, 17, 0x1, 0), +}; + +struct spdif_srr { + u32 rate; + u32 basemult; + u32 rate_factor; +}; + +static struct spdif_srr srr_values[] = { + {96000, 0x2, 0x0BB80}, + {88200, 0x2, 0x0AC44}, + {64000, 0x2, 0x07D00}, + {48000, 0x1, 0x0BB80}, + {44100, 0x1, 0x0AC44}, + {32000, 0x1, 0x07D00}, +}; + +static inline int get_srr_values(int rate) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(srr_values); i++) + if (srr_values[i].rate == rate) + return i; + + return -1; +} + +static int mxs_codec_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params, + struct snd_soc_dai *dai) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_device *socdev = rtd->socdev; + struct snd_soc_codec *codec = socdev->card->codec; + int playback = substream->stream == SNDRV_PCM_STREAM_PLAYBACK ? 1 : 0; + int i; + u32 srr_value = 0; + u32 basemult; + + i = get_srr_values(params_rate(params)); + if (i < 0) + printk(KERN_WARNING "%s doesn't support rate %d\n", + codec->name, params_rate(params)); + else { + basemult = srr_values[i].basemult; + + srr_value = BF(basemult, SPDIF_SRR_BASEMULT) | + BF(srr_values[i].rate_factor, SPDIF_SRR_RATE); + + if (playback) + __raw_writel(srr_value, REGS_SPDIF_BASE + HW_SPDIF_SRR); + } + + switch (params_format(params)) { + case SNDRV_PCM_FORMAT_S16_LE: + if (playback) + __raw_writel(BM_SPDIF_CTRL_WORD_LENGTH, + REGS_SPDIF_BASE + HW_SPDIF_CTRL_SET); + break; + case SNDRV_PCM_FORMAT_S20_3LE: + case SNDRV_PCM_FORMAT_S24_LE: + case SNDRV_PCM_FORMAT_S32_LE: + if (playback) + __raw_writel(BM_SPDIF_CTRL_WORD_LENGTH, + REGS_SPDIF_BASE + HW_SPDIF_CTRL_CLR); + break; + default: + printk(KERN_WARNING "%s doesn't support format %d\n", + codec->name, params_format(params)); + } + + return 0; +} + +static void mxs_codec_spdif_enable(struct mxs_codec_priv *mxs_spdif) +{ + /* Move SPDIF codec out of reset */ + __raw_writel(BM_SPDIF_CTRL_SFTRST, REGS_SPDIF_BASE + HW_SPDIF_CTRL_CLR); + + /* Ungate SPDIF clocks */ + __raw_writel(BM_SPDIF_CTRL_CLKGATE, + REGS_SPDIF_BASE + HW_SPDIF_CTRL_CLR); + + /* 16 bit word length */ + __raw_writel(BM_SPDIF_CTRL_WORD_LENGTH, + REGS_SPDIF_BASE + HW_SPDIF_CTRL_SET); +} + +static void mxs_codec_spdif_disable(struct mxs_codec_priv *mxs_spdif) +{ + /* Gate SPDIF clocks */ + __raw_writel(BM_SPDIF_CTRL_CLKGATE, + REGS_SPDIF_BASE + HW_SPDIF_CTRL_SET); +} + +static void mxs_codec_init(struct snd_soc_codec *codec) +{ + struct mxs_codec_priv *mxs_spdif = codec->private_data; + + /* Soft reset SPDIF block */ + __raw_writel(BM_SPDIF_CTRL_SFTRST, REGS_SPDIF_BASE + HW_SPDIF_CTRL_SET); + + while (!(__raw_readl(REGS_SPDIF_BASE + HW_SPDIF_CTRL) + & BM_SPDIF_CTRL_CLKGATE)) + ; + + mxs_codec_spdif_enable(mxs_spdif); + + snd_soc_add_controls(codec, mxs_snd_controls, + ARRAY_SIZE(mxs_snd_controls)); +} + +static void mxs_codec_exit(struct snd_soc_codec *codec) +{ + struct mxs_codec_priv *mxs_spdif = codec->private_data; + + mxs_codec_spdif_disable(mxs_spdif); +} + +struct snd_soc_dai_ops mxs_spdif_codec_dai_ops = { + .hw_params = mxs_codec_hw_params, +}; + +struct snd_soc_dai mxs_spdif_codec_dai = { + .name = "mxs spdif", + .playback = { + .stream_name = "Playback", + .channels_min = 2, + .channels_max = 2, + .rates = MXS_SPDIF_RATES, + .formats = MXS_SPDIF_FORMATS, + }, + .ops = &mxs_spdif_codec_dai_ops, +}; +EXPORT_SYMBOL_GPL(mxs_spdif_codec_dai); + +static struct snd_soc_codec *mxs_spdif_codec; + +static int mxs_codec_probe(struct platform_device *pdev) +{ + struct snd_soc_device *socdev = platform_get_drvdata(pdev); + struct snd_soc_codec *codec; + int ret = 0; + + socdev->card->codec = mxs_spdif_codec; + codec = mxs_spdif_codec; + + /* register pcms */ + ret = snd_soc_new_pcms(socdev, SNDRV_DEFAULT_IDX1, SNDRV_DEFAULT_STR1); + if (ret < 0) { + dev_err(codec->dev, "failed to create pcms\n"); + return ret; + } + + mxs_codec_init(codec); + + /* Register the socdev */ + ret = snd_soc_init_card(socdev); + if (ret < 0) { + dev_err(codec->dev, "failed to register card\n"); + snd_soc_dapm_free(socdev); + snd_soc_free_pcms(socdev); + return ret; + } + + return 0; +} + +static int mxs_codec_remove(struct platform_device *pdev) +{ + struct snd_soc_device *socdev = platform_get_drvdata(pdev); + struct snd_soc_codec *codec = socdev->card->codec; + + mxs_codec_exit(codec); + + snd_soc_free_pcms(socdev); + snd_soc_dapm_free(socdev); + + return 0; +} + +#ifdef CONFIG_PM +static int mxs_codec_suspend(struct platform_device *pdev, pm_message_t state) +{ + struct snd_soc_device *socdev = platform_get_drvdata(pdev); + struct snd_soc_codec *codec = socdev->card->codec; + struct mxs_codec_priv *mxs_spdif; + int ret = -EINVAL; + + if (codec == NULL) + goto out; + + mxs_spdif = codec->private_data; + + mxs_codec_spdif_disable(mxs_spdif); + clk_disable(mxs_spdif->clk); + ret = 0; + +out: + return ret; +} + +static int mxs_codec_resume(struct platform_device *pdev) +{ + struct snd_soc_device *socdev = platform_get_drvdata(pdev); + struct snd_soc_codec *codec = socdev->card->codec; + struct mxs_codec_priv *mxs_spdif; + int ret = -EINVAL; + + if (codec == NULL) + goto out; + + mxs_spdif = codec->private_data; + clk_enable(mxs_spdif->clk); + + /* Soft reset SPDIF block */ + __raw_writel(BM_SPDIF_CTRL_SFTRST, REGS_SPDIF_BASE + HW_SPDIF_CTRL_SET); + while (!(__raw_readl(REGS_SPDIF_BASE + HW_SPDIF_CTRL) + & BM_SPDIF_CTRL_CLKGATE)) + ; + + mxs_codec_spdif_enable(mxs_spdif); + + ret = 0; + +out: + return ret; +} +#else +#define mxs_codec_suspend NULL +#define mxs_codec_resume NULL +#endif /* CONFIG_PM */ + +struct snd_soc_codec_device soc_spdif_codec_dev_mxs = { + .probe = mxs_codec_probe, + .remove = mxs_codec_remove, + .suspend = mxs_codec_suspend, + .resume = mxs_codec_resume, +}; +EXPORT_SYMBOL_GPL(soc_spdif_codec_dev_mxs); + +static int __init mxs_spdif_probe(struct platform_device *pdev) +{ + struct snd_soc_codec *codec; + struct mxs_codec_priv *mxs_spdif; + int ret = 0; + + dev_info(&pdev->dev, "MXS SPDIF Audio Transmitter\n"); + + mxs_spdif = kzalloc(sizeof(struct mxs_codec_priv), GFP_KERNEL); + if (mxs_spdif == NULL) + return -ENOMEM; + + codec = &mxs_spdif->codec; + codec->name = "mxs spdif"; + codec->owner = THIS_MODULE; + codec->private_data = mxs_spdif; + codec->read = mxs_codec_read; + codec->write = mxs_codec_write; + codec->dai = &mxs_spdif_codec_dai; + codec->num_dai = 1; + + platform_set_drvdata(pdev, mxs_spdif); + mxs_spdif_codec = codec; + + mutex_init(&codec->mutex); + INIT_LIST_HEAD(&codec->dapm_widgets); + INIT_LIST_HEAD(&codec->dapm_paths); + + /* Turn on audio clock */ + mxs_spdif->clk = clk_get(&pdev->dev, "spdif"); + if (IS_ERR(mxs_spdif->clk)) { + ret = PTR_ERR(mxs_spdif->clk); + dev_err(&pdev->dev, "Clocks initialization failed\n"); + goto clk_err; + } + clk_enable(mxs_spdif->clk); + + ret = snd_soc_register_codec(codec); + if (ret) { + dev_err(&pdev->dev, "failed to register card\n"); + goto card_err; + } + + ret = snd_soc_register_dai(&mxs_spdif_codec_dai); + if (ret) { + dev_err(&pdev->dev, "failed to register card\n"); + goto dai_err; + } + + return 0; + +dai_err: + snd_soc_unregister_codec(codec); +card_err: + clk_disable(mxs_spdif->clk); + clk_put(mxs_spdif->clk); +clk_err: + kfree(mxs_spdif); + return ret; +} + +static int __devexit mxs_spdif_remove(struct platform_device *pdev) +{ + struct mxs_codec_priv *mxs_spdif = platform_get_drvdata(pdev); + struct snd_soc_codec *codec = &mxs_spdif->codec; + + snd_soc_unregister_codec(codec); + + clk_disable(mxs_spdif->clk); + clk_put(mxs_spdif->clk); + + kfree(mxs_spdif); + + return 0; +} + +struct platform_driver mxs_spdif_driver = { + .driver = { + .name = "mxs-spdif", + }, + .probe = mxs_spdif_probe, + .remove = __devexit_p(mxs_spdif_remove), +}; + +static int __init mxs_spdif_init(void) +{ + return platform_driver_register(&mxs_spdif_driver); +} + +static void __exit mxs_spdif_exit(void) +{ + return platform_driver_unregister(&mxs_spdif_driver); +} + +module_init(mxs_spdif_init); +module_exit(mxs_spdif_exit); + +MODULE_DESCRIPTION("MXS SPDIF transmitter"); +MODULE_AUTHOR("Vladimir Barinov"); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/codecs/mxs_spdif.h b/sound/soc/codecs/mxs_spdif.h new file mode 100644 index 000000000000..6bce044d683e --- /dev/null +++ b/sound/soc/codecs/mxs_spdif.h @@ -0,0 +1,172 @@ +/* + * ALSA SoC MXS SPDIF codec driver + * + * Copyright (C) 2008-2010 Freescale Semiconductor, Inc. + * + * Based on stmp3xxx_spdif.h by: + * Vladimir Barinov + * + * Copyright 2008 SigmaTel, Inc + * Copyright 2008 Embedded Alley Solutions, Inc + * Copyright 2008-2009 Freescale Semiconductor, Inc. + * + * This file is licensed under the terms of the GNU General Public License + * version 2. This program is licensed "as is" without any warranty of any + * kind, whether express or implied. + */ +#ifndef __MXS_SPDIF_CODEC_H +#define __MXS_SPDIF_CODEC_H + +#define SPDIF_CTRL_L 0 +#define SPDIF_CTRL_H 1 +#define SPDIF_STAT_L 2 +#define SPDIF_STAT_H 3 +#define SPDIF_FRAMECTRL_L 4 +#define SPDIF_FRAMECTRL_H 5 +#define SPDIF_SRR_L 6 +#define SPDIF_SRR_H 7 +#define SPDIF_DEBUG_L 8 +#define SPDIF_DEBUG_H 9 +#define SPDIF_DATA_L 10 +#define SPDIF_DATA_H 11 +#define SPDIF_VERSION_L 12 +#define SPDIF_VERSION_H 13 + +#define SPDIF_REGNUM 14 + +#define HW_SPDIF_CTRL (0x00000000) +#define HW_SPDIF_CTRL_SET (0x00000004) +#define HW_SPDIF_CTRL_CLR (0x00000008) +#define HW_SPDIF_CTRL_TOG (0x0000000c) + +#define BM_SPDIF_CTRL_SFTRST 0x80000000 +#define BM_SPDIF_CTRL_CLKGATE 0x40000000 +#define BP_SPDIF_CTRL_RSRVD1 21 +#define BM_SPDIF_CTRL_RSRVD1 0x3FE00000 +#define BF_SPDIF_CTRL_RSRVD1(v) \ + (((v) << 21) & BM_SPDIF_CTRL_RSRVD1) +#define BP_SPDIF_CTRL_DMAWAIT_COUNT 16 +#define BM_SPDIF_CTRL_DMAWAIT_COUNT 0x001F0000 +#define BF_SPDIF_CTRL_DMAWAIT_COUNT(v) \ + (((v) << 16) & BM_SPDIF_CTRL_DMAWAIT_COUNT) +#define BP_SPDIF_CTRL_RSRVD0 6 +#define BM_SPDIF_CTRL_RSRVD0 0x0000FFC0 +#define BF_SPDIF_CTRL_RSRVD0(v) \ + (((v) << 6) & BM_SPDIF_CTRL_RSRVD0) +#define BM_SPDIF_CTRL_WAIT_END_XFER 0x00000020 +#define BM_SPDIF_CTRL_WORD_LENGTH 0x00000010 +#define BM_SPDIF_CTRL_FIFO_UNDERFLOW_IRQ 0x00000008 +#define BM_SPDIF_CTRL_FIFO_OVERFLOW_IRQ 0x00000004 +#define BM_SPDIF_CTRL_FIFO_ERROR_IRQ_EN 0x00000002 +#define BM_SPDIF_CTRL_RUN 0x00000001 + +#define HW_SPDIF_STAT (0x00000010) +#define HW_SPDIF_STAT_SET (0x00000014) +#define HW_SPDIF_STAT_CLR (0x00000018) +#define HW_SPDIF_STAT_TOG (0x0000001c) + +#define BM_SPDIF_STAT_PRESENT 0x80000000 +#define BP_SPDIF_STAT_RSRVD1 1 +#define BM_SPDIF_STAT_RSRVD1 0x7FFFFFFE +#define BF_SPDIF_STAT_RSRVD1(v) \ + (((v) << 1) & BM_SPDIF_STAT_RSRVD1) +#define BM_SPDIF_STAT_END_XFER 0x00000001 + +#define HW_SPDIF_FRAMECTRL (0x00000020) +#define HW_SPDIF_FRAMECTRL_SET (0x00000024) +#define HW_SPDIF_FRAMECTRL_CLR (0x00000028) +#define HW_SPDIF_FRAMECTRL_TOG (0x0000002c) + +#define BP_SPDIF_FRAMECTRL_RSRVD2 18 +#define BM_SPDIF_FRAMECTRL_RSRVD2 0xFFFC0000 +#define BF_SPDIF_FRAMECTRL_RSRVD2(v) \ + (((v) << 18) & BM_SPDIF_FRAMECTRL_RSRVD2) +#define BM_SPDIF_FRAMECTRL_V_CONFIG 0x00020000 +#define BM_SPDIF_FRAMECTRL_AUTO_MUTE 0x00010000 +#define BM_SPDIF_FRAMECTRL_RSRVD1 0x00008000 +#define BM_SPDIF_FRAMECTRL_USER_DATA 0x00004000 +#define BM_SPDIF_FRAMECTRL_V 0x00002000 +#define BM_SPDIF_FRAMECTRL_L 0x00001000 +#define BM_SPDIF_FRAMECTRL_RSRVD0 0x00000800 +#define BP_SPDIF_FRAMECTRL_CC 4 +#define BM_SPDIF_FRAMECTRL_CC 0x000007F0 +#define BF_SPDIF_FRAMECTRL_CC(v) \ + (((v) << 4) & BM_SPDIF_FRAMECTRL_CC) +#define BM_SPDIF_FRAMECTRL_PRE 0x00000008 +#define BM_SPDIF_FRAMECTRL_COPY 0x00000004 +#define BM_SPDIF_FRAMECTRL_AUDIO 0x00000002 +#define BM_SPDIF_FRAMECTRL_PRO 0x00000001 + +#define HW_SPDIF_SRR (0x00000030) +#define HW_SPDIF_SRR_SET (0x00000034) +#define HW_SPDIF_SRR_CLR (0x00000038) +#define HW_SPDIF_SRR_TOG (0x0000003c) + +#define BM_SPDIF_SRR_RSRVD1 0x80000000 +#define BP_SPDIF_SRR_BASEMULT 28 +#define BM_SPDIF_SRR_BASEMULT 0x70000000 +#define BF_SPDIF_SRR_BASEMULT(v) \ + (((v) << 28) & BM_SPDIF_SRR_BASEMULT) +#define BP_SPDIF_SRR_RSRVD0 20 +#define BM_SPDIF_SRR_RSRVD0 0x0FF00000 +#define BF_SPDIF_SRR_RSRVD0(v) \ + (((v) << 20) & BM_SPDIF_SRR_RSRVD0) +#define BP_SPDIF_SRR_RATE 0 +#define BM_SPDIF_SRR_RATE 0x000FFFFF +#define BF_SPDIF_SRR_RATE(v) \ + (((v) << 0) & BM_SPDIF_SRR_RATE) + +#define HW_SPDIF_DEBUG (0x00000040) +#define HW_SPDIF_DEBUG_SET (0x00000044) +#define HW_SPDIF_DEBUG_CLR (0x00000048) +#define HW_SPDIF_DEBUG_TOG (0x0000004c) + +#define BP_SPDIF_DEBUG_RSRVD1 2 +#define BM_SPDIF_DEBUG_RSRVD1 0xFFFFFFFC +#define BF_SPDIF_DEBUG_RSRVD1(v) \ + (((v) << 2) & BM_SPDIF_DEBUG_RSRVD1) +#define BM_SPDIF_DEBUG_DMA_PREQ 0x00000002 +#define BM_SPDIF_DEBUG_FIFO_STATUS 0x00000001 + +#define HW_SPDIF_DATA (0x00000050) +#define HW_SPDIF_DATA_SET (0x00000054) +#define HW_SPDIF_DATA_CLR (0x00000058) +#define HW_SPDIF_DATA_TOG (0x0000005c) + +#define BP_SPDIF_DATA_HIGH 16 +#define BM_SPDIF_DATA_HIGH 0xFFFF0000 +#define BF_SPDIF_DATA_HIGH(v) \ + (((v) << 16) & BM_SPDIF_DATA_HIGH) +#define BP_SPDIF_DATA_LOW 0 +#define BM_SPDIF_DATA_LOW 0x0000FFFF +#define BF_SPDIF_DATA_LOW(v) \ + (((v) << 0) & BM_SPDIF_DATA_LOW) + +#define HW_SPDIF_VERSION (0x00000060) + +#define BP_SPDIF_VERSION_MAJOR 24 +#define BM_SPDIF_VERSION_MAJOR 0xFF000000 +#define BF_SPDIF_VERSION_MAJOR(v) \ + (((v) << 24) & BM_SPDIF_VERSION_MAJOR) +#define BP_SPDIF_VERSION_MINOR 16 +#define BM_SPDIF_VERSION_MINOR 0x00FF0000 +#define BF_SPDIF_VERSION_MINOR(v) \ + (((v) << 16) & BM_SPDIF_VERSION_MINOR) +#define BP_SPDIF_VERSION_STEP 0 +#define BM_SPDIF_VERSION_STEP 0x0000FFFF +#define BF_SPDIF_VERSION_STEP(v) \ + (((v) << 0) & BM_SPDIF_VERSION_STEP) + +#define MXS_SPDIF_RATES (SNDRV_PCM_RATE_32000 | SNDRV_PCM_RATE_44100 | \ + SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_64000 | \ + SNDRV_PCM_RATE_88200 | SNDRV_PCM_RATE_96000) + +#define MXS_SPDIF_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | \ + SNDRV_PCM_FMTBIT_S20_3LE | \ + SNDRV_PCM_FMTBIT_S24_LE | \ + SNDRV_PCM_FMTBIT_S32_LE) + +extern struct snd_soc_dai mxs_spdif_codec_dai; +extern struct snd_soc_codec_device soc_spdif_codec_dev_mxs; + +#endif /* __MXS_SPDIF_CODEC_H */ diff --git a/sound/soc/codecs/sgtl5000.c b/sound/soc/codecs/sgtl5000.c new file mode 100644 index 000000000000..49a6367b95e0 --- /dev/null +++ b/sound/soc/codecs/sgtl5000.c @@ -0,0 +1,1294 @@ +/* + * sgtl5000.c -- SGTL5000 ALSA SoC Audio driver + * + * Copyright (C) 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "sgtl5000.h" + +struct sgtl5000_priv { + int sysclk; + int master; + int fmt; + int rev; + int lrclk; + int capture_channels; + int playback_active; + int capture_active; + struct regulator *reg_vddio; + struct regulator *reg_vdda; + struct regulator *reg_vddd; + int vddio; /* voltage of VDDIO (mv) */ + int vdda; /* voltage of vdda (mv) */ + int vddd; /* voltage of vddd (mv), 0 if not connected */ + struct snd_pcm_substream *master_substream; + struct snd_pcm_substream *slave_substream; +}; + +static int sgtl5000_set_bias_level(struct snd_soc_codec *codec, + enum snd_soc_bias_level level); + +#define SGTL5000_MAX_CACHED_REG SGTL5000_CHIP_SHORT_CTRL +static u16 sgtl5000_regs[(SGTL5000_MAX_CACHED_REG >> 1) + 1]; + +static unsigned int sgtl5000_read_reg_cache(struct snd_soc_codec *codec, + unsigned int reg) +{ + u16 *cache = codec->reg_cache; + unsigned int offset = reg >> 1; + if (offset >= ARRAY_SIZE(sgtl5000_regs)) + return -EINVAL; + pr_debug("r r:%02x,v:%04x\n", reg, cache[offset]); + return cache[offset]; +} + +static unsigned int sgtl5000_hw_read(struct snd_soc_codec *codec, + unsigned int reg) +{ + struct i2c_client *client = codec->control_data; + int i2c_ret; + u16 value; + u8 buf0[2], buf1[2]; + u16 addr = client->addr; + u16 flags = client->flags; + struct i2c_msg msg[2] = { + {addr, flags, 2, buf0}, + {addr, flags | I2C_M_RD, 2, buf1}, + }; + + buf0[0] = (reg & 0xff00) >> 8; + buf0[1] = reg & 0xff; + i2c_ret = i2c_transfer(client->adapter, msg, 2); + if (i2c_ret < 0) { + pr_err("%s: read reg error : Reg 0x%02x\n", __func__, reg); + return 0; + } + + value = buf1[0] << 8 | buf1[1]; + + pr_debug("r r:%02x,v:%04x\n", reg, value); + return value; +} + +static unsigned int sgtl5000_read(struct snd_soc_codec *codec, unsigned int reg) +{ + if ((reg == SGTL5000_CHIP_ID) || + (reg == SGTL5000_CHIP_ADCDAC_CTRL) || + (reg == SGTL5000_CHIP_ANA_STATUS) || + (reg > SGTL5000_MAX_CACHED_REG)) + return sgtl5000_hw_read(codec, reg); + else + return sgtl5000_read_reg_cache(codec, reg); +} + +static inline void sgtl5000_write_reg_cache(struct snd_soc_codec *codec, + u16 reg, unsigned int value) +{ + u16 *cache = codec->reg_cache; + unsigned int offset = reg >> 1; + if (offset < ARRAY_SIZE(sgtl5000_regs)) + cache[offset] = value; +} + +static int sgtl5000_write(struct snd_soc_codec *codec, unsigned int reg, + unsigned int value) +{ + struct i2c_client *client = codec->control_data; + u16 addr = client->addr; + u16 flags = client->flags; + u8 buf[4]; + int i2c_ret; + struct i2c_msg msg = { addr, flags, 4, buf }; + + sgtl5000_write_reg_cache(codec, reg, value); + pr_debug("w r:%02x,v:%04x\n", reg, value); + buf[0] = (reg & 0xff00) >> 8; + buf[1] = reg & 0xff; + buf[2] = (value & 0xff00) >> 8; + buf[3] = value & 0xff; + + i2c_ret = i2c_transfer(client->adapter, &msg, 1); + if (i2c_ret < 0) { + pr_err("%s: write reg error : Reg 0x%02x = 0x%04x\n", + __func__, reg, value); + return -EIO; + } + + return i2c_ret; +} + +static void sgtl5000_sync_reg_cache(struct snd_soc_codec *codec) +{ + int reg; + for (reg = 0; reg <= SGTL5000_MAX_CACHED_REG; reg += 2) + sgtl5000_write_reg_cache(codec, reg, + sgtl5000_hw_read(codec, reg)); +} + +static int sgtl5000_restore_reg(struct snd_soc_codec *codec, unsigned int reg) +{ + unsigned int cached_val, hw_val; + + cached_val = sgtl5000_read_reg_cache(codec, reg); + hw_val = sgtl5000_hw_read(codec, reg); + + if (hw_val != cached_val) + return sgtl5000_write(codec, reg, cached_val); + + return 0; +} + +static int all_reg[] = { + SGTL5000_CHIP_ID, + SGTL5000_CHIP_DIG_POWER, + SGTL5000_CHIP_CLK_CTRL, + SGTL5000_CHIP_I2S_CTRL, + SGTL5000_CHIP_SSS_CTRL, + SGTL5000_CHIP_ADCDAC_CTRL, + SGTL5000_CHIP_DAC_VOL, + SGTL5000_CHIP_PAD_STRENGTH, + SGTL5000_CHIP_ANA_ADC_CTRL, + SGTL5000_CHIP_ANA_HP_CTRL, + SGTL5000_CHIP_ANA_CTRL, + SGTL5000_CHIP_LINREG_CTRL, + SGTL5000_CHIP_REF_CTRL, + SGTL5000_CHIP_MIC_CTRL, + SGTL5000_CHIP_LINE_OUT_CTRL, + SGTL5000_CHIP_LINE_OUT_VOL, + SGTL5000_CHIP_ANA_POWER, + SGTL5000_CHIP_PLL_CTRL, + SGTL5000_CHIP_CLK_TOP_CTRL, + SGTL5000_CHIP_ANA_STATUS, + SGTL5000_CHIP_SHORT_CTRL, +}; + +#ifdef DEBUG +static void dump_reg(struct snd_soc_codec *codec) +{ + int i, reg; + printk(KERN_DEBUG "dump begin\n"); + for (i = 0; i < 21; i++) { + reg = sgtl5000_read(codec, all_reg[i]); + printk(KERN_DEBUG "d r %04x, v %04x\n", all_reg[i], reg); + } + printk(KERN_DEBUG "dump end\n"); +} +#else +static void dump_reg(struct snd_soc_codec *codec) +{ +} +#endif + +static const char *adc_mux_text[] = { + "MIC_IN", "LINE_IN" +}; + +static const char *dac_mux_text[] = { + "DAC", "LINE_IN" +}; + +static const struct soc_enum adc_enum = +SOC_ENUM_SINGLE(SGTL5000_CHIP_ANA_CTRL, 2, 2, adc_mux_text); + +static const struct soc_enum dac_enum = +SOC_ENUM_SINGLE(SGTL5000_CHIP_ANA_CTRL, 6, 2, dac_mux_text); + +static const struct snd_kcontrol_new adc_mux = +SOC_DAPM_ENUM("ADC Mux", adc_enum); + +static const struct snd_kcontrol_new dac_mux = +SOC_DAPM_ENUM("DAC Mux", dac_enum); + +static const struct snd_soc_dapm_widget sgtl5000_dapm_widgets[] = { + SND_SOC_DAPM_INPUT("LINE_IN"), + SND_SOC_DAPM_INPUT("MIC_IN"), + + SND_SOC_DAPM_OUTPUT("HP_OUT"), + SND_SOC_DAPM_OUTPUT("LINE_OUT"), + + SND_SOC_DAPM_PGA("HP", SGTL5000_CHIP_ANA_CTRL, 4, 1, NULL, 0), + SND_SOC_DAPM_PGA("LO", SGTL5000_CHIP_ANA_CTRL, 8, 1, NULL, 0), + + SND_SOC_DAPM_MUX("ADC Mux", SND_SOC_NOPM, 0, 0, &adc_mux), + SND_SOC_DAPM_MUX("DAC Mux", SND_SOC_NOPM, 0, 0, &dac_mux), + + SND_SOC_DAPM_ADC("ADC", "Capture", SGTL5000_CHIP_DIG_POWER, 6, 0), + SND_SOC_DAPM_DAC("DAC", "Playback", SND_SOC_NOPM, 0, 0), +}; + +static const struct snd_soc_dapm_route audio_map[] = { + {"ADC Mux", "LINE_IN", "LINE_IN"}, + {"ADC Mux", "MIC_IN", "MIC_IN"}, + {"ADC", NULL, "ADC Mux"}, + {"DAC Mux", "DAC", "DAC"}, + {"DAC Mux", "LINE_IN", "LINE_IN"}, + {"LO", NULL, "DAC"}, + {"HP", NULL, "DAC Mux"}, + {"LINE_OUT", NULL, "LO"}, + {"HP_OUT", NULL, "HP"}, +}; + +static int sgtl5000_add_widgets(struct snd_soc_codec *codec) +{ + snd_soc_dapm_new_controls(codec, sgtl5000_dapm_widgets, + ARRAY_SIZE(sgtl5000_dapm_widgets)); + + snd_soc_dapm_add_routes(codec, audio_map, ARRAY_SIZE(audio_map)); + + snd_soc_dapm_new_widgets(codec); + return 0; +} + +static int dac_info_volsw(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_info *uinfo) +{ + uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; + uinfo->count = 2; + uinfo->value.integer.min = 0; + uinfo->value.integer.max = 0xfc - 0x3c; + return 0; +} + +static int dac_get_volsw(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); + int reg, l, r; + + reg = sgtl5000_read(codec, SGTL5000_CHIP_DAC_VOL); + l = (reg & SGTL5000_DAC_VOL_LEFT_MASK) >> SGTL5000_DAC_VOL_LEFT_SHIFT; + r = (reg & SGTL5000_DAC_VOL_RIGHT_MASK) >> SGTL5000_DAC_VOL_RIGHT_SHIFT; + l = l < 0x3c ? 0x3c : l; + l = l > 0xfc ? 0xfc : l; + r = r < 0x3c ? 0x3c : r; + r = r > 0xfc ? 0xfc : r; + l = 0xfc - l; + r = 0xfc - r; + + ucontrol->value.integer.value[0] = l; + ucontrol->value.integer.value[1] = r; + + return 0; +} + +static int dac_put_volsw(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); + int reg, l, r; + + l = ucontrol->value.integer.value[0]; + r = ucontrol->value.integer.value[1]; + + l = l < 0 ? 0 : l; + l = l > 0xfc - 0x3c ? 0xfc - 0x3c : l; + r = r < 0 ? 0 : r; + r = r > 0xfc - 0x3c ? 0xfc - 0x3c : r; + l = 0xfc - l; + r = 0xfc - r; + + reg = l << SGTL5000_DAC_VOL_LEFT_SHIFT | + r << SGTL5000_DAC_VOL_RIGHT_SHIFT; + + sgtl5000_write(codec, SGTL5000_CHIP_DAC_VOL, reg); + + return 0; +} + +static const char *mic_gain_text[] = { + "0dB", "20dB", "30dB", "40dB" +}; + +static const char *adc_m6db_text[] = { + "No Change", "Reduced by 6dB" +}; + +static const struct soc_enum mic_gain = +SOC_ENUM_SINGLE(SGTL5000_CHIP_MIC_CTRL, 0, 4, mic_gain_text); + +static const struct soc_enum adc_m6db = +SOC_ENUM_SINGLE(SGTL5000_CHIP_ANA_ADC_CTRL, 8, 2, adc_m6db_text); + +static const struct snd_kcontrol_new sgtl5000_snd_controls[] = { + SOC_ENUM("MIC GAIN", mic_gain), + SOC_DOUBLE("Capture Volume", SGTL5000_CHIP_ANA_ADC_CTRL, 0, 4, 0xf, 0), + SOC_ENUM("Capture Vol Reduction", adc_m6db), + {.iface = SNDRV_CTL_ELEM_IFACE_MIXER, + .name = "Playback Volume", + .access = SNDRV_CTL_ELEM_ACCESS_READWRITE | + SNDRV_CTL_ELEM_ACCESS_VOLATILE, + .info = dac_info_volsw, + .get = dac_get_volsw, + .put = dac_put_volsw, + }, + SOC_DOUBLE("Headphone Volume", SGTL5000_CHIP_ANA_HP_CTRL, 0, 8, 0x7f, + 1), +}; + +static int sgtl5000_digital_mute(struct snd_soc_dai *codec_dai, int mute) +{ + struct snd_soc_codec *codec = codec_dai->codec; + u16 adcdac_ctrl; + + adcdac_ctrl = sgtl5000_read(codec, SGTL5000_CHIP_ADCDAC_CTRL); + + if (mute) { + adcdac_ctrl |= SGTL5000_DAC_MUTE_LEFT; + adcdac_ctrl |= SGTL5000_DAC_MUTE_RIGHT; + } else { + adcdac_ctrl &= ~SGTL5000_DAC_MUTE_LEFT; + adcdac_ctrl &= ~SGTL5000_DAC_MUTE_RIGHT; + } + + sgtl5000_write(codec, SGTL5000_CHIP_ADCDAC_CTRL, adcdac_ctrl); + if (!mute) + dump_reg(codec); + return 0; +} + +static int sgtl5000_set_dai_fmt(struct snd_soc_dai *codec_dai, unsigned int fmt) +{ + struct snd_soc_codec *codec = codec_dai->codec; + struct sgtl5000_priv *sgtl5000 = snd_soc_codec_get_drvdata(codec); + u16 i2sctl = 0; + pr_debug("%s:fmt=%08x\n", __func__, fmt); + sgtl5000->master = 0; + switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) { + case SND_SOC_DAIFMT_CBS_CFS: + break; + case SND_SOC_DAIFMT_CBM_CFM: + i2sctl |= SGTL5000_I2S_MASTER; + sgtl5000->master = 1; + break; + case SND_SOC_DAIFMT_CBM_CFS: + case SND_SOC_DAIFMT_CBS_CFM: + return -EINVAL; + break; + default: + return -EINVAL; + } + + switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { + case SND_SOC_DAIFMT_DSP_A: + i2sctl |= SGTL5000_I2S_MODE_PCM; + break; + case SND_SOC_DAIFMT_DSP_B: + i2sctl |= SGTL5000_I2S_MODE_PCM; + i2sctl |= SGTL5000_I2S_LRALIGN; + break; + case SND_SOC_DAIFMT_I2S: + i2sctl |= SGTL5000_I2S_MODE_I2S_LJ; + break; + case SND_SOC_DAIFMT_RIGHT_J: + i2sctl |= SGTL5000_I2S_MODE_RJ; + i2sctl |= SGTL5000_I2S_LRPOL; + break; + case SND_SOC_DAIFMT_LEFT_J: + i2sctl |= SGTL5000_I2S_MODE_I2S_LJ; + i2sctl |= SGTL5000_I2S_LRALIGN; + break; + default: + return -EINVAL; + } + sgtl5000->fmt = fmt & SND_SOC_DAIFMT_FORMAT_MASK; + + /* Clock inversion */ + switch (fmt & SND_SOC_DAIFMT_INV_MASK) { + case SND_SOC_DAIFMT_NB_NF: + case SND_SOC_DAIFMT_NB_IF: + break; + case SND_SOC_DAIFMT_IB_IF: + case SND_SOC_DAIFMT_IB_NF: + i2sctl |= SGTL5000_I2S_SCLK_INV; + break; + default: + return -EINVAL; + } + sgtl5000_write(codec, SGTL5000_CHIP_I2S_CTRL, i2sctl); + + return 0; +} + +static int sgtl5000_set_dai_sysclk(struct snd_soc_dai *codec_dai, + int clk_id, unsigned int freq, int dir) +{ + struct snd_soc_codec *codec = codec_dai->codec; + struct sgtl5000_priv *sgtl5000 = snd_soc_codec_get_drvdata(codec); + + switch (clk_id) { + case SGTL5000_SYSCLK: + sgtl5000->sysclk = freq; + break; + case SGTL5000_LRCLK: + sgtl5000->lrclk = freq; + break; + default: + return -EINVAL; + } + return 0; +} + +static int sgtl5000_pcm_prepare(struct snd_pcm_substream *substream, + struct snd_soc_dai *dai) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_device *socdev = rtd->socdev; + struct snd_soc_codec *codec = socdev->card->codec; + struct sgtl5000_priv *sgtl5000 = snd_soc_codec_get_drvdata(codec); + int reg; + + reg = sgtl5000_read(codec, SGTL5000_CHIP_DIG_POWER); + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) + reg |= SGTL5000_I2S_IN_POWERUP; + else + reg |= SGTL5000_I2S_OUT_POWERUP; + sgtl5000_write(codec, SGTL5000_CHIP_DIG_POWER, reg); + + if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) { + reg = sgtl5000_read(codec, SGTL5000_CHIP_ANA_POWER); + reg |= SGTL5000_ADC_POWERUP; + if (sgtl5000->capture_channels == 1) + reg &= ~SGTL5000_ADC_STEREO; + else + reg |= SGTL5000_ADC_STEREO; + sgtl5000_write(codec, SGTL5000_CHIP_ANA_POWER, reg); + } + + return 0; +} + +static int sgtl5000_pcm_startup(struct snd_pcm_substream *substream, + struct snd_soc_dai *dai) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_device *socdev = rtd->socdev; + struct snd_soc_codec *codec = socdev->card->codec; + struct sgtl5000_priv *sgtl5000 = snd_soc_codec_get_drvdata(codec); + struct snd_pcm_runtime *master_runtime; + + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) + sgtl5000->playback_active++; + else + sgtl5000->capture_active++; + + /* The DAI has shared clocks so if we already have a playback or + * capture going then constrain this substream to match it. + */ + if (sgtl5000->master_substream) { + master_runtime = sgtl5000->master_substream->runtime; + + pr_debug("Constraining to %d bits\n", + master_runtime->sample_bits); + + snd_pcm_hw_constraint_minmax(substream->runtime, + SNDRV_PCM_HW_PARAM_SAMPLE_BITS, + master_runtime->sample_bits, + master_runtime->sample_bits); + + sgtl5000->slave_substream = substream; + } else + sgtl5000->master_substream = substream; + + return 0; +} + +static void sgtl5000_pcm_shutdown(struct snd_pcm_substream *substream, + struct snd_soc_dai *dai) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_device *socdev = rtd->socdev; + struct snd_soc_codec *codec = socdev->card->codec; + struct sgtl5000_priv *sgtl5000 = snd_soc_codec_get_drvdata(codec); + int reg, dig_pwr, ana_pwr; + + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) + sgtl5000->playback_active--; + else + sgtl5000->capture_active--; + + if (sgtl5000->master_substream == substream) + sgtl5000->master_substream = sgtl5000->slave_substream; + + sgtl5000->slave_substream = NULL; + + if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) { + ana_pwr = sgtl5000_read(codec, SGTL5000_CHIP_ANA_POWER); + ana_pwr &= ~(SGTL5000_ADC_POWERUP | SGTL5000_ADC_STEREO); + sgtl5000_write(codec, SGTL5000_CHIP_ANA_POWER, ana_pwr); + } + + dig_pwr = sgtl5000_read(codec, SGTL5000_CHIP_DIG_POWER); + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) + dig_pwr &= ~SGTL5000_I2S_IN_POWERUP; + else + dig_pwr &= ~SGTL5000_I2S_OUT_POWERUP; + sgtl5000_write(codec, SGTL5000_CHIP_DIG_POWER, dig_pwr); + + if (!sgtl5000->playback_active && !sgtl5000->capture_active) { + reg = sgtl5000_read(codec, SGTL5000_CHIP_I2S_CTRL); + reg &= ~SGTL5000_I2S_MASTER; + sgtl5000_write(codec, SGTL5000_CHIP_I2S_CTRL, reg); + } +} + +/* + * Set PCM DAI bit size and sample rate. + * input: params_rate, params_fmt + */ +static int sgtl5000_pcm_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params, + struct snd_soc_dai *dai) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_device *socdev = rtd->socdev; + struct snd_soc_codec *codec = socdev->card->codec; + struct sgtl5000_priv *sgtl5000 = snd_soc_codec_get_drvdata(codec); + int channels = params_channels(params); + int clk_ctl = 0; + int pll_ctl = 0; + int i2s_ctl; + int div2 = 0; + int reg; + int sys_fs; + + pr_debug("%s channels=%d\n", __func__, channels); + + if (!sgtl5000->sysclk) { + pr_err("%s: set sysclk first!\n", __func__); + return -EFAULT; + } + + if (substream == sgtl5000->slave_substream) { + pr_debug("Ignoring hw_params for slave substream\n"); + return 0; + } + + if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) + sgtl5000->capture_channels = channels; + + switch (sgtl5000->lrclk) { + case 8000: + case 16000: + sys_fs = 32000; + break; + case 11025: + case 22050: + sys_fs = 44100; + break; + default: + sys_fs = sgtl5000->lrclk; + break; + } + + switch (sys_fs / sgtl5000->lrclk) { + case 4: + clk_ctl |= SGTL5000_RATE_MODE_DIV_4 << SGTL5000_RATE_MODE_SHIFT; + break; + case 2: + clk_ctl |= SGTL5000_RATE_MODE_DIV_2 << SGTL5000_RATE_MODE_SHIFT; + break; + default: + break; + } + + switch (sys_fs) { + case 32000: + clk_ctl |= SGTL5000_SYS_FS_32k << SGTL5000_SYS_FS_SHIFT; + break; + case 44100: + clk_ctl |= SGTL5000_SYS_FS_44_1k << SGTL5000_SYS_FS_SHIFT; + break; + case 48000: + clk_ctl |= SGTL5000_SYS_FS_48k << SGTL5000_SYS_FS_SHIFT; + break; + case 96000: + clk_ctl |= SGTL5000_SYS_FS_96k << SGTL5000_SYS_FS_SHIFT; + break; + default: + pr_err("%s: sample rate %d not supported\n", __func__, + sgtl5000->lrclk); + return -EFAULT; + } + /* SGTL5000 rev1 has a IC bug to prevent switching to MCLK from PLL. */ + if (!sgtl5000->master) { + if (sys_fs * 256 == sgtl5000->sysclk) + clk_ctl |= SGTL5000_MCLK_FREQ_256FS << \ + SGTL5000_MCLK_FREQ_SHIFT; + else if (sys_fs * 384 == sgtl5000->sysclk && sys_fs != 96000) + clk_ctl |= SGTL5000_MCLK_FREQ_384FS << \ + SGTL5000_MCLK_FREQ_SHIFT; + else if (sys_fs * 512 == sgtl5000->sysclk && sys_fs != 96000) + clk_ctl |= SGTL5000_MCLK_FREQ_512FS << \ + SGTL5000_MCLK_FREQ_SHIFT; + else { + pr_err("%s: PLL not supported in slave mode\n", + __func__); + return -EINVAL; + } + } else + clk_ctl |= SGTL5000_MCLK_FREQ_PLL << SGTL5000_MCLK_FREQ_SHIFT; + + if ((clk_ctl & SGTL5000_MCLK_FREQ_MASK) == SGTL5000_MCLK_FREQ_PLL) { + u64 out, t; + unsigned int in, int_div, frac_div; + if (sgtl5000->sysclk > 17000000) { + div2 = 1; + in = sgtl5000->sysclk / 2; + } else { + div2 = 0; + in = sgtl5000->sysclk; + } + if (sys_fs == 44100) + out = 180633600; + else + out = 196608000; + t = do_div(out, in); + int_div = out; + t *= 2048; + do_div(t, in); + frac_div = t; + pll_ctl = int_div << SGTL5000_PLL_INT_DIV_SHIFT | + frac_div << SGTL5000_PLL_FRAC_DIV_SHIFT; + } + + i2s_ctl = sgtl5000_read(codec, SGTL5000_CHIP_I2S_CTRL); + switch (params_format(params)) { + case SNDRV_PCM_FORMAT_S16_LE: + if (sgtl5000->fmt == SND_SOC_DAIFMT_RIGHT_J) + return -EINVAL; + i2s_ctl |= SGTL5000_I2S_DLEN_16 << SGTL5000_I2S_DLEN_SHIFT; + i2s_ctl |= SGTL5000_I2S_SCLKFREQ_32FS << + SGTL5000_I2S_SCLKFREQ_SHIFT; + break; + case SNDRV_PCM_FORMAT_S20_3LE: + i2s_ctl |= SGTL5000_I2S_DLEN_20 << SGTL5000_I2S_DLEN_SHIFT; + i2s_ctl |= SGTL5000_I2S_SCLKFREQ_64FS << + SGTL5000_I2S_SCLKFREQ_SHIFT; + break; + case SNDRV_PCM_FORMAT_S24_LE: + i2s_ctl |= SGTL5000_I2S_DLEN_24 << SGTL5000_I2S_DLEN_SHIFT; + i2s_ctl |= SGTL5000_I2S_SCLKFREQ_64FS << + SGTL5000_I2S_SCLKFREQ_SHIFT; + break; + case SNDRV_PCM_FORMAT_S32_LE: + if (sgtl5000->fmt == SND_SOC_DAIFMT_RIGHT_J) + return -EINVAL; + i2s_ctl |= SGTL5000_I2S_DLEN_32 << SGTL5000_I2S_DLEN_SHIFT; + i2s_ctl |= SGTL5000_I2S_SCLKFREQ_64FS << + SGTL5000_I2S_SCLKFREQ_SHIFT; + break; + default: + return -EINVAL; + } + + pr_debug("\nfs=%d,clk_ctl=%04x,pll_ctl=%04x,i2s_ctl=%04x,div2=%d\n", + sgtl5000->lrclk, clk_ctl, pll_ctl, i2s_ctl, div2); + + if ((clk_ctl & SGTL5000_MCLK_FREQ_MASK) == SGTL5000_MCLK_FREQ_PLL) { + sgtl5000_write(codec, SGTL5000_CHIP_PLL_CTRL, pll_ctl); + reg = sgtl5000_read(codec, SGTL5000_CHIP_CLK_TOP_CTRL); + if (div2) + reg |= SGTL5000_INPUT_FREQ_DIV2; + else + reg &= ~SGTL5000_INPUT_FREQ_DIV2; + sgtl5000_write(codec, SGTL5000_CHIP_CLK_TOP_CTRL, reg); + reg = sgtl5000_read(codec, SGTL5000_CHIP_ANA_POWER); + reg |= SGTL5000_PLL_POWERUP | SGTL5000_VCOAMP_POWERUP; + sgtl5000_write(codec, SGTL5000_CHIP_ANA_POWER, reg); + } + sgtl5000_write(codec, SGTL5000_CHIP_CLK_CTRL, clk_ctl); + sgtl5000_write(codec, SGTL5000_CHIP_I2S_CTRL, i2s_ctl); + + return 0; +} + +static void sgtl5000_mic_bias(struct snd_soc_codec *codec, int enable) +{ + int reg, bias_r = 0; + if (enable) + bias_r = SGTL5000_BIAS_R_4k << SGTL5000_BIAS_R_SHIFT; + reg = sgtl5000_read(codec, SGTL5000_CHIP_MIC_CTRL); + if ((reg & SGTL5000_BIAS_R_MASK) != bias_r) { + reg &= ~SGTL5000_BIAS_R_MASK; + reg |= bias_r; + sgtl5000_write(codec, SGTL5000_CHIP_MIC_CTRL, reg); + } +} + +static int sgtl5000_set_bias_level(struct snd_soc_codec *codec, + enum snd_soc_bias_level level) +{ + u16 reg, ana_pwr; + int delay = 0; + pr_debug("dapm level %d\n", level); + switch (level) { + case SND_SOC_BIAS_ON: /* full On */ + if (codec->bias_level == SND_SOC_BIAS_ON) + break; + + sgtl5000_mic_bias(codec, 1); + + reg = sgtl5000_read(codec, SGTL5000_CHIP_ANA_POWER); + reg |= SGTL5000_VAG_POWERUP; + sgtl5000_write(codec, SGTL5000_CHIP_ANA_POWER, reg); + msleep(400); + + break; + + case SND_SOC_BIAS_PREPARE: /* partial On */ + if (codec->bias_level == SND_SOC_BIAS_PREPARE) + break; + + sgtl5000_mic_bias(codec, 0); + + /* must power up hp/line out before vag & dac to + avoid pops. */ + reg = sgtl5000_read(codec, SGTL5000_CHIP_ANA_POWER); + if (reg & SGTL5000_VAG_POWERUP) + delay = 600; + reg &= ~SGTL5000_VAG_POWERUP; + reg |= SGTL5000_DAC_POWERUP; + reg |= SGTL5000_HP_POWERUP; + reg |= SGTL5000_LINE_OUT_POWERUP; + sgtl5000_write(codec, SGTL5000_CHIP_ANA_POWER, reg); + if (delay) + msleep(delay); + + reg = sgtl5000_read(codec, SGTL5000_CHIP_DIG_POWER); + reg |= SGTL5000_DAC_EN; + sgtl5000_write(codec, SGTL5000_CHIP_DIG_POWER, reg); + + break; + + case SND_SOC_BIAS_STANDBY: /* Off, with power */ + /* soc doesn't do PREPARE state after record so make sure + that anything that needs to be turned OFF gets turned off. */ + if (codec->bias_level == SND_SOC_BIAS_STANDBY) + break; + + /* soc calls digital_mute to unmute before record but doesn't + call digital_mute to mute after record. */ + sgtl5000_digital_mute(&sgtl5000_dai, 1); + + sgtl5000_mic_bias(codec, 0); + + reg = sgtl5000_read(codec, SGTL5000_CHIP_ANA_POWER); + if (reg & SGTL5000_VAG_POWERUP) { + reg &= ~SGTL5000_VAG_POWERUP; + sgtl5000_write(codec, SGTL5000_CHIP_ANA_POWER, reg); + msleep(400); + } + reg &= ~SGTL5000_DAC_POWERUP; + reg &= ~SGTL5000_HP_POWERUP; + reg &= ~SGTL5000_LINE_OUT_POWERUP; + sgtl5000_write(codec, SGTL5000_CHIP_ANA_POWER, reg); + + reg = sgtl5000_read(codec, SGTL5000_CHIP_DIG_POWER); + reg &= ~SGTL5000_DAC_EN; + sgtl5000_write(codec, SGTL5000_CHIP_DIG_POWER, reg); + + break; + + case SND_SOC_BIAS_OFF: /* Off, without power */ + /* must power down hp/line out after vag & dac to + avoid pops. */ + reg = sgtl5000_read(codec, SGTL5000_CHIP_ANA_POWER); + ana_pwr = reg; + reg &= ~SGTL5000_VAG_POWERUP; + + /* Workaround for sgtl5000 rev 0x11 chip audio suspend failure + issue on mx25 */ + /* reg &= ~SGTL5000_REFTOP_POWERUP; */ + + sgtl5000_write(codec, SGTL5000_CHIP_ANA_POWER, reg); + msleep(600); + + reg &= ~SGTL5000_HP_POWERUP; + reg &= ~SGTL5000_LINE_OUT_POWERUP; + reg &= ~SGTL5000_DAC_POWERUP; + reg &= ~SGTL5000_ADC_POWERUP; + sgtl5000_write(codec, SGTL5000_CHIP_ANA_POWER, reg); + + /* save ANA POWER register value for resume */ + sgtl5000_write_reg_cache(codec, SGTL5000_CHIP_ANA_POWER, + ana_pwr); + break; + } + codec->bias_level = level; + return 0; +} + +#define SGTL5000_RATES (SNDRV_PCM_RATE_8000 |\ + SNDRV_PCM_RATE_11025 |\ + SNDRV_PCM_RATE_16000 |\ + SNDRV_PCM_RATE_22050 |\ + SNDRV_PCM_RATE_32000 |\ + SNDRV_PCM_RATE_44100 |\ + SNDRV_PCM_RATE_48000 |\ + SNDRV_PCM_RATE_96000) + +#define SGTL5000_FORMATS (SNDRV_PCM_FMTBIT_S16_LE |\ + SNDRV_PCM_FMTBIT_S20_3LE |\ + SNDRV_PCM_FMTBIT_S24_LE) + +struct snd_soc_dai_ops sgtl5000_ops = { + .prepare = sgtl5000_pcm_prepare, + .startup = sgtl5000_pcm_startup, + .shutdown = sgtl5000_pcm_shutdown, + .hw_params = sgtl5000_pcm_hw_params, + .digital_mute = sgtl5000_digital_mute, + .set_fmt = sgtl5000_set_dai_fmt, + .set_sysclk = sgtl5000_set_dai_sysclk +}; + +struct snd_soc_dai sgtl5000_dai = { + .name = "SGTL5000", + .playback = { + .stream_name = "Playback", + .channels_min = 2, + .channels_max = 2, + .rates = SGTL5000_RATES, + .formats = SGTL5000_FORMATS, + }, + .capture = { + .stream_name = "Capture", + .channels_min = 2, + .channels_max = 2, + .rates = SGTL5000_RATES, + .formats = SGTL5000_FORMATS, + }, + .ops = &sgtl5000_ops, + .symmetric_rates = 1, +}; +EXPORT_SYMBOL_GPL(sgtl5000_dai); + +static int sgtl5000_suspend(struct platform_device *pdev, pm_message_t state) +{ + struct snd_soc_device *socdev = platform_get_drvdata(pdev); + struct snd_soc_codec *codec = socdev->card->codec; + + sgtl5000_set_bias_level(codec, SND_SOC_BIAS_OFF); + + return 0; +} + +static int sgtl5000_resume(struct platform_device *pdev) +{ + struct snd_soc_device *socdev = platform_get_drvdata(pdev); + struct snd_soc_codec *codec = socdev->card->codec; + unsigned int i; + + /* Restore refs first in same order as in sgtl5000_init */ + sgtl5000_restore_reg(codec, SGTL5000_CHIP_LINREG_CTRL); + sgtl5000_restore_reg(codec, SGTL5000_CHIP_ANA_POWER); + msleep(10); + sgtl5000_restore_reg(codec, SGTL5000_CHIP_REF_CTRL); + sgtl5000_restore_reg(codec, SGTL5000_CHIP_LINE_OUT_CTRL); + + /* Restore everythine else */ + for (i = 1; i < sizeof(all_reg) / sizeof(int); i++) + sgtl5000_restore_reg(codec, all_reg[i]); + + sgtl5000_write(codec, SGTL5000_DAP_CTRL, 0); + + /* Bring the codec back up to standby first to minimise pop/clicks */ + sgtl5000_set_bias_level(codec, SND_SOC_BIAS_STANDBY); + if (codec->suspend_bias_level == SND_SOC_BIAS_ON) + sgtl5000_set_bias_level(codec, SND_SOC_BIAS_PREPARE); + sgtl5000_set_bias_level(codec, codec->suspend_bias_level); + + return 0; +} + +static struct snd_soc_codec *sgtl5000_codec; + +/* + * initialise the SGTL5000 driver + * register the mixer and dsp interfaces with the kernel + */ +static int sgtl5000_probe(struct platform_device *pdev) +{ + struct snd_soc_device *socdev = platform_get_drvdata(pdev); + struct snd_soc_codec *codec = sgtl5000_codec; + struct sgtl5000_priv *sgtl5000 = snd_soc_codec_get_drvdata(codec); + u16 reg, ana_pwr, lreg_ctrl, ref_ctrl, lo_ctrl, short_ctrl, sss; + int vag; + int ret = 0; + + socdev->card->codec = sgtl5000_codec; + + /* register pcms */ + ret = snd_soc_new_pcms(socdev, SNDRV_DEFAULT_IDX1, SNDRV_DEFAULT_STR1); + if (ret < 0) { + dev_err(codec->dev, "failed to create pcms\n"); + return ret; + } + + /* reset value */ + ana_pwr = SGTL5000_DAC_STEREO | + SGTL5000_LINREG_SIMPLE_POWERUP | + SGTL5000_STARTUP_POWERUP | + SGTL5000_ADC_STEREO | SGTL5000_REFTOP_POWERUP; + lreg_ctrl = 0; + ref_ctrl = 0; + lo_ctrl = 0; + short_ctrl = 0; + sss = SGTL5000_DAC_SEL_I2S_IN << SGTL5000_DAC_SEL_SHIFT; + + /* workaround for rev 0x11: use vddd linear regulator */ + if (!sgtl5000->vddd || (sgtl5000->rev >= 0x11)) { + /* set VDDD to 1.2v */ + lreg_ctrl |= 0x8 << SGTL5000_LINREG_VDDD_SHIFT; + /* power internal linear regulator */ + ana_pwr |= SGTL5000_LINEREG_D_POWERUP; + } else { + /* turn of startup power */ + ana_pwr &= ~SGTL5000_STARTUP_POWERUP; + ana_pwr &= ~SGTL5000_LINREG_SIMPLE_POWERUP; + } + if (sgtl5000->vddio < 3100 && sgtl5000->vdda < 3100) { + /* Enable VDDC charge pump */ + ana_pwr |= SGTL5000_VDDC_CHRGPMP_POWERUP; + } + if (sgtl5000->vddio >= 3100 && sgtl5000->vdda >= 3100) { + /* VDDC use VDDIO rail */ + lreg_ctrl |= SGTL5000_VDDC_ASSN_OVRD; + if (sgtl5000->vddio >= 3100) + lreg_ctrl |= SGTL5000_VDDC_MAN_ASSN_VDDIO << + SGTL5000_VDDC_MAN_ASSN_SHIFT; + } + /* If PLL is powered up (such as on power cycle) leave it on. */ + reg = sgtl5000_read(codec, SGTL5000_CHIP_ANA_POWER); + ana_pwr |= reg & (SGTL5000_PLL_POWERUP | SGTL5000_VCOAMP_POWERUP); + + /* set ADC/DAC ref voltage to vdda/2 */ + vag = sgtl5000->vdda / 2; + if (vag <= SGTL5000_ANA_GND_BASE) + vag = 0; + else if (vag >= SGTL5000_ANA_GND_BASE + SGTL5000_ANA_GND_STP * + (SGTL5000_ANA_GND_MASK >> SGTL5000_ANA_GND_SHIFT)) + vag = SGTL5000_ANA_GND_MASK >> SGTL5000_ANA_GND_SHIFT; + else + vag = (vag - SGTL5000_ANA_GND_BASE) / SGTL5000_ANA_GND_STP; + ref_ctrl |= vag << SGTL5000_ANA_GND_SHIFT; + + /* set line out ref voltage to vddio/2 */ + vag = sgtl5000->vddio / 2; + if (vag <= SGTL5000_LINE_OUT_GND_BASE) + vag = 0; + else if (vag >= SGTL5000_LINE_OUT_GND_BASE + SGTL5000_LINE_OUT_GND_STP * + SGTL5000_LINE_OUT_GND_MAX) + vag = SGTL5000_LINE_OUT_GND_MAX; + else + vag = (vag - SGTL5000_LINE_OUT_GND_BASE) / + SGTL5000_LINE_OUT_GND_STP; + lo_ctrl |= vag << SGTL5000_LINE_OUT_GND_SHIFT; + + /* enable small pop */ + ref_ctrl |= SGTL5000_SMALL_POP; + + /* Controls the output bias current for the lineout */ + lo_ctrl |= + (SGTL5000_LINE_OUT_CURRENT_360u << SGTL5000_LINE_OUT_CURRENT_SHIFT); + + /* set short detect */ + /* keep default */ + + /* set routing */ + /* keep default, bypass DAP */ + + sgtl5000_write(codec, SGTL5000_CHIP_LINREG_CTRL, lreg_ctrl); + sgtl5000_write(codec, SGTL5000_CHIP_ANA_POWER, ana_pwr); + msleep(10); + + /* For rev 0x11, if vddd linear reg has been enabled, we have + to disable simple reg to get proper VDDD voltage. */ + if ((ana_pwr & SGTL5000_LINEREG_D_POWERUP) && (sgtl5000->rev >= 0x11)) { + ana_pwr &= ~SGTL5000_LINREG_SIMPLE_POWERUP; + sgtl5000_write(codec, SGTL5000_CHIP_ANA_POWER, ana_pwr); + msleep(10); + } + + sgtl5000_write(codec, SGTL5000_CHIP_REF_CTRL, ref_ctrl); + sgtl5000_write(codec, SGTL5000_CHIP_LINE_OUT_CTRL, lo_ctrl); + sgtl5000_write(codec, SGTL5000_CHIP_SHORT_CTRL, short_ctrl); + sgtl5000_write(codec, SGTL5000_CHIP_SSS_CTRL, sss); + sgtl5000_write(codec, SGTL5000_CHIP_DIG_POWER, 0); + + reg = SGTL5000_DAC_VOL_RAMP_EN | + SGTL5000_DAC_MUTE_RIGHT | SGTL5000_DAC_MUTE_LEFT; + sgtl5000_write(codec, SGTL5000_CHIP_ADCDAC_CTRL, reg); + +#ifdef CONFIG_ARCH_MXC + if (cpu_is_mx25()) + sgtl5000_write(codec, SGTL5000_CHIP_PAD_STRENGTH, 0x01df); + else +#endif + sgtl5000_write(codec, SGTL5000_CHIP_PAD_STRENGTH, 0x015f); + + reg = sgtl5000_read(codec, SGTL5000_CHIP_ANA_ADC_CTRL); + reg &= ~SGTL5000_ADC_VOL_M6DB; + reg &= ~(SGTL5000_ADC_VOL_LEFT_MASK | SGTL5000_ADC_VOL_RIGHT_MASK); + reg |= (0xf << SGTL5000_ADC_VOL_LEFT_SHIFT) + | (0xf << SGTL5000_ADC_VOL_RIGHT_SHIFT); + sgtl5000_write(codec, SGTL5000_CHIP_ANA_ADC_CTRL, reg); + + reg = SGTL5000_LINE_OUT_MUTE | SGTL5000_HP_MUTE | + SGTL5000_HP_ZCD_EN | SGTL5000_ADC_ZCD_EN; + sgtl5000_write(codec, SGTL5000_CHIP_ANA_CTRL, reg); + + sgtl5000_write(codec, SGTL5000_CHIP_MIC_CTRL, 0); + sgtl5000_write(codec, SGTL5000_CHIP_CLK_TOP_CTRL, 0); + /* disable DAP */ + sgtl5000_write(codec, SGTL5000_DAP_CTRL, 0); + /* TODO: initialize DAP */ + + snd_soc_add_controls(codec, sgtl5000_snd_controls, + ARRAY_SIZE(sgtl5000_snd_controls)); + sgtl5000_add_widgets(codec); + + sgtl5000_set_bias_level(codec, SND_SOC_BIAS_STANDBY); + + ret = snd_soc_init_card(socdev); + if (ret < 0) { + printk(KERN_ERR "sgtl5000: failed to register card\n"); + snd_soc_free_pcms(socdev); + snd_soc_dapm_free(socdev); + return ret; + } + + return 0; +} + +/* power down chip */ +static int sgtl5000_remove(struct platform_device *pdev) +{ + struct snd_soc_device *socdev = platform_get_drvdata(pdev); + struct snd_soc_codec *codec = socdev->card->codec; + + if (codec->control_data) + sgtl5000_set_bias_level(codec, SND_SOC_BIAS_OFF); + snd_soc_free_pcms(socdev); + snd_soc_dapm_free(socdev); + + return 0; +} + +struct snd_soc_codec_device soc_codec_dev_sgtl5000 = { + .probe = sgtl5000_probe, + .remove = sgtl5000_remove, + .suspend = sgtl5000_suspend, + .resume = sgtl5000_resume, +}; +EXPORT_SYMBOL_GPL(soc_codec_dev_sgtl5000); + +static __devinit int sgtl5000_i2c_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + struct sgtl5000_priv *sgtl5000; + struct snd_soc_codec *codec; + struct regulator *reg; + int ret = 0; + u32 val; + + if (sgtl5000_codec) { + dev_err(&client->dev, + "Multiple SGTL5000 devices not supported\n"); + return -ENOMEM; + } + + codec = kzalloc(sizeof(struct snd_soc_codec), GFP_KERNEL); + if (codec == NULL) + return -ENOMEM; + + sgtl5000 = kzalloc(sizeof(struct sgtl5000_priv), GFP_KERNEL); + if (sgtl5000 == NULL) { + kfree(codec); + return -ENOMEM; + } + + snd_soc_codec_set_drvdata(codec, sgtl5000); + mutex_init(&codec->mutex); + INIT_LIST_HEAD(&codec->dapm_widgets); + INIT_LIST_HEAD(&codec->dapm_paths); + + i2c_set_clientdata(client, codec); + codec->control_data = client; + + reg = regulator_get(&client->dev, "VDDIO"); + if (!IS_ERR(reg)) + sgtl5000->reg_vddio = reg; + + reg = regulator_get(&client->dev, "VDDA"); + if (!IS_ERR(reg)) + sgtl5000->reg_vdda = reg; + + reg = regulator_get(&client->dev, "VDDD"); + if (!IS_ERR(reg)) + sgtl5000->reg_vddd = reg; + + if (sgtl5000->reg_vdda) { + sgtl5000->vdda = + regulator_get_voltage(sgtl5000->reg_vdda) / 1000; + regulator_enable(sgtl5000->reg_vdda); + } + if (sgtl5000->reg_vddio) { + sgtl5000->vddio = + regulator_get_voltage(sgtl5000->reg_vddio) / 1000; + regulator_enable(sgtl5000->reg_vddio); + } + if (sgtl5000->reg_vddd) { + sgtl5000->vddd = + regulator_get_voltage(sgtl5000->reg_vddd) / 1000; + regulator_enable(sgtl5000->reg_vddd); + } else { + sgtl5000->vddd = 0; /* use internal regulator */ + } + + msleep(1); + + val = sgtl5000_read(codec, SGTL5000_CHIP_ID); + if (((val & SGTL5000_PARTID_MASK) >> SGTL5000_PARTID_SHIFT) != + SGTL5000_PARTID_PART_ID) { + pr_err("Device with ID register %x is not a SGTL5000\n", val); + ret = -ENODEV; + goto err_codec_reg; + } + + sgtl5000->rev = (val & SGTL5000_REVID_MASK) >> SGTL5000_REVID_SHIFT; + dev_info(&client->dev, "SGTL5000 revision %d\n", sgtl5000->rev); + + codec->dev = &client->dev; + codec->name = "SGTL5000"; + codec->owner = THIS_MODULE; + codec->read = sgtl5000_read_reg_cache; + codec->write = sgtl5000_write; + codec->bias_level = SND_SOC_BIAS_OFF; + codec->set_bias_level = sgtl5000_set_bias_level; + codec->dai = &sgtl5000_dai; + codec->num_dai = 1; + codec->reg_cache_size = sizeof(sgtl5000_regs); + codec->reg_cache_step = 2; + codec->reg_cache = (void *)&sgtl5000_regs; + + sgtl5000_sync_reg_cache(codec); + + sgtl5000_codec = codec; + sgtl5000_dai.dev = &client->dev; + + ret = snd_soc_register_codec(codec); + if (ret != 0) { + dev_err(codec->dev, "Failed to register codec: %d\n", ret); + goto err_codec_reg; + } + + ret = snd_soc_register_dai(&sgtl5000_dai); + if (ret != 0) { + dev_err(codec->dev, "Failed to register DAIs: %d\n", ret); + goto err_codec_reg; + } + + return 0; + +err_codec_reg: + if (sgtl5000->reg_vddd) + regulator_disable(sgtl5000->reg_vddd); + if (sgtl5000->reg_vdda) + regulator_disable(sgtl5000->reg_vdda); + if (sgtl5000->reg_vddio) + regulator_disable(sgtl5000->reg_vddio); + if (sgtl5000->reg_vddd) + regulator_put(sgtl5000->reg_vddd); + if (sgtl5000->reg_vdda) + regulator_put(sgtl5000->reg_vdda); + if (sgtl5000->reg_vddio) + regulator_put(sgtl5000->reg_vddio); + kfree(sgtl5000); + kfree(codec); + return ret; +} + +static __devexit int sgtl5000_i2c_remove(struct i2c_client *client) +{ + struct snd_soc_codec *codec = i2c_get_clientdata(client); + struct sgtl5000_priv *sgtl5000 = snd_soc_codec_get_drvdata(codec); + + if (client->dev.platform_data) + clk_disable((struct clk *)client->dev.platform_data); + + snd_soc_unregister_dai(&sgtl5000_dai); + snd_soc_unregister_codec(codec); + + if (sgtl5000->reg_vddio) { + regulator_disable(sgtl5000->reg_vddio); + regulator_put(sgtl5000->reg_vddio); + } + if (sgtl5000->reg_vddd) { + regulator_disable(sgtl5000->reg_vddd); + regulator_put(sgtl5000->reg_vddd); + } + if (sgtl5000->reg_vdda) { + regulator_disable(sgtl5000->reg_vdda); + regulator_put(sgtl5000->reg_vdda); + } + + kfree(codec); + kfree(sgtl5000); + sgtl5000_codec = NULL; + return 0; +} + +static const struct i2c_device_id sgtl5000_id[] = { + {"sgtl5000-i2c", 0}, + {}, +}; + +MODULE_DEVICE_TABLE(i2c, sgtl5000_id); + +static struct i2c_driver sgtl5000_i2c_driver = { + .driver = { + .name = "sgtl5000-i2c", + .owner = THIS_MODULE, + }, + .probe = sgtl5000_i2c_probe, + .remove = __devexit_p(sgtl5000_i2c_remove), + .id_table = sgtl5000_id, +}; + +static int __init sgtl5000_modinit(void) +{ + return i2c_add_driver(&sgtl5000_i2c_driver); +} +module_init(sgtl5000_modinit); + +static void __exit sgtl5000_exit(void) +{ + i2c_del_driver(&sgtl5000_i2c_driver); +} +module_exit(sgtl5000_exit); + +MODULE_DESCRIPTION("ASoC SGTL5000 driver"); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/codecs/sgtl5000.h b/sound/soc/codecs/sgtl5000.h new file mode 100644 index 000000000000..b1a755e29d57 --- /dev/null +++ b/sound/soc/codecs/sgtl5000.h @@ -0,0 +1,406 @@ +/* + * sgtl5000.h - SGTL5000 audio codec interface + * + * Copyright (C) 2008-2010 Freescale Semiconductor, Inc. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + */ + +#ifndef _SGTL5000_H +#define _SGTL5000_H + +#include + +extern struct snd_soc_dai sgtl5000_dai; +extern struct snd_soc_codec_device soc_codec_dev_sgtl5000; + +/* + * Register values. + */ +#define SGTL5000_CHIP_ID 0x0000 +#define SGTL5000_CHIP_DIG_POWER 0x0002 +#define SGTL5000_CHIP_CLK_CTRL 0x0004 +#define SGTL5000_CHIP_I2S_CTRL 0x0006 +#define SGTL5000_CHIP_SSS_CTRL 0x000a +#define SGTL5000_CHIP_ADCDAC_CTRL 0x000e +#define SGTL5000_CHIP_DAC_VOL 0x0010 +#define SGTL5000_CHIP_PAD_STRENGTH 0x0014 +#define SGTL5000_CHIP_ANA_ADC_CTRL 0x0020 +#define SGTL5000_CHIP_ANA_HP_CTRL 0x0022 +#define SGTL5000_CHIP_ANA_CTRL 0x0024 +#define SGTL5000_CHIP_LINREG_CTRL 0x0026 +#define SGTL5000_CHIP_REF_CTRL 0x0028 +#define SGTL5000_CHIP_MIC_CTRL 0x002a +#define SGTL5000_CHIP_LINE_OUT_CTRL 0x002c +#define SGTL5000_CHIP_LINE_OUT_VOL 0x002e +#define SGTL5000_CHIP_ANA_POWER 0x0030 +#define SGTL5000_CHIP_PLL_CTRL 0x0032 +#define SGTL5000_CHIP_CLK_TOP_CTRL 0x0034 +#define SGTL5000_CHIP_ANA_STATUS 0x0036 +#define SGTL5000_CHIP_SHORT_CTRL 0x003c +#define SGTL5000_CHIP_ANA_TEST2 0x003a +#define SGTL5000_DAP_CTRL 0x0100 +#define SGTL5000_DAP_PEQ 0x0102 +#define SGTL5000_DAP_BASS_ENHANCE 0x0104 +#define SGTL5000_DAP_BASS_ENHANCE_CTRL 0x0106 +#define SGTL5000_DAP_AUDIO_EQ 0x0108 +#define SGTL5000_DAP_SURROUND 0x010a +#define SGTL5000_DAP_FLT_COEF_ACCESS 0x010c +#define SGTL5000_DAP_COEF_WR_B0_MSB 0x010e +#define SGTL5000_DAP_COEF_WR_B0_LSB 0x0110 +#define SGTL5000_DAP_EQ_BASS_BAND0 0x0116 +#define SGTL5000_DAP_EQ_BASS_BAND1 0x0118 +#define SGTL5000_DAP_EQ_BASS_BAND2 0x011a +#define SGTL5000_DAP_EQ_BASS_BAND3 0x011c +#define SGTL5000_DAP_EQ_BASS_BAND4 0x011e +#define SGTL5000_DAP_MAIN_CHAN 0x0120 +#define SGTL5000_DAP_MIX_CHAN 0x0122 +#define SGTL5000_DAP_AVC_CTRL 0x0124 +#define SGTL5000_DAP_AVC_THRESHOLD 0x0126 +#define SGTL5000_DAP_AVC_ATTACK 0x0128 +#define SGTL5000_DAP_AVC_DECAY 0x012a +#define SGTL5000_DAP_COEF_WR_B1_MSB 0x012c +#define SGTL5000_DAP_COEF_WR_B1_LSB 0x012e +#define SGTL5000_DAP_COEF_WR_B2_MSB 0x0130 +#define SGTL5000_DAP_COEF_WR_B2_LSB 0x0132 +#define SGTL5000_DAP_COEF_WR_A1_MSB 0x0134 +#define SGTL5000_DAP_COEF_WR_A1_LSB 0x0136 +#define SGTL5000_DAP_COEF_WR_A2_MSB 0x0138 +#define SGTL5000_DAP_COEF_WR_A2_LSB 0x013a + +/* + * Field Definitions. + */ + +/* + * SGTL5000_CHIP_ID + */ +#define SGTL5000_PARTID_MASK 0xff00 +#define SGTL5000_PARTID_SHIFT 8 +#define SGTL5000_PARTID_WIDTH 8 +#define SGTL5000_PARTID_PART_ID 0xa0 +#define SGTL5000_REVID_MASK 0x00ff +#define SGTL5000_REVID_SHIFT 0 +#define SGTL5000_REVID_WIDTH 8 + +/* + * SGTL5000_CHIP_DIG_POWER + */ +#define SGTL5000_ADC_EN 0x0040 +#define SGTL5000_DAC_EN 0x0020 +#define SGTL5000_DAP_POWERUP 0x0010 +#define SGTL5000_I2S_OUT_POWERUP 0x0002 +#define SGTL5000_I2S_IN_POWERUP 0x0001 + +/* + * SGTL5000_CHIP_CLK_CTRL + */ +#define SGTL5000_RATE_MODE_MASK 0x0030 +#define SGTL5000_RATE_MODE_SHIFT 4 +#define SGTL5000_RATE_MODE_WIDTH 2 +#define SGTL5000_RATE_MODE_DIV_1 0 +#define SGTL5000_RATE_MODE_DIV_2 1 +#define SGTL5000_RATE_MODE_DIV_4 2 +#define SGTL5000_RATE_MODE_DIV_6 3 +#define SGTL5000_SYS_FS_MASK 0x000c +#define SGTL5000_SYS_FS_SHIFT 2 +#define SGTL5000_SYS_FS_WIDTH 2 +#define SGTL5000_SYS_FS_32k 0x0 +#define SGTL5000_SYS_FS_44_1k 0x1 +#define SGTL5000_SYS_FS_48k 0x2 +#define SGTL5000_SYS_FS_96k 0x3 +#define SGTL5000_MCLK_FREQ_MASK 0x0003 +#define SGTL5000_MCLK_FREQ_SHIFT 0 +#define SGTL5000_MCLK_FREQ_WIDTH 2 +#define SGTL5000_MCLK_FREQ_256FS 0x0 +#define SGTL5000_MCLK_FREQ_384FS 0x1 +#define SGTL5000_MCLK_FREQ_512FS 0x2 +#define SGTL5000_MCLK_FREQ_PLL 0x3 + +/* + * SGTL5000_CHIP_I2S_CTRL + */ +#define SGTL5000_I2S_SCLKFREQ_MASK 0x0100 +#define SGTL5000_I2S_SCLKFREQ_SHIFT 8 +#define SGTL5000_I2S_SCLKFREQ_WIDTH 1 +#define SGTL5000_I2S_SCLKFREQ_64FS 0x0 +#define SGTL5000_I2S_SCLKFREQ_32FS 0x1 /* Not for RJ mode */ +#define SGTL5000_I2S_MASTER 0x0080 +#define SGTL5000_I2S_SCLK_INV 0x0040 +#define SGTL5000_I2S_DLEN_MASK 0x0030 +#define SGTL5000_I2S_DLEN_SHIFT 4 +#define SGTL5000_I2S_DLEN_WIDTH 2 +#define SGTL5000_I2S_DLEN_32 0x0 +#define SGTL5000_I2S_DLEN_24 0x1 +#define SGTL5000_I2S_DLEN_20 0x2 +#define SGTL5000_I2S_DLEN_16 0x3 +#define SGTL5000_I2S_MODE_MASK 0x000c +#define SGTL5000_I2S_MODE_SHIFT 2 +#define SGTL5000_I2S_MODE_WIDTH 2 +#define SGTL5000_I2S_MODE_I2S_LJ 0x0 +#define SGTL5000_I2S_MODE_RJ 0x1 +#define SGTL5000_I2S_MODE_PCM 0x2 +#define SGTL5000_I2S_LRALIGN 0x0002 +#define SGTL5000_I2S_LRPOL 0x0001 /* set for which mode */ + +/* + * SGTL5000_CHIP_SSS_CTRL + */ +#define SGTL5000_DAP_MIX_LRSWAP 0x4000 +#define SGTL5000_DAP_LRSWAP 0x2000 +#define SGTL5000_DAC_LRSWAP 0x1000 +#define SGTL5000_I2S_OUT_LRSWAP 0x0400 +#define SGTL5000_DAP_MIX_SEL_MASK 0x0300 +#define SGTL5000_DAP_MIX_SEL_SHIFT 8 +#define SGTL5000_DAP_MIX_SEL_WIDTH 2 +#define SGTL5000_DAP_MIX_SEL_ADC 0x0 +#define SGTL5000_DAP_MIX_SEL_I2S_IN 0x1 +#define SGTL5000_DAP_SEL_MASK 0x00c0 +#define SGTL5000_DAP_SEL_SHIFT 6 +#define SGTL5000_DAP_SEL_WIDTH 2 +#define SGTL5000_DAP_SEL_ADC 0x0 +#define SGTL5000_DAP_SEL_I2S_IN 0x1 +#define SGTL5000_DAC_SEL_MASK 0x0030 +#define SGTL5000_DAC_SEL_SHIFT 4 +#define SGTL5000_DAC_SEL_WIDTH 2 +#define SGTL5000_DAC_SEL_ADC 0x0 +#define SGTL5000_DAC_SEL_I2S_IN 0x1 +#define SGTL5000_DAC_SEL_DAP 0x3 +#define SGTL5000_I2S_OUT_SEL_MASK 0x0003 +#define SGTL5000_I2S_OUT_SEL_SHIFT 0 +#define SGTL5000_I2S_OUT_SEL_WIDTH 2 +#define SGTL5000_I2S_OUT_SEL_ADC 0x0 +#define SGTL5000_I2S_OUT_SEL_I2S_IN 0x1 +#define SGTL5000_I2S_OUT_SEL_DAP 0x3 + +/* + * SGTL5000_CHIP_ADCDAC_CTRL + */ +#define SGTL5000_VOL_BUSY_DAC_RIGHT 0x2000 +#define SGTL5000_VOL_BUSY_DAC_LEFT 0x1000 +#define SGTL5000_DAC_VOL_RAMP_EN 0x0200 +#define SGTL5000_DAC_VOL_RAMP_EXPO 0x0100 +#define SGTL5000_DAC_MUTE_RIGHT 0x0008 +#define SGTL5000_DAC_MUTE_LEFT 0x0004 +#define SGTL5000_ADC_HPF_FREEZE 0x0002 +#define SGTL5000_ADC_HPF_BYPASS 0x0001 + +/* + * SGTL5000_CHIP_DAC_VOL + */ +#define SGTL5000_DAC_VOL_RIGHT_MASK 0xff00 +#define SGTL5000_DAC_VOL_RIGHT_SHIFT 8 +#define SGTL5000_DAC_VOL_RIGHT_WIDTH 8 +#define SGTL5000_DAC_VOL_LEFT_MASK 0x00ff +#define SGTL5000_DAC_VOL_LEFT_SHIFT 0 +#define SGTL5000_DAC_VOL_LEFT_WIDTH 8 + +/* + * SGTL5000_CHIP_PAD_STRENGTH + */ +#define SGTL5000_PAD_I2S_LRCLK_MASK 0x0300 +#define SGTL5000_PAD_I2S_LRCLK_SHIFT 8 +#define SGTL5000_PAD_I2S_LRCLK_WIDTH 2 +#define SGTL5000_PAD_I2S_SCLK_MASK 0x00c0 +#define SGTL5000_PAD_I2S_SCLK_SHIFT 6 +#define SGTL5000_PAD_I2S_SCLK_WIDTH 2 +#define SGTL5000_PAD_I2S_DOUT_MASK 0x0030 +#define SGTL5000_PAD_I2S_DOUT_SHIFT 4 +#define SGTL5000_PAD_I2S_DOUT_WIDTH 2 +#define SGTL5000_PAD_I2C_SDA_MASK 0x000c +#define SGTL5000_PAD_I2C_SDA_SHIFT 2 +#define SGTL5000_PAD_I2C_SDA_WIDTH 2 +#define SGTL5000_PAD_I2C_SCL_MASK 0x0003 +#define SGTL5000_PAD_I2C_SCL_SHIFT 0 +#define SGTL5000_PAD_I2C_SCL_WIDTH 2 + +/* + * SGTL5000_CHIP_ANA_ADC_CTRL + */ +#define SGTL5000_ADC_VOL_M6DB 0x0100 +#define SGTL5000_ADC_VOL_RIGHT_MASK 0x00f0 +#define SGTL5000_ADC_VOL_RIGHT_SHIFT 4 +#define SGTL5000_ADC_VOL_RIGHT_WIDTH 4 +#define SGTL5000_ADC_VOL_LEFT_MASK 0x000f +#define SGTL5000_ADC_VOL_LEFT_SHIFT 0 +#define SGTL5000_ADC_VOL_LEFT_WIDTH 4 + +/* + * SGTL5000_CHIP_ANA_HP_CTRL + */ +#define SGTL5000_HP_VOL_RIGHT_MASK 0x7f00 +#define SGTL5000_HP_VOL_RIGHT_SHIFT 8 +#define SGTL5000_HP_VOL_RIGHT_WIDTH 7 +#define SGTL5000_HP_VOL_LEFT_MASK 0x007f +#define SGTL5000_HP_VOL_LEFT_SHIFT 0 +#define SGTL5000_HP_VOL_LEFT_WIDTH 7 + +/* + * SGTL5000_CHIP_ANA_CTRL + */ +#define SGTL5000_LINE_OUT_MUTE 0x0100 +#define SGTL5000_HP_SEL_MASK 0x0040 +#define SGTL5000_HP_SEL_SHIFT 6 +#define SGTL5000_HP_SEL_WIDTH 1 +#define SGTL5000_HP_SEL_DAC 0x0 +#define SGTL5000_HP_SEL_LINE_IN 0x1 +#define SGTL5000_HP_ZCD_EN 0x0020 +#define SGTL5000_HP_MUTE 0x0010 +#define SGTL5000_ADC_SEL_MASK 0x0004 +#define SGTL5000_ADC_SEL_SHIFT 2 +#define SGTL5000_ADC_SEL_WIDTH 1 +#define SGTL5000_ADC_SEL_MIC 0x0 +#define SGTL5000_ADC_SEL_LINE_IN 0x1 +#define SGTL5000_ADC_ZCD_EN 0x0002 +#define SGTL5000_ADC_MUTE 0x0001 + +/* + * SGTL5000_CHIP_LINREG_CTRL + */ +#define SGTL5000_VDDC_MAN_ASSN_MASK 0x0040 +#define SGTL5000_VDDC_MAN_ASSN_SHIFT 6 +#define SGTL5000_VDDC_MAN_ASSN_WIDTH 1 +#define SGTL5000_VDDC_MAN_ASSN_VDDA 0x0 +#define SGTL5000_VDDC_MAN_ASSN_VDDIO 0x1 +#define SGTL5000_VDDC_ASSN_OVRD 0x0020 +#define SGTL5000_LINREG_VDDD_MASK 0x000f +#define SGTL5000_LINREG_VDDD_SHIFT 0 +#define SGTL5000_LINREG_VDDD_WIDTH 4 + +/* + * SGTL5000_CHIP_REF_CTRL + */ +#define SGTL5000_ANA_GND_MASK 0x01f0 +#define SGTL5000_ANA_GND_SHIFT 4 +#define SGTL5000_ANA_GND_WIDTH 5 +#define SGTL5000_ANA_GND_BASE 800 /* mv */ +#define SGTL5000_ANA_GND_STP 25 /*mv */ +#define SGTL5000_BIAS_CTRL_MASK 0x000e +#define SGTL5000_BIAS_CTRL_SHIFT 1 +#define SGTL5000_BIAS_CTRL_WIDTH 3 +#define SGTL5000_SMALL_POP 0x0001 + +/* + * SGTL5000_CHIP_MIC_CTRL + */ +#define SGTL5000_BIAS_R_MASK 0x0200 +#define SGTL5000_BIAS_R_SHIFT 8 +#define SGTL5000_BIAS_R_WIDTH 2 +#define SGTL5000_BIAS_R_off 0x0 +#define SGTL5000_BIAS_R_2K 0x1 +#define SGTL5000_BIAS_R_4k 0x2 +#define SGTL5000_BIAS_R_8k 0x3 +#define SGTL5000_BIAS_VOLT_MASK 0x0070 +#define SGTL5000_BIAS_VOLT_SHIFT 4 +#define SGTL5000_BIAS_VOLT_WIDTH 3 +#define SGTL5000_MIC_GAIN_MASK 0x0003 +#define SGTL5000_MIC_GAIN_SHIFT 0 +#define SGTL5000_MIC_GAIN_WIDTH 2 + +/* + * SGTL5000_CHIP_LINE_OUT_CTRL + */ +#define SGTL5000_LINE_OUT_CURRENT_MASK 0x0f00 +#define SGTL5000_LINE_OUT_CURRENT_SHIFT 8 +#define SGTL5000_LINE_OUT_CURRENT_WIDTH 4 +#define SGTL5000_LINE_OUT_CURRENT_180u 0x0 +#define SGTL5000_LINE_OUT_CURRENT_270u 0x1 +#define SGTL5000_LINE_OUT_CURRENT_360u 0x3 +#define SGTL5000_LINE_OUT_CURRENT_450u 0x7 +#define SGTL5000_LINE_OUT_CURRENT_540u 0xf +#define SGTL5000_LINE_OUT_GND_MASK 0x003f +#define SGTL5000_LINE_OUT_GND_SHIFT 0 +#define SGTL5000_LINE_OUT_GND_WIDTH 6 +#define SGTL5000_LINE_OUT_GND_BASE 800 /* mv */ +#define SGTL5000_LINE_OUT_GND_STP 25 +#define SGTL5000_LINE_OUT_GND_MAX 0x23 + +/* + * SGTL5000_CHIP_LINE_OUT_VOL + */ +#define SGTL5000_LINE_OUT_VOL_RIGHT_MASK 0x1f00 +#define SGTL5000_LINE_OUT_VOL_RIGHT_SHIFT 8 +#define SGTL5000_LINE_OUT_VOL_RIGHT_WIDTH 5 +#define SGTL5000_LINE_OUT_VOL_LEFT_MASK 0x001f +#define SGTL5000_LINE_OUT_VOL_LEFT_SHIFT 0 +#define SGTL5000_LINE_OUT_VOL_LEFT_WIDTH 5 + +/* + * SGTL5000_CHIP_ANA_POWER + */ +#define SGTL5000_DAC_STEREO 0x4000 +#define SGTL5000_LINREG_SIMPLE_POWERUP 0x2000 +#define SGTL5000_STARTUP_POWERUP 0x1000 +#define SGTL5000_VDDC_CHRGPMP_POWERUP 0x0800 +#define SGTL5000_PLL_POWERUP 0x0400 +#define SGTL5000_LINEREG_D_POWERUP 0x0200 +#define SGTL5000_VCOAMP_POWERUP 0x0100 +#define SGTL5000_VAG_POWERUP 0x0080 +#define SGTL5000_ADC_STEREO 0x0040 +#define SGTL5000_REFTOP_POWERUP 0x0020 +#define SGTL5000_HP_POWERUP 0x0010 +#define SGTL5000_DAC_POWERUP 0x0008 +#define SGTL5000_CAPLESS_HP_POWERUP 0x0004 +#define SGTL5000_ADC_POWERUP 0x0002 +#define SGTL5000_LINE_OUT_POWERUP 0x0001 + +/* + * SGTL5000_CHIP_PLL_CTRL + */ +#define SGTL5000_PLL_INT_DIV_MASK 0xf800 +#define SGTL5000_PLL_INT_DIV_SHIFT 11 +#define SGTL5000_PLL_INT_DIV_WIDTH 5 +#define SGTL5000_PLL_FRAC_DIV_MASK 0x0700 +#define SGTL5000_PLL_FRAC_DIV_SHIFT 0 +#define SGTL5000_PLL_FRAC_DIV_WIDTH 11 + +/* + * SGTL5000_CHIP_CLK_TOP_CTRL + */ +#define SGTL5000_INT_OSC_EN 0x0800 +#define SGTL5000_INPUT_FREQ_DIV2 0x0008 + +/* + * SGTL5000_CHIP_ANA_STATUS + */ +#define SGTL5000_HP_LRSHORT 0x0200 +#define SGTL5000_CAPLESS_SHORT 0x0100 +#define SGTL5000_PLL_LOCKED 0x0010 + +/* + * SGTL5000_CHIP_SHORT_CTRL + */ +#define SGTL5000_LVLADJR_MASK 0x7000 +#define SGTL5000_LVLADJR_SHIFT 12 +#define SGTL5000_LVLADJR_WIDTH 3 +#define SGTL5000_LVLADJL_MASK 0x0700 +#define SGTL5000_LVLADJL_SHIFT 8 +#define SGTL5000_LVLADJL_WIDTH 3 +#define SGTL5000_LVLADJC_MASK 0x0070 +#define SGTL5000_LVLADJC_SHIFT 4 +#define SGTL5000_LVLADJC_WIDTH 3 +#define SGTL5000_LR_SHORT_MOD_MASK 0x000c +#define SGTL5000_LR_SHORT_MOD_SHIFT 2 +#define SGTL5000_LR_SHORT_MOD_WIDTH 2 +#define SGTL5000_CM_SHORT_MOD_MASK 0x0003 +#define SGTL5000_CM_SHORT_MOD_SHIFT 0 +#define SGTL5000_CM_SHORT_MOD_WIDTH 2 + +/* + *SGTL5000_CHIP_ANA_TEST2 + */ +#define SGTL5000_MONO_DAC 0x1000 + +/* + * SGTL5000_DAP_CTRL + */ +#define SGTL5000_DAP_MIX_EN 0x0010 +#define SGTL5000_DAP_EN 0x0001 + +#define SGTL5000_SYSCLK 0x00 +#define SGTL5000_LRCLK 0x01 + +#endif diff --git a/sound/soc/imx/Kconfig b/sound/soc/imx/Kconfig index 252defea93b5..7264bd50401e 100644 --- a/sound/soc/imx/Kconfig +++ b/sound/soc/imx/Kconfig @@ -28,3 +28,75 @@ config SND_SOC_PHYCORE_AC97 help Say Y if you want to add support for SoC audio on Phytec phyCORE and phyCARD boards in AC97 mode + +config SND_MXC_SOC_ESAI + tristate + +config SND_MXC_SOC_AC97 + tristate + +if SND_MXC_SOC + +config SND_MXC_SOC_IRAM + bool "Locate Audio DMA playback buffers in IRAM" + help + Say Y if you don't want Audio playback buffers in external ram + +config SND_SOC_IMX_3STACK_WM8350 + tristate "SoC Audio support for IMX - WM8350" + depends on MFD_WM8350 + select SND_MXC_SOC_SSI + select SND_SOC_WM8350 + help + Say Y if you want to add support for SoC audio on IMX 3STACK + with the WM8350. + +config SND_SOC_IMX_3STACK_SGTL5000 + tristate "SoC Audio support for IMX - SGTL5000" + select SND_MXC_SOC_SSI + select SND_SOC_SGTL5000 + help + Say Y if you want to add support for SoC audio on IMX 3STACK + with the SGTL5000. + +config SND_SOC_IMX_3STACK_AK4647 + tristate "SoC Audio support for IMX - AK4647" + select SND_MXC_SOC_SSI + select SND_SOC_AK4647 + help + Say Y if you want to add support for SoC audio on IMX 3STACK + with the AK4647. + +config SND_SOC_IMX_3STACK_WM8580 + tristate "SoC Audio support for IMX - WM8580" + select SND_MXC_SOC_ESAI + select SND_SOC_WM8580 + help + Say Y if you want to add support for Soc audio on IMX 3STACK + with the WM8580 + +config SND_SOC_IMX_3STACK_AK5702 + tristate "SoC Audio support for IMX - AK5702" + select SND_MXC_SOC_ESAI + select SND_SOC_AK5702 + help + Say Y if you want to add support for Soc audio on IMX 3STACK + with the AK5702 + +config SND_SOC_IMX_3STACK_BLUETOOTH + tristate "SoC Audio support for IMX - BLUETOOTH" + select SND_MXC_SOC_SSI + select SND_SOC_BLUETOOTH + help + Say Y if you want to add support for Soc audio on IMX 3STACK + with the BLUETOOTH + +config SND_SOC_IMX_3STACK_CS42888 + tristate "SoC Audio support for IMX - CS42888" + select SND_MXC_SOC_ESAI + select SND_SOC_CS42888 + help + Say Y if you want to add support for Soc audio on IMX 3STACK + with the CS42888 + +endif diff --git a/sound/soc/imx/Makefile b/sound/soc/imx/Makefile index 2d203635ac11..0a63a2fa93ab 100644 --- a/sound/soc/imx/Makefile +++ b/sound/soc/imx/Makefile @@ -1,5 +1,6 @@ # i.MX Platform Support -snd-soc-imx-objs := imx-ssi.o imx-pcm-fiq.o +snd-soc-imx-objs := imx-ssi.o imx-pcm-fiq.o imx-pcm.o +snd-soc-imx-esai-objs := imx-esai.o ifdef CONFIG_MACH_MX27 snd-soc-imx-objs += imx-pcm-dma-mx2.o @@ -13,3 +14,25 @@ snd-soc-wm1133-ev1-objs := wm1133-ev1.o obj-$(CONFIG_SND_SOC_PHYCORE_AC97) += snd-soc-phycore-ac97.o obj-$(CONFIG_SND_MXC_SOC_WM1133_EV1) += snd-soc-wm1133-ev1.o + +obj-$(CONFIG_SND_MXC_SOC) += snd-soc-imx.o +obj-$(CONFIG_SND_MXC_SOC_SSI) += snd-soc-imx-ssi.o +obj-$(CONFIG_SND_MXC_SOC_ESAI) += snd-soc-imx-esai.o +obj-$(CONFIG_SND_MXC_SOC_AC97) += snd-soc-imx-ac97.o + +# i.MX Machine Support +snd-soc-imx-3stack-wm8350-objs := imx-3stack-wm8350.o +obj-$(CONFIG_SND_SOC_IMX_3STACK_WM8350) += snd-soc-imx-3stack-wm8350.o +snd-soc-imx-3stack-sgtl5000-objs := imx-3stack-sgtl5000.o +obj-$(CONFIG_SND_SOC_IMX_3STACK_SGTL5000) += snd-soc-imx-3stack-sgtl5000.o +snd-soc-imx-3stack-ak4647-objs := imx-3stack-ak4647.o +obj-$(CONFIG_SND_SOC_IMX_3STACK_AK4647) += snd-soc-imx-3stack-ak4647.o +snd-soc-imx-3stack-wm8580-objs := imx-3stack-wm8580.o +obj-$(CONFIG_SND_SOC_IMX_3STACK_WM8580) += snd-soc-imx-3stack-wm8580.o +snd-soc-imx-3stack-ak5702-objs := imx-3stack-ak5702.o +obj-$(CONFIG_SND_SOC_IMX_3STACK_AK5702) += snd-soc-imx-3stack-ak5702.o +snd-soc-imx-3stack-bt-objs := imx-3stack-bt.o +obj-$(CONFIG_SND_SOC_IMX_3STACK_BLUETOOTH) += snd-soc-imx-3stack-bt.o +snd-soc-imx-3stack-cs42888-objs := imx-3stack-cs42888.o +obj-$(CONFIG_SND_SOC_IMX_3STACK_CS42888) += snd-soc-imx-3stack-cs42888.o + diff --git a/sound/soc/imx/imx-3stack-ak4647.c b/sound/soc/imx/imx-3stack-ak4647.c new file mode 100644 index 000000000000..56c7a498e5b1 --- /dev/null +++ b/sound/soc/imx/imx-3stack-ak4647.c @@ -0,0 +1,445 @@ +/* + * imx-3stack-ak4647.c -- SoC audio for imx_3stack + * + * Copyright (C) 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "imx-pcm.h" +#include "imx-ssi.h" + +#define AK4647_SSI_MASTER 1 + +extern struct snd_soc_dai ak4647_hifi_dai; +extern struct snd_soc_codec_device soc_codec_dev_ak4647; + +static void headphone_detect_handler(struct work_struct *work); +static DECLARE_WORK(hp_event, headphone_detect_handler); +static int ak4647_jack_func; +static int ak4647_spk_func; + +struct imx_3stack_priv { + struct platform_device *pdev; +}; + +static struct imx_3stack_priv card_priv; + +static void imx_3stack_init_dam(int ssi_port, int dai_port) +{ + /* AK4647 uses SSI1 or SSI2 via AUDMUX port dai_port for audio */ + unsigned int ssi_ptcr = 0; + unsigned int dai_ptcr = 0; + unsigned int ssi_pdcr = 0; + unsigned int dai_pdcr = 0; + + /* reset port ssi_port & dai_port */ + __raw_writel(0, DAM_PTCR(ssi_port)); + __raw_writel(0, DAM_PTCR(dai_port)); + __raw_writel(0, DAM_PDCR(ssi_port)); + __raw_writel(0, DAM_PDCR(dai_port)); + + /* set to synchronous */ + ssi_ptcr |= AUDMUX_PTCR_SYN; + dai_ptcr |= AUDMUX_PTCR_SYN; + +#if AK4647_SSI_MASTER + /* set Rx sources ssi_port <--> dai_port */ + ssi_pdcr |= AUDMUX_PDCR_RXDSEL(dai_port); + dai_pdcr |= AUDMUX_PDCR_RXDSEL(ssi_port); + + /* set Tx frame direction and source dai_port--> ssi_port output */ + ssi_ptcr |= AUDMUX_PTCR_TFSDIR; + ssi_ptcr |= AUDMUX_PTCR_TFSSEL(AUDMUX_FROM_TXFS, dai_port); + + /* set Tx Clock direction and source dai_port--> ssi_port output */ + ssi_ptcr |= AUDMUX_PTCR_TCLKDIR; + ssi_ptcr |= AUDMUX_PTCR_TCSEL(AUDMUX_FROM_TXFS, dai_port); +#else + /* set Rx sources ssi_port <--> dai_port */ + ssi_pdcr |= AUDMUX_PDCR_RXDSEL(dai_port); + dai_pdcr |= AUDMUX_PDCR_RXDSEL(ssi_port); + + /* set Tx frame direction and source ssi_port --> dai_port output */ + dai_ptcr |= AUDMUX_PTCR_TFSDIR; + dai_ptcr |= AUDMUX_PTCR_TFSSEL(AUDMUX_FROM_TXFS, ssi_port); + + /* set Tx Clock direction and source ssi_port--> dai_port output */ + dai_ptcr |= AUDMUX_PTCR_TCLKDIR; + dai_ptcr |= AUDMUX_PTCR_TCSEL(AUDMUX_FROM_TXFS, ssi_port); +#endif + + __raw_writel(ssi_ptcr, DAM_PTCR(ssi_port)); + __raw_writel(dai_ptcr, DAM_PTCR(dai_port)); + __raw_writel(ssi_pdcr, DAM_PDCR(ssi_port)); + __raw_writel(dai_pdcr, DAM_PDCR(dai_port)); +} + +static int imx_3stack_hifi_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai_link *pcm_link = rtd->dai; + struct snd_soc_dai *cpu_dai = pcm_link->cpu_dai; + struct snd_soc_dai *codec_dai = pcm_link->codec_dai; + unsigned int channels = params_channels(params); + unsigned int rate = params_rate(params); + struct imx_ssi *ssi_mode = (struct imx_ssi *)cpu_dai->private_data; + int ret = 0; + u32 dai_format; + +#if AK4647_SSI_MASTER + dai_format = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | + SND_SOC_DAIFMT_CBM_CFM; +#else + dai_format = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | + SND_SOC_DAIFMT_CBS_CFS; +#endif + + ssi_mode->sync_mode = 1; + if (channels == 1) + ssi_mode->network_mode = 0; + else + ssi_mode->network_mode = 1; + + /* set codec DAI configuration */ + ret = snd_soc_dai_set_fmt(codec_dai, dai_format); + if (ret < 0) + return ret; + + /* set i.MX active slot mask */ + snd_soc_dai_set_tdm_slot(cpu_dai, + channels == 1 ? 0xfffffffe : 0xfffffffc, 2); + + /* set cpu DAI configuration */ + ret = snd_soc_dai_set_fmt(cpu_dai, dai_format); + if (ret < 0) + return ret; + + /* set the SSI system clock as input (unused) */ + snd_soc_dai_set_sysclk(cpu_dai, IMX_SSP_SYS_CLK, 0, SND_SOC_CLOCK_IN); + + snd_soc_dai_set_sysclk(codec_dai, 0, rate, 0); + + /* set codec BCLK division for sample rate */ + snd_soc_dai_set_clkdiv(codec_dai, 0, 0); + + return 0; +} + +/* + * imx_3stack ak4647 HiFi DAI operations. + */ +static struct snd_soc_ops imx_3stack_hifi_ops = { + .hw_params = imx_3stack_hifi_hw_params, +}; + +static int ak4647_get_jack(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + ucontrol->value.integer.value[0] = ak4647_jack_func; + return 0; +} + +static int ak4647_set_jack(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); + if (ak4647_jack_func == ucontrol->value.integer.value[0]) + return 0; + + ak4647_jack_func = ucontrol->value.integer.value[0]; + + if (ak4647_jack_func) + snd_soc_dapm_enable_pin(codec, "Headphone Jack"); + else + snd_soc_dapm_disable_pin(codec, "Headphone Jack"); + + snd_soc_dapm_sync(codec); + return 1; +} + +static int ak4647_get_spk(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + ucontrol->value.integer.value[0] = ak4647_spk_func; + return 0; +} + +static int ak4647_set_spk(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); + if (ak4647_spk_func == ucontrol->value.integer.value[0]) + return 0; + + ak4647_spk_func = ucontrol->value.integer.value[0]; + if (ak4647_spk_func) + snd_soc_dapm_enable_pin(codec, "Line Out Jack"); + else + snd_soc_dapm_disable_pin(codec, "Line Out Jack"); + + snd_soc_dapm_sync(codec); + return 1; +} + +static int spk_amp_event(struct snd_soc_dapm_widget *w, + struct snd_kcontrol *kcontrol, int event) +{ + struct imx_3stack_priv *priv = &card_priv; + struct platform_device *pdev = priv->pdev; + struct mxc_audio_platform_data *plat = pdev->dev.platform_data; + + if (plat->amp_enable == NULL) + return 0; + + if (SND_SOC_DAPM_EVENT_ON(event)) + plat->amp_enable(1); + else + plat->amp_enable(0); + return 0; +} + +/* imx_3stack card dapm widgets */ +static const struct snd_soc_dapm_widget imx_3stack_dapm_widgets[] = { + SND_SOC_DAPM_MIC("Mic1 Jack", NULL), + SND_SOC_DAPM_LINE("Line In Jack", NULL), + SND_SOC_DAPM_LINE("Line Out Jack", NULL), + SND_SOC_DAPM_SPK("Ext Spk", spk_amp_event), + SND_SOC_DAPM_HP("Headphone Jack", NULL), +}; + +static const struct snd_soc_dapm_route audio_map[] = { + /* mic is connected to mic1 - with bias */ + {"Left Input", NULL, "Mic1 Jack"}, + + /* Line in jack */ + {"Left Input", NULL, "Line In Jack"}, + {"Right Input", NULL, "Line In Jack"}, + + /* Headphone jack */ + {"Headphone Jack", NULL, "HPL"}, + {"Headphone Jack", NULL, "HPR"}, + + /* Line out jack */ + {"Line Out Jack", NULL, "LOUT"}, + + /* Ext Spk */ + {"Ext Spk", NULL, "LOUT"}, + +}; + +static const char *jack_function[] = { "off", "on" }; + +static const char *spk_function[] = { "off", "on" }; + +static const struct soc_enum ak4647_enum[] = { + SOC_ENUM_SINGLE_EXT(2, jack_function), + SOC_ENUM_SINGLE_EXT(2, spk_function), +}; + +static const struct snd_kcontrol_new ak4647_card_controls[] = { + SOC_ENUM_EXT("Jack Function", ak4647_enum[0], ak4647_get_jack, + ak4647_set_jack), + SOC_ENUM_EXT("Speaker Function", ak4647_enum[1], ak4647_get_spk, + ak4647_set_spk), +}; + +static void headphone_detect_handler(struct work_struct *work) +{ + struct imx_3stack_priv *priv = &card_priv; + struct platform_device *pdev = priv->pdev; + + sysfs_notify(&pdev->dev.kobj, NULL, "headphone"); +} + +static irqreturn_t imx_headphone_detect_handler(int irq, void *dev_id) +{ + schedule_work(&hp_event); + return IRQ_HANDLED; + +} + +static ssize_t show_headphone(struct device_driver *dev, char *buf) +{ + struct imx_3stack_priv *priv = &card_priv; + struct platform_device *pdev = priv->pdev; + struct mxc_audio_platform_data *plat = pdev->dev.platform_data; + unsigned int value; + + value = plat->hp_status(); + + if (value == 0) + strcpy(buf, "speaker\n"); + else + strcpy(buf, "headphone\n"); + + return strlen(buf); +} + +DRIVER_ATTR(headphone, S_IRUGO | S_IWUSR, show_headphone, NULL); + +static int imx_3stack_ak4647_init(struct snd_soc_codec *codec) +{ + int i, ret; + for (i = 0; i < ARRAY_SIZE(ak4647_card_controls); i++) { + ret = snd_ctl_add(codec->card, + snd_soc_cnew(&ak4647_card_controls[i], + codec, NULL)); + if (ret < 0) + return ret; + } + + snd_soc_dapm_new_controls(codec, imx_3stack_dapm_widgets, + ARRAY_SIZE(imx_3stack_dapm_widgets)); + + snd_soc_dapm_add_routes(codec, audio_map, ARRAY_SIZE(audio_map)); + + snd_soc_dapm_sync(codec); + + return 0; +} + +static struct snd_soc_dai_link imx_3stack_dai = { + .name = "ak4647", + .stream_name = "ak4647", + .codec_dai = &ak4647_hifi_dai, + .init = imx_3stack_ak4647_init, + .ops = &imx_3stack_hifi_ops, +}; + +static struct snd_soc_card snd_soc_card_imx_3stack = { + .name = "imx-3stack", + .platform = &imx_soc_platform, + .dai_link = &imx_3stack_dai, + .num_links = 1, +}; + +static struct snd_soc_device imx_3stack_snd_devdata = { + .card = &snd_soc_card_imx_3stack, + .codec_dev = &soc_codec_dev_ak4647, +}; + +/* + * This function will register the snd_soc_pcm_link drivers. + * It also registers devices for platform DMA, I2S, SSP and registers an + * I2C driver to probe the codec. + */ +static int __init imx_3stack_ak4647_probe(struct platform_device *pdev) +{ + struct mxc_audio_platform_data *dev_data = pdev->dev.platform_data; + struct imx_3stack_priv *priv = &card_priv; + struct snd_soc_dai *ak4647_cpu_dai; + int ret = 0; + + dev_data->init(); + + if (dev_data->src_port == 1) + ak4647_cpu_dai = imx_ssi_dai[0]; + else + ak4647_cpu_dai = imx_ssi_dai[2]; + + imx_3stack_dai.cpu_dai = ak4647_cpu_dai; + + imx_3stack_init_dam(dev_data->src_port, dev_data->ext_port); + + ret = request_irq(dev_data->intr_id_hp, imx_headphone_detect_handler, 0, + "headphone", NULL); + if (ret < 0) + goto err; + + ret = driver_create_file(pdev->dev.driver, &driver_attr_headphone); + if (ret < 0) + goto sysfs_err; + + priv->pdev = pdev; + return ret; + +sysfs_err: + free_irq(dev_data->intr_id_hp, NULL); +err: + return ret; +} + +static int __devexit imx_3stack_ak4647_remove(struct platform_device *pdev) +{ + struct mxc_audio_platform_data *dev_data = pdev->dev.platform_data; + free_irq(dev_data->intr_id_hp, NULL); + driver_remove_file(pdev->dev.driver, &driver_attr_headphone); + return 0; +} + +static struct platform_driver imx_3stack_ak4647_driver = { + .probe = imx_3stack_ak4647_probe, + .remove = __devexit_p(imx_3stack_ak4647_remove), + .driver = { + .name = "imx-3stack-ak4647", + .owner = THIS_MODULE, + }, +}; + +static struct platform_device *imx_3stack_snd_device; + +static int __init imx_3stack_asoc_init(void) +{ + int ret; + + ret = platform_driver_register(&imx_3stack_ak4647_driver); + if (ret < 0) + goto exit; + + if (snd_soc_card_imx_3stack.codec == NULL) { + ret = -ENOMEM; + goto err_device_alloc; + } + + imx_3stack_snd_device = platform_device_alloc("soc-audio", 3); + if (!imx_3stack_snd_device) + goto err_device_alloc; + platform_set_drvdata(imx_3stack_snd_device, &imx_3stack_snd_devdata); + imx_3stack_snd_devdata.dev = &imx_3stack_snd_device->dev; + ret = platform_device_add(imx_3stack_snd_device); + if (0 == ret) + goto exit; + + platform_device_put(imx_3stack_snd_device); +err_device_alloc: + platform_driver_unregister(&imx_3stack_ak4647_driver); +exit: + return ret; +} + +static void __exit imx_3stack_asoc_exit(void) +{ + platform_driver_unregister(&imx_3stack_ak4647_driver); + platform_device_unregister(imx_3stack_snd_device); +} + +module_init(imx_3stack_asoc_init); +module_exit(imx_3stack_asoc_exit); + +/* Module information */ +MODULE_DESCRIPTION("ALSA SoC ak4647 imx_3stack"); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/imx/imx-3stack-ak5702.c b/sound/soc/imx/imx-3stack-ak5702.c new file mode 100644 index 000000000000..eac550fa37ed --- /dev/null +++ b/sound/soc/imx/imx-3stack-ak5702.c @@ -0,0 +1,226 @@ +/* + * imx-3stack-ak5702.c -- SoC audio for imx_3stack + * + * Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "imx-pcm.h" +#include "imx-esai.h" +#include "../codecs/ak5702.h" + +struct imx_3stack_pcm_state { + int lr_clk_active; +}; + +static struct imx_3stack_pcm_state clk_state; + +static int imx_3stack_startup(struct snd_pcm_substream *substream) +{ + clk_state.lr_clk_active++; + return 0; +} + +static void imx_3stack_shutdown(struct snd_pcm_substream *substream) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai_link *pcm_link = rtd->dai; + struct snd_soc_dai *codec_dai = pcm_link->codec_dai; + + /* disable the PLL if there are no active Rx channels */ + if (!codec_dai->active) + snd_soc_dai_set_pll(codec_dai, 0, 0, 0); + clk_state.lr_clk_active--; +} + +static int imx_3stack_surround_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai_link *pcm_link = rtd->dai; + struct snd_soc_dai *cpu_dai = pcm_link->cpu_dai; + struct snd_soc_dai *codec_dai = pcm_link->codec_dai; + unsigned int rate = params_rate(params); + struct imx_esai *esai_mode = (struct imx_esai *)cpu_dai->private_data; + u32 dai_format; + + if (clk_state.lr_clk_active > 1) + return 0; + + dai_format = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | + SND_SOC_DAIFMT_CBM_CFM; + + esai_mode->sync_mode = 0; + esai_mode->network_mode = 1; + + /* set codec DAI configuration */ + snd_soc_dai_set_fmt(codec_dai, dai_format); + + /* set cpu DAI configuration */ + snd_soc_dai_set_fmt(cpu_dai, dai_format); + + /* set i.MX active slot mask */ + snd_soc_dai_set_tdm_slot(cpu_dai, 0xffffffff, 2); + + /* set the ESAI system clock as input */ + snd_soc_dai_set_sysclk(cpu_dai, 0, 0, SND_SOC_CLOCK_IN); + + /* set codec BCLK division */ + snd_soc_dai_set_clkdiv(codec_dai, AK5702_BCLK_CLKDIV, + AK5702_BCLK_DIV_32); + + snd_soc_dai_set_sysclk(codec_dai, 0, rate, SND_SOC_CLOCK_OUT); + + snd_soc_dai_set_pll(codec_dai, 1, 12000000, 0); + return 0; +} + +/* + * imx_3stack ak5702 DAI opserations. + */ +static struct snd_soc_ops imx_3stack_surround_ops = { + .startup = imx_3stack_startup, + .shutdown = imx_3stack_shutdown, + .hw_params = imx_3stack_surround_hw_params, +}; + +/* imx_3stack card dapm widgets */ +static const struct snd_soc_dapm_widget imx_3stack_dapm_widgets[] = { + SND_SOC_DAPM_LINE("Line In Jack", NULL), +}; + +/* example card audio map */ +static const struct snd_soc_dapm_route audio_map[] = { + /* Line in jack */ + {"ADCA Left Input", NULL, "Line In Jack"}, + {"ADCA Right Input", NULL, "Line In Jack"}, + {"ADCB Left Input", NULL, "Line In Jack"}, + {"ADCB Right Input", NULL, "Line In Jack"}, +}; + +static int imx_3stack_ak5702_init(struct snd_soc_codec *codec) +{ + snd_soc_dapm_new_controls(codec, imx_3stack_dapm_widgets, + ARRAY_SIZE(imx_3stack_dapm_widgets)); + snd_soc_dapm_add_routes(codec, audio_map, ARRAY_SIZE(audio_map)); + snd_soc_dapm_sync(codec); + return 0; +} + +static struct snd_soc_dai_link imx_3stack_dai = { + .name = "ak5702", + .stream_name = "ak5702", + .codec_dai = &ak5702_dai, + .init = imx_3stack_ak5702_init, + .ops = &imx_3stack_surround_ops, +}; + +static int imx_3stack_card_remove(struct platform_device *pdev) +{ + struct snd_soc_device *socdev = platform_get_drvdata(pdev); + + kfree(socdev->codec_data); + return 0; +} + +static struct snd_soc_card snd_soc_card_imx_3stack = { + .name = "imx-3stack", + .platform = &imx_soc_platform, + .dai_link = &imx_3stack_dai, + .num_links = 1, + .remove = imx_3stack_card_remove, +}; + +static struct snd_soc_device imx_3stack_snd_devdata = { + .card = &snd_soc_card_imx_3stack, + .codec_dev = &soc_codec_dev_ak5702, +}; + +static int __devinit imx_3stack_ak5702_probe(struct platform_device *pdev) +{ + struct ak5702_setup_data *setup; + + imx_3stack_dai.cpu_dai = &imx_esai_dai[2]; + + setup = kzalloc(sizeof(struct ak5702_setup_data), GFP_KERNEL); + setup->i2c_bus = 1; + setup->i2c_address = 0x13; + imx_3stack_snd_devdata.codec_data = setup; + + return 0; +} + +static int imx_3stack_ak5702_remove(struct platform_device *pdev) +{ + return 0; +} + +static struct platform_driver imx_3stack_ak5702_driver = { + .probe = imx_3stack_ak5702_probe, + .remove = imx_3stack_ak5702_remove, + .driver = { + .name = "imx-3stack-ak5702", + }, +}; + +static struct platform_device *imx_3stack_snd_device; + +static int __init imx_3stack_asoc_init(void) +{ + int ret; + + ret = platform_driver_register(&imx_3stack_ak5702_driver); + if (ret) + return -ENOMEM; + + imx_3stack_snd_device = platform_device_alloc("soc-audio", -1); + if (!imx_3stack_snd_device) + return -ENOMEM; + + platform_set_drvdata(imx_3stack_snd_device, &imx_3stack_snd_devdata); + imx_3stack_snd_devdata.dev = &imx_3stack_snd_device->dev; + ret = platform_device_add(imx_3stack_snd_device); + if (ret) + platform_device_put(imx_3stack_snd_device); + + return ret; +} + +static void __exit imx_3stack_asoc_exit(void) +{ + platform_driver_unregister(&imx_3stack_ak5702_driver); + platform_device_unregister(imx_3stack_snd_device); +} + +module_init(imx_3stack_asoc_init); +module_exit(imx_3stack_asoc_exit); + +/* Module information */ +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("ALSA SoC ak5702 imx_3stack"); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/imx/imx-3stack-bt.c b/sound/soc/imx/imx-3stack-bt.c new file mode 100644 index 000000000000..4b6e36b629e6 --- /dev/null +++ b/sound/soc/imx/imx-3stack-bt.c @@ -0,0 +1,256 @@ +/* + * imx-3stack-bt.c -- SoC bluetooth audio for imx_3stack + * + * Copyright (C) 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "imx-pcm.h" +#include "imx-ssi.h" +#include "imx-3stack-bt.h" + +#define BT_SSI_MASTER 1 + +struct imx_3stack_priv { + struct platform_device *pdev; + int active; +}; + +static struct imx_3stack_priv card_priv; + +static void imx_3stack_init_dam(int ssi_port, int dai_port) +{ + /* bt uses SSI1 or SSI2 via AUDMUX port dai_port for audio */ + unsigned int ssi_ptcr = 0; + unsigned int dai_ptcr = 0; + unsigned int ssi_pdcr = 0; + unsigned int dai_pdcr = 0; + + /* reset port ssi_port & dai_port */ + __raw_writel(0, DAM_PTCR(ssi_port)); + __raw_writel(0, DAM_PTCR(dai_port)); + __raw_writel(0, DAM_PDCR(ssi_port)); + __raw_writel(0, DAM_PDCR(dai_port)); + + /* set to synchronous */ + ssi_ptcr |= AUDMUX_PTCR_SYN; + dai_ptcr |= AUDMUX_PTCR_SYN; + +#if BT_SSI_MASTER + /* set Rx sources ssi_port <--> dai_port */ + ssi_pdcr |= AUDMUX_PDCR_RXDSEL(dai_port); + dai_pdcr |= AUDMUX_PDCR_RXDSEL(ssi_port); + + /* set Tx frame direction and source dai_port--> ssi_port output */ + ssi_ptcr |= AUDMUX_PTCR_TFSDIR; + ssi_ptcr |= AUDMUX_PTCR_TFSSEL(AUDMUX_FROM_TXFS, dai_port); + + /* set Tx Clock direction and source dai_port--> ssi_port output */ + ssi_ptcr |= AUDMUX_PTCR_TCLKDIR; + ssi_ptcr |= AUDMUX_PTCR_TCSEL(AUDMUX_FROM_TXFS, dai_port); +#else + /* set Rx sources ssi_port <--> dai_port */ + ssi_pdcr |= AUDMUX_PDCR_RXDSEL(dai_port); + dai_pdcr |= AUDMUX_PDCR_RXDSEL(ssi_port); + + /* set Tx frame direction and source ssi_port --> dai_port output */ + dai_ptcr |= AUDMUX_PTCR_TFSDIR; + dai_ptcr |= AUDMUX_PTCR_TFSSEL(AUDMUX_FROM_TXFS, ssi_port); + + /* set Tx Clock direction and source ssi_port--> dai_port output */ + dai_ptcr |= AUDMUX_PTCR_TCLKDIR; + dai_ptcr |= AUDMUX_PTCR_TCSEL(AUDMUX_FROM_TXFS, ssi_port); +#endif + + __raw_writel(ssi_ptcr, DAM_PTCR(ssi_port)); + __raw_writel(dai_ptcr, DAM_PTCR(dai_port)); + __raw_writel(ssi_pdcr, DAM_PDCR(ssi_port)); + __raw_writel(dai_pdcr, DAM_PDCR(dai_port)); +} + +static int imx_3stack_bt_startup(struct snd_pcm_substream *substream) +{ + struct imx_3stack_priv *priv = &card_priv; + + if (!priv->active) + gpio_activate_bt_audio_port(); + priv->active++; + return 0; +} + +static int imx_3stack_bt_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai_link *pcm_link = rtd->dai; + struct snd_soc_dai *cpu_dai = pcm_link->cpu_dai; + unsigned int channels = params_channels(params); + struct imx_ssi *ssi_mode = (struct imx_ssi *)cpu_dai->private_data; + int ret = 0; + u32 dai_format; + +#if BT_SSI_MASTER + dai_format = SND_SOC_DAIFMT_LEFT_J | SND_SOC_DAIFMT_IB_IF | + SND_SOC_DAIFMT_CBM_CFM; +#else + dai_format = SND_SOC_DAIFMT_LEFT_J | SND_SOC_DAIFMT_IB_IF | + SND_SOC_DAIFMT_CBS_CFS; +#endif + + ssi_mode->sync_mode = 1; + if (channels == 1) + ssi_mode->network_mode = 0; + else + ssi_mode->network_mode = 1; + + /* set i.MX active slot mask */ + snd_soc_dai_set_tdm_slot(cpu_dai, + channels == 1 ? 0xfffffffe : 0xfffffffc, 2); + + /* set cpu DAI configuration */ + ret = snd_soc_dai_set_fmt(cpu_dai, dai_format); + if (ret < 0) + return ret; + + /* set the SSI system clock as input (unused) */ + snd_soc_dai_set_sysclk(cpu_dai, IMX_SSP_SYS_CLK, 0, SND_SOC_CLOCK_IN); + + return 0; +} + +static void imx_3stack_bt_shutdown(struct snd_pcm_substream *substream) +{ + struct imx_3stack_priv *priv = &card_priv; + + priv->active--; + if (!priv->active) + gpio_inactivate_bt_audio_port(); +} + +/* + * imx_3stack bt DAI opserations. + */ +static struct snd_soc_ops imx_3stack_bt_ops = { + .startup = imx_3stack_bt_startup, + .hw_params = imx_3stack_bt_hw_params, + .shutdown = imx_3stack_bt_shutdown, +}; + +static struct snd_soc_dai_link imx_3stack_dai = { + .name = "bluetooth", + .stream_name = "bluetooth", + .codec_dai = &bt_dai, + .ops = &imx_3stack_bt_ops, +}; + +static struct snd_soc_card snd_soc_card_imx_3stack = { + .name = "imx-3stack", + .platform = &imx_soc_platform, + .dai_link = &imx_3stack_dai, + .num_links = 1, +}; + +static struct snd_soc_device imx_3stack_snd_devdata = { + .card = &snd_soc_card_imx_3stack, + .codec_dev = &soc_codec_dev_bt, +}; + +/* + * This function will register the snd_soc_pcm_link drivers. + * It also registers devices for platform DMA, I2S, SSP and registers an + * I2C driver to probe the codec. + */ +static int __init imx_3stack_bt_probe(struct platform_device *pdev) +{ + struct mxc_audio_platform_data *dev_data = pdev->dev.platform_data; + struct imx_3stack_priv *priv = &card_priv; + struct snd_soc_dai *bt_cpu_dai; + + if (dev_data->src_port == 1) + bt_cpu_dai = imx_ssi_dai[0]; + else + bt_cpu_dai = imx_ssi_dai[2]; + + bt_cpu_dai->dev = &pdev->dev; + imx_3stack_dai.cpu_dai = bt_cpu_dai; + + /* Configure audio port */ + imx_3stack_init_dam(dev_data->src_port, dev_data->ext_port); + + priv->pdev = pdev; + priv->active = 0; + return 0; + +} + +static int __devexit imx_3stack_bt_remove(struct platform_device *pdev) +{ + return 0; +} + +static struct platform_driver imx_3stack_bt_driver = { + .probe = imx_3stack_bt_probe, + .remove = __devexit_p(imx_3stack_bt_remove), + .driver = { + .name = "imx-3stack-bt", + .owner = THIS_MODULE, + }, +}; + +static struct platform_device *imx_3stack_snd_device; + +static int __init imx_3stack_asoc_init(void) +{ + int ret; + + ret = platform_driver_register(&imx_3stack_bt_driver); + if (ret < 0) + goto exit; + imx_3stack_snd_device = platform_device_alloc("soc-audio", 4); + if (!imx_3stack_snd_device) + goto err_device_alloc; + platform_set_drvdata(imx_3stack_snd_device, &imx_3stack_snd_devdata); + imx_3stack_snd_devdata.dev = &imx_3stack_snd_device->dev; + ret = platform_device_add(imx_3stack_snd_device); + if (0 == ret) + goto exit; + + platform_device_put(imx_3stack_snd_device); +err_device_alloc: + platform_driver_unregister(&imx_3stack_bt_driver); +exit: + return ret; +} + +static void __exit imx_3stack_asoc_exit(void) +{ + platform_driver_unregister(&imx_3stack_bt_driver); + platform_device_unregister(imx_3stack_snd_device); +} + +module_init(imx_3stack_asoc_init); +module_exit(imx_3stack_asoc_exit); + +/* Module information */ +MODULE_DESCRIPTION("ALSA SoC bluetooth imx_3stack"); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/imx/imx-3stack-bt.h b/sound/soc/imx/imx-3stack-bt.h new file mode 100644 index 000000000000..50ff66bd738e --- /dev/null +++ b/sound/soc/imx/imx-3stack-bt.h @@ -0,0 +1,21 @@ +/* + * imx-3stack-bt.h -- Bluetooth PCM driver header file for Freescale IMX + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#ifndef _MXC_BTPCM_H +#define _MXC_BTPCM_H + +extern struct snd_soc_dai bt_dai; +extern struct snd_soc_codec_device soc_codec_dev_bt; +#endif diff --git a/sound/soc/imx/imx-3stack-cs42888.c b/sound/soc/imx/imx-3stack-cs42888.c new file mode 100644 index 000000000000..726bdfba063e --- /dev/null +++ b/sound/soc/imx/imx-3stack-cs42888.c @@ -0,0 +1,410 @@ +/* + * Copyright (C) 2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "imx-pcm.h" +#include "imx-esai.h" +#include "../codecs/cs42888.h" + +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) +#include +#endif + +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) +static unsigned int asrc_rates[] = { + 0, + 8000, + 11025, + 16000, + 22050, + 32000, + 44100, + 48000, + 64000, + 88200, + 96000, + 176400, + 192000, +}; + +struct asrc_esai { + unsigned int cpu_dai_rates; + unsigned int codec_dai_rates; + enum asrc_pair_index asrc_index; + unsigned int output_sample_rate; +}; + +static struct asrc_esai asrc_esai_data; + +#endif + +struct imx_3stack_pcm_state { + int lr_clk_active; +}; + +static struct imx_3stack_pcm_state clk_state; + +static int imx_3stack_startup(struct snd_pcm_substream *substream) +{ + clk_state.lr_clk_active++; +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) + if (asrc_esai_data.output_sample_rate >= 32000) { + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai_link *pcm_link = rtd->dai; + struct snd_soc_dai *cpu_dai = pcm_link->cpu_dai; + struct snd_soc_dai *codec_dai = pcm_link->codec_dai; + asrc_esai_data.cpu_dai_rates = cpu_dai->playback.rates; + asrc_esai_data.codec_dai_rates = codec_dai->playback.rates; + cpu_dai->playback.rates = + SNDRV_PCM_RATE_8000_192000 | SNDRV_PCM_RATE_KNOT; + codec_dai->playback.rates = + SNDRV_PCM_RATE_8000_192000 | SNDRV_PCM_RATE_KNOT; + } +#endif + + return 0; +} + +static void imx_3stack_shutdown(struct snd_pcm_substream *substream) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai_link *pcm_link = rtd->dai; + +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) + if (asrc_esai_data.output_sample_rate >= 32000) { + struct snd_soc_dai *cpu_dai = pcm_link->cpu_dai; + codec_dai->playback.rates = asrc_esai_data.codec_dai_rates; + cpu_dai->playback.rates = asrc_esai_data.cpu_dai_rates; + asrc_release_pair(asrc_esai_data.asrc_index); + } +#endif + + clk_state.lr_clk_active--; +} + +static int imx_3stack_surround_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai_link *pcm_link = rtd->dai; + struct snd_soc_dai *cpu_dai = pcm_link->cpu_dai; + struct snd_soc_dai *codec_dai = pcm_link->codec_dai; + unsigned int rate = params_rate(params); + u32 dai_format; + unsigned int mclk_freq = 0, lrclk_ratio = 0; + unsigned int channel = params_channels(params); + struct imx_esai *esai_mode = (struct imx_esai *)cpu_dai->private_data; + if (clk_state.lr_clk_active > 1) + return 0; + +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) + if (asrc_esai_data.output_sample_rate >= 32000) { + unsigned int asrc_input_rate = rate; + struct mxc_runtime_data *pcm_data = + substream->runtime->private_data; + struct asrc_config config; + int retVal = 0;; + + retVal = asrc_req_pair(channel, &asrc_esai_data.asrc_index); + if (retVal < 0) { + pr_err("Fail to request asrc pair\n"); + return -1; + } + + config.pair = asrc_esai_data.asrc_index; + config.channel_num = channel; + config.input_sample_rate = asrc_input_rate; + config.output_sample_rate = asrc_esai_data.output_sample_rate; + config.inclk = INCLK_NONE; + config.word_width = 32; + config.outclk = OUTCLK_ESAI_TX; + retVal = asrc_config_pair(&config); + if (retVal < 0) { + pr_err("Fail to config asrc\n"); + asrc_release_pair(asrc_esai_data.asrc_index); + return retVal; + } + rate = asrc_esai_data.output_sample_rate; + pcm_data->asrc_index = asrc_esai_data.asrc_index; + pcm_data->asrc_enable = 1; + } +#endif + + switch (rate) { + case 32000: + lrclk_ratio = 3; + mclk_freq = 12288000; + break; + case 48000: + lrclk_ratio = 3; + mclk_freq = 12288000; + break; + case 64000: + lrclk_ratio = 1; + mclk_freq = 12288000; + break; + case 96000: + lrclk_ratio = 1; + mclk_freq = 12288000; + break; + case 128000: + lrclk_ratio = 1; + mclk_freq = 12288000; + break; + case 44100: + lrclk_ratio = 3; + mclk_freq = 11289600; + break; + case 88200: + lrclk_ratio = 1; + mclk_freq = 11289600; + break; + case 176400: + lrclk_ratio = 0; + mclk_freq = 11289600; + break; + case 192000: + lrclk_ratio = 0; + mclk_freq = 12288000; + break; + default: + pr_info("Rate not support.\n"); + return -EINVAL;; + } + + dai_format = SND_SOC_DAIFMT_LEFT_J | SND_SOC_DAIFMT_NB_NF | + SND_SOC_DAIFMT_CBS_CFS; + + esai_mode->sync_mode = 0; + esai_mode->network_mode = 1; + + /* set cpu DAI configuration */ + snd_soc_dai_set_fmt(cpu_dai, dai_format); + /* set i.MX active slot mask */ + snd_soc_dai_set_tdm_slot(cpu_dai, channel == 1 ? 0x1 : 0x3, 2); + /* set the ESAI system clock as output */ + snd_soc_dai_set_sysclk(cpu_dai, ESAI_CLK_EXTAL, + mclk_freq, SND_SOC_CLOCK_OUT); + /* set the ratio */ + snd_soc_dai_set_clkdiv(cpu_dai, ESAI_TX_DIV_PSR, 1); + snd_soc_dai_set_clkdiv(cpu_dai, ESAI_TX_DIV_PM, 0); + snd_soc_dai_set_clkdiv(cpu_dai, ESAI_TX_DIV_FP, lrclk_ratio); + snd_soc_dai_set_clkdiv(cpu_dai, ESAI_RX_DIV_PSR, 1); + snd_soc_dai_set_clkdiv(cpu_dai, ESAI_RX_DIV_PM, 0); + snd_soc_dai_set_clkdiv(cpu_dai, ESAI_RX_DIV_FP, lrclk_ratio); + + + /* set codec DAI configuration */ + snd_soc_dai_set_fmt(codec_dai, dai_format); + /* set codec Master clock */ + snd_soc_dai_set_sysclk(codec_dai, 0, mclk_freq, SND_SOC_CLOCK_IN); + + return 0; +} + +static struct snd_soc_ops imx_3stack_surround_ops = { + .startup = imx_3stack_startup, + .shutdown = imx_3stack_shutdown, + .hw_params = imx_3stack_surround_hw_params, +}; + +static const struct snd_soc_dapm_widget imx_3stack_dapm_widgets[] = { + SND_SOC_DAPM_LINE("Line Out Jack", NULL), + SND_SOC_DAPM_LINE("Line In Jack", NULL), +}; + +static const struct snd_soc_dapm_route audio_map[] = { + /* Line out jack */ + {"Line Out Jack", NULL, "AOUT1L"}, + {"Line Out Jack", NULL, "AOUT1R"}, + {"Line Out Jack", NULL, "AOUT2L"}, + {"Line Out Jack", NULL, "AOUT2R"}, + {"Line Out Jack", NULL, "AOUT3L"}, + {"Line Out Jack", NULL, "AOUT3R"}, + {"Line Out Jack", NULL, "AOUT4L"}, + {"Line Out Jack", NULL, "AOUT4R"}, + {"AIN1L", NULL, "Line In Jack"}, + {"AIN1R", NULL, "Line In Jack"}, + {"AIN2L", NULL, "Line In Jack"}, + {"AIN2R", NULL, "Line In Jack"}, +}; + +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) +static int asrc_func; + +static const char *asrc_function[] = { + "disable", "32KHz", "44.1KHz", + "48KHz", "64KHz", "88.2KHz", "96KHz", "176.4KHz", "192KHz" +}; + +static const struct soc_enum asrc_enum[] = { + SOC_ENUM_SINGLE_EXT(9, asrc_function), +}; + +static int asrc_get_rate(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + ucontrol->value.enumerated.item[0] = asrc_func; + return 0; +} + +static int asrc_set_rate(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + if (asrc_func == ucontrol->value.enumerated.item[0]) + return 0; + + asrc_func = ucontrol->value.enumerated.item[0]; + asrc_esai_data.output_sample_rate = asrc_rates[asrc_func + 4]; + + return 1; +} + +static const struct snd_kcontrol_new asrc_controls[] = { + SOC_ENUM_EXT("ASRC", asrc_enum[0], asrc_get_rate, + asrc_set_rate), +}; + +#endif + +static int imx_3stack_cs42888_init(struct snd_soc_codec *codec) +{ + +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) + int i; + int ret; + for (i = 0; i < ARRAY_SIZE(asrc_controls); i++) { + ret = snd_ctl_add(codec->card, + snd_soc_cnew(&asrc_controls[i], codec, NULL)); + if (ret < 0) + return ret; + } + asrc_esai_data.output_sample_rate = asrc_rates[asrc_func + 4]; +#endif + + snd_soc_dapm_new_controls(codec, imx_3stack_dapm_widgets, + ARRAY_SIZE(imx_3stack_dapm_widgets)); + + snd_soc_dapm_add_routes(codec, audio_map, ARRAY_SIZE(audio_map)); + + snd_soc_dapm_sync(codec); + + return 0; +} + +static struct snd_soc_dai_link imx_3stack_dai = { + .name = "cs42888", + .stream_name = "cs42888", + .codec_dai = &cs42888_dai, + .init = imx_3stack_cs42888_init, + .ops = &imx_3stack_surround_ops, +}; + +static int imx_3stack_card_remove(struct platform_device *pdev) +{ + struct snd_soc_device *socdev = platform_get_drvdata(pdev); + kfree(socdev->codec_data); + return 0; +} + +static struct snd_soc_card snd_soc_card_imx_3stack = { + .name = "imx-3stack", + .platform = &imx_soc_platform, + .dai_link = &imx_3stack_dai, + .num_links = 1, + .remove = imx_3stack_card_remove, +}; + +static struct snd_soc_device imx_3stack_snd_devdata = { + .card = &snd_soc_card_imx_3stack, + .codec_dev = &soc_codec_device_cs42888, +}; + +/* + * This function will register the snd_soc_pcm_link drivers. + */ +static int __devinit imx_3stack_cs42888_probe(struct platform_device *pdev) +{ + imx_3stack_dai.cpu_dai = &imx_esai_dai[2]; + imx_3stack_dai.cpu_dai->dev = &pdev->dev; + + return 0; +} + +static int __devexit imx_3stack_cs42888_remove(struct platform_device *pdev) +{ + return 0; +} + +static struct platform_driver imx_3stack_cs42888_driver = { + .probe = imx_3stack_cs42888_probe, + .remove = __devexit_p(imx_3stack_cs42888_remove), + .driver = { + .name = "imx-3stack-cs42888", + .owner = THIS_MODULE, + }, +}; + +static struct platform_device *imx_3stack_snd_device; + +static int __init imx_3stack_asoc_init(void) +{ + int ret; + ret = platform_driver_register(&imx_3stack_cs42888_driver); + if (ret < 0) + goto exit; + + imx_3stack_snd_device = platform_device_alloc("soc-audio", 1); + if (!imx_3stack_snd_device) + goto err_device_alloc; + platform_set_drvdata(imx_3stack_snd_device, &imx_3stack_snd_devdata); + imx_3stack_snd_devdata.dev = &imx_3stack_snd_device->dev; + ret = platform_device_add(imx_3stack_snd_device); + if (0 == ret && snd_soc_card_imx_3stack.codec != NULL) + goto exit; + + platform_device_unregister(imx_3stack_snd_device); +err_device_alloc: + platform_driver_unregister(&imx_3stack_cs42888_driver); +exit: + return ret; +} + +static void __exit imx_3stack_asoc_exit(void) +{ + platform_driver_unregister(&imx_3stack_cs42888_driver); + platform_device_unregister(imx_3stack_snd_device); +} + +module_init(imx_3stack_asoc_init); +module_exit(imx_3stack_asoc_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("ALSA SoC cs42888 imx_3stack"); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/imx/imx-3stack-sgtl5000.c b/sound/soc/imx/imx-3stack-sgtl5000.c new file mode 100644 index 000000000000..16530d01904c --- /dev/null +++ b/sound/soc/imx/imx-3stack-sgtl5000.c @@ -0,0 +1,689 @@ +/* + * imx-3stack-sgtl5000.c -- i.MX 3Stack Driver for Freescale SGTL5000 Codec + * + * Copyright (C) 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * Revision history + * 21th Oct 2008 Initial version. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "../codecs/sgtl5000.h" +#include "imx-ssi.h" +#include "imx-pcm.h" + +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) +#include + +static unsigned int sgtl5000_rates[] = { + 0, + 32000, + 44100, + 48000, + 96000, +}; + +struct asrc_esai { + unsigned int cpu_dai_rates; + unsigned int codec_dai_rates; + enum asrc_pair_index asrc_index; + unsigned int output_sample_rate; +}; + +static struct asrc_esai asrc_ssi_data; +#endif + +/* SSI BCLK and LRC master */ +#define SGTL5000_SSI_MASTER 1 + +struct imx_3stack_priv { + int sysclk; + int hw; + struct platform_device *pdev; +}; + +static struct imx_3stack_priv card_priv; + +static int imx_3stack_audio_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai_link *machine = rtd->dai; + struct snd_soc_dai *cpu_dai = machine->cpu_dai; + struct snd_soc_dai *codec_dai = machine->codec_dai; + struct imx_3stack_priv *priv = &card_priv; + unsigned int rate = params_rate(params); + struct imx_ssi *ssi_mode = (struct imx_ssi *)cpu_dai->private_data; + int ret = 0; + + unsigned int channels = params_channels(params); + u32 dai_format; + + /* only need to do this once as capture and playback are sync */ + if (priv->hw) + return 0; + priv->hw = 1; + +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) + if ((asrc_ssi_data.output_sample_rate != 0) + && (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)) { + unsigned int asrc_input_rate = rate; + unsigned int channel = params_channels(params); + struct mxc_runtime_data *pcm_data = + substream->runtime->private_data; + struct asrc_config config; + struct mxc_audio_platform_data *plat; + struct imx_3stack_priv *priv = &card_priv; + int retVal = 0; + retVal = asrc_req_pair(channel, &asrc_ssi_data.asrc_index); + if (retVal < 0) { + pr_err("asrc_req_pair fail\n"); + return -1; + } + config.pair = asrc_ssi_data.asrc_index; + config.channel_num = channel; + config.input_sample_rate = asrc_input_rate; + config.output_sample_rate = asrc_ssi_data.output_sample_rate; + config.inclk = INCLK_NONE; + config.word_width = 32; + plat = priv->pdev->dev.platform_data; + if (plat->src_port == 1) + config.outclk = OUTCLK_SSI1_TX; + else + config.outclk = OUTCLK_SSI2_TX; + retVal = asrc_config_pair(&config); + if (retVal < 0) { + pr_err("Fail to config asrc\n"); + asrc_release_pair(asrc_ssi_data.asrc_index); + return retVal; + } + rate = asrc_ssi_data.output_sample_rate; + pcm_data->asrc_index = asrc_ssi_data.asrc_index; + pcm_data->asrc_enable = 1; + } +#endif + + snd_soc_dai_set_sysclk(codec_dai, SGTL5000_SYSCLK, priv->sysclk, 0); + snd_soc_dai_set_sysclk(codec_dai, SGTL5000_LRCLK, rate, 0); + +#if SGTL5000_SSI_MASTER + dai_format = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | + SND_SOC_DAIFMT_CBM_CFM; +#else + dai_format = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | + SND_SOC_DAIFMT_CBS_CFS; +#endif + + ssi_mode->sync_mode = 1; + if (channels == 1) + ssi_mode->network_mode = 0; + else + ssi_mode->network_mode = 1; + + /* set codec DAI configuration */ + ret = snd_soc_dai_set_fmt(codec_dai, dai_format); + if (ret < 0) + return ret; + + /* set i.MX active slot mask */ + snd_soc_dai_set_tdm_slot(cpu_dai, + channels == 1 ? 0xfffffffe : 0xfffffffc, 2); + + /* set cpu DAI configuration */ + ret = snd_soc_dai_set_fmt(cpu_dai, dai_format); + if (ret < 0) + return ret; + + /* set the SSI system clock as input (unused) */ + snd_soc_dai_set_sysclk(cpu_dai, IMX_SSP_SYS_CLK, 0, SND_SOC_CLOCK_IN); + + return 0; +} + +static int imx_3stack_startup(struct snd_pcm_substream *substream) +{ +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + if (asrc_ssi_data.output_sample_rate != 0) { + struct snd_soc_pcm_runtime *rtd = + substream->private_data; + struct snd_soc_dai_link *pcm_link = rtd->dai; + struct snd_soc_dai *cpu_dai = pcm_link->cpu_dai; + struct snd_soc_dai *codec_dai = pcm_link->codec_dai; + asrc_ssi_data.cpu_dai_rates = cpu_dai->playback.rates; + asrc_ssi_data.codec_dai_rates = + codec_dai->playback.rates; + cpu_dai->playback.rates = + SNDRV_PCM_RATE_8000_192000 | SNDRV_PCM_RATE_KNOT; + codec_dai->playback.rates = + SNDRV_PCM_RATE_8000_192000 | SNDRV_PCM_RATE_KNOT; + } + } +#endif + return 0; +} + +static void imx_3stack_shutdown(struct snd_pcm_substream *substream) +{ + struct imx_3stack_priv *priv = &card_priv; + +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + if (asrc_ssi_data.output_sample_rate != 0) { + struct snd_soc_pcm_runtime *rtd = + substream->private_data; + struct snd_soc_dai_link *pcm_link = rtd->dai; + struct snd_soc_dai *cpu_dai = pcm_link->cpu_dai; + struct snd_soc_dai *codec_dai = pcm_link->codec_dai; + codec_dai->playback.rates = + asrc_ssi_data.codec_dai_rates; + cpu_dai->playback.rates = asrc_ssi_data.cpu_dai_rates; + asrc_release_pair(asrc_ssi_data.asrc_index); + } + } +#endif + + priv->hw = 0; +} + +/* + * imx_3stack SGTL5000 audio DAI opserations. + */ +static struct snd_soc_ops imx_3stack_ops = { + .startup = imx_3stack_startup, + .shutdown = imx_3stack_shutdown, + .hw_params = imx_3stack_audio_hw_params, +}; + +static void imx_3stack_init_dam(int ssi_port, int dai_port) +{ + unsigned int ssi_ptcr = 0; + unsigned int dai_ptcr = 0; + unsigned int ssi_pdcr = 0; + unsigned int dai_pdcr = 0; + /* SGTL5000 uses SSI1 or SSI2 via AUDMUX port dai_port for audio */ + + /* reset port ssi_port & dai_port */ + __raw_writel(0, DAM_PTCR(ssi_port)); + __raw_writel(0, DAM_PTCR(dai_port)); + __raw_writel(0, DAM_PDCR(ssi_port)); + __raw_writel(0, DAM_PDCR(dai_port)); + + /* set to synchronous */ + ssi_ptcr |= AUDMUX_PTCR_SYN; + dai_ptcr |= AUDMUX_PTCR_SYN; + +#if SGTL5000_SSI_MASTER + /* set Rx sources ssi_port <--> dai_port */ + ssi_pdcr |= AUDMUX_PDCR_RXDSEL(dai_port); + dai_pdcr |= AUDMUX_PDCR_RXDSEL(ssi_port); + + /* set Tx frame direction and source dai_port--> ssi_port output */ + ssi_ptcr |= AUDMUX_PTCR_TFSDIR; + ssi_ptcr |= AUDMUX_PTCR_TFSSEL(AUDMUX_FROM_TXFS, dai_port); + + /* set Tx Clock direction and source dai_port--> ssi_port output */ + ssi_ptcr |= AUDMUX_PTCR_TCLKDIR; + ssi_ptcr |= AUDMUX_PTCR_TCSEL(AUDMUX_FROM_TXFS, dai_port); +#else + /* set Rx sources ssi_port <--> dai_port */ + ssi_pdcr |= AUDMUX_PDCR_RXDSEL(dai_port); + dai_pdcr |= AUDMUX_PDCR_RXDSEL(ssi_port); + + /* set Tx frame direction and source ssi_port --> dai_port output */ + dai_ptcr |= AUDMUX_PTCR_TFSDIR; + dai_ptcr |= AUDMUX_PTCR_TFSSEL(AUDMUX_FROM_TXFS, ssi_port); + + /* set Tx Clock direction and source ssi_port--> dai_port output */ + dai_ptcr |= AUDMUX_PTCR_TCLKDIR; + dai_ptcr |= AUDMUX_PTCR_TCSEL(AUDMUX_FROM_TXFS, ssi_port); +#endif + + __raw_writel(ssi_ptcr, DAM_PTCR(ssi_port)); + __raw_writel(dai_ptcr, DAM_PTCR(dai_port)); + __raw_writel(ssi_pdcr, DAM_PDCR(ssi_port)); + __raw_writel(dai_pdcr, DAM_PDCR(dai_port)); +} + +/* imx_3stack machine connections to the codec pins */ +static const struct snd_soc_dapm_route audio_map[] = { + + /* Mic Jack --> MIC_IN (with automatic bias) */ + {"MIC_IN", NULL, "Mic Jack"}, + + /* Line in Jack --> LINE_IN */ + {"LINE_IN", NULL, "Line In Jack"}, + + /* HP_OUT --> Headphone Jack */ + {"Headphone Jack", NULL, "HP_OUT"}, + + /* LINE_OUT --> Ext Speaker */ + {"Ext Spk", NULL, "LINE_OUT"}, +}; + +static int sgtl5000_jack_func; +static int sgtl5000_spk_func; +static int sgtl5000_line_in_func; + +static void headphone_detect_handler(struct work_struct *work) +{ + struct imx_3stack_priv *priv = &card_priv; + struct platform_device *pdev = priv->pdev; + struct mxc_audio_platform_data *plat = pdev->dev.platform_data; + int hp_status; + + sysfs_notify(&pdev->dev.kobj, NULL, "headphone"); + hp_status = plat->hp_status(); + if (hp_status) + set_irq_type(plat->hp_irq, IRQ_TYPE_EDGE_FALLING); + else + set_irq_type(plat->hp_irq, IRQ_TYPE_EDGE_RISING); + enable_irq(plat->hp_irq); +} + +static DECLARE_DELAYED_WORK(hp_event, headphone_detect_handler); + +static irqreturn_t imx_headphone_detect_handler(int irq, void *data) +{ + disable_irq_nosync(irq); + schedule_delayed_work(&hp_event, msecs_to_jiffies(200)); + return IRQ_HANDLED; +} + +static ssize_t show_headphone(struct device_driver *dev, char *buf) +{ + struct imx_3stack_priv *priv = &card_priv; + struct platform_device *pdev = priv->pdev; + struct mxc_audio_platform_data *plat = pdev->dev.platform_data; + u16 hp_status; + + /* determine whether hp is plugged in */ + hp_status = plat->hp_status(); + + if (hp_status == 0) + strcpy(buf, "speaker\n"); + else + strcpy(buf, "headphone\n"); + + return strlen(buf); +} + +static DRIVER_ATTR(headphone, S_IRUGO | S_IWUSR, show_headphone, NULL); + +static const char *jack_function[] = { "off", "on"}; + +static const char *spk_function[] = { "off", "on" }; + +static const char *line_in_function[] = { "off", "on" }; + +static const struct soc_enum sgtl5000_enum[] = { + SOC_ENUM_SINGLE_EXT(2, jack_function), + SOC_ENUM_SINGLE_EXT(2, spk_function), + SOC_ENUM_SINGLE_EXT(2, line_in_function), +}; + +static int sgtl5000_get_jack(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + ucontrol->value.enumerated.item[0] = sgtl5000_jack_func; + return 0; +} + +static int sgtl5000_set_jack(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); + + if (sgtl5000_jack_func == ucontrol->value.enumerated.item[0]) + return 0; + + sgtl5000_jack_func = ucontrol->value.enumerated.item[0]; + if (sgtl5000_jack_func) + snd_soc_dapm_enable_pin(codec, "Headphone Jack"); + else + snd_soc_dapm_disable_pin(codec, "Headphone Jack"); + + snd_soc_dapm_sync(codec); + return 1; +} + +static int sgtl5000_get_spk(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + ucontrol->value.enumerated.item[0] = sgtl5000_spk_func; + return 0; +} + +static int sgtl5000_set_spk(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); + + if (sgtl5000_spk_func == ucontrol->value.enumerated.item[0]) + return 0; + + sgtl5000_spk_func = ucontrol->value.enumerated.item[0]; + if (sgtl5000_spk_func) + snd_soc_dapm_enable_pin(codec, "Ext Spk"); + else + snd_soc_dapm_disable_pin(codec, "Ext Spk"); + + snd_soc_dapm_sync(codec); + return 1; +} + +static int sgtl5000_get_line_in(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + ucontrol->value.enumerated.item[0] = sgtl5000_line_in_func; + return 0; +} + +static int sgtl5000_set_line_in(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); + + if (sgtl5000_line_in_func == ucontrol->value.enumerated.item[0]) + return 0; + + sgtl5000_line_in_func = ucontrol->value.enumerated.item[0]; + if (sgtl5000_line_in_func) + snd_soc_dapm_enable_pin(codec, "Line In Jack"); + else + snd_soc_dapm_disable_pin(codec, "Line In Jack"); + + snd_soc_dapm_sync(codec); + return 1; +} + +static int spk_amp_event(struct snd_soc_dapm_widget *w, + struct snd_kcontrol *kcontrol, int event) +{ + struct imx_3stack_priv *priv = &card_priv; + struct platform_device *pdev = priv->pdev; + struct mxc_audio_platform_data *plat = pdev->dev.platform_data; + + if (plat->amp_enable == NULL) + return 0; + + if (SND_SOC_DAPM_EVENT_ON(event)) + plat->amp_enable(1); + else + plat->amp_enable(0); + + return 0; +} + +/* imx_3stack card dapm widgets */ +static const struct snd_soc_dapm_widget imx_3stack_dapm_widgets[] = { + SND_SOC_DAPM_MIC("Mic Jack", NULL), + SND_SOC_DAPM_LINE("Line In Jack", NULL), + SND_SOC_DAPM_SPK("Ext Spk", spk_amp_event), + SND_SOC_DAPM_HP("Headphone Jack", NULL), +}; + +static const struct snd_kcontrol_new sgtl5000_machine_controls[] = { + SOC_ENUM_EXT("Jack Function", sgtl5000_enum[0], sgtl5000_get_jack, + sgtl5000_set_jack), + SOC_ENUM_EXT("Speaker Function", sgtl5000_enum[1], sgtl5000_get_spk, + sgtl5000_set_spk), + SOC_ENUM_EXT("Line In Function", sgtl5000_enum[1], sgtl5000_get_line_in, + sgtl5000_set_line_in), +}; + +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) +static int asrc_func; + +static const char *asrc_function[] = { + "disable", "32KHz", "44.1KHz", "48KHz", "96KHz" }; + +static const struct soc_enum asrc_enum[] = { + SOC_ENUM_SINGLE_EXT(5, asrc_function), +}; + +static int asrc_get_rate(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + ucontrol->value.enumerated.item[0] = asrc_func; + return 0; +} + +static int asrc_set_rate(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + if (asrc_func == ucontrol->value.enumerated.item[0]) + return 0; + + asrc_func = ucontrol->value.enumerated.item[0]; + asrc_ssi_data.output_sample_rate = sgtl5000_rates[asrc_func]; + + return 1; +} + +static const struct snd_kcontrol_new asrc_controls[] = { + SOC_ENUM_EXT("ASRC", asrc_enum[0], asrc_get_rate, + asrc_set_rate), +}; +#endif + +static int imx_3stack_sgtl5000_init(struct snd_soc_codec *codec) +{ + int i, ret; + +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) + for (i = 0; i < ARRAY_SIZE(asrc_controls); i++) { + ret = snd_ctl_add(codec->card, + snd_soc_cnew(&asrc_controls[i], codec, NULL)); + if (ret < 0) + return ret; + } + asrc_ssi_data.output_sample_rate = sgtl5000_rates[asrc_func]; +#endif + + /* Add imx_3stack specific controls */ + for (i = 0; i < ARRAY_SIZE(sgtl5000_machine_controls); i++) { + ret = snd_ctl_add(codec->card, + snd_soc_cnew(&sgtl5000_machine_controls[i], + codec, NULL)); + if (ret < 0) + return ret; + } + + /* Add imx_3stack specific widgets */ + snd_soc_dapm_new_controls(codec, imx_3stack_dapm_widgets, + ARRAY_SIZE(imx_3stack_dapm_widgets)); + + /* Set up imx_3stack specific audio path audio_map */ + snd_soc_dapm_add_routes(codec, audio_map, ARRAY_SIZE(audio_map)); + + snd_soc_dapm_disable_pin(codec, "Line In Jack"); + + snd_soc_dapm_sync(codec); + + return 0; +} + +/* imx_3stack digital audio interface glue - connects codec <--> CPU */ +static struct snd_soc_dai_link imx_3stack_dai = { + .name = "SGTL5000", + .stream_name = "SGTL5000", + .codec_dai = &sgtl5000_dai, + .init = imx_3stack_sgtl5000_init, + .ops = &imx_3stack_ops, +}; + +static int imx_3stack_card_remove(struct platform_device *pdev) +{ + struct imx_3stack_priv *priv = &card_priv; + struct mxc_audio_platform_data *plat; + if (priv->pdev) { + plat = priv->pdev->dev.platform_data; + if (plat->finit) + plat->finit(); + } + + return 0; +} + +static struct snd_soc_card snd_soc_card_imx_3stack = { + .name = "imx-3stack", + .platform = &imx_soc_platform, + .dai_link = &imx_3stack_dai, + .num_links = 1, + .remove = imx_3stack_card_remove, +}; + +static struct snd_soc_device imx_3stack_snd_devdata = { + .card = &snd_soc_card_imx_3stack, + .codec_dev = &soc_codec_dev_sgtl5000, +}; + +static int __devinit imx_3stack_sgtl5000_probe(struct platform_device *pdev) +{ + struct mxc_audio_platform_data *plat = pdev->dev.platform_data; + struct imx_3stack_priv *priv = &card_priv; + struct snd_soc_dai *sgtl5000_cpu_dai; + int ret = 0; + + priv->pdev = pdev; + + gpio_activate_audio_ports(); + imx_3stack_init_dam(plat->src_port, plat->ext_port); + + if (plat->src_port == 2) + sgtl5000_cpu_dai = imx_ssi_dai[2]; + else + sgtl5000_cpu_dai = imx_ssi_dai[0]; + + imx_3stack_dai.cpu_dai = sgtl5000_cpu_dai; + + ret = driver_create_file(pdev->dev.driver, &driver_attr_headphone); + if (ret < 0) { + pr_err("%s:failed to create driver_attr_headphone\n", __func__); + goto sysfs_err; + } + + ret = -EINVAL; + if (plat->init && plat->init()) + goto err_plat_init; + + priv->sysclk = plat->sysclk; + + /* The SGTL5000 has an internal reset that is deasserted 8 SYS_MCLK + cycles after all power rails have been brought up. After this time + communication can start */ + + if (plat->hp_status()) + ret = request_irq(plat->hp_irq, + imx_headphone_detect_handler, + IRQ_TYPE_EDGE_FALLING, pdev->name, priv); + else + ret = request_irq(plat->hp_irq, + imx_headphone_detect_handler, + IRQ_TYPE_EDGE_RISING, pdev->name, priv); + if (ret < 0) { + pr_err("%s: request irq failed\n", __func__); + goto err_card_reg; + } + + sgtl5000_jack_func = 1; + sgtl5000_spk_func = 1; + sgtl5000_line_in_func = 0; + + return 0; + +err_card_reg: + if (plat->finit) + plat->finit(); +err_plat_init: + driver_remove_file(pdev->dev.driver, &driver_attr_headphone); +sysfs_err: + return ret; +} + +static int imx_3stack_sgtl5000_remove(struct platform_device *pdev) +{ + struct mxc_audio_platform_data *plat = pdev->dev.platform_data; + struct imx_3stack_priv *priv = &card_priv; + + free_irq(plat->hp_irq, priv); + + if (plat->finit) + plat->finit(); + + driver_remove_file(pdev->dev.driver, &driver_attr_headphone); + + return 0; +} + +static struct platform_driver imx_3stack_sgtl5000_audio_driver = { + .probe = imx_3stack_sgtl5000_probe, + .remove = imx_3stack_sgtl5000_remove, + .driver = { + .name = "imx-3stack-sgtl5000", + }, +}; + +static struct platform_device *imx_3stack_snd_device; + +static int __init imx_3stack_init(void) +{ + int ret; + + ret = platform_driver_register(&imx_3stack_sgtl5000_audio_driver); + if (ret) + return -ENOMEM; + + imx_3stack_snd_device = platform_device_alloc("soc-audio", 2); + if (!imx_3stack_snd_device) + return -ENOMEM; + + platform_set_drvdata(imx_3stack_snd_device, &imx_3stack_snd_devdata); + imx_3stack_snd_devdata.dev = &imx_3stack_snd_device->dev; + ret = platform_device_add(imx_3stack_snd_device); + + if (ret) + platform_device_put(imx_3stack_snd_device); + + return ret; +} + +static void __exit imx_3stack_exit(void) +{ + platform_driver_unregister(&imx_3stack_sgtl5000_audio_driver); + platform_device_unregister(imx_3stack_snd_device); +} + +module_init(imx_3stack_init); +module_exit(imx_3stack_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("SGTL5000 Driver for i.MX 3STACK"); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/imx/imx-3stack-wm8350.c b/sound/soc/imx/imx-3stack-wm8350.c new file mode 100644 index 000000000000..1cd51d31e128 --- /dev/null +++ b/sound/soc/imx/imx-3stack-wm8350.c @@ -0,0 +1,696 @@ +/* + * imx-3stack-wm8350.c -- i.MX 3Stack Driver for Wolfson WM8350 Codec + * + * Copyright 2007 Wolfson Microelectronics PLC. + * Copyright (C) 2007-2010 Freescale Semiconductor, Inc. + * + * Author: Liam Girdwood + * liam.girdwood@wolfsonmicro.com or linux@wolfsonmicro.com + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * Revision history + * 19th Jun 2007 Initial version. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "../codecs/wm8350.h" +#include "imx-ssi.h" +#include "imx-pcm.h" + +void gpio_activate_audio_ports(void); + +/* SSI BCLK and LRC master */ +#define WM8350_SSI_MASTER 1 + +struct imx_3stack_priv { + int lr_clk_active; + int playback_active; + int capture_active; + struct platform_device *pdev; + struct wm8350 *wm8350; +}; + +static struct imx_3stack_priv machine_priv; + +struct _wm8350_audio { + unsigned int channels; + snd_pcm_format_t format; + unsigned int rate; + unsigned int sysclk; + unsigned int bclkdiv; + unsigned int clkdiv; + unsigned int lr_rate; +}; + +/* in order of power consumption per rate (lowest first) */ +static const struct _wm8350_audio wm8350_audio[] = { + /* 16bit mono modes */ + + {1, SNDRV_PCM_FORMAT_S16_LE, 8000, 12288000, + WM8350_BCLK_DIV_48, WM8350_DACDIV_6, 32,}, + {1, SNDRV_PCM_FORMAT_S16_LE, 16000, 12288000, + WM8350_BCLK_DIV_24, WM8350_DACDIV_6, 32,}, + {1, SNDRV_PCM_FORMAT_S16_LE, 32000, 12288000, + WM8350_BCLK_DIV_12, WM8350_DACDIV_3, 32,}, + {1, SNDRV_PCM_FORMAT_S16_LE, 48000, 12288000, + WM8350_BCLK_DIV_8, WM8350_DACDIV_2, 32,}, + {1, SNDRV_PCM_FORMAT_S16_LE, 96000, 24576000, + WM8350_BCLK_DIV_8, WM8350_DACDIV_2, 32,}, + {1, SNDRV_PCM_FORMAT_S16_LE, 11025, 11289600, + WM8350_BCLK_DIV_32, WM8350_DACDIV_4, 32,}, + {1, SNDRV_PCM_FORMAT_S16_LE, 22050, 11289600, + WM8350_BCLK_DIV_16, WM8350_DACDIV_4, 32,}, + {1, SNDRV_PCM_FORMAT_S16_LE, 44100, 11289600, + WM8350_BCLK_DIV_8, WM8350_DACDIV_2, 32,}, + {1, SNDRV_PCM_FORMAT_S16_LE, 88200, 22579200, + WM8350_BCLK_DIV_8, WM8350_DACDIV_2, 32,}, + + /* 16 bit stereo modes */ + {2, SNDRV_PCM_FORMAT_S16_LE, 8000, 12288000, + WM8350_BCLK_DIV_48, WM8350_DACDIV_6, 32,}, + {2, SNDRV_PCM_FORMAT_S16_LE, 16000, 12288000, + WM8350_BCLK_DIV_24, WM8350_DACDIV_3, 32,}, + {2, SNDRV_PCM_FORMAT_S16_LE, 32000, 12288000, + WM8350_BCLK_DIV_12, WM8350_DACDIV_1_5, 32,}, + {2, SNDRV_PCM_FORMAT_S16_LE, 48000, 12288000, + WM8350_BCLK_DIV_8, WM8350_DACDIV_1, 32,}, + {2, SNDRV_PCM_FORMAT_S16_LE, 96000, 24576000, + WM8350_BCLK_DIV_8, WM8350_DACDIV_1, 32,}, + {2, SNDRV_PCM_FORMAT_S16_LE, 11025, 11289600, + WM8350_BCLK_DIV_32, WM8350_DACDIV_4, 32,}, + {2, SNDRV_PCM_FORMAT_S16_LE, 22050, 11289600, + WM8350_BCLK_DIV_16, WM8350_DACDIV_2, 32,}, + {2, SNDRV_PCM_FORMAT_S16_LE, 44100, 11289600, + WM8350_BCLK_DIV_8, WM8350_DACDIV_1, 32,}, + {2, SNDRV_PCM_FORMAT_S16_LE, 88200, 22579200, + WM8350_BCLK_DIV_8, WM8350_DACDIV_1, 32,}, + + /* 24bit stereo modes */ + {2, SNDRV_PCM_FORMAT_S24_LE, 48000, 12288000, + WM8350_BCLK_DIV_4, WM8350_DACDIV_1, 64,}, + {2, SNDRV_PCM_FORMAT_S24_LE, 96000, 24576000, + WM8350_BCLK_DIV_4, WM8350_DACDIV_1, 64,}, + {2, SNDRV_PCM_FORMAT_S24_LE, 44100, 11289600, + WM8350_BCLK_DIV_4, WM8350_DACDIV_1, 64,}, + {2, SNDRV_PCM_FORMAT_S24_LE, 88200, 22579200, + WM8350_BCLK_DIV_4, WM8350_DACDIV_1, 64,}, +}; + +#if WM8350_SSI_MASTER +static int imx_3stack_startup(struct snd_pcm_substream *substream) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_codec *codec = rtd->socdev->card->codec; + struct wm8350 *wm8350 = codec->control_data; + struct imx_3stack_priv *priv = &machine_priv; + + /* In master mode the LR clock can come from either the DAC or ADC. + * We use the LR clock from whatever stream is enabled first. + */ + + if (!priv->lr_clk_active) { + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) + wm8350_clear_bits(wm8350, WM8350_CLOCK_CONTROL_2, + WM8350_LRC_ADC_SEL); + else + wm8350_set_bits(wm8350, WM8350_CLOCK_CONTROL_2, + WM8350_LRC_ADC_SEL); + } + priv->lr_clk_active++; + if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) + priv->capture_active = 1; + else + priv->playback_active = 1; + return 0; +} +#else +#define imx_3stack_startup NULL +#endif + +static int imx_3stack_audio_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai_link *machine = rtd->dai; + struct snd_soc_dai *cpu_dai = machine->cpu_dai; + struct snd_soc_dai *codec_dai = machine->codec_dai; + struct imx_3stack_priv *priv = &machine_priv; + int ret = 0; + int i, found = 0; + snd_pcm_format_t format = params_format(params); + unsigned int rate = params_rate(params); + unsigned int channels = params_channels(params); + struct imx_ssi *ssi_mode = (struct imx_ssi *)cpu_dai->private_data; + u32 dai_format; + + /* only need to do this once as capture and playback are sync */ + if (priv->lr_clk_active > 1) + return 0; + + /* find the correct audio parameters */ + for (i = 0; i < ARRAY_SIZE(wm8350_audio); i++) { + if (rate == wm8350_audio[i].rate && + format == wm8350_audio[i].format && + channels == wm8350_audio[i].channels) { + found = 1; + break; + } + } + if (!found) { + printk(KERN_ERR "%s: invalid params\n", __func__); + return -EINVAL; + } + +#if WM8350_SSI_MASTER + /* codec FLL input is 32768 kHz from MCLK */ + snd_soc_dai_set_pll(codec_dai, 0, 32768, wm8350_audio[i].sysclk); +#else + /* codec FLL input is rate from DAC LRC */ + snd_soc_dai_set_pll(codec_dai, 0, rate, wm8350_audio[i].sysclk); +#endif + +#if WM8350_SSI_MASTER + dai_format = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | + SND_SOC_DAIFMT_CBM_CFM; + + ssi_mode->sync_mode = 1; + if (channels == 1) + ssi_mode->network_mode = 0; + else + ssi_mode->network_mode = 1; + + /* set codec DAI configuration */ + ret = snd_soc_dai_set_fmt(codec_dai, dai_format); + if (ret < 0) + return ret; + + /* set cpu DAI configuration */ + if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) { + dai_format &= ~SND_SOC_DAIFMT_INV_MASK; + /* Invert frame to switch mic from right channel to left */ + dai_format |= SND_SOC_DAIFMT_NB_IF; + } + + /* set i.MX active slot mask */ + snd_soc_dai_set_tdm_slot(cpu_dai, + channels == 1 ? 0xfffffffe : 0xfffffffc, + channels); + + ret = snd_soc_dai_set_fmt(cpu_dai, dai_format); + if (ret < 0) + return ret; + + /* set 32KHZ as the codec system clock for DAC and ADC */ + snd_soc_dai_set_sysclk(codec_dai, WM8350_MCLK_SEL_PLL_32K, + wm8350_audio[i].sysclk, SND_SOC_CLOCK_IN); +#else + dai_format = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | + SND_SOC_DAIFMT_CBS_CFS; + + /* set codec DAI configuration */ + ret = snd_soc_dai_set_fmt(codec_dai, dai_format); + if (ret < 0) + return ret; + + /* set i.MX active slot mask */ + snd_soc_dai_set_tdm_slot(cpu_dai, + channels == 1 ? 0xfffffffe : 0xfffffffc, + channels); + + /* set cpu DAI configuration */ + ret = snd_soc_dai_set_fmt(cpu_dai, dai_format); + if (ret < 0) + return ret; + + /* set DAC LRC as the codec system clock for DAC and ADC */ + snd_soc_dai_set_sysclk(codec_dai, WM8350_MCLK_SEL_PLL_DAC, + wm8350_audio[i].sysclk, SND_SOC_CLOCK_IN); +#endif + + /* set the SSI system clock as input (unused) */ + snd_soc_dai_set_sysclk(cpu_dai, IMX_SSP_SYS_CLK, 0, SND_SOC_CLOCK_IN); + + /* set codec BCLK division for sample rate */ + snd_soc_dai_set_clkdiv(codec_dai, WM8350_BCLK_CLKDIV, + wm8350_audio[i].bclkdiv); + + /* DAI is synchronous and clocked with DAC LRCLK & ADC LRC */ + snd_soc_dai_set_clkdiv(codec_dai, + WM8350_DACLR_CLKDIV, + wm8350_audio[i].lr_rate); + snd_soc_dai_set_clkdiv(codec_dai, + WM8350_ADCLR_CLKDIV, + wm8350_audio[i].lr_rate); + + /* now configure DAC and ADC clocks */ + snd_soc_dai_set_clkdiv(codec_dai, + WM8350_DAC_CLKDIV, wm8350_audio[i].clkdiv); + + snd_soc_dai_set_clkdiv(codec_dai, + WM8350_ADC_CLKDIV, wm8350_audio[i].clkdiv); + + return 0; +} + +static void imx_3stack_shutdown(struct snd_pcm_substream *substream) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_codec *codec = rtd->socdev->card->codec; + struct snd_soc_dai_link *machine = rtd->dai; + struct snd_soc_dai *codec_dai = machine->codec_dai; + struct imx_3stack_priv *priv = &machine_priv; + struct wm8350 *wm8350 = codec->control_data; + + /* disable the PLL if there are no active Tx or Rx channels */ + if (!codec_dai->active) + snd_soc_dai_set_pll(codec_dai, 0, 0, 0); + priv->lr_clk_active--; + + /* + * We need to keep track of active streams in master mode and + * switch LRC source if necessary. + */ + + if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) + priv->capture_active = 0; + else + priv->playback_active = 0; + + if (priv->capture_active) + wm8350_set_bits(wm8350, WM8350_CLOCK_CONTROL_2, + WM8350_LRC_ADC_SEL); + else if (priv->playback_active) + wm8350_clear_bits(wm8350, WM8350_CLOCK_CONTROL_2, + WM8350_LRC_ADC_SEL); +} + +/* + * imx_3stack WM8350 HiFi DAI operations. + */ +static struct snd_soc_ops imx_3stack_ops = { + .startup = imx_3stack_startup, + .shutdown = imx_3stack_shutdown, + .hw_params = imx_3stack_audio_hw_params, +}; + +static void imx_3stack_init_dam(int ssi_port, int dai_port) +{ + unsigned int ssi_ptcr = 0; + unsigned int dai_ptcr = 0; + unsigned int ssi_pdcr = 0; + unsigned int dai_pdcr = 0; + /* WM8350 uses SSI1 or SSI2 via AUDMUX port dai_port for audio */ + + /* reset port ssi_port & dai_port */ + __raw_writel(0, DAM_PTCR(ssi_port)); + __raw_writel(0, DAM_PTCR(dai_port)); + __raw_writel(0, DAM_PDCR(ssi_port)); + __raw_writel(0, DAM_PDCR(dai_port)); + + /* set to synchronous */ + ssi_ptcr |= AUDMUX_PTCR_SYN; + dai_ptcr |= AUDMUX_PTCR_SYN; + +#if WM8350_SSI_MASTER + /* set Rx sources ssi_port <--> dai_port */ + ssi_pdcr |= AUDMUX_PDCR_RXDSEL(dai_port); + dai_pdcr |= AUDMUX_PDCR_RXDSEL(ssi_port); + + /* set Tx frame direction and source dai_port--> ssi_port output */ + ssi_ptcr |= AUDMUX_PTCR_TFSDIR; + ssi_ptcr |= AUDMUX_PTCR_TFSSEL(AUDMUX_FROM_TXFS, dai_port); + + /* set Tx Clock direction and source dai_port--> ssi_port output */ + ssi_ptcr |= AUDMUX_PTCR_TCLKDIR; + ssi_ptcr |= AUDMUX_PTCR_TCSEL(AUDMUX_FROM_TXFS, dai_port); +#else + /* set Rx sources ssi_port <--> dai_port */ + ssi_pdcr |= AUDMUX_PDCR_RXDSEL(dai_port); + dai_pdcr |= AUDMUX_PDCR_RXDSEL(ssi_port); + + /* set Tx frame direction and source ssi_port --> dai_port output */ + dai_ptcr |= AUDMUX_PTCR_TFSDIR; + dai_ptcr |= AUDMUX_PTCR_TFSSEL(AUDMUX_FROM_TXFS, ssi_port); + + /* set Tx Clock direction and source ssi_port--> dai_port output */ + dai_ptcr |= AUDMUX_PTCR_TCLKDIR; + dai_ptcr |= AUDMUX_PTCR_TCSEL(AUDMUX_FROM_TXFS, ssi_port); +#endif + + __raw_writel(ssi_ptcr, DAM_PTCR(ssi_port)); + __raw_writel(dai_ptcr, DAM_PTCR(dai_port)); + __raw_writel(ssi_pdcr, DAM_PDCR(ssi_port)); + __raw_writel(dai_pdcr, DAM_PDCR(dai_port)); +} + +static const struct snd_soc_dapm_route audio_map[] = { + /* SiMIC --> IN1LN (with automatic bias) via SP1 */ + {"IN1RP", NULL, "Mic Bias"}, + {"Mic Bias", NULL, "SiMIC"}, + + /* Mic 1 Jack --> IN1LN and IN1LP (with automatic bias) */ + {"IN1LN", NULL, "Mic Bias"}, + {"IN1LP", NULL, "Mic1 Jack"}, + {"Mic Bias", NULL, "Mic1 Jack"}, + + /* Mic 2 Jack --> IN1RN and IN1RP (with automatic bias) */ + {"IN1RN", NULL, "Mic2 Jack"}, + {"IN1RP", NULL, "Mic Bias"}, + {"Mic Bias", NULL, "Mic2 Jack"}, + + /* Line in Jack --> AUX (L+R) */ + {"IN3R", NULL, "Line In Jack"}, + {"IN3L", NULL, "Line In Jack"}, + + /* Out1 --> Headphone Jack */ + {"Headphone Jack", NULL, "OUT1R"}, + {"Headphone Jack", NULL, "OUT1L"}, + + /* Out1 --> Line Out Jack */ + {"Line Out Jack", NULL, "OUT2R"}, + {"Line Out Jack", NULL, "OUT2L"}, +}; + +static int wm8350_jack_func; +static int wm8350_spk_func; + +static void headphone_detect_handler(struct work_struct *work) +{ + struct imx_3stack_priv *priv = &machine_priv; + struct platform_device *pdev = priv->pdev; + struct wm8350 *wm8350 = priv->wm8350; + + sysfs_notify(&pdev->dev.kobj, NULL, "headphone"); + wm8350_unmask_irq(wm8350, WM8350_IRQ_CODEC_JCK_DET_R); +} + +static DECLARE_DELAYED_WORK(hp_event, headphone_detect_handler); + +static void imx_3stack_jack_handler(struct wm8350 *wm8350, int irq, void *data) +{ + wm8350_mask_irq(wm8350, WM8350_IRQ_CODEC_JCK_DET_R); + schedule_delayed_work(&hp_event, msecs_to_jiffies(200)); +} + +static ssize_t show_headphone(struct device_driver *dev, char *buf) +{ + struct imx_3stack_priv *priv = &machine_priv; + u16 reg; + + reg = wm8350_reg_read(priv->wm8350, WM8350_JACK_PIN_STATUS); + + if (reg & WM8350_JACK_R_LVL) + strcpy(buf, "speaker\n"); + else + strcpy(buf, "headphone\n"); + + return strlen(buf); +} + +static DRIVER_ATTR(headphone, S_IRUGO | S_IWUSR, show_headphone, NULL); + +static const char *jack_function[] = { "off", "on" +}; + +static const char *spk_function[] = { "off", "on" }; + +static const struct soc_enum wm8350_enum[] = { + SOC_ENUM_SINGLE_EXT(2, jack_function), + SOC_ENUM_SINGLE_EXT(2, spk_function), +}; + +static int wm8350_get_jack(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + ucontrol->value.enumerated.item[0] = wm8350_jack_func; + return 0; +} + +static int wm8350_set_jack(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); + + if (wm8350_jack_func == ucontrol->value.enumerated.item[0]) + return 0; + + wm8350_jack_func = ucontrol->value.enumerated.item[0]; + if (wm8350_jack_func) + snd_soc_dapm_enable_pin(codec, "Headphone Jack"); + else + snd_soc_dapm_disable_pin(codec, "Headphone Jack"); + + snd_soc_dapm_sync(codec); + return 1; +} + +static int wm8350_get_spk(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + ucontrol->value.enumerated.item[0] = wm8350_spk_func; + return 0; +} + +static int wm8350_set_spk(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); + + if (wm8350_spk_func == ucontrol->value.enumerated.item[0]) + return 0; + + wm8350_spk_func = ucontrol->value.enumerated.item[0]; + if (wm8350_spk_func) + snd_soc_dapm_enable_pin(codec, "Line Out Jack"); + else + snd_soc_dapm_disable_pin(codec, "Line Out Jack"); + + snd_soc_dapm_sync(codec); + return 1; +} + +static int spk_amp_event(struct snd_soc_dapm_widget *w, + struct snd_kcontrol *kcontrol, int event) +{ + struct imx_3stack_priv *priv = &machine_priv; + struct platform_device *pdev = priv->pdev; + struct mxc_audio_platform_data *plat = pdev->dev.platform_data; + + if (plat->amp_enable == NULL) + return 0; + + if (SND_SOC_DAPM_EVENT_ON(event)) + plat->amp_enable(1); + else + plat->amp_enable(0); + + return 0; +} + +static const struct snd_soc_dapm_widget imx_3stack_dapm_widgets[] = { + SND_SOC_DAPM_MIC("SiMIC", NULL), + SND_SOC_DAPM_MIC("Mic1 Jack", NULL), + SND_SOC_DAPM_MIC("Mic2 Jack", NULL), + SND_SOC_DAPM_LINE("Line In Jack", NULL), + SND_SOC_DAPM_LINE("Line Out Jack", NULL), + SND_SOC_DAPM_SPK("Ext Spk", spk_amp_event), + SND_SOC_DAPM_HP("Headphone Jack", NULL), +}; + +static const struct snd_kcontrol_new wm8350_machine_controls[] = { + SOC_ENUM_EXT("Jack Function", wm8350_enum[0], wm8350_get_jack, + wm8350_set_jack), + SOC_ENUM_EXT("Speaker Function", wm8350_enum[1], wm8350_get_spk, + wm8350_set_spk), +}; + +static int imx_3stack_wm8350_init(struct snd_soc_codec *codec) +{ + struct imx_3stack_priv *priv = &machine_priv; + struct wm8350 *wm8350 = priv->wm8350; + int i, ret; + + codec->control_data = wm8350; + + /* Add imx_3stack specific controls */ + for (i = 0; i < ARRAY_SIZE(wm8350_machine_controls); i++) { + ret = snd_ctl_add(codec->card, + snd_soc_cnew(&wm8350_machine_controls[i], + codec, NULL)); + if (ret < 0) + return ret; + } + + /* Add imx_3stack specific widgets */ + snd_soc_dapm_new_controls(codec, imx_3stack_dapm_widgets, + ARRAY_SIZE(imx_3stack_dapm_widgets)); + + /* Set up imx_3stack specific audio path audio_map */ + snd_soc_dapm_add_routes(codec, audio_map, ARRAY_SIZE(audio_map)); + + snd_soc_dapm_sync(codec); + + return 0; + +} + +/* imx_3stack digital audio interface glue - connects codec <--> CPU */ +static struct snd_soc_dai_link imx_3stack_dai = { + .name = "WM8350", + .stream_name = "WM8350", + .codec_dai = &wm8350_dai, + .init = imx_3stack_wm8350_init, + .ops = &imx_3stack_ops, +}; + +static int imx_3stack_machine_probe(struct platform_device *pdev) +{ + struct snd_soc_device *socdev = platform_get_drvdata(pdev); + struct imx_3stack_priv *priv = &machine_priv; + struct wm8350 *wm8350 = priv->wm8350; + + socdev->codec_data = wm8350; + + return 0; +} + +static struct snd_soc_card snd_soc_card_imx_3stack = { + .name = "imx-3stack", + .platform = &imx_soc_platform, + .dai_link = &imx_3stack_dai, + .num_links = 1, + .probe = imx_3stack_machine_probe, +}; + +static struct snd_soc_device imx_3stack_snd_devdata = { + .card = &snd_soc_card_imx_3stack, + .codec_dev = &soc_codec_dev_wm8350, +}; + +static int __devinit imx_3stack_wm8350_probe(struct platform_device *pdev) +{ + struct mxc_audio_platform_data *plat = pdev->dev.platform_data; + struct imx_3stack_priv *priv = &machine_priv; + struct wm8350 *wm8350 = plat->priv; + struct snd_soc_dai *wm8350_cpu_dai; + int ret = 0; + u16 reg; + + priv->pdev = pdev; + priv->wm8350 = wm8350; + + gpio_activate_audio_ports(); + imx_3stack_init_dam(plat->src_port, plat->ext_port); + + if (plat->src_port == 2) + wm8350_cpu_dai = imx_ssi_dai[2]; + else + wm8350_cpu_dai = imx_ssi_dai[0]; + + imx_3stack_dai.cpu_dai = wm8350_cpu_dai; + + ret = driver_create_file(pdev->dev.driver, &driver_attr_headphone); + if (ret < 0) { + pr_err("%s:failed to create driver_attr_headphone\n", __func__); + return ret; + } + + /* enable slow clock gen for jack detect */ + reg = wm8350_reg_read(wm8350, WM8350_POWER_MGMT_4); + wm8350_reg_write(wm8350, WM8350_POWER_MGMT_4, reg | WM8350_TOCLK_ENA); + /* enable jack detect */ + reg = wm8350_reg_read(wm8350, WM8350_JACK_DETECT); + wm8350_reg_write(wm8350, WM8350_JACK_DETECT, reg | WM8350_JDR_ENA); + wm8350_register_irq(wm8350, WM8350_IRQ_CODEC_JCK_DET_R, + imx_3stack_jack_handler, NULL); + wm8350_unmask_irq(wm8350, WM8350_IRQ_CODEC_JCK_DET_R); + + wm8350_jack_func = 1; + wm8350_spk_func = 1; + + return 0; +} + +static int imx_3stack_wm8350_remove(struct platform_device *pdev) +{ + struct imx_3stack_priv *priv = &machine_priv; + struct wm8350 *wm8350 = priv->wm8350; + + wm8350_mask_irq(wm8350, WM8350_IRQ_CODEC_JCK_DET_R); + wm8350_free_irq(wm8350, WM8350_IRQ_CODEC_JCK_DET_R); + + return 0; +} + +static struct platform_driver imx_3stack_wm8350_audio_driver = { + .probe = imx_3stack_wm8350_probe, + .remove = __devexit_p(imx_3stack_wm8350_remove), + .driver = { + .name = "wm8350-imx-3stack-audio", + }, +}; + +static struct platform_device *imx_3stack_snd_device; + +static int __init imx_3stack_init(void) +{ + int ret; + + ret = platform_driver_register(&imx_3stack_wm8350_audio_driver); + if (ret) + return -ENOMEM; + + imx_3stack_snd_device = platform_device_alloc("soc-audio", -1); + if (!imx_3stack_snd_device) + return -ENOMEM; + + platform_set_drvdata(imx_3stack_snd_device, &imx_3stack_snd_devdata); + imx_3stack_snd_devdata.dev = &imx_3stack_snd_device->dev; + ret = platform_device_add(imx_3stack_snd_device); + + if (ret) + platform_device_put(imx_3stack_snd_device); + + return ret; +} + +static void __exit imx_3stack_exit(void) +{ + platform_driver_unregister(&imx_3stack_wm8350_audio_driver); + platform_device_unregister(imx_3stack_snd_device); +} + +module_init(imx_3stack_init); +module_exit(imx_3stack_exit); + +MODULE_AUTHOR("Liam Girdwood"); +MODULE_DESCRIPTION("PMIC WM8350 Driver for i.MX 3STACK"); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/imx/imx-3stack-wm8580.c b/sound/soc/imx/imx-3stack-wm8580.c new file mode 100644 index 000000000000..647034d87e1d --- /dev/null +++ b/sound/soc/imx/imx-3stack-wm8580.c @@ -0,0 +1,434 @@ +/* + * imx-3stack-wm8580.c -- SoC 5.1 audio for imx_3stack + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "imx-pcm.h" +#include "imx-esai.h" +#include "../codecs/wm8580.h" + +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) +#include +#endif + +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) +static unsigned int asrc_rates[] = { + 0, + 8000, + 11025, + 16000, + 22050, + 32000, + 44100, + 48000, + 64000, + 88200, + 96000, + 176400, + 192000, +}; + +struct asrc_esai { + unsigned int cpu_dai_rates; + unsigned int codec_dai_rates; + enum asrc_pair_index asrc_index; + unsigned int output_sample_rate; +}; + +static struct asrc_esai asrc_esai_data; + +#endif + +struct imx_3stack_pcm_state { + int lr_clk_active; +}; + +static struct imx_3stack_pcm_state clk_state; + +static int imx_3stack_startup(struct snd_pcm_substream *substream) +{ + clk_state.lr_clk_active++; +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) + if (asrc_esai_data.output_sample_rate >= 32000) { + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai_link *pcm_link = rtd->dai; + struct snd_soc_dai *cpu_dai = pcm_link->cpu_dai; + struct snd_soc_dai *codec_dai = pcm_link->codec_dai; + asrc_esai_data.cpu_dai_rates = cpu_dai->playback.rates; + asrc_esai_data.codec_dai_rates = codec_dai->playback.rates; + cpu_dai->playback.rates = + SNDRV_PCM_RATE_8000_192000 | SNDRV_PCM_RATE_KNOT; + codec_dai->playback.rates = + SNDRV_PCM_RATE_8000_192000 | SNDRV_PCM_RATE_KNOT; + } +#endif + + return 0; +} + +static void imx_3stack_shutdown(struct snd_pcm_substream *substream) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai_link *pcm_link = rtd->dai; + struct snd_soc_dai *codec_dai = pcm_link->codec_dai; + +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) + if (asrc_esai_data.output_sample_rate >= 32000) { + struct snd_soc_dai *cpu_dai = pcm_link->cpu_dai; + codec_dai->playback.rates = asrc_esai_data.codec_dai_rates; + cpu_dai->playback.rates = asrc_esai_data.cpu_dai_rates; + asrc_release_pair(asrc_esai_data.asrc_index); + } +#endif + + /* disable the PLL if there are no active Tx or Rx channels */ + if (!codec_dai->active) + snd_soc_dai_set_pll(codec_dai, 0, 0, 0); + clk_state.lr_clk_active--; +} + +static int imx_3stack_surround_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai_link *pcm_link = rtd->dai; + struct snd_soc_dai *cpu_dai = pcm_link->cpu_dai; + struct snd_soc_dai *codec_dai = pcm_link->codec_dai; + unsigned int rate = params_rate(params); + u32 dai_format; + unsigned int pll_out = 0, lrclk_ratio = 0; + unsigned int channel = params_channels(params); + struct imx_esai *esai_mode = (struct imx_esai *)cpu_dai->private_data; + + if (clk_state.lr_clk_active > 1) + return 0; + +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) + if (asrc_esai_data.output_sample_rate >= 32000) { + unsigned int asrc_input_rate = rate; + struct mxc_runtime_data *pcm_data = + substream->runtime->private_data; + struct asrc_config config; + int retVal = 0;; + + retVal = asrc_req_pair(channel, &asrc_esai_data.asrc_index); + if (retVal < 0) { + pr_err("Fail to request asrc pair\n"); + return -1; + } + + config.pair = asrc_esai_data.asrc_index; + config.channel_num = channel; + config.input_sample_rate = asrc_input_rate; + config.output_sample_rate = asrc_esai_data.output_sample_rate; + config.inclk = INCLK_NONE; + config.word_width = 32; + config.outclk = OUTCLK_ESAI_TX; + retVal = asrc_config_pair(&config); + if (retVal < 0) { + pr_err("Fail to config asrc\n"); + asrc_release_pair(asrc_esai_data.asrc_index); + return retVal; + } + rate = asrc_esai_data.output_sample_rate; + pcm_data->asrc_index = asrc_esai_data.asrc_index; + pcm_data->asrc_enable = 1; + } +#endif + + switch (rate) { + case 8000: + lrclk_ratio = 5; + pll_out = 6144000; + break; + case 11025: + lrclk_ratio = 4; + pll_out = 5644800; + break; + case 16000: + lrclk_ratio = 3; + pll_out = 6144000; + break; + case 32000: + lrclk_ratio = 3; + pll_out = 12288000; + break; + case 48000: + lrclk_ratio = 2; + pll_out = 12288000; + break; + case 64000: + lrclk_ratio = 1; + pll_out = 12288000; + break; + case 96000: + lrclk_ratio = 2; + pll_out = 24576000; + break; + case 128000: + lrclk_ratio = 1; + pll_out = 24576000; + break; + case 22050: + lrclk_ratio = 4; + pll_out = 11289600; + break; + case 44100: + lrclk_ratio = 2; + pll_out = 11289600; + break; + case 88200: + lrclk_ratio = 0; + pll_out = 11289600; + break; + case 176400: + lrclk_ratio = 0; + pll_out = 22579200; + break; + case 192000: + lrclk_ratio = 0; + pll_out = 24576000; + break; + default: + pr_info("Rate not support.\n"); + return -EINVAL;; + } + + dai_format = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | + SND_SOC_DAIFMT_CBM_CFM; + + esai_mode->sync_mode = 0; + esai_mode->network_mode = 1; + + /* set codec DAI configuration */ + snd_soc_dai_set_fmt(codec_dai, dai_format); + + /* set cpu DAI configuration */ + snd_soc_dai_set_fmt(cpu_dai, dai_format); + + /* set i.MX active slot mask */ + snd_soc_dai_set_tdm_slot(cpu_dai, channel == 1 ? 0x1 : 0x3, 2); + + /* set the ESAI system clock as input (unused) */ + snd_soc_dai_set_sysclk(cpu_dai, 0, 0, SND_SOC_CLOCK_IN); + + snd_soc_dai_set_clkdiv(codec_dai, WM8580_MCLK, WM8580_CLKSRC_PLLA); + snd_soc_dai_set_clkdiv(codec_dai, WM8580_DAC_CLKSEL, + WM8580_CLKSRC_PLLA); + + /* set codec LRCLK and BCLK */ + snd_soc_dai_set_sysclk(codec_dai, WM8580_BCLK_CLKDIV, 0, + SND_SOC_CLOCK_OUT); + snd_soc_dai_set_sysclk(codec_dai, WM8580_LRCLK_CLKDIV, lrclk_ratio, + SND_SOC_CLOCK_OUT); + + snd_soc_dai_set_pll(codec_dai, 1, 12000000, pll_out); + return 0; +} + +static struct snd_soc_ops imx_3stack_surround_ops = { + .startup = imx_3stack_startup, + .shutdown = imx_3stack_shutdown, + .hw_params = imx_3stack_surround_hw_params, +}; + +static const struct snd_soc_dapm_widget imx_3stack_dapm_widgets[] = { + SND_SOC_DAPM_LINE("Line Out Jack", NULL), +}; + +static const struct snd_soc_dapm_route audio_map[] = { + /* Line out jack */ + {"Line Out Jack", NULL, "VOUT1L"}, + {"Line Out Jack", NULL, "VOUT1R"}, + {"Line Out Jack", NULL, "VOUT2L"}, + {"Line Out Jack", NULL, "VOUT2R"}, + {"Line Out Jack", NULL, "VOUT3L"}, + {"Line Out Jack", NULL, "VOUT3R"}, +}; + +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) +static int asrc_func; + +static const char *asrc_function[] = { + "disable", "32KHz", "44.1KHz", + "48KHz", "64KHz", "88.2KHz", "96KHz", "176.4KHz", "192KHz" +}; + +static const struct soc_enum asrc_enum[] = { + SOC_ENUM_SINGLE_EXT(9, asrc_function), +}; + +static int asrc_get_rate(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + ucontrol->value.enumerated.item[0] = asrc_func; + return 0; +} + +static int asrc_set_rate(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + if (asrc_func == ucontrol->value.enumerated.item[0]) + return 0; + + asrc_func = ucontrol->value.enumerated.item[0]; + asrc_esai_data.output_sample_rate = asrc_rates[asrc_func + 4]; + + return 1; +} + +static const struct snd_kcontrol_new asrc_controls[] = { + SOC_ENUM_EXT("ASRC", asrc_enum[0], asrc_get_rate, + asrc_set_rate), +}; + +#endif + +static int imx_3stack_wm8580_init(struct snd_soc_codec *codec) +{ + +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) + int i; + int ret; + for (i = 0; i < ARRAY_SIZE(asrc_controls); i++) { + ret = snd_ctl_add(codec->card, + snd_soc_cnew(&asrc_controls[i], codec, NULL)); + if (ret < 0) + return ret; + } + asrc_esai_data.output_sample_rate = asrc_rates[asrc_func + 4]; +#endif + + snd_soc_dapm_new_controls(codec, imx_3stack_dapm_widgets, + ARRAY_SIZE(imx_3stack_dapm_widgets)); + + snd_soc_dapm_add_routes(codec, audio_map, ARRAY_SIZE(audio_map)); + + snd_soc_dapm_sync(codec); + + return 0; +} + +static struct snd_soc_dai_link imx_3stack_dai = { + .name = "wm8580", + .stream_name = "wm8580", + .codec_dai = wm8580_dai, + .init = imx_3stack_wm8580_init, + .ops = &imx_3stack_surround_ops, +}; + +static int imx_3stack_card_remove(struct platform_device *pdev) +{ + struct snd_soc_device *socdev = platform_get_drvdata(pdev); + kfree(socdev->codec_data); + return 0; +} + +static struct snd_soc_card snd_soc_card_imx_3stack = { + .name = "imx-3stack", + .platform = &imx_soc_platform, + .dai_link = &imx_3stack_dai, + .num_links = 1, + .remove = imx_3stack_card_remove, +}; + +static struct snd_soc_device imx_3stack_snd_devdata = { + .card = &snd_soc_card_imx_3stack, + .codec_dev = &soc_codec_dev_wm8580, +}; + +/* + * This function will register the snd_soc_pcm_link drivers. + */ +static int __devinit imx_3stack_wm8580_probe(struct platform_device *pdev) +{ + struct wm8580_setup_data *setup; + + imx_3stack_dai.cpu_dai = &imx_esai_dai[2]; + imx_3stack_dai.cpu_dai->dev = &pdev->dev; + + setup = kzalloc(sizeof(struct wm8580_setup_data), GFP_KERNEL); + setup->spi = 1; + imx_3stack_snd_devdata.codec_data = setup; + + return 0; +} + +static int __devexit imx_3stack_wm8580_remove(struct platform_device *pdev) +{ + return 0; +} + +static struct platform_driver imx_3stack_wm8580_driver = { + .probe = imx_3stack_wm8580_probe, + .remove = __devexit_p(imx_3stack_wm8580_remove), + .driver = { + .name = "imx-3stack-wm8580", + .owner = THIS_MODULE, + }, +}; + +static struct platform_device *imx_3stack_snd_device; + +static int __init imx_3stack_asoc_init(void) +{ + int ret; + + ret = platform_driver_register(&imx_3stack_wm8580_driver); + if (ret < 0) + goto exit; + imx_3stack_snd_device = platform_device_alloc("soc-audio", 1); + if (!imx_3stack_snd_device) + goto err_device_alloc; + platform_set_drvdata(imx_3stack_snd_device, &imx_3stack_snd_devdata); + imx_3stack_snd_devdata.dev = &imx_3stack_snd_device->dev; + ret = platform_device_add(imx_3stack_snd_device); + if (0 == ret) + goto exit; + + platform_device_put(imx_3stack_snd_device); + err_device_alloc: + platform_driver_unregister(&imx_3stack_wm8580_driver); + exit: + return ret; +} + +static void __exit imx_3stack_asoc_exit(void) +{ + platform_driver_unregister(&imx_3stack_wm8580_driver); + platform_device_unregister(imx_3stack_snd_device); +} + +module_init(imx_3stack_asoc_init); +module_exit(imx_3stack_asoc_exit); + +/* Module information */ +MODULE_DESCRIPTION("ALSA SoC wm8580 imx_3stack"); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/imx/imx-ac97.c b/sound/soc/imx/imx-ac97.c new file mode 100644 index 000000000000..801e98efb4f8 --- /dev/null +++ b/sound/soc/imx/imx-ac97.c @@ -0,0 +1,564 @@ +/* + * imx-ac97.c -- AC97 driver for Freescale IMX + * + * + * Copyright 2009-2010 Freescale Semiconductor, Inc. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * Revision history + * 26th Nov. 2009 Initial version. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "imx-ssi.h" +#include "imx-pcm.h" + +static DEFINE_MUTEX(ac97_mutex); +static DECLARE_COMPLETION(ac97_completion); + +struct imx_ac97_runtime { + u32 id; + u32 playback; + u32 capture; +}; + +static struct imx_ac97_runtime imx_ac97_para; +static struct imx_ssi imx_ac97_data[2]; + +#define IMX_SSI_DUMP 0 +#if IMX_SSI_DUMP +#define SSI_DUMP() \ + do { \ + printk(KERN_INFO "dump @ %s\n", __func__); \ + printk(KERN_INFO "scr %x\t, %x\n", \ + __raw_readl(SSI1_SCR), __raw_readl(SSI2_SCR)); \ + printk(KERN_INFO "sisr %x\t, %x\n", \ + __raw_readl(SSI1_SISR), __raw_readl(SSI2_SISR)); \ + printk(KERN_INFO "stcr %x\t, %x\n", \ + __raw_readl(SSI1_STCR), __raw_readl(SSI2_STCR)); \ + printk(KERN_INFO "srcr %x\t, %x\n", \ + __raw_readl(SSI1_SRCR), __raw_readl(SSI2_SRCR)); \ + printk(KERN_INFO "stccr %x\t, %x\n", \ + __raw_readl(SSI1_STCCR), __raw_readl(SSI2_STCCR)); \ + printk(KERN_INFO "srccr %x\t, %x\n", \ + __raw_readl(SSI1_SRCCR), __raw_readl(SSI2_SRCCR)); \ + printk(KERN_INFO "sfcsr %x\t, %x\n", \ + __raw_readl(SSI1_SFCSR), __raw_readl(SSI2_SFCSR)); \ + printk(KERN_INFO "stmsk %x\t, %x\n", \ + __raw_readl(SSI1_STMSK), __raw_readl(SSI2_STMSK)); \ + printk(KERN_INFO "srmsk %x\t, %x\n", \ + __raw_readl(SSI1_SRMSK), __raw_readl(SSI2_SRMSK)); \ + printk(KERN_INFO "sier %x\t, %x\n", \ + __raw_readl(SSI1_SIER), __raw_readl(SSI2_SIER)); \ + printk(KERN_INFO "sacnt %x\t, %x\n", \ + __raw_readl(SSI1_SACNT), __raw_readl(SSI2_SACNT)); \ + printk(KERN_INFO "sacdd %x\t, %x\n", \ + __raw_readl(SSI1_SACADD), __raw_readl(SSI2_SACADD)); \ + printk(KERN_INFO "sacdat %x\t, %x\n", \ + __raw_readl(SSI1_SACDAT), __raw_readl(SSI2_SACDAT)); \ + printk(KERN_INFO "satag %x\t, %x\n", \ + __raw_readl(SSI1_SATAG), __raw_readl(SSI2_SATAG)); \ + printk(KERN_INFO "saccst %x\t, %x\n", \ + __raw_readl(SSI1_SACCST), __raw_readl(SSI2_SACCST)); \ + printk(KERN_INFO "saccen %x\t, %x\n", \ + __raw_readl(SSI1_SACCEN), __raw_readl(SSI2_SACCEN)); \ + printk(KERN_INFO "saccdis %x\t, %x\n", \ + __raw_readl(SSI1_SACCDIS), __raw_readl(SSI2_SACCDIS)); \ + } while (0); +#else +#define SSI_DUMP() +#endif + +/* + * Read register value from codec, the read command is sent from + * AC97 slot 2 - 3. The register value is sent back at slot 2 -3 + * in next RX frame. + */ +static unsigned short imx_ac97_read(struct snd_ac97 *ac97, unsigned short reg) +{ + u32 sacdat, sier, scr; + mutex_lock(&ac97_mutex); + if (imx_ac97_para.id == IMX_DAI_AC97_1) { + sier = __raw_readl(SSI1_SIER); + scr = __raw_readl(SSI1_SCR); + __raw_writel((reg << 12), SSI1_SACADD); + __raw_writel(sier | SSI_SIER_CMDDU_EN, SSI1_SIER); + __raw_writel(SSI_SACNT_RD | __raw_readl(SSI1_SACNT), + SSI1_SACNT); + __raw_writel(scr | SSI_SCR_TE | SSI_SCR_RE, SSI1_SCR); + wait_for_completion_timeout(&ac97_completion, HZ); + sacdat = __raw_readl(SSI1_SACDAT); + __raw_writel(sier, SSI1_SIER); + __raw_writel(scr, SSI1_SCR); + } else { + sier = __raw_readl(SSI2_SIER); + scr = __raw_readl(SSI2_SCR); + __raw_writel((reg << 12), SSI2_SACADD); + __raw_writel(sier | SSI_SIER_CMDDU_EN, SSI2_SIER); + __raw_writel(SSI_SACNT_RD | __raw_readl(SSI2_SACNT), + SSI2_SACNT); + __raw_writel(scr | SSI_SCR_TE | SSI_SCR_RE, SSI2_SCR); + wait_for_completion_timeout(&ac97_completion, HZ); + sacdat = __raw_readl(SSI2_SACDAT); + __raw_writel(sier, SSI2_SIER); + __raw_writel(scr, SSI2_SCR); + } + mutex_unlock(&ac97_mutex); + return (unsigned short)(sacdat >> 4); + +} + +/* + * This fucntion is used to send command to codec. + */ +static void imx_ac97_write(struct snd_ac97 *ac97, unsigned short reg, + unsigned short val) +{ + u32 scr; + mutex_lock(&ac97_mutex); + if (imx_ac97_para.id == IMX_DAI_AC97_1) { + scr = __raw_readl(SSI1_SCR); + __raw_writel(reg << 12, SSI1_SACADD); + __raw_writel(val << 4, SSI1_SACDAT); + __raw_writel(SSI_SACNT_WR | __raw_readl(SSI1_SACNT), + SSI1_SACNT); + __raw_writel(scr | SSI_SCR_TE | SSI_SCR_RE, SSI1_SCR); + udelay(100); + __raw_writel(scr, SSI1_SCR); + } else { + scr = __raw_readl(SSI2_SCR); + __raw_writel(reg << 12, SSI2_SACADD); + __raw_writel(val << 4, SSI2_SACDAT); + __raw_writel(SSI_SACNT_WR | __raw_readl(SSI2_SACNT), + SSI2_SACNT); + __raw_writel(scr | SSI_SCR_TE | SSI_SCR_RE, SSI2_SCR); + udelay(100); + __raw_writel(scr, SSI1_SCR); + } + mutex_unlock(&ac97_mutex); + +} + +struct snd_ac97_bus_ops soc_ac97_ops = { + .read = imx_ac97_read, + .write = imx_ac97_write, +}; +EXPORT_SYMBOL_GPL(soc_ac97_ops); + +static struct clk *ssi1_clk; +static struct clk *ssi2_clk; + +static int imx_ac97_hw_tx_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params, + struct snd_soc_dai *cpu_dai) +{ + struct imx_ssi *ssi_mode = (struct imx_ssi *)cpu_dai->private_data; + u32 channel = params_channels(params); + u32 stccr, sier; + + if (cpu_dai->id == IMX_DAI_AC97_1) { + stccr = + __raw_readl(SSI1_STCCR) & ~(SSI_STCCR_WL_MASK | + SSI_STCCR_DC_MASK); + sier = __raw_readl(SSI1_SIER); + } else { + stccr = + __raw_readl(SSI2_STCCR) & ~(SSI_STCCR_WL_MASK | + SSI_STCCR_DC_MASK); + sier = __raw_readl(SSI2_SIER); + } + + /* DAI data (word) size */ + switch (params_format(params)) { + case SNDRV_PCM_FORMAT_S16_LE: + stccr |= SSI_STCCR_WL(16) | SSI_STCCR_DC(0x0C); + break; + case SNDRV_PCM_FORMAT_S20_3LE: + stccr |= SSI_STCCR_WL(20) | SSI_STCCR_DC(0x0C); + break; + } + if (ssi_mode->ac97_rx_slots) + __raw_writel(ssi_mode->ac97_rx_slots, SSI1_SACCEN); + else + __raw_writel(((1 << channel) - 1) << (10 - channel), + SSI1_SACCEN); + + sier |= SSI_SIER_TDMAE; + + if (cpu_dai->id == IMX_DAI_SSI0 || cpu_dai->id == IMX_DAI_SSI1) { + __raw_writel(stccr, SSI1_STCCR); + __raw_writel(sier, SSI1_SIER); + } else { + __raw_writel(stccr, SSI2_STCCR); + __raw_writel(sier, SSI2_SIER); + } + + return 0; +} + +static int imx_ac97_hw_rx_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params, + struct snd_soc_dai *cpu_dai) +{ + struct imx_ssi *ssi_mode = (struct imx_ssi *)cpu_dai->private_data; + u32 channel = params_channels(params); + u32 srccr, sier; + + if (cpu_dai->id == IMX_DAI_AC97_1) { + srccr = __raw_readl(SSI1_SRCCR); + sier = __raw_readl(SSI1_SIER); + } else { + srccr = __raw_readl(SSI2_SRCCR); + sier = __raw_readl(SSI2_SIER); + } + srccr &= ~(SSI_SRCCR_WL_MASK | SSI_SRCCR_DC_MASK); + + /* DAI data (word) size */ + switch (params_format(params)) { + case SNDRV_PCM_FORMAT_S16_LE: + srccr |= SSI_SRCCR_WL(16) | SSI_SRCCR_DC(0x0C); + break; + case SNDRV_PCM_FORMAT_S20_3LE: + srccr |= SSI_SRCCR_WL(20) | SSI_SRCCR_DC(0x0C); + break; + } + + if (ssi_mode->ac97_tx_slots) + __raw_writel(ssi_mode->ac97_tx_slots, SSI1_SACCEN); + else + __raw_writel(((1 << channel) - 1) << (10 - channel), + SSI1_SACCEN); + + /* enable interrupts */ + sier |= SSI_SIER_RDMAE; + + if (cpu_dai->id == IMX_DAI_AC97_1) { + __raw_writel(srccr, SSI1_SRCCR); + __raw_writel(sier, SSI1_SIER); + } else { + __raw_writel(srccr, SSI2_SRCCR); + __raw_writel(sier, SSI2_SIER); + } + return 0; +} + +static int imx_ac97_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params, + struct snd_soc_dai *cpu_dai) +{ + u32 rate = params_rate(params); + u32 sacnt; + + if (cpu_dai->id == IMX_DAI_AC97_1) + sacnt = __raw_readl(SSI1_SACNT); + else + sacnt = __raw_readl(SSI2_SACNT); + + switch (rate) { + case 8000: + sacnt |= SSI_SACNT_FV | SSI_SACNT_FRDIV(0x05); + break; + case 11050: + sacnt |= SSI_SACNT_FV | SSI_SACNT_FRDIV(0x03); + break; + case 16000: + sacnt |= SSI_SACNT_FV | SSI_SACNT_FRDIV(0x02); + break; + case 22050: + sacnt |= SSI_SACNT_FV | SSI_SACNT_FRDIV(0x01); + break; + case 44100: + case 48000: + sacnt |= SSI_SACNT_FV | SSI_SACNT_FRDIV(0x00); + break; + } + + if (cpu_dai->id == IMX_DAI_AC97_1) + __raw_writel(sacnt, SSI1_SACNT); + else + __raw_writel(sacnt, SSI2_SACNT); + + /* Tx/Rx config */ + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) + return imx_ac97_hw_tx_params(substream, params, cpu_dai); + else + return imx_ac97_hw_rx_params(substream, params, cpu_dai); +} + +static int imx_ac97_trigger(struct snd_pcm_substream *substream, int cmd) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai *cpu_dai = rtd->dai->cpu_dai; + u32 scr, i, reg; + + if (cpu_dai->id == IMX_DAI_AC97_1) + scr = __raw_readl(SSI1_SCR); + else + scr = __raw_readl(SSI2_SCR); + + switch (cmd) { + case SNDRV_PCM_TRIGGER_START: + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + for (i = 0; i < 12; i++) + __raw_writel(0x0, SSI1_STX0); + } else { + for (i = 0; i < 12; i++) + reg = __raw_readl(SSI1_SRX0); + } + case SNDRV_PCM_TRIGGER_RESUME: + case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) + imx_ac97_para.playback = 1; + else + imx_ac97_para.capture = 1; + scr |= SSI_SCR_TE | SSI_SCR_RE; + break; + case SNDRV_PCM_TRIGGER_SUSPEND: + case SNDRV_PCM_TRIGGER_STOP: + case SNDRV_PCM_TRIGGER_PAUSE_PUSH: + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) + imx_ac97_para.playback = 0; + else + imx_ac97_para.capture = 0; + + if ((imx_ac97_para.playback == 0) + && (imx_ac97_para.capture == 0)) + scr &= ~(SSI_SCR_TE | SSI_SCR_RE); + break; + default: + return -EINVAL; + } + if (cpu_dai->id == IMX_DAI_SSI0 || cpu_dai->id == IMX_DAI_SSI1) + __raw_writel(scr, SSI1_SCR); + else + __raw_writel(scr, SSI2_SCR); + SSI_DUMP(); + return 0; +} + +#ifdef CONFIG_PM +static int imx_ac97_suspend(struct snd_soc_dai *dai) +{ + if (!dai->active) + return 0; + + /* do we need to disable any clocks? */ + + return 0; +} + +static int imx_ac97_resume(struct snd_soc_dai *dai) +{ + if (!dai->active) + return 0; + + /* do we need to enable any clocks? */ + + return 0; +} +#else +#define imx_ac97_suspend NULL +#define imx_ac97_resume NULL +#endif + +static irqreturn_t ssi1_irq(int irq, void *dev_id) +{ + u32 sier, sisr, reg; + sier = __raw_readl(SSI1_SIER); + sisr = __raw_readl(SSI1_SISR); + if ((sier & SSI_SIER_CMDDU_EN) && (sisr & SSI_SISR_CMDDU)) { + reg = __raw_readl(SSI1_SACADD); + reg = __raw_readl(SSI1_SACDAT); + complete(&ac97_completion); + } + return IRQ_HANDLED; +} + +static irqreturn_t ssi2_irq(int irq, void *dev_id) +{ + u32 sier, sisr, reg; + sier = __raw_readl(SSI1_SIER); + sisr = __raw_readl(SSI1_SISR); + if ((sier & SSI_SIER_CMDDU_EN) && (sisr & SSI_SISR_CMDDU)) { + reg = __raw_readl(SSI2_SACADD); + reg = __raw_readl(SSI2_SACDAT); + complete(&ac97_completion); + } + return IRQ_HANDLED; +} + +static int imx_ac97_probe(struct platform_device *pdev, struct snd_soc_dai *dai) +{ + + u32 stccr; + stccr = SSI_STCCR_WL(16) | SSI_STCCR_DC(0x0C); + + if (!strcmp(dai->name, "imx-ac97-1")) { + dai->id = IMX_DAI_AC97_1; + ssi1_clk = clk_get(NULL, "ssi_clk.0"); + clk_enable(ssi1_clk); + + __raw_writel(SSI_SCR_SSIEN, SSI1_SCR); + + __raw_writel((SSI_SFCSR_RFWM1(SSI_RXFIFO_WATERMARK) | + SSI_SFCSR_RFWM0(SSI_RXFIFO_WATERMARK) | + SSI_SFCSR_TFWM1(SSI_TXFIFO_WATERMARK) | + SSI_SFCSR_TFWM0(SSI_TXFIFO_WATERMARK)), + SSI1_SFCSR); + + __raw_writel(stccr, SSI1_STCCR); + __raw_writel(stccr, SSI1_SRCCR); + __raw_writel(SSI_SACNT_AC97EN, SSI1_SACNT); + } else if (!strcmp(dai->name, "imx-ac97-2")) { + dai->id = IMX_DAI_AC97_2; + ssi2_clk = clk_get(NULL, "ssi_clk.1"); + clk_enable(ssi2_clk); + + __raw_writel(SSI_SCR_SSIEN, SSI2_SCR); + + __raw_writel((SSI_SFCSR_RFWM1(SSI_RXFIFO_WATERMARK) | + SSI_SFCSR_RFWM0(SSI_RXFIFO_WATERMARK) | + SSI_SFCSR_TFWM1(SSI_TXFIFO_WATERMARK) | + SSI_SFCSR_TFWM0(SSI_TXFIFO_WATERMARK)), + SSI2_SFCSR); + + __raw_writel(stccr, SSI2_STCCR); + __raw_writel(stccr, SSI2_SRCCR); + + __raw_writel(SSI_SACNT_AC97EN, SSI2_SACNT); + } else { + printk(KERN_ERR "%s: invalid device %s\n", __func__, dai->name); + return -ENODEV; + } + + if (!strcmp(dai->name, "imx-ac97-1")) { + if (request_irq(MXC_INT_SSI1, ssi1_irq, 0, "ssi1", dai)) { + printk(KERN_ERR + "%s: failure requesting irq %s\n", + __func__, "ssi1"); + return -EBUSY; + } + } + + if (!strcmp(dai->name, "imx-ac97-2")) { + if (request_irq(MXC_INT_SSI2, ssi2_irq, 0, "ssi2", dai)) { + printk(KERN_ERR + "%s: failure requesting irq %s\n", + __func__, "ssi2"); + return -EBUSY; + } + } + + return 0; +} + +static void imx_ac97_remove(struct platform_device *pdev, + struct snd_soc_dai *dai) +{ + if (!strcmp(dai->name, "imx-ac97-1")) + free_irq(MXC_INT_SSI1, dai); + + if (!strcmp(dai->name, "imx-ac97-2")) + free_irq(MXC_INT_SSI2, dai); +} + +#define IMX_AC97_RATES \ + (SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_11025 | \ + SNDRV_PCM_RATE_16000 | SNDRV_PCM_RATE_22050 | \ + SNDRV_PCM_RATE_32000 | SNDRV_PCM_RATE_44100 | \ + SNDRV_PCM_RATE_48000) + +#define IMX_AC97_FORMATS \ + (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE) + +static struct snd_soc_dai_ops imx_ac97_dai_ops = { + .hw_params = imx_ac97_hw_params, + .trigger = imx_ac97_trigger, +}; + +struct snd_soc_dai imx_ac97_dai[] = { + { + .name = "imx-ac97-1", + .id = 0, + .ac97_control = 1, + .probe = imx_ac97_probe, + .remove = imx_ac97_remove, + .suspend = imx_ac97_suspend, + .resume = imx_ac97_resume, + .playback = { + .stream_name = "AC97 Playback", + .channels_min = 1, + .channels_max = 10, + .rates = IMX_AC97_RATES, + .formats = IMX_AC97_FORMATS, + }, + .capture = { + .stream_name = "AC97 Capture", + .channels_min = 1, + .channels_max = 6, + .rates = IMX_AC97_RATES, + .formats = IMX_AC97_FORMATS, + }, + .ops = &imx_ac97_dai_ops, + .private_data = &imx_ac97_data[IMX_DAI_AC97_1], + }, + { + .name = "imx-ac97-2", + .id = 1, + .ac97_control = 1, + .probe = imx_ac97_probe, + .remove = imx_ac97_remove, + .suspend = imx_ac97_suspend, + .resume = imx_ac97_resume, + .playback = { + .stream_name = "AC97 Playback", + .channels_min = 1, + .channels_max = 10, + .rates = IMX_AC97_RATES, + .formats = IMX_AC97_FORMATS, + }, + .capture = { + .stream_name = "AC97 Capture", + .channels_min = 1, + .channels_max = 6, + .rates = IMX_AC97_RATES, + .formats = IMX_AC97_FORMATS, + }, + .ops = &imx_ac97_dai_ops, + .private_data = &imx_ac97_data[IMX_DAI_AC97_2], + }, +}; +EXPORT_SYMBOL_GPL(imx_ac97_dai); + +static int __init imx_ac97_init(void) +{ + return snd_soc_register_dais(imx_ac97_dai, ARRAY_SIZE(imx_ac97_dai)); +} + +static void __exit imx_ac97_exit(void) +{ + snd_soc_unregister_dais(imx_ac97_dai, ARRAY_SIZE(imx_ac97_dai)); +} + +module_init(imx_ac97_init); +module_exit(imx_ac97_exit); + +MODULE_DESCRIPTION("i.MX ASoC AC97 driver"); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/imx/imx-esai.c b/sound/soc/imx/imx-esai.c new file mode 100644 index 000000000000..0c6b234f29ec --- /dev/null +++ b/sound/soc/imx/imx-esai.c @@ -0,0 +1,709 @@ +/* + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + + /*! + * @file imx-esai.c + * @brief this file implements the esai interface + * in according to ASoC architeture + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "imx-esai.h" +#include "imx-pcm.h" + +static int imx_esai_txrx_state; +static struct imx_esai imx_esai_priv[3]; +static void __iomem *esai_ioaddr; + +static int imx_esai_set_dai_sysclk(struct snd_soc_dai *cpu_dai, + int clk_id, unsigned int freq, int dir) +{ + u32 ecr, tccr, rccr; + + ecr = __raw_readl(ESAI_ECR); + tccr = __raw_readl(ESAI_TCCR); + rccr = __raw_readl(ESAI_RCCR); + + if (dir == SND_SOC_CLOCK_IN) { + if (cpu_dai->id & IMX_DAI_ESAI_TX) + tccr &= + ~(ESAI_TCCR_THCKD | ESAI_TCCR_TCKD | + ESAI_TCCR_TFSD); + if (cpu_dai->id & IMX_DAI_ESAI_RX) + rccr &= + ~(ESAI_RCCR_RHCKD | ESAI_RCCR_RCKD | + ESAI_RCCR_RFSD); + } else { + tccr |= + ESAI_TCCR_THCKD | ESAI_TCCR_TCKD | ESAI_TCCR_TFSD; + rccr |= + ESAI_RCCR_RHCKD | ESAI_RCCR_RCKD | ESAI_RCCR_RFSD; + if (clk_id == ESAI_CLK_FSYS) { + if (cpu_dai->id & IMX_DAI_ESAI_TX) + ecr &= ~(ESAI_ECR_ETI | ESAI_ECR_ETO); + if (cpu_dai->id & IMX_DAI_ESAI_RX) + ecr &= ~(ESAI_ECR_ERI | ESAI_ECR_ERO); + } else if (clk_id == ESAI_CLK_EXTAL) { + ecr |= ESAI_ECR_ETI; + ecr &= ~ESAI_ECR_ETO; + ecr |= ESAI_ECR_ERI; + ecr &= ~ESAI_ECR_ERO; + } + } + + __raw_writel(ecr, ESAI_ECR); + if (cpu_dai->id & IMX_DAI_ESAI_TX) + __raw_writel(tccr, ESAI_TCCR); + if (cpu_dai->id & IMX_DAI_ESAI_RX) + __raw_writel(rccr, ESAI_RCCR); + + ESAI_DUMP(); + + return 0; +} + +static int imx_esai_set_dai_clkdiv(struct snd_soc_dai *cpu_dai, + int div_id, int div) +{ + u32 tccr, rccr; + + tccr = __raw_readl(ESAI_TCCR); + rccr = __raw_readl(ESAI_RCCR); + + switch (div_id) { + case ESAI_TX_DIV_PSR: + tccr &= ESAI_TCCR_TPSR_MASK; + if (div) + tccr |= ESAI_TCCR_TPSR_BYPASS; + else + tccr &= ~ESAI_TCCR_TPSR_DIV8; + break; + case ESAI_TX_DIV_PM: + tccr &= ESAI_TCCR_TPM_MASK; + tccr |= ESAI_TCCR_TPM(div); + break; + case ESAI_TX_DIV_FP: + tccr &= ESAI_TCCR_TFP_MASK; + tccr |= ESAI_TCCR_TFP(div); + break; + case ESAI_RX_DIV_PSR: + rccr &= ESAI_RCCR_RPSR_MASK; + if (div) + rccr |= ESAI_RCCR_RPSR_BYPASS; + else + rccr &= ~ESAI_RCCR_RPSR_DIV8; + break; + case ESAI_RX_DIV_PM: + rccr &= ESAI_RCCR_RPM_MASK; + rccr |= ESAI_RCCR_RPM(div); + break; + case ESAI_RX_DIV_FP: + rccr &= ESAI_RCCR_RFP_MASK; + rccr |= ESAI_RCCR_RFP(div); + break; + return -EINVAL; + } + if (cpu_dai->id & IMX_DAI_ESAI_TX) + __raw_writel(tccr, ESAI_TCCR); + if (cpu_dai->id & IMX_DAI_ESAI_RX) + __raw_writel(rccr, ESAI_RCCR); + return 0; +} + +/* + * ESAI Network Mode or TDM slots configuration. + */ +static int imx_esai_set_dai_tdm_slot(struct snd_soc_dai *cpu_dai, + unsigned int mask, int slots) +{ + u32 tccr, rccr; + + if (cpu_dai->id & IMX_DAI_ESAI_TX) { + tccr = __raw_readl(ESAI_TCCR); + + tccr &= ESAI_TCCR_TDC_MASK; + tccr |= ESAI_TCCR_TDC(slots - 1); + + __raw_writel(tccr, ESAI_TCCR); + __raw_writel((mask & 0xffff), ESAI_TSMA); + __raw_writel(((mask >> 16) & 0xffff), ESAI_TSMB); + } + + if (cpu_dai->id & IMX_DAI_ESAI_RX) { + rccr = __raw_readl(ESAI_RCCR); + + rccr &= ESAI_RCCR_RDC_MASK; + rccr |= ESAI_RCCR_RDC(slots - 1); + + __raw_writel(rccr, ESAI_RCCR); + __raw_writel((mask & 0xffff), ESAI_RSMA); + __raw_writel(((mask >> 16) & 0xffff), ESAI_RSMB); + } + + ESAI_DUMP(); + + return 0; +} + +/* + * ESAI DAI format configuration. + */ +static int imx_esai_set_dai_fmt(struct snd_soc_dai *cpu_dai, unsigned int fmt) +{ + struct imx_esai *esai_mode = (struct imx_esai *)cpu_dai->private_data; + u32 tcr, tccr, rcr, rccr, saicr; + + tcr = __raw_readl(ESAI_TCR); + tccr = __raw_readl(ESAI_TCCR); + rcr = __raw_readl(ESAI_RCR); + rccr = __raw_readl(ESAI_RCCR); + saicr = __raw_readl(ESAI_SAICR); + + /* DAI mode */ + switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { + case SND_SOC_DAIFMT_I2S: + /* data on rising edge of bclk, frame low 1clk before data */ + tcr &= ~ESAI_TCR_TFSL; + tcr |= ESAI_TCR_TFSR; + rcr &= ~ESAI_RCR_RFSL; + rcr |= ESAI_RCR_RFSR; + break; + case SND_SOC_DAIFMT_LEFT_J: + /* data on rising edge of bclk, frame high with data */ + tcr &= ~(ESAI_TCR_TFSL | ESAI_TCR_TFSR); + rcr &= ~(ESAI_RCR_RFSL | ESAI_RCR_RFSR); + break; + case SND_SOC_DAIFMT_DSP_B: + /* data on rising edge of bclk, frame high with data */ + tcr |= ESAI_TCR_TFSL; + rcr |= ESAI_RCR_RFSL; + break; + case SND_SOC_DAIFMT_DSP_A: + /* data on rising edge of bclk, frame high 1clk before data */ + tcr |= ESAI_TCR_TFSL; + rcr |= ESAI_RCR_RFSL; + break; + } + + /* DAI clock inversion */ + switch (fmt & SND_SOC_DAIFMT_INV_MASK) { + case SND_SOC_DAIFMT_IB_IF: + tccr |= ESAI_TCCR_TFSP; + tccr &= ~(ESAI_TCCR_TCKP | ESAI_TCCR_THCKP); + rccr &= ~(ESAI_RCCR_RCKP | ESAI_RCCR_RHCKP); + rccr |= ESAI_RCCR_RFSP; + break; + case SND_SOC_DAIFMT_IB_NF: + tccr &= ~(ESAI_TCCR_TCKP | ESAI_TCCR_THCKP | ESAI_TCCR_TFSP); + rccr &= ~(ESAI_RCCR_RCKP | ESAI_RCCR_RHCKP | ESAI_RCCR_RFSP); + break; + case SND_SOC_DAIFMT_NB_IF: + tccr |= ESAI_TCCR_TCKP | ESAI_TCCR_THCKP | ESAI_TCCR_TFSP; + rccr |= ESAI_RCCR_RCKP | ESAI_RCCR_RHCKP | ESAI_RCCR_RFSP; + break; + case SND_SOC_DAIFMT_NB_NF: + tccr &= ~ESAI_TCCR_TFSP; + tccr |= ESAI_TCCR_TCKP | ESAI_TCCR_THCKP; + rccr &= ~ESAI_RCCR_RFSP; + rccr |= ESAI_RCCR_RCKP | ESAI_RCCR_RHCKP; + break; + } + + /* DAI clock master masks */ + switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) { + case SND_SOC_DAIFMT_CBM_CFM: + tccr &= ~(ESAI_TCCR_TFSD | ESAI_TCCR_TCKD); + rccr &= ~(ESAI_RCCR_RFSD | ESAI_RCCR_RCKD); + break; + case SND_SOC_DAIFMT_CBS_CFM: + tccr &= ~ESAI_TCCR_TFSD; + tccr |= ESAI_TCCR_TCKD; + rccr &= ~ESAI_RCCR_RFSD; + rccr |= ESAI_RCCR_RCKD; + break; + case SND_SOC_DAIFMT_CBM_CFS: + tccr &= ~ESAI_TCCR_TCKD; + tccr |= ESAI_TCCR_TFSD; + rccr &= ~ESAI_RCCR_RCKD; + rccr |= ESAI_RCCR_RFSD; + break; + case SND_SOC_DAIFMT_CBS_CFS: + tccr |= (ESAI_TCCR_TFSD | ESAI_TCCR_TCKD); + rccr |= (ESAI_RCCR_RFSD | ESAI_RCCR_RCKD); + } + + /* sync */ + if (esai_mode->sync_mode) + saicr |= ESAI_SAICR_SYNC; + else + saicr &= ~ESAI_SAICR_SYNC; + + tcr &= ESAI_TCR_TMOD_MASK; + rcr &= ESAI_RCR_RMOD_MASK; + if (esai_mode->network_mode) { + tcr |= ESAI_TCR_TMOD_NETWORK; + rcr |= ESAI_RCR_RMOD_NETWORK; + } else { + tcr |= ESAI_TCR_TMOD_NORMAL; + rcr |= ESAI_RCR_RMOD_NORMAL; + } + + if (cpu_dai->id & IMX_DAI_ESAI_TX) { + __raw_writel(tcr, ESAI_TCR); + __raw_writel(tccr, ESAI_TCCR); + } + if (cpu_dai->id & IMX_DAI_ESAI_RX) { + __raw_writel(rcr, ESAI_RCR); + __raw_writel(rccr, ESAI_RCCR); + } + + __raw_writel(saicr, ESAI_SAICR); + + ESAI_DUMP(); + return 0; +} + +static struct clk *esai_clk; + +static int fifo_err_counter; + +static irqreturn_t esai_irq(int irq, void *dev_id) +{ + if (fifo_err_counter++ % 1000 == 0) + printk(KERN_ERR + "esai_irq SAISR %x fifo_errs=%d\n", + __raw_readl(ESAI_SAISR), fifo_err_counter); + return IRQ_HANDLED; +} + +static int imx_esai_startup(struct snd_pcm_substream *substream, + struct snd_soc_dai *cpu_dai) +{ + if (cpu_dai->playback.active && (cpu_dai->id & IMX_DAI_ESAI_TX)) + return 0; + if (cpu_dai->capture.active && (cpu_dai->id & IMX_DAI_ESAI_RX)) + return 0; + + if (!(imx_esai_txrx_state & IMX_DAI_ESAI_TXRX)) { + if (request_irq(MXC_INT_ESAI, esai_irq, 0, "esai", NULL)) { + pr_err("%s: failure requesting esai irq\n", __func__); + return -EBUSY; + } + clk_enable(esai_clk); + __raw_writel(ESAI_ECR_ERST, ESAI_ECR); + __raw_writel(ESAI_ECR_ESAIEN, ESAI_ECR); + + __raw_writel(ESAI_GPIO_ESAI, ESAI_PRRC); + __raw_writel(ESAI_GPIO_ESAI, ESAI_PCRC); + } + + if (cpu_dai->id & IMX_DAI_ESAI_TX) { + imx_esai_txrx_state |= IMX_DAI_ESAI_TX; + __raw_writel(ESAI_TCR_TPR, ESAI_TCR); + } + if (cpu_dai->id & IMX_DAI_ESAI_RX) { + imx_esai_txrx_state |= IMX_DAI_ESAI_RX; + __raw_writel(ESAI_RCR_RPR, ESAI_RCR); + } + + ESAI_DUMP(); + return 0; +} + +/* + * This function is called to initialize the TX port before enable + * the tx port. + */ +static int imx_esai_hw_tx_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params, + struct snd_soc_dai *dai) +{ + u32 tcr, tfcr; + unsigned int channels; + + tcr = __raw_readl(ESAI_TCR); + tfcr = __raw_readl(ESAI_TFCR); + + tfcr |= ESAI_TFCR_TFR; + __raw_writel(tfcr, ESAI_TFCR); + tfcr &= ~ESAI_TFCR_TFR; + /* DAI data (word) size */ + tfcr &= ESAI_TFCR_TWA_MASK; + tcr &= ESAI_TCR_TSWS_MASK; + switch (params_format(params)) { + case SNDRV_PCM_FORMAT_S16_LE: + tfcr |= ESAI_WORD_LEN_16; + tcr |= ESAI_TCR_TSHFD_MSB | ESAI_TCR_TSWS_STL32_WDL16; + break; + case SNDRV_PCM_FORMAT_S20_3LE: + tfcr |= ESAI_WORD_LEN_20; + tcr |= ESAI_TCR_TSHFD_MSB | ESAI_TCR_TSWS_STL32_WDL20; + break; + case SNDRV_PCM_FORMAT_S24_LE: + tfcr |= ESAI_WORD_LEN_24; + tcr |= ESAI_TCR_TSHFD_MSB | ESAI_TCR_TSWS_STL32_WDL24; + break; + } + + channels = params_channels(params); + tfcr &= ESAI_TFCR_TE_MASK; + tfcr |= ESAI_TFCR_TE(channels); + + tfcr |= ESAI_TFCR_TFWM(64); + + /* Left aligned, Zero padding */ + tcr |= ESAI_TCR_PADC; + + __raw_writel(tcr, ESAI_TCR); + __raw_writel(tfcr, ESAI_TFCR); + + ESAI_DUMP(); + return 0; +} + +/* + * This function is called to initialize the RX port before enable + * the rx port. + */ +static int imx_esai_hw_rx_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params, + struct snd_soc_dai *dai) +{ + u32 rcr, rfcr; + unsigned int channels; + + rcr = __raw_readl(ESAI_RCR); + rfcr = __raw_readl(ESAI_RFCR); + + rfcr |= ESAI_RFCR_RFR; + __raw_writel(rfcr, ESAI_RFCR); + rfcr &= ~ESAI_RFCR_RFR; + + rfcr &= ESAI_RFCR_RWA_MASK; + rcr &= ESAI_RCR_RSWS_MASK; + switch (params_format(params)) { + case SNDRV_PCM_FORMAT_S16_LE: + rfcr |= ESAI_WORD_LEN_16; + rcr |= ESAI_RCR_RSHFD_MSB | ESAI_RCR_RSWS_STL32_WDL16; + break; + } + + channels = params_channels(params); + rfcr &= ESAI_RFCR_RE_MASK; + rfcr |= ESAI_RFCR_RE(channels); + + rfcr |= ESAI_RFCR_RFWM(64); + + __raw_writel(rcr, ESAI_RCR); + __raw_writel(rfcr, ESAI_RFCR); + return 0; +} + +/* + * This function is called to initialize the TX or RX port, + */ +static int imx_esai_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params, + struct snd_soc_dai *dai) +{ + /* Tx/Rx config */ + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + if (__raw_readl(ESAI_TCR) & ESAI_TCR_TE0) + return 0; + return imx_esai_hw_tx_params(substream, params, dai); + } else { + if (__raw_readl(ESAI_RCR) & ESAI_RCR_RE1) + return 0; + return imx_esai_hw_rx_params(substream, params, dai); + } +} + +static int imx_esai_trigger(struct snd_pcm_substream *substream, int cmd, + struct snd_soc_dai *dai) +{ + u32 reg, tfcr = 0, rfcr = 0; + u32 temp; + + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + tfcr = __raw_readl(ESAI_TFCR); + reg = __raw_readl(ESAI_TCR); + } else { + rfcr = __raw_readl(ESAI_RFCR); + reg = __raw_readl(ESAI_RCR); + } + switch (cmd) { + case SNDRV_PCM_TRIGGER_START: + case SNDRV_PCM_TRIGGER_RESUME: + case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + tfcr |= ESAI_TFCR_TFEN; + __raw_writel(tfcr, ESAI_TFCR); + reg &= ~ESAI_TCR_TPR; + reg |= ESAI_TCR_TE(substream->runtime->channels); + __raw_writel(reg, ESAI_TCR); + } else { + temp = __raw_readl(ESAI_TCR); + temp &= ~ESAI_TCR_TPR; + __raw_writel(temp, ESAI_TCR); + rfcr |= ESAI_RFCR_RFEN; + __raw_writel(rfcr, ESAI_RFCR); + reg &= ~ESAI_RCR_RPR; + reg |= ESAI_RCR_RE(substream->runtime->channels); + __raw_writel(reg, ESAI_RCR); + } + break; + case SNDRV_PCM_TRIGGER_SUSPEND: + case SNDRV_PCM_TRIGGER_STOP: + case SNDRV_PCM_TRIGGER_PAUSE_PUSH: + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + reg &= ~ESAI_TCR_TE(substream->runtime->channels); + __raw_writel(reg, ESAI_TCR); + reg |= ESAI_TCR_TPR; + __raw_writel(reg, ESAI_TCR); + tfcr |= ESAI_TFCR_TFR; + tfcr &= ~ESAI_TFCR_TFEN; + __raw_writel(tfcr, ESAI_TFCR); + tfcr &= ~ESAI_TFCR_TFR; + __raw_writel(tfcr, ESAI_TFCR); + } else { + reg &= ~ESAI_RCR_RE(substream->runtime->channels); + __raw_writel(reg, ESAI_RCR); + reg |= ESAI_RCR_RPR; + __raw_writel(reg, ESAI_RCR); + rfcr |= ESAI_RFCR_RFR; + rfcr &= ~ESAI_RFCR_RFEN; + __raw_writel(rfcr, ESAI_RFCR); + rfcr &= ~ESAI_RFCR_RFR; + __raw_writel(rfcr, ESAI_RFCR); + } + break; + default: + return -EINVAL; + } + ESAI_DUMP(); + return 0; +} + +static void imx_esai_shutdown(struct snd_pcm_substream *substream, + struct snd_soc_dai *dai) +{ + if (dai->id & IMX_DAI_ESAI_TX) + imx_esai_txrx_state &= ~IMX_DAI_ESAI_TX; + if (dai->id & IMX_DAI_ESAI_RX) + imx_esai_txrx_state &= ~IMX_DAI_ESAI_RX; + + /* shutdown ESAI if neither Tx or Rx is active */ + if (!(imx_esai_txrx_state & IMX_DAI_ESAI_TXRX)) { + free_irq(MXC_INT_ESAI, NULL); + clk_disable(esai_clk); + } +} + +#ifdef CONFIG_PM +static int imx_esai_suspend(struct snd_soc_dai *dai) +{ + if (!dai->active) + return 0; + + /*do we need to disable any clocks */ + return 0; +} + +static int imx_esai_resume(struct snd_soc_dai *dai) +{ + if (!dai->active) + return 0; + + /* do we need to enable any clocks */ + return 0; +} + +#else +#define imx_esai_suspend NULL +#define imx_esai_resume NULL +#endif + +static int imx_esai_probe(struct platform_device *pdev, struct snd_soc_dai *dai) +{ + imx_esai_txrx_state = 0; + + esai_clk = clk_get(NULL, "esai_clk"); + + return 0; +} + +static void imx_esai_remove(struct platform_device *pdev, + struct snd_soc_dai *dai) +{ + + clk_put(esai_clk); +} + +#define IMX_ESAI_RATES SNDRV_PCM_RATE_8000_192000 + +#define IMX_ESAI_FORMATS \ + (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE | \ + SNDRV_PCM_FMTBIT_S24_LE) + +static struct snd_soc_dai_ops imx_esai_dai_ops = { + .startup = imx_esai_startup, + .shutdown = imx_esai_shutdown, + .trigger = imx_esai_trigger, + .hw_params = imx_esai_hw_params, + .set_sysclk = imx_esai_set_dai_sysclk, + .set_clkdiv = imx_esai_set_dai_clkdiv, + .set_fmt = imx_esai_set_dai_fmt, + .set_tdm_slot = imx_esai_set_dai_tdm_slot, +}; + +struct snd_soc_dai imx_esai_dai[] = { + { + .name = "imx-esai-tx", + .id = IMX_DAI_ESAI_TX, + .probe = imx_esai_probe, + .remove = imx_esai_remove, + .suspend = imx_esai_suspend, + .resume = imx_esai_resume, + .playback = { + .channels_min = 1, + .channels_max = 6, + .rates = IMX_ESAI_RATES, + .formats = IMX_ESAI_FORMATS, + }, + .capture = { + .channels_min = 1, + .channels_max = 4, + .rates = IMX_ESAI_RATES, + .formats = IMX_ESAI_FORMATS, + }, + .ops = &imx_esai_dai_ops, + .private_data = &imx_esai_priv[0], + }, + { + .name = "imx-esai-rx", + .id = IMX_DAI_ESAI_RX, + .probe = imx_esai_probe, + .remove = imx_esai_remove, + .suspend = imx_esai_suspend, + .resume = imx_esai_resume, + .playback = { + .channels_min = 1, + .channels_max = 6, + .rates = IMX_ESAI_RATES, + .formats = IMX_ESAI_FORMATS, + }, + .capture = { + .channels_min = 1, + .channels_max = 4, + .rates = IMX_ESAI_RATES, + .formats = IMX_ESAI_FORMATS, + }, + .ops = &imx_esai_dai_ops, + .private_data = &imx_esai_priv[1], + }, + { + .name = "imx-esai-txrx", + .id = IMX_DAI_ESAI_TXRX, + .probe = imx_esai_probe, + .remove = imx_esai_remove, + .suspend = imx_esai_suspend, + .resume = imx_esai_resume, + .playback = { + .channels_min = 1, + .channels_max = 6, + .rates = IMX_ESAI_RATES, + .formats = IMX_ESAI_FORMATS, + }, + .capture = { + .channels_min = 1, + .channels_max = 4, + .rates = IMX_ESAI_RATES, + .formats = IMX_ESAI_FORMATS, + }, + .ops = &imx_esai_dai_ops, + .private_data = &imx_esai_priv[2], + }, + +}; + +EXPORT_SYMBOL_GPL(imx_esai_dai); + +static int imx_esai_dev_probe(struct platform_device *pdev) +{ + struct resource *res; + struct mxc_esai_platform_data *plat_data = pdev->dev.platform_data; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!res) + return -ENODEV; + + esai_ioaddr = ioremap(res->start, res->end - res->start + 1); + + if (plat_data->activate_esai_ports) + plat_data->activate_esai_ports(); + + snd_soc_register_dais(imx_esai_dai, ARRAY_SIZE(imx_esai_dai)); + return 0; +} + +static int __devexit imx_esai_dev_remove(struct platform_device *pdev) +{ + + struct mxc_esai_platform_data *plat_data = pdev->dev.platform_data; + iounmap(esai_ioaddr); + if (plat_data->deactivate_esai_ports) + plat_data->deactivate_esai_ports(); + + snd_soc_unregister_dais(imx_esai_dai, ARRAY_SIZE(imx_esai_dai)); + return 0; +} + + +static struct platform_driver imx_esai_driver = { + .probe = imx_esai_dev_probe, + .remove = __devexit_p(imx_esai_dev_remove), + .driver = { + .name = "mxc_esai", + }, +}; + +static int __init imx_esai_init(void) +{ + return platform_driver_register(&imx_esai_driver); +} + +static void __exit imx_esai_exit(void) +{ + platform_driver_unregister(&imx_esai_driver); +} + +module_init(imx_esai_init); +module_exit(imx_esai_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("i.MX ASoC ESAI driver"); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/imx/imx-esai.h b/sound/soc/imx/imx-esai.h new file mode 100644 index 000000000000..6e2cce0eff4a --- /dev/null +++ b/sound/soc/imx/imx-esai.h @@ -0,0 +1,314 @@ +/* + * imx-esai.h -- ESAI driver header file for Freescale IMX + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#ifndef _MXC_ESAI_H +#define _MXC_ESAI_H + +/*#define IMX_ESAI_DUMP 1*/ + +#ifdef IMX_ESAI_DUMP +#define ESAI_DUMP() \ + do {pr_info("dump @ %s\n", __func__); \ + pr_info("ecr %x\n", __raw_readl(ESAI_ECR)); \ + pr_info("esr %x\n", __raw_readl(ESAI_ESR)); \ + pr_info("tfcr %x\n", __raw_readl(ESAI_TFCR)); \ + pr_info("tfsr %x\n", __raw_readl(ESAI_TFSR)); \ + pr_info("rfcr %x\n", __raw_readl(ESAI_RFCR)); \ + pr_info("rfsr %x\n", __raw_readl(ESAI_RFSR)); \ + pr_info("tsr %x\n", __raw_readl(ESAI_TSR)); \ + pr_info("saisr %x\n", __raw_readl(ESAI_SAISR)); \ + pr_info("saicr %x\n", __raw_readl(ESAI_SAICR)); \ + pr_info("tcr %x\n", __raw_readl(ESAI_TCR)); \ + pr_info("tccr %x\n", __raw_readl(ESAI_TCCR)); \ + pr_info("rcr %x\n", __raw_readl(ESAI_RCR)); \ + pr_info("rccr %x\n", __raw_readl(ESAI_RCCR)); \ + pr_info("tsma %x\n", __raw_readl(ESAI_TSMA)); \ + pr_info("tsmb %x\n", __raw_readl(ESAI_TSMB)); \ + pr_info("rsma %x\n", __raw_readl(ESAI_RSMA)); \ + pr_info("rsmb %x\n", __raw_readl(ESAI_RSMB)); \ + pr_info("prrc %x\n", __raw_readl(ESAI_PRRC)); \ + pr_info("pcrc %x\n", __raw_readl(ESAI_PCRC)); } while (0); +#else +#define ESAI_DUMP() +#endif + +#define ESAI_IO_BASE_ADDR (esai_ioaddr) + +#define ESAI_ETDR (ESAI_IO_BASE_ADDR + 0x00) +#define ESAI_ERDR (ESAI_IO_BASE_ADDR + 0x04) +#define ESAI_ECR (ESAI_IO_BASE_ADDR + 0x08) +#define ESAI_ESR (ESAI_IO_BASE_ADDR + 0x0C) +#define ESAI_TFCR (ESAI_IO_BASE_ADDR + 0x10) +#define ESAI_TFSR (ESAI_IO_BASE_ADDR + 0x14) +#define ESAI_RFCR (ESAI_IO_BASE_ADDR + 0x18) +#define ESAI_RFSR (ESAI_IO_BASE_ADDR + 0x1C) +#define ESAI_TX0 (ESAI_IO_BASE_ADDR + 0x80) +#define ESAI_TX1 (ESAI_IO_BASE_ADDR + 0x84) +#define ESAI_TX2 (ESAI_IO_BASE_ADDR + 0x88) +#define ESAI_TX3 (ESAI_IO_BASE_ADDR + 0x8C) +#define ESAI_TX4 (ESAI_IO_BASE_ADDR + 0x90) +#define ESAI_TX5 (ESAI_IO_BASE_ADDR + 0x94) +#define ESAI_TSR (ESAI_IO_BASE_ADDR + 0x98) +#define ESAI_RX0 (ESAI_IO_BASE_ADDR + 0xA0) +#define ESAI_RX1 (ESAI_IO_BASE_ADDR + 0xA4) +#define ESAI_RX2 (ESAI_IO_BASE_ADDR + 0xA8) +#define ESAI_RX3 (ESAI_IO_BASE_ADDR + 0xAC) +#define ESAI_SAISR (ESAI_IO_BASE_ADDR + 0xCC) +#define ESAI_SAICR (ESAI_IO_BASE_ADDR + 0xD0) +#define ESAI_TCR (ESAI_IO_BASE_ADDR + 0xD4) +#define ESAI_TCCR (ESAI_IO_BASE_ADDR + 0xD8) +#define ESAI_RCR (ESAI_IO_BASE_ADDR + 0xDC) +#define ESAI_RCCR (ESAI_IO_BASE_ADDR + 0xE0) +#define ESAI_TSMA (ESAI_IO_BASE_ADDR + 0xE4) +#define ESAI_TSMB (ESAI_IO_BASE_ADDR + 0xE8) +#define ESAI_RSMA (ESAI_IO_BASE_ADDR + 0xEC) +#define ESAI_RSMB (ESAI_IO_BASE_ADDR + 0xF0) +#define ESAI_PRRC (ESAI_IO_BASE_ADDR + 0xF8) +#define ESAI_PCRC (ESAI_IO_BASE_ADDR + 0xFC) + +#define ESAI_ECR_ETI (1 << 19) +#define ESAI_ECR_ETO (1 << 18) +#define ESAI_ECR_ERI (1 << 17) +#define ESAI_ECR_ERO (1 << 16) +#define ESAI_ECR_ERST (1 << 1) +#define ESAI_ECR_ESAIEN (1 << 0) + +#define ESAI_ESR_TINIT (1 << 10) +#define ESAI_ESR_RFF (1 << 9) +#define ESAI_ESR_TFE (1 << 8) +#define ESAI_ESR_TLS (1 << 7) +#define ESAI_ESR_TDE (1 << 6) +#define ESAI_ESR_TED (1 << 5) +#define ESAI_ESR_TD (1 << 4) +#define ESAI_ESR_RLS (1 << 3) +#define ESAI_ESR_RDE (1 << 2) +#define ESAI_ESR_RED (1 << 1) +#define ESAI_ESR_RD (1 << 0) + +#define ESAI_TFCR_TIEN (1 << 19) +#define ESAI_TFCR_TE5 (1 << 7) +#define ESAI_TFCR_TE4 (1 << 6) +#define ESAI_TFCR_TE3 (1 << 5) +#define ESAI_TFCR_TE2 (1 << 4) +#define ESAI_TFCR_TE1 (1 << 3) +#define ESAI_TFCR_TE0 (1 << 2) +#define ESAI_TFCR_TFR (1 << 1) +#define ESAI_TFCR_TFEN (1 << 0) +#define ESAI_TFCR_TE(x) ((0x3f >> (6 - ((x + 1) >> 1))) << 2) +#define ESAI_TFCR_TE_MASK 0xfff03 +#define ESAI_TFCR_TFWM(x) ((x - 1) << 8) +#define ESAI_TFCR_TWA_MASK 0xf8ffff + +#define ESAI_RFCR_REXT (1 << 19) +#define ESAI_RFCR_RE3 (1 << 5) +#define ESAI_RFCR_RE2 (1 << 4) +#define ESAI_RFCR_RE1 (1 << 3) +#define ESAI_RFCR_RE0 (1 << 2) +#define ESAI_RFCR_RFR (1 << 1) +#define ESAI_RFCR_RFEN (1 << 0) +#define ESAI_RFCR_RE(x) ((0xf >> (4 - ((x + 1) >> 1))) << 2) +#define ESAI_RFCR_RE_MASK 0xfffc3 +#define ESAI_RFCR_RFWM(x) ((x-1) << 8) +#define ESAI_RFCR_RWA_MASK 0xf8ffff + +#define ESAI_WORD_LEN_32 (0x00 << 16) +#define ESAI_WORD_LEN_28 (0x01 << 16) +#define ESAI_WORD_LEN_24 (0x02 << 16) +#define ESAI_WORD_LEN_20 (0x03 << 16) +#define ESAI_WORD_LEN_16 (0x04 << 16) +#define ESAI_WORD_LEN_12 (0x05 << 16) +#define ESAI_WORD_LEN_8 (0x06 << 16) +#define ESAI_WORD_LEN_4 (0x07 << 16) + +#define ESAI_SAISR_TODFE (1 << 17) +#define ESAI_SAISR_TEDE (1 << 16) +#define ESAI_SAISR_TDE (1 << 15) +#define ESAI_SAISR_TUE (1 << 14) +#define ESAI_SAISR_TFS (1 << 13) +#define ESAI_SAISR_RODF (1 << 10) +#define ESAI_SAISR_REDF (1 << 9) +#define ESAI_SAISR_RDF (1 << 8) +#define ESAI_SAISR_ROE (1 << 7) +#define ESAI_SAISR_RFS (1 << 6) +#define ESAI_SAISR_IF2 (1 << 2) +#define ESAI_SAISR_IF1 (1 << 1) +#define ESAI_SAISR_IF0 (1 << 0) + +#define ESAI_SAICR_ALC (1 << 8) +#define ESAI_SAICR_TEBE (1 << 7) +#define ESAI_SAICR_SYNC (1 << 6) +#define ESAI_SAICR_OF2 (1 << 2) +#define ESAI_SAICR_OF1 (1 << 1) +#define ESAI_SAICR_OF0 (1 << 0) + +#define ESAI_TCR_TLIE (1 << 23) +#define ESAI_TCR_TIE (1 << 22) +#define ESAI_TCR_TEDIE (1 << 21) +#define ESAI_TCR_TEIE (1 << 20) +#define ESAI_TCR_TPR (1 << 19) +#define ESAI_TCR_PADC (1 << 17) +#define ESAI_TCR_TFSR (1 << 16) +#define ESAI_TCR_TFSL (1 << 15) +#define ESAI_TCR_TWA (1 << 7) +#define ESAI_TCR_TSHFD_MSB (0 << 6) +#define ESAI_TCR_TSHFD_LSB (1 << 6) +#define ESAI_TCR_TE5 (1 << 5) +#define ESAI_TCR_TE4 (1 << 4) +#define ESAI_TCR_TE3 (1 << 3) +#define ESAI_TCR_TE2 (1 << 2) +#define ESAI_TCR_TE1 (1 << 1) +#define ESAI_TCR_TE0 (1 << 0) +#define ESAI_TCR_TE(x) (0x3f >> (6 - ((x + 1) >> 1))) + +#define ESAI_TCR_TSWS_MASK 0xff83ff +#define ESAI_TCR_TSWS_STL8_WDL8 (0x00 << 10) +#define ESAI_TCR_TSWS_STL12_WDL8 (0x04 << 10) +#define ESAI_TCR_TSWS_STL12_WDL12 (0x01 << 10) +#define ESAI_TCR_TSWS_STL16_WDL8 (0x08 << 10) +#define ESAI_TCR_TSWS_STL16_WDL12 (0x05 << 10) +#define ESAI_TCR_TSWS_STL16_WDL16 (0x02 << 10) +#define ESAI_TCR_TSWS_STL20_WDL8 (0x0c << 10) +#define ESAI_TCR_TSWS_STL20_WDL12 (0x09 << 10) +#define ESAI_TCR_TSWS_STL20_WDL16 (0x06 << 10) +#define ESAI_TCR_TSWS_STL20_WDL20 (0x03 << 10) +#define ESAI_TCR_TSWS_STL24_WDL8 (0x10 << 10) +#define ESAI_TCR_TSWS_STL24_WDL12 (0x0d << 10) +#define ESAI_TCR_TSWS_STL24_WDL16 (0x0a << 10) +#define ESAI_TCR_TSWS_STL24_WDL20 (0x07 << 10) +#define ESAI_TCR_TSWS_STL24_WDL24 (0x1e << 10) +#define ESAI_TCR_TSWS_STL32_WDL8 (0x18 << 10) +#define ESAI_TCR_TSWS_STL32_WDL12 (0x15 << 10) +#define ESAI_TCR_TSWS_STL32_WDL16 (0x12 << 10) +#define ESAI_TCR_TSWS_STL32_WDL20 (0x0f << 10) +#define ESAI_TCR_TSWS_STL32_WDL24 (0x1f << 10) + +#define ESAI_TCR_TMOD_MASK 0xfffcff +#define ESAI_TCR_TMOD_NORMAL (0x00 << 8) +#define ESAI_TCR_TMOD_ONDEMAND (0x01 << 8) +#define ESAI_TCR_TMOD_NETWORK (0x01 << 8) +#define ESAI_TCR_TMOD_RESERVED (0x02 << 8) +#define ESAI_TCR_TMOD_AC97 (0x03 << 8) + +#define ESAI_TCCR_THCKD (1 << 23) +#define ESAI_TCCR_TFSD (1 << 22) +#define ESAI_TCCR_TCKD (1 << 21) +#define ESAI_TCCR_THCKP (1 << 20) +#define ESAI_TCCR_TFSP (1 << 19) +#define ESAI_TCCR_TCKP (1 << 18) + +#define ESAI_TCCR_TPSR_MASK 0xfffeff +#define ESAI_TCCR_TPSR_BYPASS (1 << 8) +#define ESAI_TCCR_TPSR_DIV8 (0 << 8) + +#define ESAI_TCCR_TFP_MASK 0xfc3fff +#define ESAI_TCCR_TFP(x) ((x & 0xf) << 14) + +#define ESAI_TCCR_TDC_MASK 0xffc1ff +#define ESAI_TCCR_TDC(x) (((x) & 0x1f) << 9) + +#define ESAI_TCCR_TPM_MASK 0xffff00 +#define ESAI_TCCR_TPM(x) (x & 0xff) + +#define ESAI_RCR_RLIE (1 << 23) +#define ESAI_RCR_RIE (1 << 22) +#define ESAI_RCR_REDIE (1 << 21) +#define ESAI_RCR_REIE (1 << 20) +#define ESAI_RCR_RPR (1 << 19) +#define ESAI_RCR_RFSR (1 << 16) +#define ESAI_RCR_RFSL (1 << 15) +#define ESAI_RCR_RWA (1 << 7) +#define ESAI_RCR_RSHFD_MSB (0 << 6) +#define ESAI_RCR_RSHFD_LSB (1 << 6) +#define ESAI_RCR_RE3 (1 << 3) +#define ESAI_RCR_RE2 (1 << 2) +#define ESAI_RCR_RE1 (1 << 1) +#define ESAI_RCR_RE0 (1 << 0) +#define ESAI_RCR_RE(x) (0xf >> (4 - ((x + 1) >> 1))) + +#define ESAI_RCR_RSWS_MASK 0xff83ff +#define ESAI_RCR_RSWS_STL8_WDL8 (0x00 << 10) +#define ESAI_RCR_RSWS_STL12_WDL8 (0x04 << 10) +#define ESAI_RCR_RSWS_STL12_WDL12 (0x01 << 10) +#define ESAI_RCR_RSWS_STL16_WDL8 (0x08 << 10) +#define ESAI_RCR_RSWS_STL16_WDL12 (0x05 << 10) +#define ESAI_RCR_RSWS_STL16_WDL16 (0x02 << 10) +#define ESAI_RCR_RSWS_STL20_WDL8 (0x0c << 10) +#define ESAI_RCR_RSWS_STL20_WDL12 (0x09 << 10) +#define ESAI_RCR_RSWS_STL20_WDL16 (0x06 << 10) +#define ESAI_RCR_RSWS_STL20_WDL20 (0x03 << 10) +#define ESAI_RCR_RSWS_STL24_WDL8 (0x10 << 10) +#define ESAI_RCR_RSWS_STL24_WDL12 (0x0d << 10) +#define ESAI_RCR_RSWS_STL24_WDL16 (0x0a << 10) +#define ESAI_RCR_RSWS_STL24_WDL20 (0x07 << 10) +#define ESAI_RCR_RSWS_STL24_WDL24 (0x1e << 10) +#define ESAI_RCR_RSWS_STL32_WDL8 (0x18 << 10) +#define ESAI_RCR_RSWS_STL32_WDL12 (0x15 << 10) +#define ESAI_RCR_RSWS_STL32_WDL16 (0x12 << 10) +#define ESAI_RCR_RSWS_STL32_WDL20 (0x0f << 10) +#define ESAI_RCR_RSWS_STL32_WDL24 (0x1f << 10) + +#define ESAI_RCR_RMOD_MASK 0xfffcff +#define ESAI_RCR_RMOD_NORMAL (0x00 << 8) +#define ESAI_RCR_RMOD_ONDEMAND (0x01 << 8) +#define ESAI_RCR_RMOD_NETWORK (0x01 << 8) +#define ESAI_RCR_RMOD_RESERVED (0x02 << 8) +#define ESAI_RCR_RMOD_AC97 (0x03 << 8) + +#define ESAI_RCCR_RHCKD (1 << 23) +#define ESAI_RCCR_RFSD (1 << 22) +#define ESAI_RCCR_RCKD (1 << 21) +#define ESAI_RCCR_RHCKP (1 << 20) +#define ESAI_RCCR_RFSP (1 << 19) +#define ESAI_RCCR_RCKP (1 << 18) + +#define ESAI_RCCR_RPSR_MASK 0xfffeff +#define ESAI_RCCR_RPSR_BYPASS (1 << 8) +#define ESAI_RCCR_RPSR_DIV8 (0 << 8) + +#define ESAI_RCCR_RFP_MASK 0xfc3fff +#define ESAI_RCCR_RFP(x) ((x & 0xf) << 14) + +#define ESAI_RCCR_RDC_MASK 0xffc1ff +#define ESAI_RCCR_RDC(x) (((x) & 0x1f) << 9) + +#define ESAI_RCCR_RPM_MASK 0xffff00 +#define ESAI_RCCR_RPM(x) (x & 0xff) + +#define ESAI_GPIO_ESAI 0xfff + +/* ESAI clock source */ +#define ESAI_CLK_FSYS 0 +#define ESAI_CLK_EXTAL 1 + +/* ESAI clock divider */ +#define ESAI_TX_DIV_PSR 0 +#define ESAI_TX_DIV_PM 1 +#define ESAI_TX_DIV_FP 2 +#define ESAI_RX_DIV_PSR 3 +#define ESAI_RX_DIV_PM 4 +#define ESAI_RX_DIV_FP 5 + +#define IMX_DAI_ESAI_TX 0x04 +#define IMX_DAI_ESAI_RX 0x08 +#define IMX_DAI_ESAI_TXRX (IMX_DAI_ESAI_TX | IMX_DAI_ESAI_RX) + +struct imx_esai { + bool network_mode; + bool sync_mode; +}; + +extern struct snd_soc_dai imx_esai_dai[]; + +#endif diff --git a/sound/soc/imx/imx-pcm.c b/sound/soc/imx/imx-pcm.c new file mode 100644 index 000000000000..3e8a90da35c2 --- /dev/null +++ b/sound/soc/imx/imx-pcm.c @@ -0,0 +1,688 @@ +/* + * imx-pcm.c -- ALSA SoC interface for the Freescale i.MX3 CPU's + * + * Copyright 2006 Wolfson Microelectronics PLC. + * Copyright (C) 2006-2010 Freescale Semiconductor, Inc. + * Author: Liam Girdwood + * liam.girdwood@wolfsonmicro.com or linux@wolfsonmicro.com + * + * Based on imx31-pcm.c by Nicolas Pitre, (C) 2004 MontaVista Software, Inc. + * and on mxc-alsa-mc13783 (C) 2006 Freescale. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "imx-pcm.h" +#include "imx-ssi.h" +#include "imx-esai.h" + +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) +#include +#include +#endif + +#ifdef CONFIG_SND_MXC_SOC_IRAM +static bool UseIram = 1; +#else +static bool UseIram; +#endif + +/* debug */ +#define IMX_PCM_DEBUG 0 +#if IMX_PCM_DEBUG +#define dbg(format, arg...) printk(format, ## arg) +#else +#define dbg(format, arg...) +#endif + +static const struct snd_pcm_hardware imx_pcm_hardware = { + .info = (SNDRV_PCM_INFO_INTERLEAVED | + SNDRV_PCM_INFO_BLOCK_TRANSFER | + SNDRV_PCM_INFO_MMAP | + SNDRV_PCM_INFO_MMAP_VALID | + SNDRV_PCM_INFO_PAUSE | SNDRV_PCM_INFO_RESUME), + .formats = SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S24_LE, +#ifdef CONFIG_SND_MXC_SOC_IRAM + .buffer_bytes_max = SND_RAM_SIZE, + .period_bytes_max = SND_RAM_SIZE / 4, +#else + .buffer_bytes_max = 64 * 1024, + .period_bytes_max = 16 * 1024, +#endif + .period_bytes_min = 2 * SZ_1K, + .periods_min = 2, + .periods_max = 255, + .fifo_size = 0, +}; + +static struct vm_operations_struct snd_mxc_audio_playback_vm_ops = { + .open = snd_pcm_mmap_data_open, + .close = snd_pcm_mmap_data_close, +}; + +/* + enable user space access to iram buffer +*/ +static int imx_iram_audio_playback_mmap(struct snd_pcm_substream *substream, + struct vm_area_struct *area) +{ + struct snd_dma_buffer *buf = &substream->dma_buffer; + unsigned long off; + unsigned long phys; + unsigned long size; + int ret = 0; + + area->vm_ops = &snd_mxc_audio_playback_vm_ops; + area->vm_private_data = substream; + + off = area->vm_pgoff << PAGE_SHIFT; + phys = buf->addr + off; + size = area->vm_end - area->vm_start; + + if (off + size > SND_RAM_SIZE) + return -EINVAL; + + area->vm_page_prot = pgprot_writecombine(area->vm_page_prot); + area->vm_flags |= VM_IO; + ret = + remap_pfn_range(area, area->vm_start, phys >> PAGE_SHIFT, + size, area->vm_page_prot); + if (ret == 0) + area->vm_ops->open(area); + + return ret; +} + +static int imx_get_sdma_transfer(int format, int dai_port, + struct snd_pcm_substream *substream) +{ + int transfer = -1; + +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) + struct snd_pcm_runtime *runtime = substream->runtime; + struct mxc_runtime_data *prtd = runtime->private_data; + if (prtd->asrc_enable == 1) { + if (dai_port == IMX_DAI_SSI0) { + if (prtd->asrc_index == 0) + transfer = MXC_DMA_ASRCA_SSI1_TX0; + else if (prtd->asrc_index == 1) + transfer = MXC_DMA_ASRCB_SSI1_TX0; + } else if (dai_port == IMX_DAI_SSI1) { + if (prtd->asrc_index == 0) + transfer = MXC_DMA_ASRCA_SSI1_TX1; + else if (prtd->asrc_index == 1) + transfer = MXC_DMA_ASRCB_SSI1_TX1; + } else if (dai_port == IMX_DAI_SSI2) { + if (prtd->asrc_index == 0) + transfer = MXC_DMA_ASRCA_SSI2_TX0; + else if (prtd->asrc_index == 1) + transfer = MXC_DMA_ASRCB_SSI2_TX0; + } else if (dai_port == IMX_DAI_SSI3) { + if (prtd->asrc_index == 0) + transfer = MXC_DMA_ASRCA_SSI2_TX1; + else if (prtd->asrc_index == 1) + transfer = MXC_DMA_ASRCB_SSI2_TX1; + } else if (dai_port & IMX_DAI_ESAI_TX) { + if (prtd->asrc_index == 0) + transfer = MXC_DMA_ASRCA_ESAI; + else if (prtd->asrc_index == 1) + transfer = MXC_DMA_ASRCB_ESAI; + else + transfer = MXC_DMA_ASRCC_ESAI; + } + } else { +#endif + + if (dai_port == IMX_DAI_SSI0) { + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + if (format == SNDRV_PCM_FORMAT_S16_LE) + transfer = MXC_DMA_SSI1_16BIT_TX0; + else if (format == SNDRV_PCM_FORMAT_S24_LE) + transfer = MXC_DMA_SSI1_24BIT_TX0; + else if (format == SNDRV_PCM_FORMAT_S20_3LE) + transfer = MXC_DMA_SSI1_24BIT_TX0; + } else { + if (format == SNDRV_PCM_FORMAT_S16_LE) + transfer = MXC_DMA_SSI1_16BIT_RX0; + else if (format == SNDRV_PCM_FORMAT_S24_LE) + transfer = MXC_DMA_SSI1_24BIT_RX0; + else if (format == SNDRV_PCM_FORMAT_S20_3LE) + transfer = MXC_DMA_SSI1_24BIT_RX0; + } + } else if (dai_port == IMX_DAI_SSI1) { + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + if (format == SNDRV_PCM_FORMAT_S16_LE) + transfer = MXC_DMA_SSI1_16BIT_TX1; + else if (format == SNDRV_PCM_FORMAT_S24_LE) + transfer = MXC_DMA_SSI1_24BIT_TX1; + else if (format == SNDRV_PCM_FORMAT_S20_3LE) + transfer = MXC_DMA_SSI1_24BIT_TX1; + } else { + if (format == SNDRV_PCM_FORMAT_S16_LE) + transfer = MXC_DMA_SSI1_16BIT_RX1; + else if (format == SNDRV_PCM_FORMAT_S24_LE) + transfer = MXC_DMA_SSI1_24BIT_RX1; + else if (format == SNDRV_PCM_FORMAT_S20_3LE) + transfer = MXC_DMA_SSI1_24BIT_RX1; + } + } else if (dai_port == IMX_DAI_SSI2) { + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + if (format == SNDRV_PCM_FORMAT_S16_LE) + transfer = MXC_DMA_SSI2_16BIT_TX0; + else if (format == SNDRV_PCM_FORMAT_S24_LE) + transfer = MXC_DMA_SSI2_24BIT_TX0; + else if (format == SNDRV_PCM_FORMAT_S20_3LE) + transfer = MXC_DMA_SSI2_24BIT_TX0; + } else { + if (format == SNDRV_PCM_FORMAT_S16_LE) + transfer = MXC_DMA_SSI2_16BIT_RX0; + else if (format == SNDRV_PCM_FORMAT_S24_LE) + transfer = MXC_DMA_SSI2_24BIT_RX0; + else if (format == SNDRV_PCM_FORMAT_S20_3LE) + transfer = MXC_DMA_SSI2_24BIT_RX0; + } + } else if (dai_port == IMX_DAI_SSI3) { + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + if (format == SNDRV_PCM_FORMAT_S16_LE) + transfer = MXC_DMA_SSI2_16BIT_TX1; + else if (format == SNDRV_PCM_FORMAT_S24_LE) + transfer = MXC_DMA_SSI2_24BIT_TX1; + else if (format == SNDRV_PCM_FORMAT_S20_3LE) + transfer = MXC_DMA_SSI2_24BIT_TX1; + } else { + if (format == SNDRV_PCM_FORMAT_S16_LE) + transfer = MXC_DMA_SSI2_16BIT_RX1; + else if (format == SNDRV_PCM_FORMAT_S24_LE) + transfer = MXC_DMA_SSI2_24BIT_RX1; + else if (format == SNDRV_PCM_FORMAT_S20_3LE) + transfer = MXC_DMA_SSI2_24BIT_RX1; + } + } else if ((dai_port & IMX_DAI_ESAI_TX) + || (dai_port & IMX_DAI_ESAI_RX)) { + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + if (format == SNDRV_PCM_FORMAT_S16_LE) + transfer = MXC_DMA_ESAI_16BIT_TX; + else if (format == SNDRV_PCM_FORMAT_S24_LE) + transfer = MXC_DMA_ESAI_24BIT_TX; + else if (format == SNDRV_PCM_FORMAT_S20_3LE) + transfer = MXC_DMA_ESAI_24BIT_TX; + } else { + if (format == SNDRV_PCM_FORMAT_S16_LE) + transfer = MXC_DMA_ESAI_16BIT_RX; + else if (format == SNDRV_PCM_FORMAT_S24_LE) + transfer = MXC_DMA_ESAI_24BIT_RX; + else if (format == SNDRV_PCM_FORMAT_S20_3LE) + transfer = MXC_DMA_ESAI_24BIT_RX; + } + } +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) + } +#endif + return transfer; +} + +static int dma_new_period(struct snd_pcm_substream *substream) +{ + struct snd_pcm_runtime *runtime = substream->runtime; + struct mxc_runtime_data *prtd = runtime->private_data; + unsigned int dma_size = frames_to_bytes(runtime, runtime->period_size); + unsigned int offset = dma_size * prtd->period; + int ret = 0; + mxc_dma_requestbuf_t sdma_request; + + if (!prtd->active) + return 0; + + memset(&sdma_request, 0, sizeof(mxc_dma_requestbuf_t)); + + dbg("period pos ALSA %x DMA %x\n", runtime->periods, prtd->period); + dbg("period size ALSA %x DMA %x Offset %x dmasize %x\n", + (unsigned int)runtime->period_size, + runtime->dma_bytes, offset, dma_size); + dbg("DMA addr %x\n", runtime->dma_addr + offset); + + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) + sdma_request.src_addr = + (dma_addr_t) (runtime->dma_addr + offset); + else + sdma_request.dst_addr = + (dma_addr_t) (runtime->dma_addr + offset); + + sdma_request.num_of_bytes = dma_size; + + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + mxc_dma_config(prtd->dma_wchannel, + &sdma_request, 1, MXC_DMA_MODE_WRITE); + ret = mxc_dma_enable(prtd->dma_wchannel); + } else { + + mxc_dma_config(prtd->dma_wchannel, + &sdma_request, 1, MXC_DMA_MODE_READ); + ret = mxc_dma_enable(prtd->dma_wchannel); + } + prtd->dma_active = 1; + prtd->period++; + prtd->period %= runtime->periods; + + return ret; +} + +static void audio_dma_irq(void *data) +{ + struct snd_pcm_substream *substream = (struct snd_pcm_substream *)data; + struct snd_pcm_runtime *runtime = substream->runtime; + struct mxc_runtime_data *prtd = runtime->private_data; + + prtd->dma_active = 0; + prtd->periods++; + prtd->periods %= runtime->periods; + + dbg("irq per %d offset %x\n", prtd->periods, + frames_to_bytes(runtime, runtime->period_size) * prtd->periods); + + if (prtd->active) + snd_pcm_period_elapsed(substream); + dma_new_period(substream); +} + +static int imx_pcm_prepare(struct snd_pcm_substream *substream) +{ + struct snd_pcm_runtime *runtime = substream->runtime; + struct mxc_runtime_data *prtd = runtime->private_data; + int ret = 0, channel = 0; + + if (prtd->dma_alloc) { + mxc_dma_free(prtd->dma_wchannel); + prtd->dma_alloc = 0; + } + + /* only allocate the DMA chn once */ + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) + if (prtd->asrc_enable == 1) { + struct dma_channel_info info; + mxc_dma_requestbuf_t sdma_request; + info.asrc.channs = runtime->channels; + if (prtd->dma_asrc) { + mxc_dma_free(prtd->dma_asrc); + prtd->dma_asrc = 0; + } + memset(&sdma_request, 0, sizeof(mxc_dma_requestbuf_t)); + /* num_of_bytes can be set any value except for zero */ + sdma_request.num_of_bytes = 0x40; + channel = + mxc_dma_request_ext(prtd->dma_ch, + "ALSA TX SDMA", &info); + + mxc_dma_config(channel, &sdma_request, + 1, MXC_DMA_MODE_WRITE); + prtd->dma_asrc = channel; + if (prtd->asrc_index == 0) + prtd->dma_ch = MXC_DMA_ASRC_A_RX; + else if (prtd->asrc_index == 1) + prtd->dma_ch = MXC_DMA_ASRC_B_RX; + else + prtd->dma_ch = MXC_DMA_ASRC_C_RX; + + channel = + mxc_dma_request(MXC_DMA_ASRC_A_RX, "ALSA ASRC RX"); + } else + channel = mxc_dma_request(prtd->dma_ch, "ALSA TX SDMA"); +#else + channel = mxc_dma_request(prtd->dma_ch, "ALSA TX SDMA"); +#endif + if (channel < 0) { + pr_err("imx-pcm: error requesting \ + a write dma channel\n"); + return channel; + } + ret = mxc_dma_callback_set(channel, (mxc_dma_callback_t) + audio_dma_irq, (void *)substream); + + } else { + channel = mxc_dma_request(prtd->dma_ch, "ALSA RX SDMA"); + if (channel < 0) { + pr_err("imx-pcm: error requesting \ + a read dma channel\n"); + return channel; + } + ret = mxc_dma_callback_set(channel, (mxc_dma_callback_t) + audio_dma_irq, (void *)substream); + } + prtd->dma_wchannel = channel; + prtd->dma_alloc = 1; + + prtd->period = 0; + prtd->periods = 0; + return 0; +} + +static int imx_pcm_hw_params(struct snd_pcm_substream + *substream, struct snd_pcm_hw_params *params) +{ + struct snd_pcm_runtime *runtime = substream->runtime; + struct mxc_runtime_data *prtd = runtime->private_data; + struct snd_soc_pcm_runtime *rtd = substream->private_data; + + prtd->dma_ch = + imx_get_sdma_transfer(params_format(params), + rtd->dai->cpu_dai->id, substream); + + if (prtd->dma_ch < 0) { + printk(KERN_ERR "imx-pcm: invaild sdma transfer type"); + return -1; + } + + snd_pcm_set_runtime_buffer(substream, &substream->dma_buffer); + + return 0; +} + +static int imx_pcm_hw_free(struct snd_pcm_substream *substream) +{ + struct snd_pcm_runtime *runtime = substream->runtime; + struct mxc_runtime_data *prtd = runtime->private_data; + + if (prtd->dma_wchannel) { + mxc_dma_free(prtd->dma_wchannel); + prtd->dma_wchannel = 0; + prtd->dma_alloc = 0; + } +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) + if ((prtd->asrc_enable == 1) && prtd->dma_asrc) { + mxc_dma_free(prtd->dma_asrc); + prtd->dma_asrc = 0; + } +#endif + + return 0; +} + +static int imx_pcm_trigger(struct snd_pcm_substream *substream, int cmd) +{ + struct mxc_runtime_data *prtd = substream->runtime->private_data; + int ret = 0; + + switch (cmd) { + case SNDRV_PCM_TRIGGER_START: + case SNDRV_PCM_TRIGGER_RESUME: + case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: + prtd->dma_active = 0; + prtd->active = 1; + ret = dma_new_period(substream); + ret = dma_new_period(substream); +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) + if (prtd->asrc_enable == 1) { + ret = mxc_dma_enable(prtd->dma_asrc); + asrc_start_conv(prtd->asrc_index); + /* There is underrun, if immediately enable SSI after + start ASRC */ + mdelay(1); + } +#endif + break; + case SNDRV_PCM_TRIGGER_STOP: + case SNDRV_PCM_TRIGGER_SUSPEND: + case SNDRV_PCM_TRIGGER_PAUSE_PUSH: + prtd->active = 0; +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) + if (prtd->asrc_enable == 1) { + mxc_dma_disable(prtd->dma_asrc); + asrc_stop_conv(prtd->asrc_index); + } +#endif + break; + default: + ret = -EINVAL; + break; + } + + return ret; +} + +static snd_pcm_uframes_t imx_pcm_pointer(struct + snd_pcm_substream + *substream) +{ + struct snd_pcm_runtime *runtime = substream->runtime; + struct mxc_runtime_data *prtd = runtime->private_data; + unsigned int offset = 0; + + offset = (runtime->period_size * (prtd->periods)); + if (offset >= runtime->buffer_size) + offset = 0; + dbg("pointer offset %x\n", offset); + + return offset; +} + +static int imx_pcm_open(struct snd_pcm_substream *substream) +{ + struct snd_pcm_runtime *runtime = substream->runtime; + struct mxc_runtime_data *prtd; + int ret; + + snd_soc_set_runtime_hwparams(substream, &imx_pcm_hardware); + + ret = snd_pcm_hw_constraint_integer(runtime, + SNDRV_PCM_HW_PARAM_PERIODS); + if (ret < 0) + return ret; + + prtd = kzalloc(sizeof(struct mxc_runtime_data), GFP_KERNEL); + if (prtd == NULL) + return -ENOMEM; + + runtime->private_data = prtd; + return 0; +} + +static int imx_pcm_close(struct snd_pcm_substream *substream) +{ + struct snd_pcm_runtime *runtime = substream->runtime; + struct mxc_runtime_data *prtd = runtime->private_data; + + kfree(prtd); + return 0; +} + +static int +imx_pcm_mmap(struct snd_pcm_substream *substream, struct vm_area_struct *vma) +{ + struct snd_pcm_runtime *runtime = substream->runtime; + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_device *socdev = rtd->socdev; + struct snd_soc_dai *cpu_dai = socdev->card->dai_link->cpu_dai; + struct mxc_audio_platform_data *dev_data; + int ext_ram = 0; + int ret = 0; + + dbg("+imx_pcm_mmap:" + "UseIram=%d dma_addr=%x dma_area=%x dma_bytes=%d\n", + UseIram, (unsigned int)runtime->dma_addr, + runtime->dma_area, runtime->dma_bytes); + + if (cpu_dai->dev && cpu_dai->dev->platform_data) { + dev_data = cpu_dai->dev->platform_data; + ext_ram = dev_data->ext_ram; + } + + if ((substream->stream == SNDRV_PCM_STREAM_CAPTURE) + || ext_ram || !UseIram) { + ret = + dma_mmap_writecombine(substream->pcm->card-> + dev, vma, + runtime->dma_area, + runtime->dma_addr, + runtime->dma_bytes); + return ret; + } else + return imx_iram_audio_playback_mmap(substream, vma); +} + +struct snd_pcm_ops imx_pcm_ops = { + .open = imx_pcm_open, + .close = imx_pcm_close, + .ioctl = snd_pcm_lib_ioctl, + .hw_params = imx_pcm_hw_params, + .hw_free = imx_pcm_hw_free, + .prepare = imx_pcm_prepare, + .trigger = imx_pcm_trigger, + .pointer = imx_pcm_pointer, + .mmap = imx_pcm_mmap, +}; + +static int imx_pcm_preallocate_dma_buffer(struct snd_pcm *pcm, int stream) +{ + struct snd_pcm_substream *substream = pcm->streams[stream].substream; + struct snd_dma_buffer *buf = &substream->dma_buffer; + struct snd_soc_pcm_runtime *rtd = pcm->private_data; + struct snd_soc_device *socdev = rtd->socdev; + struct snd_soc_dai *cpu_dai = socdev->card->dai_link->cpu_dai; + struct mxc_audio_platform_data *dev_data; + unsigned long buf_paddr; + int ext_ram = 0; + size_t size = imx_pcm_hardware.buffer_bytes_max; + + if (cpu_dai->dev && cpu_dai->dev->platform_data) { + dev_data = cpu_dai->dev->platform_data; + ext_ram = dev_data->ext_ram; + } + + buf->dev.type = SNDRV_DMA_TYPE_DEV; + buf->dev.dev = pcm->card->dev; + buf->private_data = NULL; + + if ((stream == SNDRV_PCM_STREAM_CAPTURE) || ext_ram || !UseIram) + buf->area = + dma_alloc_writecombine(pcm->card->dev, size, + &buf->addr, GFP_KERNEL); + else { + buf->area = iram_alloc(size, &buf_paddr); + buf->addr = buf_paddr; + + if (!buf->area) { + pr_warning("imx-pcm: Falling back to external ram.\n"); + UseIram = 0; + buf->area = + dma_alloc_writecombine(pcm->card->dev, size, + &buf->addr, GFP_KERNEL); + } + } + + if (!buf->area) + return -ENOMEM; + buf->bytes = size; + printk(KERN_INFO "DMA Sound Buffers Allocated:" + "UseIram=%d buf->addr=%x buf->area=%p size=%d\n", + UseIram, buf->addr, buf->area, size); + return 0; +} + +static void imx_pcm_free_dma_buffers(struct snd_pcm *pcm) +{ + struct snd_pcm_substream *substream; + struct snd_dma_buffer *buf; + struct snd_soc_pcm_runtime *rtd = pcm->private_data; + struct snd_soc_device *socdev = rtd->socdev; + struct snd_soc_dai *cpu_dai = socdev->card->dai_link->cpu_dai; + struct mxc_audio_platform_data *dev_data; + int ext_ram = 0; + int stream; + + if (cpu_dai->dev && cpu_dai->dev->platform_data) { + dev_data = cpu_dai->dev->platform_data; + ext_ram = dev_data->ext_ram; + } + + for (stream = 0; stream < 2; stream++) { + substream = pcm->streams[stream].substream; + if (!substream) + continue; + + buf = &substream->dma_buffer; + if (!buf->area) + continue; + + if ((stream == SNDRV_PCM_STREAM_CAPTURE) + || ext_ram || !UseIram) + dma_free_writecombine(pcm->card->dev, + buf->bytes, buf->area, buf->addr); + else { + iram_free(buf->addr, imx_pcm_hardware.buffer_bytes_max); + } + buf->area = NULL; + } +} + +static u64 imx_pcm_dmamask = 0xffffffff; + +static int imx_pcm_new(struct snd_card *card, + struct snd_soc_dai *dai, struct snd_pcm *pcm) +{ + int ret = 0; + + if (!card->dev->dma_mask) + card->dev->dma_mask = &imx_pcm_dmamask; + if (!card->dev->coherent_dma_mask) + card->dev->coherent_dma_mask = 0xffffffff; + + if (dai->playback.channels_min) { + ret = imx_pcm_preallocate_dma_buffer(pcm, + SNDRV_PCM_STREAM_PLAYBACK); + if (ret) + goto out; + } + + if (dai->capture.channels_min) { + ret = imx_pcm_preallocate_dma_buffer(pcm, + SNDRV_PCM_STREAM_CAPTURE); + if (ret) + goto out; + } + out: + return ret; +} + +struct snd_soc_platform imx_soc_platform = { + .name = "imx-audio", + .pcm_ops = &imx_pcm_ops, + .pcm_new = imx_pcm_new, + .pcm_free = imx_pcm_free_dma_buffers, +}; +EXPORT_SYMBOL_GPL(imx_soc_platform); + +static int __init imx_pcm_init(void) +{ + return snd_soc_register_platform(&imx_soc_platform); +} +module_init(imx_pcm_init); + +static void __exit imx_pcm_exit(void) +{ + snd_soc_unregister_platform(&imx_soc_platform); +} +module_exit(imx_pcm_exit); + +MODULE_AUTHOR("Liam Girdwood"); +MODULE_DESCRIPTION("Freescale i.MX3x PCM DMA module"); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/imx/imx-pcm.h b/sound/soc/imx/imx-pcm.h new file mode 100644 index 000000000000..5a7efa171a71 --- /dev/null +++ b/sound/soc/imx/imx-pcm.h @@ -0,0 +1,83 @@ +/* + * imx-pcm.h :- ASoC platform header for Freescale i.MX + * + * Copyright 2006 Wolfson Microelectronics PLC. + * Copyright 2006, 2009-2010 Freescale Semiconductor, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ + +#ifndef _MXC_PCM_H +#define _MXC_PCM_H + +#include + +/* AUDMUX regs definition */ +#define AUDMUX_IO_BASE_ADDR IO_ADDRESS(AUDMUX_BASE_ADDR) + +#define DAM_PTCR1 ((AUDMUX_IO_BASE_ADDR) + 0x00) +#define DAM_PDCR1 ((AUDMUX_IO_BASE_ADDR) + 0x04) +#define DAM_PTCR2 ((AUDMUX_IO_BASE_ADDR) + 0x08) +#define DAM_PDCR2 ((AUDMUX_IO_BASE_ADDR) + 0x0C) +#define DAM_PTCR3 ((AUDMUX_IO_BASE_ADDR) + 0x10) +#define DAM_PDCR3 ((AUDMUX_IO_BASE_ADDR) + 0x14) +#define DAM_PTCR4 ((AUDMUX_IO_BASE_ADDR) + 0x18) +#define DAM_PDCR4 ((AUDMUX_IO_BASE_ADDR) + 0x1C) +#define DAM_PTCR5 ((AUDMUX_IO_BASE_ADDR) + 0x20) +#define DAM_PDCR5 ((AUDMUX_IO_BASE_ADDR) + 0x24) +#define DAM_PTCR6 ((AUDMUX_IO_BASE_ADDR) + 0x28) +#define DAM_PDCR6 ((AUDMUX_IO_BASE_ADDR) + 0x2C) +#define DAM_PTCR7 ((AUDMUX_IO_BASE_ADDR) + 0x30) +#define DAM_PDCR7 ((AUDMUX_IO_BASE_ADDR) + 0x34) +#define DAM_CNMCR ((AUDMUX_IO_BASE_ADDR) + 0x38) +#define DAM_PTCR(a) ((AUDMUX_IO_BASE_ADDR) + (a-1)*8) +#define DAM_PDCR(a) ((AUDMUX_IO_BASE_ADDR) + 4 + (a-1)*8) + +#define AUDMUX_PTCR_TFSDIR (1 << 31) +#define AUDMUX_PTCR_TFSSEL(x, y) \ + ((x << 30) | (((y - 1) & 0x7) << 27)) +#define AUDMUX_PTCR_TCLKDIR (1 << 26) +#define AUDMUX_PTCR_TCSEL(x, y) \ + ((x << 25) | (((y - 1) & 0x7) << 22)) +#define AUDMUX_PTCR_RFSDIR (1 << 21) +#define AUDMUX_PTCR_RFSSEL(x, y) \ + ((x << 20) | (((y - 1) & 0x7) << 17)) +#define AUDMUX_PTCR_RCLKDIR (1 << 16) +#define AUDMUX_PTCR_RCSEL(x, y) \ + ((x << 15) | (((y - 1) & 0x7) << 12)) +#define AUDMUX_PTCR_SYN (1 << 11) + +#define AUDMUX_FROM_TXFS 0 +#define AUDMUX_FROM_RXFS 1 + +#define AUDMUX_PDCR_RXDSEL(x) (((x - 1) & 0x7) << 13) +#define AUDMUX_PDCR_TXDXEN (1 << 12) +#define AUDMUX_PDCR_MODE(x) (((x) & 0x3) << 8) +#define AUDMUX_PDCR_INNMASK(x) (((x) & 0xff) << 0) + +#define AUDMUX_CNMCR_CEN (1 << 18) +#define AUDMUX_CNMCR_FSPOL (1 << 17) +#define AUDMUX_CNMCR_CLKPOL (1 << 16) +#define AUDMUX_CNMCR_CNTHI(x) (((x) & 0xff) << 8) +#define AUDMUX_CNMCR_CNTLOW(x) (((x) & 0xff) << 0) + + +struct mxc_runtime_data { + int dma_ch; + spinlock_t dma_lock; + int active, period, periods; + int dma_wchannel; + int dma_active; + int dma_alloc; +#if defined(CONFIG_MXC_ASRC) || defined(CONFIG_MXC_ASRC_MODULE) + int dma_asrc; + int asrc_index; + int asrc_enable; +#endif +}; + +extern struct snd_soc_platform imx_soc_platform; + +#endif diff --git a/sound/soc/imx/imx-ssi.c b/sound/soc/imx/imx-ssi.c index 80b4fee2442b..e617f89b6eb4 100644 --- a/sound/soc/imx/imx-ssi.c +++ b/sound/soc/imx/imx-ssi.c @@ -47,10 +47,12 @@ #include #include +#include #include #include #include "imx-ssi.h" +#include "imx-pcm.h" #define SSI_SACNT_DEFAULT (SSI_SACNT_AC97EN | SSI_SACNT_FV) @@ -335,12 +337,14 @@ static int imx_ssi_trigger(struct snd_pcm_substream *substream, int cmd, } static struct snd_soc_dai_ops imx_ssi_pcm_dai_ops = { - .hw_params = imx_ssi_hw_params, - .set_fmt = imx_ssi_set_dai_fmt, - .set_clkdiv = imx_ssi_set_dai_clkdiv, - .set_sysclk = imx_ssi_set_dai_sysclk, - .set_tdm_slot = imx_ssi_set_dai_tdm_slot, - .trigger = imx_ssi_trigger, + .startup = imx_ssi_startup, + .trigger = imx_ssi_trigger, + .prepare = imx_ssi_prepare, + .hw_params = imx_ssi_hw_params, + .set_sysclk = imx_ssi_set_dai_sysclk, + .set_clkdiv = imx_ssi_set_dai_clkdiv, + .set_fmt = imx_ssi_set_dai_fmt, + .set_tdm_slot = imx_ssi_set_dai_tdm_slot, }; static struct snd_soc_dai imx_ssi_dai = { @@ -348,13 +352,17 @@ static struct snd_soc_dai imx_ssi_dai = { .channels_min = 2, .channels_max = 2, .rates = SNDRV_PCM_RATE_8000_96000, - .formats = SNDRV_PCM_FMTBIT_S16_LE, + .formats = (SNDRV_PCM_FMTBIT_S16_LE | \ + SNDRV_PCM_FMTBIT_S20_3LE | \ + SNDRV_PCM_FMTBIT_S24_LE), }, .capture = { .channels_min = 2, .channels_max = 2, .rates = SNDRV_PCM_RATE_8000_96000, - .formats = SNDRV_PCM_FMTBIT_S16_LE, + .formats = (SNDRV_PCM_FMTBIT_S16_LE | \ + SNDRV_PCM_FMTBIT_S20_3LE | \ + SNDRV_PCM_FMTBIT_S24_LE), }, .ops = &imx_ssi_pcm_dai_ops, }; @@ -570,7 +578,7 @@ struct snd_ac97_bus_ops soc_ac97_ops = { }; EXPORT_SYMBOL_GPL(soc_ac97_ops); -struct snd_soc_dai imx_ssi_pcm_dai[2]; +struct snd_soc_dai *imx_ssi_pcm_dai[MAX_SSI_CHANNELS]; EXPORT_SYMBOL_GPL(imx_ssi_pcm_dai); static int imx_ssi_probe(struct platform_device *pdev) @@ -760,4 +768,3 @@ module_exit(imx_ssi_exit); MODULE_AUTHOR("Sascha Hauer, "); MODULE_DESCRIPTION("i.MX I2S/ac97 SoC Interface"); MODULE_LICENSE("GPL"); - diff --git a/sound/soc/mxs/Kconfig b/sound/soc/mxs/Kconfig new file mode 100644 index 000000000000..213feb404a6b --- /dev/null +++ b/sound/soc/mxs/Kconfig @@ -0,0 +1,51 @@ +config SND_MXS_SOC + tristate "SoC Audio for the MXS chips" + depends on ARCH_MXS && SND_SOC + select SND_PCM + help + Say Y or M if you want to add support for codecs attached to + the MXS I2S or SSP interface. + + +config SND_MXS_SOC_SPDIF_DAI + tristate + +config SND_MXS_SOC_EVK_DEVB + tristate "SoC Audio support for MXS-EVK SGTL5000" + depends on SND_MXS_SOC && ARCH_MX28 + select SND_SOC_SGTL5000 + help + Say Y if you want to add support for SoC audio on MXS EVK development + board with the sgtl5000 codec. + +config SND_MXS_SOC_EVK_ADC + tristate "SoC Audio support for MXS-EVK ADC/DAC" + depends on SND_MXS_SOC && ARCH_MX23 + select SND_SOC_MXS_ADC_CODEC + help + Say Y if you want to add support for SoC audio on MXS EVK development + board with ADC/DAC audio interface. + +config SND_MXS_SOC_DAI + tristate "MXS Digital Audio Interface SAIF" + default y + depends on SND_MXS_SOC_EVK_DEVB + help + Enable MXS Digital Audio Interface SAIF + +config SND_MXS_SOC_ADC + tristate "MXS ADC/DAC Audio Interface" + default y + depends on SND_MXS_SOC_EVK_ADC + help + Enable MXS ADC/DAC Audio Interface + +config SND_MXS_SOC_EVK_DEVB_SPDIF + tristate "SoC SPDIF support for MXS EVK Development Board" + default n + depends on SND_MXS_SOC && ARCH_MXS + select SND_MXS_SOC_SPDIF_DAI + select SND_SOC_MXS_SPDIF + help + Say Y if you want to add support for SoC audio on MXS EVK development + board with the SPDIF transmitter. diff --git a/sound/soc/mxs/Makefile b/sound/soc/mxs/Makefile new file mode 100644 index 000000000000..971c622a34fb --- /dev/null +++ b/sound/soc/mxs/Makefile @@ -0,0 +1,16 @@ +# MXS platfrom support +snd-soc-mxs-objs := mxs-pcm.o +snd-soc-mxs-dai-objs := mxs-dai.o +snd-soc-mxs-spdif-dai-objs := mxs-spdif-dai.o +snd-soc-mxs-devb-objs := mxs-devb.o +snd-soc-mxs-devb-spdif-objs := mxs-devb-spdif.o +snd-soc-mxs-adc-objs := mxs-adc.o +snd-soc-mxs-evk-adc-objs := mxs-evk-adc.o + +obj-$(CONFIG_SND_MXS_SOC) += snd-soc-mxs.o +obj-$(CONFIG_SND_MXS_SOC_DAI) += snd-soc-mxs-dai.o +obj-$(CONFIG_SND_MXS_SOC_SPDIF_DAI) += snd-soc-mxs-spdif-dai.o +obj-$(CONFIG_SND_MXS_SOC_EVK_DEVB) += snd-soc-mxs-devb.o +obj-$(CONFIG_SND_MXS_SOC_EVK_DEVB_SPDIF) += snd-soc-mxs-devb-spdif.o +obj-$(CONFIG_SND_MXS_SOC_ADC) += snd-soc-mxs-adc.o +obj-$(CONFIG_SND_MXS_SOC_EVK_ADC) += snd-soc-mxs-evk-adc.o diff --git a/sound/soc/mxs/mxs-adc.c b/sound/soc/mxs/mxs-adc.c new file mode 100644 index 000000000000..7069927b1ac3 --- /dev/null +++ b/sound/soc/mxs/mxs-adc.c @@ -0,0 +1,453 @@ +/* + * ASoC Audio Layer for Freescale MXS ADC/DAC + * + * Author: Vladislav Buzov + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. + * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "mxs-pcm.h" + +#define MXS_ADC_RATES SNDRV_PCM_RATE_8000_192000 +#define MXS_ADC_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | \ + SNDRV_PCM_FMTBIT_S32_LE) +#define ADC_VOLUME_MIN 0x37 + +struct mxs_pcm_dma_params mxs_audio_in = { + .name = "mxs-audio-in", + .dma_ch = MXS_DMA_CHANNEL_AHB_APBX_AUDIOADC, + .irq = IRQ_ADC_DMA, +}; + +struct mxs_pcm_dma_params mxs_audio_out = { + .name = "mxs-audio-out", + .dma_ch = MXS_DMA_CHANNEL_AHB_APBX_AUDIODAC, + .irq = IRQ_DAC_DMA, +}; + +static struct delayed_work work; +static struct delayed_work adc_ramp_work; +static struct delayed_work dac_ramp_work; +static bool adc_ramp_done = 1; +static bool dac_ramp_done = 1; + +static void mxs_adc_schedule_work(struct delayed_work *work) +{ + schedule_delayed_work(work, HZ / 10); +} +static void mxs_adc_work(struct work_struct *work) +{ + /* disable irq */ + disable_irq(IRQ_HEADPHONE_SHORT); + + while (true) { + __raw_writel(BM_AUDIOOUT_PWRDN_HEADPHONE, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_PWRDN_CLR); + msleep(10); + if ((__raw_readl(REGS_AUDIOOUT_BASE + HW_AUDIOOUT_ANACTRL) + & BM_AUDIOOUT_ANACTRL_SHORT_LR_STS) != 0) { + /* rearm the short protection */ + __raw_writel(BM_AUDIOOUT_ANACTRL_SHORTMODE_LR, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_ANACTRL_CLR); + __raw_writel(BM_AUDIOOUT_ANACTRL_SHORT_LR_STS, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_ANACTRL_CLR); + __raw_writel(BF_AUDIOOUT_ANACTRL_SHORTMODE_LR(0x1), + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_ANACTRL_SET); + + __raw_writel(BM_AUDIOOUT_PWRDN_HEADPHONE, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_PWRDN_SET); + printk(KERN_WARNING "WARNING : Headphone LR short!\r\n"); + } else { + printk(KERN_WARNING "INFO : Headphone LR no longer short!\r\n"); + break; + } + msleep(1000); + } + + /* power up the HEADPHONE and un-mute the HPVOL */ + __raw_writel(BM_AUDIOOUT_HPVOL_MUTE, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_HPVOL_CLR); + __raw_writel(BM_AUDIOOUT_PWRDN_HEADPHONE, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_PWRDN_CLR); + + /* enable irq for next short detect*/ + enable_irq(IRQ_HEADPHONE_SHORT); +} + +static void mxs_adc_schedule_ramp_work(struct delayed_work *work) +{ + schedule_delayed_work(work, msecs_to_jiffies(2)); + adc_ramp_done = 0; +} + +static void mxs_adc_ramp_work(struct work_struct *work) +{ + u32 reg = 0; + u32 reg1 = 0; + u32 reg2 = 0; + u32 l, r; + u32 ll, rr; + int i; + + reg = __raw_readl(REGS_AUDIOIN_BASE + \ + HW_AUDIOIN_ADCVOLUME); + + reg1 = reg & ~BM_AUDIOIN_ADCVOLUME_VOLUME_LEFT; + reg1 = reg1 & ~BM_AUDIOIN_ADCVOLUME_VOLUME_RIGHT; + /* minimize adc volume */ + reg2 = reg1 | + BF_AUDIOIN_ADCVOLUME_VOLUME_LEFT(ADC_VOLUME_MIN) | + BF_AUDIOIN_ADCVOLUME_VOLUME_RIGHT(ADC_VOLUME_MIN); + __raw_writel(reg2, + REGS_AUDIOIN_BASE + HW_AUDIOIN_ADCVOLUME); + msleep(1); + + l = (reg & BM_AUDIOIN_ADCVOLUME_VOLUME_LEFT) >> + BP_AUDIOIN_ADCVOLUME_VOLUME_LEFT; + r = (reg & BM_AUDIOIN_ADCVOLUME_VOLUME_RIGHT) >> + BP_AUDIOIN_ADCVOLUME_VOLUME_RIGHT; + + /* fade in adc vol */ + for (i = ADC_VOLUME_MIN; (i < l) || (i < r);) { + i += 0x8; + ll = i < l ? i : l; + rr = i < r ? i : r; + reg2 = reg1 | + BF_AUDIOIN_ADCVOLUME_VOLUME_LEFT(ll) | + BF_AUDIOIN_ADCVOLUME_VOLUME_RIGHT(rr); + __raw_writel(reg2, + REGS_AUDIOIN_BASE + HW_AUDIOIN_ADCVOLUME); + msleep(1); + } + adc_ramp_done = 1; +} + +static void mxs_dac_schedule_ramp_work(struct delayed_work *work) +{ + schedule_delayed_work(work, msecs_to_jiffies(2)); + dac_ramp_done = 0; +} + +static void mxs_dac_ramp_work(struct work_struct *work) +{ + u32 reg = 0; + u32 reg1 = 0; + u32 l, r; + u32 ll, rr; + int i; + + /* unmute hp and speaker */ + __raw_writel(BM_AUDIOOUT_HPVOL_MUTE, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_HPVOL_CLR); + __raw_writel(BM_AUDIOOUT_SPEAKERCTRL_MUTE, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_SPEAKERCTRL_CLR); + + reg = __raw_readl(REGS_AUDIOOUT_BASE + \ + HW_AUDIOOUT_HPVOL); + + reg1 = reg & ~BM_AUDIOOUT_HPVOL_VOL_LEFT; + reg1 = reg1 & ~BM_AUDIOOUT_HPVOL_VOL_RIGHT; + + l = (reg & BM_AUDIOOUT_HPVOL_VOL_LEFT) >> + BP_AUDIOOUT_HPVOL_VOL_LEFT; + r = (reg & BM_AUDIOOUT_HPVOL_VOL_RIGHT) >> + BP_AUDIOOUT_HPVOL_VOL_RIGHT; + /* fade in hp vol */ + for (i = 0x7f; i > 0 ;) { + i -= 0x8; + ll = i > (int)l ? i : l; + rr = i > (int)r ? i : r; + reg = reg1 | BF_AUDIOOUT_HPVOL_VOL_LEFT(ll) + | BF_AUDIOOUT_HPVOL_VOL_RIGHT(rr); + __raw_writel(reg, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_HPVOL); + msleep(1); + } + dac_ramp_done = 1; +} + +static irqreturn_t mxs_short_irq(int irq, void *dev_id) +{ + __raw_writel(BM_AUDIOOUT_ANACTRL_SHORTMODE_LR, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_ANACTRL_CLR); + __raw_writel(BM_AUDIOOUT_ANACTRL_SHORT_LR_STS, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_ANACTRL_CLR); + __raw_writel(BF_AUDIOOUT_ANACTRL_SHORTMODE_LR(0x1), + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_ANACTRL_SET); + + __raw_writel(BM_AUDIOOUT_HPVOL_MUTE, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_HPVOL_SET); + __raw_writel(BM_AUDIOOUT_PWRDN_HEADPHONE, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_PWRDN_SET); + __raw_writel(BM_AUDIOOUT_ANACTRL_HP_CLASSAB, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_ANACTRL_SET); + + mxs_adc_schedule_work(&work); + return IRQ_HANDLED; +} +static irqreturn_t mxs_err_irq(int irq, void *dev_id) +{ + struct snd_pcm_substream *substream = dev_id; + int playback = substream->stream == SNDRV_PCM_STREAM_PLAYBACK ? 1 : 0; + u32 ctrl_reg; + u32 overflow_mask; + u32 underflow_mask; + + if (playback) { + ctrl_reg = __raw_readl(REGS_AUDIOOUT_BASE + HW_AUDIOOUT_CTRL); + underflow_mask = BM_AUDIOOUT_CTRL_FIFO_UNDERFLOW_IRQ; + overflow_mask = BM_AUDIOOUT_CTRL_FIFO_OVERFLOW_IRQ; + } else { + ctrl_reg = __raw_readl(REGS_AUDIOIN_BASE + HW_AUDIOIN_CTRL); + underflow_mask = BM_AUDIOIN_CTRL_FIFO_UNDERFLOW_IRQ; + overflow_mask = BM_AUDIOIN_CTRL_FIFO_OVERFLOW_IRQ; + } + + if (ctrl_reg & underflow_mask) { + printk(KERN_DEBUG "%s underflow detected\n", + playback ? "DAC" : "ADC"); + + if (playback) + __raw_writel( + BM_AUDIOOUT_CTRL_FIFO_UNDERFLOW_IRQ, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_CTRL_CLR); + else + __raw_writel( + BM_AUDIOIN_CTRL_FIFO_UNDERFLOW_IRQ, + REGS_AUDIOIN_BASE + HW_AUDIOIN_CTRL_CLR); + + } else if (ctrl_reg & overflow_mask) { + printk(KERN_DEBUG "%s overflow detected\n", + playback ? "DAC" : "ADC"); + + if (playback) + __raw_writel( + BM_AUDIOOUT_CTRL_FIFO_OVERFLOW_IRQ, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_CTRL_CLR); + else + __raw_writel(BM_AUDIOIN_CTRL_FIFO_OVERFLOW_IRQ, + REGS_AUDIOIN_BASE + HW_AUDIOIN_CTRL_CLR); + } else + printk(KERN_WARNING "Unknown DAC error interrupt\n"); + + return IRQ_HANDLED; +} + +static int mxs_adc_trigger(struct snd_pcm_substream *substream, + int cmd, + struct snd_soc_dai *dai) +{ + int playback = substream->stream == SNDRV_PCM_STREAM_PLAYBACK ? 1 : 0; + int ret = 0; + + switch (cmd) { + case SNDRV_PCM_TRIGGER_START: + + if (playback) { + /* enable the fifo error interrupt */ + __raw_writel(BM_AUDIOOUT_CTRL_FIFO_ERROR_IRQ_EN, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_CTRL_SET); + /* write a data to data reg to trigger the transfer */ + __raw_writel(0x0, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_DATA); + mxs_dac_schedule_ramp_work(&dac_ramp_work); + } else { + __raw_writel(BM_AUDIOIN_CTRL_RUN, + REGS_AUDIOIN_BASE + HW_AUDIOIN_CTRL_SET); + mxs_adc_schedule_ramp_work(&adc_ramp_work); + } + break; + + case SNDRV_PCM_TRIGGER_STOP: + + if (playback) { + if (dac_ramp_done == 0) { + cancel_delayed_work(&dac_ramp_work); + dac_ramp_done = 1; + } + __raw_writel(BM_AUDIOOUT_HPVOL_MUTE, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_HPVOL_SET); + __raw_writel(BM_AUDIOOUT_SPEAKERCTRL_MUTE, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_SPEAKERCTRL_SET); + /* disable the fifo error interrupt */ + __raw_writel(BM_AUDIOOUT_CTRL_FIFO_ERROR_IRQ_EN, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_CTRL_CLR); + } else { + if (adc_ramp_done == 0) { + cancel_delayed_work(&adc_ramp_work); + adc_ramp_done = 1; + } + __raw_writel(BM_AUDIOIN_CTRL_RUN, + REGS_AUDIOIN_BASE + HW_AUDIOIN_CTRL_CLR); + } + break; + + case SNDRV_PCM_TRIGGER_RESUME: + case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: + case SNDRV_PCM_TRIGGER_SUSPEND: + case SNDRV_PCM_TRIGGER_PAUSE_PUSH: + break; + default: + ret = -EINVAL; + } + + return ret; +} + +static int mxs_adc_startup(struct snd_pcm_substream *substream, + struct snd_soc_dai *dai) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai *cpu_dai = rtd->dai->cpu_dai; + int playback = substream->stream == SNDRV_PCM_STREAM_PLAYBACK ? 1 : 0; + int irq; + int irq_short; + int ret; + + INIT_DELAYED_WORK(&work, mxs_adc_work); + INIT_DELAYED_WORK(&adc_ramp_work, mxs_adc_ramp_work); + INIT_DELAYED_WORK(&dac_ramp_work, mxs_dac_ramp_work); + + if (playback) { + irq = IRQ_DAC_ERROR; + cpu_dai->dma_data = &mxs_audio_out; + } else { + irq = IRQ_ADC_ERROR; + cpu_dai->dma_data = &mxs_audio_in; + } + + ret = request_irq(irq, mxs_err_irq, 0, "MXS DAC/ADC Error", + substream); + if (ret) { + printk(KERN_ERR "%s: Unable to request ADC/DAC error irq %d\n", + __func__, IRQ_DAC_ERROR); + return ret; + } + + irq_short = IRQ_HEADPHONE_SHORT; + ret = request_irq(irq_short, mxs_short_irq, + IRQF_DISABLED | IRQF_SHARED, "MXS DAC/ADC HP SHORT", substream); + if (ret) { + printk(KERN_ERR "%s: Unable to request ADC/DAC HP SHORT irq %d\n", + __func__, IRQ_DAC_ERROR); + return ret; + } + + /* Enable error interrupt */ + if (playback) { + __raw_writel(BM_AUDIOOUT_CTRL_FIFO_OVERFLOW_IRQ, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_CTRL_CLR); + __raw_writel(BM_AUDIOOUT_CTRL_FIFO_UNDERFLOW_IRQ, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_CTRL_CLR); + } else { + __raw_writel(BM_AUDIOIN_CTRL_FIFO_OVERFLOW_IRQ, + REGS_AUDIOIN_BASE + HW_AUDIOIN_CTRL_CLR); + __raw_writel(BM_AUDIOIN_CTRL_FIFO_UNDERFLOW_IRQ, + REGS_AUDIOIN_BASE + HW_AUDIOIN_CTRL_CLR); + __raw_writel(BM_AUDIOIN_CTRL_FIFO_ERROR_IRQ_EN, + REGS_AUDIOIN_BASE + HW_AUDIOIN_CTRL_SET); + } + + return 0; +} + +static void mxs_adc_shutdown(struct snd_pcm_substream *substream, + struct snd_soc_dai *dai) +{ + int playback = substream->stream == SNDRV_PCM_STREAM_PLAYBACK ? 1 : 0; + + /* Disable error interrupt */ + if (playback) { + __raw_writel(BM_AUDIOOUT_CTRL_FIFO_ERROR_IRQ_EN, + REGS_AUDIOOUT_BASE + HW_AUDIOOUT_CTRL_CLR); + free_irq(IRQ_DAC_ERROR, substream); + } else { + __raw_writel(BM_AUDIOIN_CTRL_FIFO_ERROR_IRQ_EN, + REGS_AUDIOIN_BASE + HW_AUDIOIN_CTRL_CLR); + free_irq(IRQ_ADC_ERROR, substream); + } +} + +#ifdef CONFIG_PM +static int mxs_adc_suspend(struct snd_soc_dai *cpu_dai) +{ + return 0; +} + +static int mxs_adc_resume(struct snd_soc_dai *cpu_dai) +{ + return 0; +} +#else +#define mxs_adc_suspend NULL +#define mxs_adc_resume NULL +#endif /* CONFIG_PM */ + +struct snd_soc_dai_ops mxs_adc_dai_ops = { + .startup = mxs_adc_startup, + .shutdown = mxs_adc_shutdown, + .trigger = mxs_adc_trigger, +}; + +struct snd_soc_dai mxs_adc_dai = { + .name = "mxs adc/dac", + .id = 0, + .suspend = mxs_adc_suspend, + .resume = mxs_adc_resume, + .playback = { + .channels_min = 2, + .channels_max = 2, + .rates = MXS_ADC_RATES, + .formats = MXS_ADC_FORMATS, + }, + .capture = { + .channels_min = 2, + .channels_max = 2, + .rates = MXS_ADC_RATES, + .formats = MXS_ADC_FORMATS, + }, + .ops = &mxs_adc_dai_ops, +}; +EXPORT_SYMBOL_GPL(mxs_adc_dai); + +static int __init mxs_adc_dai_init(void) +{ + return snd_soc_register_dai(&mxs_adc_dai); +} + +static void __exit mxs_adc_dai_exit(void) +{ + snd_soc_unregister_dai(&mxs_adc_dai); +} +module_init(mxs_adc_dai_init); +module_exit(mxs_adc_dai_exit); + +MODULE_AUTHOR("Vladislav Buzov"); +MODULE_DESCRIPTION("MXS ADC/DAC DAI"); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/mxs/mxs-adc.h b/sound/soc/mxs/mxs-adc.h new file mode 100644 index 000000000000..b922c14cb894 --- /dev/null +++ b/sound/soc/mxs/mxs-adc.h @@ -0,0 +1,21 @@ +/* + * ASoC Audio Layer for Freescale MXS ADC/DAC + * + * Author: Vladislav Buzov + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. + * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#ifndef _MXS_ADC_H +#define _MXS_ADC_H +extern struct snd_soc_dai mxs_adc_dai; +#endif diff --git a/sound/soc/mxs/mxs-dai.c b/sound/soc/mxs/mxs-dai.c new file mode 100644 index 000000000000..a548b9948516 --- /dev/null +++ b/sound/soc/mxs/mxs-dai.c @@ -0,0 +1,657 @@ +/* + * Copyright (C) 2010 Freescale Semiconductor, Inc. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "mxs-pcm.h" +#include "mxs-dai.h" + +#define SAIF0_CTRL (IO_ADDRESS(SAIF0_PHYS_ADDR) + HW_SAIF_CTRL) +#define SAIF1_CTRL (IO_ADDRESS(SAIF1_PHYS_ADDR) + HW_SAIF_CTRL) +#define SAIF0_CTRL_SET (IO_ADDRESS(SAIF0_PHYS_ADDR) + HW_SAIF_CTRL_SET) +#define SAIF1_CTRL_SET (IO_ADDRESS(SAIF1_PHYS_ADDR) + HW_SAIF_CTRL_SET) +#define SAIF0_CTRL_CLR (IO_ADDRESS(SAIF0_PHYS_ADDR) + HW_SAIF_CTRL_CLR) +#define SAIF1_CTRL_CLR (IO_ADDRESS(SAIF1_PHYS_ADDR) + HW_SAIF_CTRL_CLR) + +#define SAIF0_STAT (IO_ADDRESS(SAIF0_PHYS_ADDR) + HW_SAIF_STAT) +#define SAIF1_STAT (IO_ADDRESS(SAIF1_PHYS_ADDR) + HW_SAIF_STAT) +#define SAIF0_STAT_SET (IO_ADDRESS(SAIF0_PHYS_ADDR) + HW_SAIF_STAT_SET) +#define SAIF1_STAT_SET (IO_ADDRESS(SAIF1_PHYS_ADDR) + HW_SAIF_STAT_SET) +#define SAIF0_STAT_CLR (IO_ADDRESS(SAIF0_PHYS_ADDR) + HW_SAIF_STAT_CLR) +#define SAIF1_STAT_CLR (IO_ADDRESS(SAIF1_PHYS_ADDR) + HW_SAIF_STAT_CLR) + +#define SAIF0_DATA (IO_ADDRESS(SAIF0_PHYS_ADDR) + HW_SAIF_DATA) +#define SAIF1_DATA (IO_ADDRESS(SAIF1_PHYS_ADDR) + HW_SAIF_DATA) +#define SAIF0_DATA_SET (IO_ADDRESS(SAIF0_PHYS_ADDR) + HW_SAIF_DATA_SET) +#define SAIF1_DATA_SET (IO_ADDRESS(SAIF1_PHYS_ADDR) + HW_SAIF_DATA_SET) +#define SAIF0_DATA_CLR (IO_ADDRESS(SAIF0_PHYS_ADDR) + HW_SAIF_DATA_CLR) +#define SAIF1_DATA_CLR (IO_ADDRESS(SAIF1_PHYS_ADDR) + HW_SAIF_DATA_CLR) + +#define SAIF0_VERSION (IO_ADDRESS(SAIF0_PHYS_ADDR) + HW_SAIF_VERSION) +#define SAIF1_VERSION (IO_ADDRESS(SAIF1_PHYS_ADDR) + HW_SAIF_VERSION) + +#define HW_SAIF_CTRL (0x00000000) +#define HW_SAIF_CTRL_SET (0x00000004) +#define HW_SAIF_CTRL_CLR (0x00000008) +#define HW_SAIF_CTRL_TOG (0x0000000c) + +#define BM_SAIF_CTRL_SFTRST 0x80000000 +#define BM_SAIF_CTRL_CLKGATE 0x40000000 +#define BP_SAIF_CTRL_BITCLK_MULT_RATE 27 +#define BM_SAIF_CTRL_BITCLK_MULT_RATE 0x38000000 +#define BF_SAIF_CTRL_BITCLK_MULT_RATE(v) \ + (((v) << 27) & BM_SAIF_CTRL_BITCLK_MULT_RATE) +#define BM_SAIF_CTRL_BITCLK_BASE_RATE 0x04000000 +#define BM_SAIF_CTRL_FIFO_ERROR_IRQ_EN 0x02000000 +#define BM_SAIF_CTRL_FIFO_SERVICE_IRQ_EN 0x01000000 +#define BP_SAIF_CTRL_RSRVD2 21 +#define BM_SAIF_CTRL_RSRVD2 0x00E00000 +#define BF_SAIF_CTRL_RSRVD2(v) \ + (((v) << 21) & BM_SAIF_CTRL_RSRVD2) +#define BP_SAIF_CTRL_DMAWAIT_COUNT 16 +#define BM_SAIF_CTRL_DMAWAIT_COUNT 0x001F0000 +#define BF_SAIF_CTRL_DMAWAIT_COUNT(v) \ + (((v) << 16) & BM_SAIF_CTRL_DMAWAIT_COUNT) +#define BP_SAIF_CTRL_CHANNEL_NUM_SELECT 14 +#define BM_SAIF_CTRL_CHANNEL_NUM_SELECT 0x0000C000 +#define BF_SAIF_CTRL_CHANNEL_NUM_SELECT(v) \ + (((v) << 14) & BM_SAIF_CTRL_CHANNEL_NUM_SELECT) +#define BM_SAIF_CTRL_LRCLK_PULSE 0x00002000 +#define BM_SAIF_CTRL_BIT_ORDER 0x00001000 +#define BM_SAIF_CTRL_DELAY 0x00000800 +#define BM_SAIF_CTRL_JUSTIFY 0x00000400 +#define BM_SAIF_CTRL_LRCLK_POLARITY 0x00000200 +#define BM_SAIF_CTRL_BITCLK_EDGE 0x00000100 +#define BP_SAIF_CTRL_WORD_LENGTH 4 +#define BM_SAIF_CTRL_WORD_LENGTH 0x000000F0 +#define BF_SAIF_CTRL_WORD_LENGTH(v) \ + (((v) << 4) & BM_SAIF_CTRL_WORD_LENGTH) +#define BM_SAIF_CTRL_BITCLK_48XFS_ENABLE 0x00000008 +#define BM_SAIF_CTRL_SLAVE_MODE 0x00000004 +#define BM_SAIF_CTRL_READ_MODE 0x00000002 +#define BM_SAIF_CTRL_RUN 0x00000001 + +#define HW_SAIF_STAT (0x00000010) +#define HW_SAIF_STAT_SET (0x00000014) +#define HW_SAIF_STAT_CLR (0x00000018) +#define HW_SAIF_STAT_TOG (0x0000001c) + +#define BM_SAIF_STAT_PRESENT 0x80000000 +#define BP_SAIF_STAT_RSRVD2 17 +#define BM_SAIF_STAT_RSRVD2 0x7FFE0000 +#define BF_SAIF_STAT_RSRVD2(v) \ + (((v) << 17) & BM_SAIF_STAT_RSRVD2) +#define BM_SAIF_STAT_DMA_PREQ 0x00010000 +#define BP_SAIF_STAT_RSRVD1 7 +#define BM_SAIF_STAT_RSRVD1 0x0000FF80 +#define BF_SAIF_STAT_RSRVD1(v) \ + (((v) << 7) & BM_SAIF_STAT_RSRVD1) +#define BM_SAIF_STAT_FIFO_UNDERFLOW_IRQ 0x00000040 +#define BM_SAIF_STAT_FIFO_OVERFLOW_IRQ 0x00000020 +#define BM_SAIF_STAT_FIFO_SERVICE_IRQ 0x00000010 +#define BP_SAIF_STAT_RSRVD0 1 +#define BM_SAIF_STAT_RSRVD0 0x0000000E +#define BF_SAIF_STAT_RSRVD0(v) \ + (((v) << 1) & BM_SAIF_STAT_RSRVD0) +#define BM_SAIF_STAT_BUSY 0x00000001 + +#define HW_SAIF_DATA (0x00000020) +#define HW_SAIF_DATA_SET (0x00000024) +#define HW_SAIF_DATA_CLR (0x00000028) +#define HW_SAIF_DATA_TOG (0x0000002c) + +#define BP_SAIF_DATA_PCM_RIGHT 16 +#define BM_SAIF_DATA_PCM_RIGHT 0xFFFF0000 +#define BF_SAIF_DATA_PCM_RIGHT(v) \ + (((v) << 16) & BM_SAIF_DATA_PCM_RIGHT) +#define BP_SAIF_DATA_PCM_LEFT 0 +#define BM_SAIF_DATA_PCM_LEFT 0x0000FFFF +#define BF_SAIF_DATA_PCM_LEFT(v) \ + (((v) << 0) & BM_SAIF_DATA_PCM_LEFT) + +#define HW_SAIF_VERSION (0x00000030) + +#define BP_SAIF_VERSION_MAJOR 24 +#define BM_SAIF_VERSION_MAJOR 0xFF000000 +#define BF_SAIF_VERSION_MAJOR(v) \ + (((v) << 24) & BM_SAIF_VERSION_MAJOR) +#define BP_SAIF_VERSION_MINOR 16 +#define BM_SAIF_VERSION_MINOR 0x00FF0000 +#define BF_SAIF_VERSION_MINOR(v) \ + (((v) << 16) & BM_SAIF_VERSION_MINOR) +#define BP_SAIF_VERSION_STEP 0 +#define BM_SAIF_VERSION_STEP 0x0000FFFF +#define BF_SAIF_VERSION_STEP(v) \ + (((v) << 0) & BM_SAIF_VERSION_STEP) +/* debug */ +#define MXS_SAIF_DEBUG 0 +#if MXS_SAIF_DEBUG +#define dbg(format, arg...) printk(format, ## arg) +#else +#define dbg(format, arg...) +#endif + +#define MXS_SAIF_DUMP 0 +#if MXS_SAIF_DUMP +#define SAIF_DUMP() \ + do { \ + printk(KERN_INFO "dump @ %s\n", __func__);\ + printk(KERN_INFO "scr %x\t, %x\n", \ + __raw_readl(SAIF0_CTRL), __raw_readl(SAIF1_CTRL));\ + printk(KERN_INFO "stat %x\t, %x\n", \ + __raw_readl(SAIF0_STAT), __raw_readl(SAIF1_STAT));\ + printk(KERN_INFO "data %x\t, %x\n", \ + __raw_readl(SAIF0_DATA), __raw_readl(SAIF1_DATA));\ + printk(KERN_INFO "version %x\t, %x\n", \ + __raw_readl(SAIF0_VERSION), __raw_readl(SAIF1_VERSION)); + } while (0); +#else +#define SAIF_DUMP() +#endif + +#define SAIF0_PORT 0 +#define SAIF1_PORT 1 + +#define MXS_DAI_SAIF0 0 +#define MXS_DAI_SAIF1 1 + +static struct mxs_saif mxs_saif_en; + +static int saif_active[2] = { 0, 0 }; + +struct mxs_pcm_dma_params mxs_saif_0 = { + .name = "mxs-saif-0", + .dma_ch = MXS_DMA_CHANNEL_AHB_APBX_SAIF0, + .irq = IRQ_SAIF0_DMA, +}; + +struct mxs_pcm_dma_params mxs_saif_1 = { + .name = "mxs-saif-1", + .dma_ch = MXS_DMA_CHANNEL_AHB_APBX_SAIF1, + .irq = IRQ_SAIF1_DMA, +}; + +/* +* SAIF system clock configuration. +* Should only be called when port is inactive. +*/ +static int mxs_saif_set_dai_sysclk(struct snd_soc_dai *cpu_dai, + int clk_id, unsigned int freq, int dir) +{ + struct clk *saif_clk; + u32 scr; + struct mxs_saif *saif_select = (struct mxs_saif *)cpu_dai->private_data; + + switch (clk_id) { + case IMX_SSP_SYS_CLK: + saif_clk = saif_select->saif_mclk; + if (IS_ERR(saif_clk)) { + pr_err("%s:failed to get sys_clk\n", __func__); + return -EINVAL; + } + clk_set_rate(saif_clk, freq); + clk_enable(saif_clk); + break; + default: + return -EINVAL; + } + return 0; +} + +/* + * SAIF Clock dividers + * Should only be called when port is inactive. + */ +static int mxs_saif_set_dai_clkdiv(struct snd_soc_dai *cpu_dai, + int div_id, int div) +{ + u32 scr; + struct mxs_saif *saif_select = (struct mxs_saif *)cpu_dai->private_data; + + if (saif_select->saif_en == SAIF0) + scr = __raw_readl(SAIF0_CTRL); + else + scr = __raw_readl(SAIF1_CTRL); + + scr &= ~BM_SAIF_CTRL_BITCLK_MULT_RATE; + scr &= ~BM_SAIF_CTRL_BITCLK_BASE_RATE; + + switch (div_id) { + case IMX_SSP_SYS_MCLK: + switch (div) { + case 32: + scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(4); + scr &= ~BM_SAIF_CTRL_BITCLK_BASE_RATE; + break; + case 64: + scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(3); + scr &= ~BM_SAIF_CTRL_BITCLK_BASE_RATE; + break; + case 128: + scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(2); + scr &= ~BM_SAIF_CTRL_BITCLK_BASE_RATE; + break; + case 256: + scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(1); + scr &= ~BM_SAIF_CTRL_BITCLK_BASE_RATE; + break; + case 512: + scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(0); + scr &= ~BM_SAIF_CTRL_BITCLK_BASE_RATE; + break; + case 48: + scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(3); + scr |= BM_SAIF_CTRL_BITCLK_BASE_RATE; + break; + case 96: + scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(2); + scr |= BM_SAIF_CTRL_BITCLK_BASE_RATE; + break; + case 192: + scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(1); + scr |= BM_SAIF_CTRL_BITCLK_BASE_RATE; + break; + case 384: + scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(0); + scr |= BM_SAIF_CTRL_BITCLK_BASE_RATE; + break; + default: + return -EINVAL; + } + default: + return -EINVAL; + } + + if (saif_select->saif_en == SAIF0) + __raw_writel(scr, SAIF0_CTRL); + else + __raw_writel(scr, SAIF1_CTRL); + + return 0; +} + +/* + * SAIF DAI format configuration. + * Should only be called when port is inactive. + * Note: We don't use the I2S modes but instead manually configure the + * SAIF for I2S. + */ +static int mxs_saif_set_dai_fmt(struct snd_soc_dai *cpu_dai, unsigned int fmt) +{ + u32 scr, stat; + struct mxs_saif *saif_select = (struct mxs_saif *)cpu_dai->private_data; + if (saif_select->saif_en == SAIF0) { + scr = __raw_readl(SAIF0_CTRL); + stat = __raw_readl(SAIF0_STAT); + } else { + scr = __raw_readl(SAIF1_CTRL); + stat = __raw_readl(SAIF1_STAT); + } + + if (stat & BM_SAIF_STAT_BUSY) + return 0; + + /* DAI mode */ + switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { + case SND_SOC_DAIFMT_I2S: + /* data frame low 1clk before data */ + scr |= BM_SAIF_CTRL_DELAY; + scr &= ~BM_SAIF_CTRL_LRCLK_POLARITY; + break; + case SND_SOC_DAIFMT_LEFT_J: + /* data frame high with data */ + scr &= ~BM_SAIF_CTRL_DELAY; + scr &= ~BM_SAIF_CTRL_LRCLK_POLARITY; + scr &= ~BM_SAIF_CTRL_JUSTIFY; + break; + } + + /* DAI clock inversion */ + switch (fmt & SND_SOC_DAIFMT_INV_MASK) { + case SND_SOC_DAIFMT_IB_IF: + scr |= BM_SAIF_CTRL_BITCLK_EDGE; + scr |= BM_SAIF_CTRL_LRCLK_POLARITY; + break; + case SND_SOC_DAIFMT_IB_NF: + scr |= BM_SAIF_CTRL_BITCLK_EDGE; + scr &= ~BM_SAIF_CTRL_LRCLK_POLARITY; + break; + case SND_SOC_DAIFMT_NB_IF: + scr &= ~BM_SAIF_CTRL_BITCLK_EDGE; + scr |= BM_SAIF_CTRL_LRCLK_POLARITY; + break; + case SND_SOC_DAIFMT_NB_NF: + scr &= ~BM_SAIF_CTRL_BITCLK_EDGE; + scr &= ~BM_SAIF_CTRL_LRCLK_POLARITY; + break; + } + + /* DAI clock master masks */ + switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) { + case SND_SOC_DAIFMT_CBS_CFS: + scr &= ~BM_SAIF_CTRL_SLAVE_MODE; + break; + case SND_SOC_DAIFMT_CBM_CFS: + break; + case SND_SOC_DAIFMT_CBS_CFM: + break; + case SND_SOC_DAIFMT_CBM_CFM: + scr |= BM_SAIF_CTRL_SLAVE_MODE; + break; + } + if (saif_select->saif_en == SAIF0) + __raw_writel(scr, SAIF0_CTRL); + else + __raw_writel(scr, SAIF1_CTRL); + + SAIF_DUMP(); + return 0; +} + +static int mxs_saif_startup(struct snd_pcm_substream *substream, + struct snd_soc_dai *cpu_dai) +{ + /* we cant really change any saif values after saif is enabled*/ + struct mxs_saif *saif_select = (struct mxs_saif *)cpu_dai->private_data; + + if (((saif_select->stream_mapping == PLAYBACK_SAIF0_CAPTURE_SAIF1) && \ + (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)) || \ + ((saif_select->stream_mapping == PLAYBACK_SAIF1_CAPTURE_SAIF0) \ + && (substream->stream == SNDRV_PCM_STREAM_CAPTURE))) + cpu_dai->dma_data = &mxs_saif_0; + else + cpu_dai->dma_data = &mxs_saif_1; + + if (cpu_dai->playback.active && cpu_dai->capture.active) + return 0; + + if (saif_select->saif_en == SAIF0) + if (saif_active[SAIF0_PORT]++) + return 0; + if (saif_select->saif_en == SAIF1) + if (saif_active[SAIF1_PORT]++) + return 0; + SAIF_DUMP(); + return 0; +} + +/* + * Should only be called when port is inactive. + * although can be called multiple times by upper layers. + */ +static int mxs_saif_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params, + struct snd_soc_dai *cpu_dai) +{ + u32 scr, stat; + struct mxs_saif *saif_select = (struct mxs_saif *)cpu_dai->private_data; + if (saif_select->saif_en == SAIF0) { + scr = __raw_readl(SAIF0_CTRL); + stat = __raw_readl(SAIF0_STAT); + } else { + scr = __raw_readl(SAIF1_CTRL); + stat = __raw_readl(SAIF1_STAT); + } + /* cant change any parameters when SAIF is running */ + /* DAI data (word) size */ + scr &= ~BM_SAIF_CTRL_WORD_LENGTH; + scr &= ~BM_SAIF_CTRL_BITCLK_48XFS_ENABLE; + switch (params_format(params)) { + case SNDRV_PCM_FORMAT_S16_LE: + scr |= BF_SAIF_CTRL_WORD_LENGTH(0); + break; + case SNDRV_PCM_FORMAT_S20_3LE: + scr |= BF_SAIF_CTRL_WORD_LENGTH(4); + scr |= BM_SAIF_CTRL_BITCLK_48XFS_ENABLE; + break; + case SNDRV_PCM_FORMAT_S24_LE: + scr |= BF_SAIF_CTRL_WORD_LENGTH(8); + scr |= BM_SAIF_CTRL_BITCLK_48XFS_ENABLE; + break; + } + /* Tx/Rx config */ + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + /* enable TX mode */ + scr &= ~BM_SAIF_CTRL_READ_MODE; + } else { + /* enable RX mode */ + scr |= BM_SAIF_CTRL_READ_MODE; + } + + if (saif_select->saif_en == SAIF0) + __raw_writel(scr, SAIF0_CTRL); + else + __raw_writel(scr, SAIF1_CTRL); + return 0; +} + +static int mxs_saif_prepare(struct snd_pcm_substream *substream, + struct snd_soc_dai *cpu_dai) +{ + struct mxs_saif *saif_select = (struct mxs_saif *)cpu_dai->private_data; + if (saif_select->saif_en == SAIF0) + __raw_writel(BM_SAIF_CTRL_CLKGATE, SAIF0_CTRL_CLR); + else + __raw_writel(BM_SAIF_CTRL_CLKGATE, SAIF1_CTRL_CLR); + SAIF_DUMP(); + return 0; +} + +static int mxs_saif_trigger(struct snd_pcm_substream *substream, int cmd, + struct snd_soc_dai *cpu_dai) +{ + void __iomem *reg; + struct mxs_saif *saif_select = (struct mxs_saif *)cpu_dai->private_data; + switch (cmd) { + case SNDRV_PCM_TRIGGER_START: + case SNDRV_PCM_TRIGGER_RESUME: + case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: + + if (saif_select->saif_en == SAIF0) + reg = (void __iomem *)SAIF0_DATA; + else + reg = (void __iomem *)SAIF1_DATA; + + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) + /*write a data to saif data register to trigger + the transfer*/ + __raw_writel(0, reg); + else + /*read a data from saif data register to trigger + the receive*/ + __raw_readl(reg); + break; + case SNDRV_PCM_TRIGGER_SUSPEND: + case SNDRV_PCM_TRIGGER_STOP: + case SNDRV_PCM_TRIGGER_PAUSE_PUSH: + break; + default: + return -EINVAL; + } + SAIF_DUMP(); + return 0; +} + +static void mxs_saif_shutdown(struct snd_pcm_substream *substream, + struct snd_soc_dai *cpu_dai) +{ + struct mxs_saif *saif_select = (struct mxs_saif *)cpu_dai->private_data; + /* shutdown SAIF if neither Tx or Rx is active */ + if (cpu_dai->playback.active || cpu_dai->capture.active) + return; + + if (saif_select->saif_en == SAIF0) { + if (--saif_active[SAIF0_PORT] > 1) + return; + } + if (saif_select->saif_en == SAIF1) { + if (--saif_active[SAIF1_PORT]) + return; + } +} + +#ifdef CONFIG_PM +static int mxs_saif_suspend(struct snd_soc_dai *dai) +{ + if (!dai->active) + return 0; + /* do we need to disable any clocks? */ + return 0; +} + +static int mxs_saif_resume(struct snd_soc_dai *dai) +{ + if (!dai->active) + return 0; + /* do we need to enable any clocks? */ + return 0; +} +#else +#define mxs_saif_suspend NULL +#define mxs_saif_resume NULL +#endif + +static int fifo_err_counter; + +static irqreturn_t saif0_irq(int irq, void *dev_id) +{ + if (fifo_err_counter++ % 100 == 0) + printk(KERN_ERR "saif0_irq SAIF_STAT %x SAIF_CTRL %x fifo_errs=\ + %d\n", + __raw_readl(SAIF0_STAT), + __raw_readl(SAIF0_CTRL), + fifo_err_counter); + __raw_writel(BM_SAIF_STAT_FIFO_UNDERFLOW_IRQ | \ + BM_SAIF_STAT_FIFO_OVERFLOW_IRQ, SAIF0_STAT_CLR); + return IRQ_HANDLED; +} + +static irqreturn_t saif1_irq(int irq, void *dev_id) +{ + if (fifo_err_counter++ % 100 == 0) + printk(KERN_ERR "saif1_irq SAIF_STAT %x SAIF_CTRL %x \ + fifo_errs=%d\n", + __raw_readl(SAIF1_STAT), + __raw_readl(SAIF1_CTRL), + fifo_err_counter); + __raw_writel(BM_SAIF_STAT_FIFO_UNDERFLOW_IRQ | \ + BM_SAIF_STAT_FIFO_OVERFLOW_IRQ, SAIF1_STAT_CLR); + return IRQ_HANDLED; +} + +static int mxs_saif_probe(struct platform_device *pdev, struct snd_soc_dai *dai) +{ + if (request_irq(IRQ_SAIF0, saif0_irq, 0, "saif0", dai)) { + printk(KERN_ERR "%s: failure requesting irq %s\n", + __func__, "saif0"); + return -EBUSY; + } + + if (request_irq(IRQ_SAIF1, saif1_irq, 0, "saif1", dai)) { + printk(KERN_ERR "%s: failure requesting irq %s\n", + __func__, "saif1"); + return -EBUSY; + } + return 0; +} + +static void mxs_saif_remove(struct platform_device *pdev, + struct snd_soc_dai *dai) +{ + free_irq(IRQ_SAIF0, dai); + free_irq(IRQ_SAIF1, dai); +} + +#define MXS_SAIF_RATES \ + (SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_11025 | \ + SNDRV_PCM_RATE_16000 | SNDRV_PCM_RATE_22050 | \ + SNDRV_PCM_RATE_32000 | SNDRV_PCM_RATE_44100 | \ + SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_88200 | \ + SNDRV_PCM_RATE_96000 | SNDRV_PCM_RATE_176400 | \ + SNDRV_PCM_RATE_192000) + +#define MXS_SAIF_FORMATS \ + (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE | \ + SNDRV_PCM_FMTBIT_S24_LE) + +static struct snd_soc_dai_ops mxs_saif_dai_ops = { + .startup = mxs_saif_startup, + .shutdown = mxs_saif_shutdown, + .trigger = mxs_saif_trigger, + .prepare = mxs_saif_prepare, + .hw_params = mxs_saif_hw_params, + .set_sysclk = mxs_saif_set_dai_sysclk, + .set_clkdiv = mxs_saif_set_dai_clkdiv, + .set_fmt = mxs_saif_set_dai_fmt, +}; + +struct snd_soc_dai mxs_saif_dai[] = { + { + .name = "mxs-saif", + .probe = mxs_saif_probe, + .remove = mxs_saif_remove, + .suspend = mxs_saif_suspend, + .resume = mxs_saif_resume, + .playback = { + .channels_min = 2, + .channels_max = 2, + .rates = MXS_SAIF_RATES, + .formats = MXS_SAIF_FORMATS, + }, + .capture = { + .channels_min = 2, + .channels_max = 2, + .rates = MXS_SAIF_RATES, + .formats = MXS_SAIF_FORMATS, + }, + .ops = &mxs_saif_dai_ops, + .private_data = &mxs_saif_en, + } +}; +EXPORT_SYMBOL_GPL(mxs_saif_dai); + +static int __init mxs_saif_init(void) +{ + return snd_soc_register_dais(mxs_saif_dai, ARRAY_SIZE(mxs_saif_dai)); +} + +static void __exit mxs_saif_exit(void) +{ + snd_soc_unregister_dais(mxs_saif_dai, ARRAY_SIZE(mxs_saif_dai)); +} + +module_init(mxs_saif_init); +module_exit(mxs_saif_exit); +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("i.MX28 ASoC I2S driver"); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/mxs/mxs-dai.h b/sound/soc/mxs/mxs-dai.h new file mode 100644 index 000000000000..c75fa09ae82b --- /dev/null +++ b/sound/soc/mxs/mxs-dai.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#ifndef _MXS_SAIF_H +#define _MXS_SAIF_H + +#include + +/* SAIF clock sources */ +#define IMX_SSP_SYS_CLK 0 +#define IMX_SSP_SYS_MCLK 1 + +#define SAIF0 0 +#define SAIF1 1 + +/*private info*/ +struct mxs_saif { + u8 saif_en; +#define PLAYBACK_SAIF0_CAPTURE_SAIF1 0 +#define PLAYBACK_SAIF1_CAPTURE_SAIF0 1 + u16 stream_mapping; + struct clk *saif_mclk; +}; + +extern struct snd_soc_dai mxs_saif_dai[]; + +#endif diff --git a/sound/soc/mxs/mxs-devb-spdif.c b/sound/soc/mxs/mxs-devb-spdif.c new file mode 100644 index 000000000000..9ed62110dff7 --- /dev/null +++ b/sound/soc/mxs/mxs-devb-spdif.c @@ -0,0 +1,90 @@ +/* + * ASoC driver for MXS Evk development board + * + * Copyright (C) 2008-2010 Freescale Semiconductor, Inc. + * + * based on stmp3780_devb_spdif.c + * + * Vladimir Barinov + * + * Copyright 2008 SigmaTel, Inc + * Copyright 2008 Embedded Alley Solutions, Inc + * + * This file is licensed under the terms of the GNU General Public License + * version 2. This program is licensed "as is" without any warranty of any + * kind, whether express or implied. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "mxs-spdif-dai.h" +#include "../codecs/mxs_spdif.h" +#include "mxs-pcm.h" + +/* mxs devb digital audio interface glue - connects codec <--> CPU */ +static struct snd_soc_dai_link mxs_devb_dai = { + .name = "MXS SPDIF", + .stream_name = "MXS SPDIF", + .cpu_dai = &mxs_spdif_dai, + .codec_dai = &mxs_spdif_codec_dai, +}; + +/* mxs devb audio machine driver */ +static struct snd_soc_card snd_soc_machine_mxs_devb = { + .name = "mxs-evk", + .platform = &mxs_soc_platform, + .dai_link = &mxs_devb_dai, + .num_links = 1, +}; + +/* mxs devb audio subsystem */ +static struct snd_soc_device mxs_devb_snd_devdata = { + .card = &snd_soc_machine_mxs_devb, + .codec_dev = &soc_spdif_codec_dev_mxs, +}; + +static struct platform_device *mxs_devb_snd_device; + +static int __init mxs_devb_init(void) +{ + int ret = 0; + + mxs_devb_snd_device = platform_device_alloc("soc-audio", 2); + if (!mxs_devb_snd_device) + return -ENOMEM; + + platform_set_drvdata(mxs_devb_snd_device, + &mxs_devb_snd_devdata); + mxs_devb_snd_devdata.dev = &mxs_devb_snd_device->dev; + mxs_devb_snd_device->dev.platform_data = + &mxs_devb_snd_devdata; + + ret = platform_device_add(mxs_devb_snd_device); + if (ret) + platform_device_put(mxs_devb_snd_device); + + return ret; +} + +static void __exit mxs_devb_exit(void) +{ + platform_device_unregister(mxs_devb_snd_device); +} + +module_init(mxs_devb_init); +module_exit(mxs_devb_exit); + +MODULE_AUTHOR("Vladimir Barinov"); +MODULE_DESCRIPTION("MXS EVK development board ASoC driver"); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/mxs/mxs-devb.c b/sound/soc/mxs/mxs-devb.c new file mode 100644 index 000000000000..1c73d72466e5 --- /dev/null +++ b/sound/soc/mxs/mxs-devb.c @@ -0,0 +1,296 @@ +/* + * Copyright (C) 2010 Freescale Semiconductor, Inc. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "mxs-dai.h" +#include "mxs-pcm.h" +#include "../codecs/sgtl5000.h" + +struct mxs_evk_priv { + int sysclk; + int hw; + struct platform_device *pdev; +}; + +static struct mxs_evk_priv card_priv; + +static int mxs_evk_audio_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai_link *machine = rtd->dai; + struct snd_soc_dai *cpu_dai = machine->cpu_dai; + struct snd_soc_dai *codec_dai = machine->codec_dai; + struct mxs_evk_priv *priv = &card_priv; + unsigned int rate = params_rate(params); + int ret = 0; + + u32 dai_format; + + /* only need to do this once as capture and playback are sync */ + if (priv->hw) + return 0; + priv->hw = 1; + priv->sysclk = 512 * rate; + + snd_soc_dai_set_sysclk(codec_dai, SGTL5000_SYSCLK, (priv->sysclk)/2, 0); + snd_soc_dai_set_sysclk(codec_dai, SGTL5000_LRCLK, rate, 0); + + snd_soc_dai_set_clkdiv(cpu_dai, IMX_SSP_SYS_MCLK, 256); + /* set codec to slave mode */ + dai_format = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | + SND_SOC_DAIFMT_CBS_CFS; + + /* set codec DAI configuration */ + ret = snd_soc_dai_set_fmt(codec_dai, dai_format); + if (ret < 0) + return ret; + /* set cpu_dai to master mode for playback, slave mode for record */ + if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) + dai_format = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | + SND_SOC_DAIFMT_CBM_CFM; + + /* set cpu DAI configuration */ + ret = snd_soc_dai_set_fmt(cpu_dai, dai_format); + if (ret < 0) + return ret; + + /* set the SAIF system clock as output */ + snd_soc_dai_set_sysclk(cpu_dai, IMX_SSP_SYS_CLK, priv->sysclk, \ + SND_SOC_CLOCK_OUT); + + return 0; +} + +static int mxs_evk_startup(struct snd_pcm_substream *substream) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai_link *machine = rtd->dai; + struct snd_soc_dai *cpu_dai = machine->cpu_dai; + struct mxs_saif *saif_select = (struct mxs_saif *)cpu_dai->private_data; + + if (((saif_select->stream_mapping == PLAYBACK_SAIF0_CAPTURE_SAIF1) && \ + (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)) || \ + ((saif_select->stream_mapping == PLAYBACK_SAIF1_CAPTURE_SAIF0) \ + && (substream->stream == SNDRV_PCM_STREAM_CAPTURE))) + saif_select->saif_en = 0; + else + saif_select->saif_en = 1; + return 0; +} + +static void mxs_evk_shutdown(struct snd_pcm_substream *substream) +{ + struct mxs_evk_priv *priv = &card_priv; + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai_link *machine = rtd->dai; + struct snd_soc_dai *cpu_dai = machine->cpu_dai; + + if (cpu_dai->playback.active || cpu_dai->capture.active) + priv->hw = 1; + else + priv->hw = 0; +} + +/* + * mxs_evk SGTL5000 audio DAI opserations. + */ +static struct snd_soc_ops mxs_evk_ops = { + .startup = mxs_evk_startup, + .shutdown = mxs_evk_shutdown, + .hw_params = mxs_evk_audio_hw_params, +}; + +/* mxs_evk machine connections to the codec pins */ +static const struct snd_soc_dapm_route audio_map[] = { + + /* Mic Jack --> MIC_IN (with automatic bias) */ + {"MIC_IN", NULL, "Mic Jack"}, + + /* Line in Jack --> LINE_IN */ + {"LINE_IN", NULL, "Line In Jack"}, + + /* HP_OUT --> Headphone Jack */ + {"Headphone Jack", NULL, "HP_OUT"}, + + /* LINE_OUT --> Ext Speaker */ + {"Ext Spk", NULL, "LINE_OUT"}, +}; + +static const char *jack_function[] = { "off", "on"}; + +static const char *spk_function[] = { "off", "on" }; + +static const char *line_in_function[] = { "off", "on" }; + +static const struct soc_enum sgtl5000_enum[] = { + SOC_ENUM_SINGLE_EXT(2, jack_function), + SOC_ENUM_SINGLE_EXT(2, spk_function), + SOC_ENUM_SINGLE_EXT(2, line_in_function), +}; + +/* mxs_evk card dapm widgets */ +static const struct snd_soc_dapm_widget mxs_evk_dapm_widgets[] = { + SND_SOC_DAPM_MIC("Mic Jack", NULL), + SND_SOC_DAPM_LINE("Line In Jack", NULL), + SND_SOC_DAPM_HP("Headphone Jack", NULL), +}; + +static int mxs_evk_sgtl5000_init(struct snd_soc_codec *codec) +{ + /* Add mxs_evk specific widgets */ + snd_soc_dapm_new_controls(codec, mxs_evk_dapm_widgets, + ARRAY_SIZE(mxs_evk_dapm_widgets)); + + /* Set up mxs_evk specific audio path audio_map */ + snd_soc_dapm_add_routes(codec, audio_map, ARRAY_SIZE(audio_map)); + + snd_soc_dapm_disable_pin(codec, "Line In Jack"); + + snd_soc_dapm_sync(codec); + + return 0; +} + +/* mxs_evk digital audio interface glue - connects codec <--> CPU */ +static struct snd_soc_dai_link mxs_evk_dai = { + .name = "SGTL5000", + .stream_name = "SGTL5000", + .codec_dai = &sgtl5000_dai, + .init = mxs_evk_sgtl5000_init, + .ops = &mxs_evk_ops, +}; + +static int mxs_evk_card_remove(struct platform_device *pdev) +{ + struct mxs_evk_priv *priv = &card_priv; + struct mxs_audio_platform_data *plat; + if (priv->pdev) { + plat = priv->pdev->dev.platform_data; + if (plat->finit) + plat->finit(); + } + + return 0; +} + +static struct snd_soc_card snd_soc_card_mxs_evk = { + .name = "mxs-evk", + .platform = &mxs_soc_platform, + .dai_link = &mxs_evk_dai, + .num_links = 1, + .remove = mxs_evk_card_remove, +}; + +static struct snd_soc_device mxs_evk_snd_devdata = { + .card = &snd_soc_card_mxs_evk, + .codec_dev = &soc_codec_dev_sgtl5000, +}; + +static int __devinit mxs_evk_sgtl5000_probe(struct platform_device *pdev) +{ + struct mxs_audio_platform_data *plat = pdev->dev.platform_data; + struct mxs_saif *saif_select; + int ret = -EINVAL; + if (plat->init && plat->init()) + goto err_plat_init; + mxs_evk_dai.cpu_dai = &mxs_saif_dai[0]; + saif_select = (struct mxs_saif *)mxs_evk_dai.cpu_dai->private_data; + saif_select->stream_mapping = PLAYBACK_SAIF0_CAPTURE_SAIF1; + saif_select->saif_mclk = plat->saif_mclock; + return 0; +err_plat_init: + if (plat->finit) + plat->finit(); + return ret; +} + +static int mxs_evk_sgtl5000_remove(struct platform_device *pdev) +{ + struct mxs_audio_platform_data *plat = pdev->dev.platform_data; + + if (plat->finit) + plat->finit(); + return 0; +} + +static struct platform_driver mxs_evk_sgtl5000_audio_driver = { + .probe = mxs_evk_sgtl5000_probe, + .remove = mxs_evk_sgtl5000_remove, + .driver = { + .name = "mxs-sgtl5000", + }, +}; + +static struct platform_device *mxs_evk_snd_device; + +static int __init mxs_evk_init(void) +{ + int ret; + + ret = platform_driver_register(&mxs_evk_sgtl5000_audio_driver); + if (ret) + return -ENOMEM; + + mxs_evk_snd_device = platform_device_alloc("soc-audio", 1); + if (!mxs_evk_snd_device) + return -ENOMEM; + + platform_set_drvdata(mxs_evk_snd_device, &mxs_evk_snd_devdata); + mxs_evk_snd_devdata.dev = &mxs_evk_snd_device->dev; + ret = platform_device_add(mxs_evk_snd_device); + + if (ret) + platform_device_put(mxs_evk_snd_device); + + return ret; +} + +static void __exit mxs_evk_exit(void) +{ + platform_driver_unregister(&mxs_evk_sgtl5000_audio_driver); + platform_device_unregister(mxs_evk_snd_device); +} + +module_init(mxs_evk_init); +module_exit(mxs_evk_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("SGTL5000 Driver for MXS EVK"); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/mxs/mxs-evk-adc.c b/sound/soc/mxs/mxs-evk-adc.c new file mode 100644 index 000000000000..16c1cb4fab96 --- /dev/null +++ b/sound/soc/mxs/mxs-evk-adc.c @@ -0,0 +1,198 @@ +/* + * ASoC driver for Freescale MXS EVK board + * + * Author: Vladislav Buzov + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. + * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "../codecs/mxs-adc-codec.h" +#include "mxs-adc.h" +#include "mxs-pcm.h" + +/* mxs evk machine connections to the codec pins */ +static const struct snd_soc_dapm_route audio_map[] = { + /* HPR/HPL OUT --> Headphone Jack */ + {"Headphone Jack", NULL, "HPR"}, + {"Headphone Jack", NULL, "HPL"}, + + /* SPEAKER OUT --> Ext Speaker */ + {"Ext Spk", NULL, "SPEAKER"}, +}; + +static int mxs_evk_jack_func; +static int mxs_evk_spk_func; + +static const char *jack_function[] = { "off", "on"}; + +static const char *spk_function[] = { "off", "on" }; + + +static const struct soc_enum mxs_evk_enum[] = { + SOC_ENUM_SINGLE_EXT(2, jack_function), + SOC_ENUM_SINGLE_EXT(2, spk_function), +}; + +static int mxs_evk_get_jack(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + ucontrol->value.enumerated.item[0] = mxs_evk_jack_func; + return 0; +} + +static int mxs_evk_set_jack(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); + + if (mxs_evk_jack_func == ucontrol->value.enumerated.item[0]) + return 0; + + mxs_evk_jack_func = ucontrol->value.enumerated.item[0]; + if (mxs_evk_jack_func) + snd_soc_dapm_enable_pin(codec, "Headphone Jack"); + else + snd_soc_dapm_disable_pin(codec, "Headphone Jack"); + + snd_soc_dapm_sync(codec); + return 1; +} + +static int mxs_evk_get_spk(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + ucontrol->value.enumerated.item[0] = mxs_evk_spk_func; + return 0; +} + +static int mxs_evk_set_spk(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); + + if (mxs_evk_spk_func == ucontrol->value.enumerated.item[0]) + return 0; + + mxs_evk_spk_func = ucontrol->value.enumerated.item[0]; + if (mxs_evk_spk_func) + snd_soc_dapm_enable_pin(codec, "Ext Spk"); + else + snd_soc_dapm_disable_pin(codec, "Ext Spk"); + + snd_soc_dapm_sync(codec); + return 1; +} +/* mxs evk card dapm widgets */ +static const struct snd_soc_dapm_widget mxs_evk_dapm_widgets[] = { + SND_SOC_DAPM_SPK("Ext Spk", NULL), + SND_SOC_DAPM_HP("Headphone Jack", NULL), +}; + +static const struct snd_kcontrol_new mxs_evk_controls[] = { + SOC_ENUM_EXT("HP Playback Switch", mxs_evk_enum[0], mxs_evk_get_jack, + mxs_evk_set_jack), + SOC_ENUM_EXT("Speaker Playback Switch", mxs_evk_enum[1], + mxs_evk_get_spk, mxs_evk_set_spk), +}; + +static int mxs_evk_codec_init(struct snd_soc_codec *codec) +{ + int i, ret; + /* Add mxs evk specific controls */ + snd_soc_add_controls(codec, mxs_evk_controls, + ARRAY_SIZE(mxs_evk_controls)); + + /* Add mxs evk specific widgets */ + snd_soc_dapm_new_controls(codec, mxs_evk_dapm_widgets, + ARRAY_SIZE(mxs_evk_dapm_widgets)); + + /* Set up mxs evk specific audio path audio_map */ + snd_soc_dapm_add_routes(codec, audio_map, ARRAY_SIZE(audio_map)); + + snd_soc_dapm_sync(codec); + /* default on */ + mxs_evk_jack_func = 1; + mxs_evk_spk_func = 1; + + return ret; +} +/* mxs evk dac/adc audio interface glue - connects codec <--> CPU */ +static struct snd_soc_dai_link mxs_evk_codec_dai = { + .name = "MXS ADC/DAC", + .stream_name = "MXS ADC/DAC", + .cpu_dai = &mxs_adc_dai, + .codec_dai = &mxs_codec_dai, + .init = mxs_evk_codec_init, +}; + +/* mxs evk audio machine driver */ +static struct snd_soc_card snd_soc_card_mxs_evk = { + .name = "MXS EVK", + .platform = &mxs_soc_platform, + .dai_link = &mxs_evk_codec_dai, + .num_links = 1, +}; + +/* mxs evk audio subsystem */ +static struct snd_soc_device mxs_evk_snd_devdata = { + .card = &snd_soc_card_mxs_evk, + .codec_dev = &soc_codec_dev_mxs, +}; + +static struct platform_device *mxs_evk_snd_device; + +static int __init mxs_evk_adc_init(void) +{ + int ret = 0; + + mxs_evk_snd_device = platform_device_alloc("soc-audio", 0); + if (!mxs_evk_snd_device) + return -ENOMEM; + + platform_set_drvdata(mxs_evk_snd_device, + &mxs_evk_snd_devdata); + mxs_evk_snd_devdata.dev = &mxs_evk_snd_device->dev; + mxs_evk_snd_device->dev.platform_data = + &mxs_evk_snd_devdata; + + ret = platform_device_add(mxs_evk_snd_device); + if (ret) + platform_device_put(mxs_evk_snd_device); + + return ret; +} + +static void __exit mxs_evk_adc_exit(void) +{ + platform_device_unregister(mxs_evk_snd_device); +} + +module_init(mxs_evk_adc_init); +module_exit(mxs_evk_adc_exit); + +MODULE_AUTHOR("Vladislav Buzov"); +MODULE_DESCRIPTION("MXS EVK board ADC/DAC driver"); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/mxs/mxs-pcm.c b/sound/soc/mxs/mxs-pcm.c new file mode 100644 index 000000000000..f3cdcdbd2861 --- /dev/null +++ b/sound/soc/mxs/mxs-pcm.c @@ -0,0 +1,505 @@ +/* + * Copyright (C) 2010 Freescale Semiconductor, Inc. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include + +#include "mxs-pcm.h" +static const struct snd_pcm_hardware mxs_pcm_hardware = { + .info = SNDRV_PCM_INFO_MMAP | + SNDRV_PCM_INFO_MMAP_VALID | + SNDRV_PCM_INFO_PAUSE | + SNDRV_PCM_INFO_RESUME | + SNDRV_PCM_INFO_INTERLEAVED, + .formats = SNDRV_PCM_FMTBIT_S16_LE | + SNDRV_PCM_FMTBIT_S20_3LE | + SNDRV_PCM_FMTBIT_S24_LE | + SNDRV_PCM_FMTBIT_S32_LE, + .channels_min = 2, + .channels_max = 2, + .period_bytes_min = 32, + .period_bytes_max = 8192, + .periods_min = 1, + .periods_max = 255, + .buffer_bytes_max = 64 * 1024, + .fifo_size = 32, +}; + +/* + * Required to request DMA channels + */ +struct device *mxs_pcm_dev; + +struct mxs_runtime_data { + u32 dma_ch; + u32 dma_period; + u32 dma_totsize; + unsigned long appl_ptr_bytes; + int format; + + struct mxs_pcm_dma_params *params; + struct mxs_dma_desc *dma_desc_array[255]; +}; + +static irqreturn_t mxs_pcm_dma_irq(int irq, void *dev_id) +{ + struct snd_pcm_substream *substream = dev_id; + struct snd_pcm_runtime *runtime = substream->runtime; + struct mxs_runtime_data *prtd = substream->runtime->private_data; + struct mxs_dma_info dma_info; + void *pdma; + unsigned long prev_appl_offset, appl_count, cont, appl_ptr_bytes; + + mxs_dma_get_info(prtd->dma_ch, &dma_info); + + if (dma_info.status) { + printk(KERN_WARNING "%s: DMA audio channel %d (%s) error\n", + __func__, prtd->params->dma_ch, prtd->params->name); + mxs_dma_ack_irq(prtd->dma_ch); + } else { + if ((prtd->params->dma_ch == MXS_DMA_CHANNEL_AHB_APBX_SPDIF) && + (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) && + (runtime->access == SNDRV_PCM_ACCESS_MMAP_INTERLEAVED) && + ((prtd->format == SNDRV_PCM_FORMAT_S24_LE) + || (prtd->format == SNDRV_PCM_FORMAT_S20_3LE))) { + + appl_ptr_bytes = + frames_to_bytes(runtime, + runtime->control->appl_ptr); + + appl_count = appl_ptr_bytes - prtd->appl_ptr_bytes; + prev_appl_offset = + prtd->appl_ptr_bytes % prtd->dma_totsize; + cont = prtd->dma_totsize - prev_appl_offset; + + if (appl_count > cont) { + pdma = runtime->dma_area + prev_appl_offset; + memmove(pdma + 1, pdma, cont - 1); + pdma = runtime->dma_area; + memmove(pdma + 1, pdma, appl_count - cont - 1); + } else { + pdma = runtime->dma_area + prev_appl_offset; + memmove(pdma + 1, pdma, appl_count - 1); + } + prtd->appl_ptr_bytes = appl_ptr_bytes; + } + mxs_dma_ack_irq(prtd->dma_ch); + snd_pcm_period_elapsed(substream); + } + return IRQ_HANDLED; +} + +/* + * Make a circular DMA descriptor list + */ +static int mxs_pcm_prepare(struct snd_pcm_substream *substream) +{ + struct snd_pcm_runtime *runtime = substream->runtime; + struct mxs_runtime_data *prtd = runtime->private_data; + dma_addr_t dma_buffer_phys; + int periods_num, playback, i; + + playback = substream->stream == SNDRV_PCM_STREAM_PLAYBACK ? 1 : 0; + periods_num = prtd->dma_totsize / prtd->dma_period; + + dma_buffer_phys = runtime->dma_addr; + + /* Reset DMA channel, enable interrupt */ + mxs_dma_reset(prtd->dma_ch); + + /* Set up a DMA chain to sent DMA buffer */ + for (i = 0; i < periods_num; i++) { + int ret; + /* Link with previous command */ + prtd->dma_desc_array[i]->cmd.cmd.bits.bytes = prtd->dma_period; + prtd->dma_desc_array[i]->cmd.cmd.bits.irq = 1; + prtd->dma_desc_array[i]->cmd.cmd.bits.dec_sem = 0; + prtd->dma_desc_array[i]->cmd.cmd.bits.chain = 1; + /* Set DMA direction */ + if (playback) + prtd->dma_desc_array[i]->cmd.cmd.bits.command = \ + DMA_READ; + else + prtd->dma_desc_array[i]->cmd.cmd.bits.command = \ + DMA_WRITE; + + prtd->dma_desc_array[i]->cmd.address = dma_buffer_phys; + + ret = mxs_dma_desc_append(prtd->dma_ch, \ + prtd->dma_desc_array[i]); + if (ret) { + printk(KERN_ERR "%s: Failed to append DMA descriptor\n", + __func__); + return ret; + } + /* Next data chunk */ + dma_buffer_phys += prtd->dma_period; + } + + return 0; +} + +/* + * Stop circular DMA descriptor list + * We should not stop DMA in a middle of current transaction once we receive + * stop request from ALSA core. This function finds the next DMA descriptor + * and set it up to decrement DMA channel semaphore. So the current transaction + * is the last data transfer. + */ +static void mxs_pcm_stop(struct snd_pcm_substream *substream) +{ + struct snd_pcm_runtime *runtime = substream->runtime; + struct mxs_runtime_data *prtd = runtime->private_data; + struct mxs_dma_info dma_info; + int desc; + + /* Freez DMA channel for a moment */ + mxs_dma_freeze(prtd->dma_ch); + mxs_dma_get_info(prtd->dma_ch, &dma_info); + + desc = (dma_info.buf_addr - runtime->dma_addr) / prtd->dma_period; + + /* Set up the next descriptor to decrement DMA channel sempahore */ + prtd->dma_desc_array[(desc + 1)%8]->cmd.cmd.bits.bytes = 0; + prtd->dma_desc_array[(desc + 1)%8]->cmd.cmd.bits.pio_words = 0; + prtd->dma_desc_array[(desc + 1)%8]->cmd.cmd.bits.dec_sem = 1; + prtd->dma_desc_array[(desc + 1)%8]->cmd.cmd.bits.irq = 0; + prtd->dma_desc_array[(desc + 1)%8]->cmd.cmd.bits.command = NO_DMA_XFER; + + mxs_dma_unfreeze(prtd->dma_ch); + + mxs_dma_disable(prtd->dma_ch); +} + +static int mxs_pcm_trigger(struct snd_pcm_substream *substream, int cmd) +{ + struct snd_pcm_runtime *runtime = substream->runtime; + struct mxs_runtime_data *prtd = substream->runtime->private_data; + int ret = 0; + switch (cmd) { + + case SNDRV_PCM_TRIGGER_START: + if ((prtd->params->dma_ch == MXS_DMA_CHANNEL_AHB_APBX_SPDIF) && + (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) && + (runtime->access == SNDRV_PCM_ACCESS_MMAP_INTERLEAVED) && + ((prtd->format == SNDRV_PCM_FORMAT_S24_LE) + || (prtd->format == SNDRV_PCM_FORMAT_S20_3LE))) { + prtd->appl_ptr_bytes = + frames_to_bytes(runtime, + runtime->control->appl_ptr); + memmove(runtime->dma_area + 1, runtime->dma_area, + prtd->appl_ptr_bytes - 1); + } + mxs_dma_enable(prtd->dma_ch); + break; + + case SNDRV_PCM_TRIGGER_STOP: + mxs_pcm_stop(substream); + break; + + case SNDRV_PCM_TRIGGER_RESUME: + case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: + mxs_dma_unfreeze(prtd->dma_ch); + break; + + case SNDRV_PCM_TRIGGER_SUSPEND: + case SNDRV_PCM_TRIGGER_PAUSE_PUSH: + mxs_dma_freeze(prtd->dma_ch); + break; + + default: + ret = -EINVAL; + break; + } + + return ret; +} + +static snd_pcm_uframes_t +mxs_pcm_pointer(struct snd_pcm_substream *substream) +{ + struct snd_pcm_runtime *runtime = substream->runtime; + struct mxs_runtime_data *prtd = runtime->private_data; + struct mxs_dma_info dma_info; + unsigned int offset; + dma_addr_t pos; + + mxs_dma_get_info(prtd->params->dma_ch, &dma_info); + pos = dma_info.buf_addr; + + offset = bytes_to_frames(runtime, pos - runtime->dma_addr); + + if (offset >= runtime->buffer_size) + offset = 0; + + return offset; +} + +static int mxs_pcm_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *hw_params) +{ + struct mxs_runtime_data *prtd = substream->runtime->private_data; + + prtd->dma_period = params_period_bytes(hw_params); + prtd->dma_totsize = params_buffer_bytes(hw_params); + prtd->format = params_format(hw_params); + + return snd_pcm_lib_malloc_pages(substream, + params_buffer_bytes(hw_params)); +} + +static int mxs_pcm_hw_free(struct snd_pcm_substream *substream) +{ + return snd_pcm_lib_free_pages(substream); +} + +static int mxs_pcm_dma_request(struct snd_pcm_substream *substream) +{ + struct snd_pcm_runtime *runtime = substream->runtime; + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct mxs_runtime_data *prtd = runtime->private_data; + struct mxs_pcm_dma_params *dma_data = rtd->dai->cpu_dai->dma_data; + int desc_num = mxs_pcm_hardware.periods_max; + int desc; + int ret; + + if (!dma_data) + return -ENODEV; + + prtd->params = dma_data; + prtd->dma_ch = dma_data->dma_ch; + + ret = mxs_dma_request(prtd->dma_ch, mxs_pcm_dev, + prtd->params->name); + if (ret) { + printk(KERN_ERR "%s: Failed to request DMA channel (%d:%d)\n", + __func__, dma_data->dma_bus, dma_data->dma_ch); + return ret; + } + + /* Allocate memory for data and pio DMA descriptors */ + for (desc = 0; desc < desc_num; desc++) { + prtd->dma_desc_array[desc] = mxs_dma_alloc_desc(); + if (prtd->dma_desc_array[desc] == NULL) { + printk(KERN_ERR"%s Unable to allocate DMA command %d\n", + __func__, desc); + goto err; + } + } + + ret = request_irq(prtd->params->irq, mxs_pcm_dma_irq, 0, + "MXS PCM DMA", substream); + if (ret) { + printk(KERN_ERR "%s: Unable to request DMA irq %d\n", __func__, + prtd->params->irq); + goto err; + } + /* Enable completion interrupt */ + mxs_dma_ack_irq(prtd->dma_ch); + mxs_dma_enable_irq(prtd->dma_ch, 1); + + return 0; + +err: + while (--desc >= 0) + mxs_dma_free_desc(prtd->dma_desc_array[desc]); + mxs_dma_release(prtd->dma_ch, mxs_pcm_dev); + + return ret; +} + +static int mxs_pcm_open(struct snd_pcm_substream *substream) +{ + struct snd_pcm_runtime *runtime = substream->runtime; + struct mxs_runtime_data *prtd; + int ret; + + /* Ensure that buffer size is a multiple of the period size */ + ret = snd_pcm_hw_constraint_integer(runtime, + SNDRV_PCM_HW_PARAM_PERIODS); + if (ret < 0) + return ret; + + snd_soc_set_runtime_hwparams(substream, &mxs_pcm_hardware); + + prtd = kzalloc(sizeof(struct mxs_runtime_data), GFP_KERNEL); + if (prtd == NULL) + return -ENOMEM; + + runtime->private_data = prtd; + + ret = mxs_pcm_dma_request(substream); + if (ret) { + printk(KERN_ERR "mxs_pcm: Failed to request channels\n"); + kfree(prtd); + return ret; + } + return 0; +} + +static int mxs_pcm_close(struct snd_pcm_substream *substream) +{ + struct snd_pcm_runtime *runtime = substream->runtime; + struct mxs_runtime_data *prtd = runtime->private_data; + int desc_num = mxs_pcm_hardware.periods_max; + int desc; + + static LIST_HEAD(list); + mxs_dma_disable(prtd->dma_ch); + /* Free DMA irq */ + free_irq(prtd->params->irq, substream); + mxs_dma_get_cooked(prtd->dma_ch, &list); + /* Free DMA channel*/ + for (desc = 0; desc < desc_num; desc++) + mxs_dma_free_desc(prtd->dma_desc_array[desc]); + mxs_dma_release(prtd->dma_ch, mxs_pcm_dev); + + /* Free private runtime data */ + kfree(prtd); + return 0; +} + +static int mcs_pcm_copy(struct snd_pcm_substream *substream, int channel, + snd_pcm_uframes_t hwoff, void __user *buf, + snd_pcm_uframes_t frames) +{ + struct snd_pcm_runtime *runtime = substream->runtime; + struct mxs_runtime_data *prtd = runtime->private_data; + char *hwbuf = runtime->dma_area + frames_to_bytes(runtime, hwoff); + unsigned long count = frames_to_bytes(runtime, frames); + + /* For S/PDIF 24-bit playback, fix the buffer. Code taken from + snd_pcm_lib_write_transfer() and snd_pcm_lib_read_transfer() + in sound/core/pcm_lib.c */ + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + if ((prtd->params->dma_ch == MXS_DMA_CHANNEL_AHB_APBX_SPDIF) && + ((prtd->format == SNDRV_PCM_FORMAT_S24_LE) + || (prtd->format == SNDRV_PCM_FORMAT_S20_3LE))) { + if (copy_from_user(hwbuf + 1, buf, count - 1)) + return -EFAULT; + } else { + if (copy_from_user(hwbuf, buf, count)) + return -EFAULT; + } + } else { + if (copy_to_user(buf, hwbuf, count)) + return -EFAULT; + } + + return 0; +} + +static int mxs_pcm_mmap(struct snd_pcm_substream *substream, + struct vm_area_struct *vma) +{ + struct snd_pcm_runtime *runtime = substream->runtime; + + return dma_mmap_coherent(NULL, vma, runtime->dma_area, + runtime->dma_addr, runtime->dma_bytes); +} + +struct snd_pcm_ops mxs_pcm_ops = { + .open = mxs_pcm_open, + .close = mxs_pcm_close, + .ioctl = snd_pcm_lib_ioctl, + .hw_params = mxs_pcm_hw_params, + .hw_free = mxs_pcm_hw_free, + .prepare = mxs_pcm_prepare, + .trigger = mxs_pcm_trigger, + .pointer = mxs_pcm_pointer, + .copy = mcs_pcm_copy, + .mmap = mxs_pcm_mmap, +}; + +static u64 mxs_pcm_dma_mask = DMA_BIT_MASK(32); + +static int mxs_pcm_new(struct snd_card *card, + struct snd_soc_dai *dai, struct snd_pcm *pcm) +{ + size_t size = mxs_pcm_hardware.buffer_bytes_max; + + if (!card->dev->dma_mask) + card->dev->dma_mask = &mxs_pcm_dma_mask; + + if (!card->dev->coherent_dma_mask) + card->dev->coherent_dma_mask = DMA_BIT_MASK(32); + + snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV, NULL, + size, size); + + return 0; +} + +static void mxs_pcm_free(struct snd_pcm *pcm) +{ + snd_pcm_lib_preallocate_free_for_all(pcm); +} + +/* + * We need probe/remove callbacks to setup mxs_pcm_dev + */ +static int mxs_pcm_probe(struct platform_device *pdev) +{ + mxs_pcm_dev = &pdev->dev; + return 0; +} + +static int mxs_pcm_remove(struct platform_device *pdev) +{ + mxs_pcm_dev = NULL; + return 0; +} + +struct snd_soc_platform mxs_soc_platform = { + .name = "MXS Audio", + .pcm_ops = &mxs_pcm_ops, + .probe = mxs_pcm_probe, + .remove = mxs_pcm_remove, + .pcm_new = mxs_pcm_new, + .pcm_free = mxs_pcm_free, +}; +EXPORT_SYMBOL_GPL(mxs_soc_platform); + +static int __init mxs_pcm_init(void) +{ + return snd_soc_register_platform(&mxs_soc_platform); +} + +static void __exit mxs_pcm_exit(void) +{ + snd_soc_unregister_platform(&mxs_soc_platform); +} +module_init(mxs_pcm_init); +module_exit(mxs_pcm_exit); + +MODULE_AUTHOR("Freescale Semiconductor, Inc."); +MODULE_DESCRIPTION("MXS DMA Module"); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/mxs/mxs-pcm.h b/sound/soc/mxs/mxs-pcm.h new file mode 100644 index 000000000000..08a9d92e2afe --- /dev/null +++ b/sound/soc/mxs/mxs-pcm.h @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#ifndef _MXS_PCM_H +#define _MXS_PCM_H + +struct mxs_pcm_dma_params { + char *name; + int dma_bus; /* DMA bus */ + int dma_ch; /* DMA channel number */ + int irq; /* DMA interrupt number */ +}; + +extern struct snd_soc_platform mxs_soc_platform; + +#endif diff --git a/sound/soc/mxs/mxs-spdif-dai.c b/sound/soc/mxs/mxs-spdif-dai.c new file mode 100644 index 000000000000..052c404c496d --- /dev/null +++ b/sound/soc/mxs/mxs-spdif-dai.c @@ -0,0 +1,203 @@ +/* + * ALSA SoC SPDIF Audio Layer for MXS + * + * Copyright (C) 2008-2010 Freescale Semiconductor, Inc. + * + * Based on stmp3xxx_spdif_dai.c + * Vladimir Barinov + * Copyright 2008 SigmaTel, Inc + * Copyright 2008 Embedded Alley Solutions, Inc + * + * This file is licensed under the terms of the GNU General Public License + * version 2. This program is licensed "as is" without any warranty of any + * kind, whether express or implied. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../codecs/mxs_spdif.h" +#include "mxs-pcm.h" + +#define REGS_SPDIF_BASE IO_ADDRESS(SPDIF_PHYS_ADDR) + +struct mxs_pcm_dma_params mxs_spdif = { + .name = "mxs spdif", + .dma_ch = MXS_DMA_CHANNEL_AHB_APBX_SPDIF, + .irq = IRQ_SPDIF_DMA, +}; + +static irqreturn_t mxs_err_irq(int irq, void *dev_id) +{ + struct snd_pcm_substream *substream = dev_id; + int playback = substream->stream == SNDRV_PCM_STREAM_PLAYBACK ? 1 : 0; + u32 ctrl_reg = 0; + u32 overflow_mask; + u32 underflow_mask; + + if (playback) { + ctrl_reg = __raw_readl(REGS_SPDIF_BASE + HW_SPDIF_CTRL); + underflow_mask = BM_SPDIF_CTRL_FIFO_UNDERFLOW_IRQ; + overflow_mask = BM_SPDIF_CTRL_FIFO_OVERFLOW_IRQ; + } + + if (ctrl_reg & underflow_mask) { + printk(KERN_DEBUG "underflow detected SPDIF\n"); + + if (playback) + __raw_writel(BM_SPDIF_CTRL_FIFO_UNDERFLOW_IRQ, + REGS_SPDIF_BASE + HW_SPDIF_CTRL_CLR); + } else if (ctrl_reg & overflow_mask) { + printk(KERN_DEBUG "overflow detected SPDIF\n"); + + if (playback) + __raw_writel(BM_SPDIF_CTRL_FIFO_OVERFLOW_IRQ, + REGS_SPDIF_BASE + HW_SPDIF_CTRL_CLR); + } else + printk(KERN_WARNING "Unknown SPDIF error interrupt\n"); + + return IRQ_HANDLED; +} + +static int mxs_spdif_trigger(struct snd_pcm_substream *substream, int cmd, + struct snd_soc_dai *dai) +{ + int playback = substream->stream == SNDRV_PCM_STREAM_PLAYBACK ? 1 : 0; + int ret = 0; + + switch (cmd) { + case SNDRV_PCM_TRIGGER_START: + if (playback) + __raw_writel(BM_SPDIF_CTRL_RUN, + REGS_SPDIF_BASE + HW_SPDIF_CTRL_SET); + break; + case SNDRV_PCM_TRIGGER_STOP: + if (playback) + __raw_writel(BM_SPDIF_CTRL_RUN, + REGS_SPDIF_BASE + HW_SPDIF_CTRL_CLR); + break; + case SNDRV_PCM_TRIGGER_RESUME: + case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: + case SNDRV_PCM_TRIGGER_SUSPEND: + case SNDRV_PCM_TRIGGER_PAUSE_PUSH: + + default: + ret = -EINVAL; + } + + return ret; +} + +static int mxs_spdif_startup(struct snd_pcm_substream *substream, + struct snd_soc_dai *dai) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai *cpu_dai = rtd->dai->cpu_dai; + int playback = substream->stream == SNDRV_PCM_STREAM_PLAYBACK ? 1 : 0; + int irq; + int ret; + + if (playback) { + irq = IRQ_SPDIF_ERROR; + cpu_dai->dma_data = &mxs_spdif; + } + + ret = request_irq(irq, mxs_err_irq, 0, "Mxs SPDIF Error", + substream); + if (ret) { + printk(KERN_ERR "%s: Unable to request SPDIF error irq %d\n", + __func__, IRQ_SPDIF_ERROR); + return ret; + } + + /* Enable error interrupt */ + if (playback) { + __raw_writel(BM_SPDIF_CTRL_FIFO_OVERFLOW_IRQ, + REGS_SPDIF_BASE + HW_SPDIF_CTRL_CLR); + __raw_writel(BM_SPDIF_CTRL_FIFO_UNDERFLOW_IRQ, + REGS_SPDIF_BASE + HW_SPDIF_CTRL_CLR); + __raw_writel(BM_SPDIF_CTRL_FIFO_ERROR_IRQ_EN, + REGS_SPDIF_BASE + HW_SPDIF_CTRL_SET); + } + + return 0; +} + +static void mxs_spdif_shutdown(struct snd_pcm_substream *substream, + struct snd_soc_dai *dai) +{ + int playback = substream->stream == SNDRV_PCM_STREAM_PLAYBACK ? 1 : 0; + + /* Disable error interrupt */ + if (playback) { + __raw_writel(BM_SPDIF_CTRL_FIFO_ERROR_IRQ_EN, + REGS_SPDIF_BASE + HW_SPDIF_CTRL_CLR); + free_irq(IRQ_SPDIF_ERROR, substream); + } +} + +#ifdef CONFIG_PM +static int mxs_spdif_suspend(struct snd_soc_dai *cpu_dai) +{ + return 0; +} + +static int mxs_spdif_resume(struct snd_soc_dai *cpu_dai) +{ + return 0; +} +#else +#define mxs_spdif_suspend NULL +#define mxs_spdif_resume NULL +#endif /* CONFIG_PM */ + +struct snd_soc_dai_ops mxs_spdif_dai_ops = { + .startup = mxs_spdif_startup, + .shutdown = mxs_spdif_shutdown, + .trigger = mxs_spdif_trigger, +}; + +struct snd_soc_dai mxs_spdif_dai = { + .name = "mxs-spdif", + .id = 0, + .suspend = mxs_spdif_suspend, + .resume = mxs_spdif_resume, + .playback = { + .channels_min = 2, + .channels_max = 2, + .rates = MXS_SPDIF_RATES, + .formats = MXS_SPDIF_FORMATS, + }, + .capture = { + .channels_min = 2, + .channels_max = 2, + .rates = MXS_SPDIF_RATES, + .formats = MXS_SPDIF_FORMATS, + }, + .ops = &mxs_spdif_dai_ops, +}; +EXPORT_SYMBOL_GPL(mxs_spdif_dai); + +static int __init mxs_spdif_dai_init(void) +{ + return snd_soc_register_dai(&mxs_spdif_dai); +} + +static void __exit mxs_spdif_dai_exit(void) +{ + snd_soc_unregister_dai(&mxs_spdif_dai); +} +module_init(mxs_spdif_dai_init); +module_exit(mxs_spdif_dai_exit); + +MODULE_AUTHOR("Vladimir Barinov"); +MODULE_DESCRIPTION("MXS SPDIF DAI"); +MODULE_LICENSE("GPL"); diff --git a/sound/soc/mxs/mxs-spdif-dai.h b/sound/soc/mxs/mxs-spdif-dai.h new file mode 100644 index 000000000000..035369af9676 --- /dev/null +++ b/sound/soc/mxs/mxs-spdif-dai.h @@ -0,0 +1,21 @@ +/* + * ASoC Audio Layer for Freescale STMP3XXX SPDIF transmitter + * + * Author: Vladimir Barinov + * + * Copyright 2008-2010 Freescale Semiconductor, Inc. + * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ +#ifndef _STMP3XXX_SPDIF_H +#define _STMP3XXX_SPDIF_H +extern struct snd_soc_dai mxs_spdif_dai; +#endif -- cgit v1.2.3